farmitry_hvac/app/services/modbus/service.rb

39 lines
1.2 KiB
Ruby

require_relative "operations"
Dir[File.join(__dir__.to_s, "commands", "**", "*.rb")].each do |file|
load file
end
class Modbus::Service
include Modbus::Operations
include Modbus::Commands
def initialize(type:, start_address:, end_address: nil, value: nil)
@type = type
@start_address = start_address.to_i
@end_address = end_address&.to_i
@value = value
@slave_id = 1
@plc_host = "rubyon.co.kr"
@plc_port = 502
end
def execute
ModBus::TCPClient.new(@plc_host, @plc_port) do |client|
client.with_slave(@slave_id) do |slave|
method_name = @type.strip
# Commands 모듈에 정의된 메서드만 허용
if Modbus::Commands.instance_methods(false).include?(method_name.to_sym)
return send(method_name, slave)
else
available_commands = Modbus::Commands.instance_methods(false).sort.map(&:to_s)
command_list = available_commands.join("\r\n")
raise ArgumentError, "지원되지 않는 type: #{@type}\r\n사용 가능한 명령어 목록:\r\n#{command_list}"
end
end
end
rescue => e
Rails.logger.error "[#{Time.current}] Service 오류: #{e.message}"
end
end