module Modbus class PollingService class << self def start return if $modbus_polling_threads.any?(&:alive?) thread = Thread.new do puts "[#{Time.current}] Modbus polling service 시작됨" last_logged_hour = nil loop do begin now = Time.now current_hour = now.hour if current_hour != last_logged_hour && now.min == 0 schedule = Schedule.find_by(hour: current_hour) Modbus::Service.new( type: "write_int16", start_address: 2, end_address: 2, value: schedule.temperature * 10 ).execute puts "[Schedule] #{current_hour}:00 -> Target temp: #{schedule.temperature}°C" last_logged_hour = current_hour end rescue StandardError => e error_message = "[#{Time.current}] 오류: #{e.message}" puts error_message ensure sleep 0.1 end end end $modbus_polling_threads << thread end def stop $modbus_polling_threads.each { |t| t.kill if t.alive? } $modbus_polling_threads.clear puts "[#{Time.now}] Modbus polling service 중지됨" end def running? $modbus_polling_threads.any?(&:alive?) end end end end