분 추가 (스케쥴 new 추가 필요)
This commit is contained in:
@@ -3,45 +3,68 @@ module Modbus
|
||||
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
|
||||
$modbus_polling_threads << start_thread
|
||||
end
|
||||
|
||||
def stop
|
||||
$modbus_polling_threads.each { |t| t.kill if t.alive? }
|
||||
$modbus_polling_threads.clear
|
||||
puts "[#{Time.now}] Modbus polling service 중지됨"
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user