farmitry_hvac/app/services/modbus/polling_service.rb

60 lines
1.7 KiB
Ruby

# polling_service.rb
require "rufus-scheduler"
module Modbus
class PollingService
class << self
def start
return if defined?(@scheduler) && @scheduler.jobs.any?
puts "[#{Time.current}] Modbus polling service 시작됨 (Rufus)"
@scheduler = Rufus::Scheduler.new
@scheduler.cron "0 * * * * *" do
now = Time.now
current_time = format("%02d:%02d", now.hour, now.min)
puts "# current time: #{current_time}.#{now.sec}"
schedule = Schedule.find_by(hour: now.hour, minute: now.min)
apply_schedule(schedule) if schedule
end
end
def stop
if defined?(@scheduler)
@scheduler.shutdown(:kill)
puts "[#{Time.current}] Modbus polling service 중지됨"
else
puts "[#{Time.current}] Scheduler 인스턴스 없음"
end
end
def running?
defined?(@scheduler) && @scheduler.jobs.any?
end
private
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] #{format('%02d:%02d', 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