48 lines
1.3 KiB
Ruby
48 lines
1.3 KiB
Ruby
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)
|
|
|
|
serial_path = Rails.root.join("serial.rb")
|
|
system("ruby", serial_path.to_s, "#{schedule.temperature * 10}")
|
|
|
|
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
|