farmitry_hvac/app/services/modbus/polling_service.rb

47 lines
1.3 KiB
Ruby

module Modbus
class PollingService
class << self
def start
return if @thread&.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
end
def stop
if @thread
@thread.exit
@thread = nil
puts "[#{Time.now}] Modbus polling service 중지됨"
end
end
end
end
end