farmitry_hvac/app/services/modbus/polling_service.rb

52 lines
1.7 KiB
Ruby

# polling_service.rb
require "rufus-scheduler"
module Modbus
class PollingService
class << self
def start
return if @scheduler
puts "[#{Time.now}] 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}"
schedules = Schedule.where(hour: now.hour, minute: now.min)
schedules.each { |schedule| apply_schedule(schedule) }
end
end
private
def apply_schedule(schedule)
if schedule.is_active
run_script("on_off.rb", "#{schedule.controller.station_id}", "0", "[Schedule] #{schedule.controller.name} ON")
sleep 2
run_script(
"serial.rb",
"#{schedule.controller.station_id}",
(schedule.temperature * 10).to_i.to_s,
"[Schedule] #{schedule.controller.name} #{format('%02d:%02d', schedule.hour, schedule.minute)}#{schedule.temperature}°C"
)
else
run_script("on_off.rb", "#{schedule.controller.station_id}", "1", "[Schedule] #{schedule.controller.name} OFF")
end
end
def run_script(file, controller_id, value, success_msg)
path = Rails.root.join(file)
if system("ruby", path.to_s, controller_id, value)
puts success_msg
Rails.logger.info success_msg
else
error_message = "[#{Time.now}] #{file} 실행 실패 (station_id: #{controller_id}, value: #{value})"
puts error_message
Rails.logger.error error_message
end
end
end
end
end