farmitry_hvac/app/services/modbus/polling_service.rb

71 lines
1.8 KiB
Ruby

module Modbus
class PollingService
class << self
def start
return if $modbus_polling_threads.any?(&:alive?)
$modbus_polling_threads << start_thread
end
def stop
$modbus_polling_threads.each { |t| t.kill if t.alive? }
$modbus_polling_threads.clear
puts "Modbus polling service 중지됨"
end
def running?
$modbus_polling_threads.any?(&:alive?)
end
private
def start_thread
Thread.new { run_polling_loop }
end
def run_polling_loop
puts "Modbus polling service 시작됨"
last_logged = nil
loop do
begin
now = Time.now
current = [ now.hour, now.min ]
if current != last_logged
puts "시간 변경 감지됨: #{current.join(':')}"
schedule = Schedule.find_by(hour: current[0], minute: current[1])
apply_schedule(schedule) if schedule
last_logged = current
end
rescue => e
puts "[#{Time.current}] #{file} 에러: #{e.message}"
ensure
sleep 1
end
end
end
def apply_schedule(schedule)
if schedule.is_active
run_script("on_off.rb", "0", "[Schedule] ON")
run_script(
"serial.rb",
(schedule.temperature * 10).to_i.to_s,
"[Schedule] #{schedule.hour}:#{schedule.minute}#{schedule.temperature}°C"
)
else
run_script("on_off.rb", "1", "[Schedule] OFF")
end
end
def run_script(file, arg, success_msg)
path = Rails.root.join(file)
if system("ruby", path.to_s, arg)
puts success_msg
else
puts "[#{Time.current}] #{file} 실행 실패 (args: #{arg})"
end
end
end
end
end