def _init_modbus(self, ): """modbusServer初始化 Returns: server -- server服务器 slave -- 从机 """ # 钩子 hooks.install_hook('modbus.Slave.handle_write_multiple_registers_request', self._handle_write_multiple_registers_request) hooks.install_hook('modbus.Slave.handle_write_single_register_request', self._handle_write_single_registers_request) # 初始化 server = modbus_tcp.TcpServer(address='0.0.0.0', port=PORT) # 服务启动 server.start() # 建立从机 slave = server.add_slave(SLAVE_ID) # 建立块 # slave.add_block('0', cst.DISCRETE_INPUTS, 0, 100) # slave.add_block('0', cst.COILS, 0, 100) slave.add_block(SYS_ANALOG_INPUTS_BLOCK_NAME, cst.ANALOG_INPUTS, SYS_ANALOG_INPUTS_BLOCK_ADDRESS, 171) slave.add_block(SYS_HOLDING_REGISTERS_BLOCK_NAME, cst.HOLDING_REGISTERS, SYS_HOLDING_REGISTERS_BLOCK_ADDRESS, 6) # slave.add_block(HIDDEN_HOLDING_REGISTERS_BLOCK_NAME, cst.HOLDING_REGISTERS, 5999, 20) return server, slave
def testExpectedLengthTooShort(self): """check that an error is raised if expected_length is too low""" self.slave1.set_values("hr0-100", 0, range(100)) ok = True def check_length_hook(args): (master, response) = args LOGGER.debug("expected: %d - actual: %d", check_length_hook.expected_length, len(response)) check_length_hook.test.assertEqual( check_length_hook.expected_length, len(response)) check_length_hook.test = self hooks.install_hook("modbus_rtu.RtuMaster.after_recv", check_length_hook) for x in (5, 204): try: check_length_hook.expected_length = x self.master.execute(1, modbus_tk.defines.READ_HOLDING_REGISTERS, 0, 100, expected_length=x) except: pass else: ok = False hooks.uninstall_hook("modbus_rtu.RtuMaster.after_recv", check_length_hook) self.assert_(ok)
def testHookOnSetBlockData(self): slave = self.server.add_slave(22) def setblock_hook(args): (block, slice, values) = args setblock_hook.calls += 1 setblock_hook.calls = 0 install_hook('modbus.ModbusBlock.setitem', setblock_hook) for block_type in (modbus_tk.defines.COILS, modbus_tk.defines.DISCRETE_INPUTS, modbus_tk.defines.HOLDING_REGISTERS, modbus_tk.defines.ANALOG_INPUTS): slave.add_block(str(block_type), block_type, 0, 20) slave.set_values(str(block_type), 0, 1) slave.set_values(str(block_type), 5, (1, 0, 1)) self.assertEquals(setblock_hook.calls, 8)
def __init__( self, port: str = "/dev/ttyUSB0", baudrate: int = 115200, address: int = 1, serial: Serial = None, master: RtuMaster = None, close_after_call: bool = False, ): self.address = address self.serial = serial or Serial(port, baudrate) self.master = master or RtuMaster(self.serial) # Fixes "Response length is invalid 0" error # If you experience this error, try changing your baudrate self.master.set_timeout(0.05) # Windows requires opening/closing the com port after each call # This is a workaround that will drasticly reduce performance if close_after_call: hooks.install_hook("modbus_rtu.RtuMaster.before_send", lambda self: self._do_open()) hooks.install_hook("modbus_rtu.RtuMaster.after_recv", lambda self: self._do_close()) self.init() self.v_multi = 100 self.i_multi = 100 self.p_multi = 100 self.v_in_multi = 100 if 60180 <= self.id <= 60189: self.type = "RD6018" elif 60120 <= self.id <= 60129: self.type = "RD6012" elif 60060 <= self.id <= 60064: self.type = "RD6006" self.i_multi = 1000 elif self.id == 60065: self.type = "RD6006P" self.v_multi = 1000 self.i_multi = 10000 self.p_multi = 1000 self.update()
def __init__(self, parent): super(ModSlaveBusMonitorWindow,self).__init__(parent) self._logger = logging.getLogger("modbus_tk") self._model = QtCore.QStringListModel() self._string_list = [] self._max_no_of_bus_monitor_lines = 50 self.packets = 0 self.errors = 0 self.svr = None #setup UI self.setupUI() self.ui.lstRawData.setModel(self._model) #install hooks install_hook(SERVER_RTU_HOOKS[0], self._req_rtu_data) install_hook(SERVER_RTU_HOOKS[1], self._resp_rtu_data) install_hook(SERVER_TCP_HOOKS[0], self._req_tcp_data) install_hook(SERVER_TCP_HOOKS[1], self._resp_tcp_data) install_hook(SLAVE_HOOKS, self._error_data)
def __init__(self,modSvr,slaveAddress,timeIntervalSim, start_addr_coils = 0 ,no_coils = 10, start_addr_dis_inputs = 0, no_dis_inputs = 10, start_addr_input_regs = 0, no_input_regs = 10, start_addr_hold_regs = 0, no_hold_regs = 10): super(ModSlave,self).__init__() self._sim_interval = timeIntervalSim self._start_addr_coils = start_addr_coils self._no_coils = no_coils self._start_addr_dis_inputs = start_addr_dis_inputs self._no_dis_inputs = no_dis_inputs self._start_addr_input_regs = start_addr_input_regs self._no_input_regs = no_input_regs self._start_addr_hold_regs = start_addr_hold_regs self._no_hold_regs = no_hold_regs self._logger = logging.getLogger("modbus_tk") # data models self.coils_data_model = ModSlaveMBDataModel(start_addr_coils, no_coils, 0) self.coils_data_model.update_data.connect(self.set_coils_data) self.dis_inputs_data_model = ModSlaveMBDataModel(start_addr_dis_inputs, no_dis_inputs, 0) self.dis_inputs_data_model.update_data.connect(self.set_dis_inputs_data) self.input_regs_data_model = ModSlaveMBDataModel(start_addr_input_regs, no_input_regs, 0) self.input_regs_data_model.update_data.connect(self.set_input_regs_data) self.hold_regs_data_model = ModSlaveMBDataModel(start_addr_hold_regs, no_hold_regs, 0) self.hold_regs_data_model.update_data.connect(self.set_hold_regs_data) #install hooks install_hook(SERVER_HOOKS[1], self._update) try: #add slave self.slave= modSvr.add_slave(slaveAddress) #add blocks self.slave.add_block('0', cst.COILS , start_addr_coils, no_coils) self.slave.add_block('1', cst.DISCRETE_INPUTS, start_addr_dis_inputs, no_dis_inputs) self.slave.add_block('3', cst.ANALOG_INPUTS , start_addr_input_regs, no_input_regs) self.slave.add_block('4', cst.HOLDING_REGISTERS, start_addr_hold_regs, no_hold_regs) #create timer -> repeat timer self._sim_timer=rt.RepeatTimer(timeIntervalSim,self._blockValues,0) except Exception as err: self._logger.error("Slave Init Error : {0}".format(err)) #update data self._blockValues()
def testExpectedLengthTooShort(self): """check that an error is raised if expected_length is too low""" self.slave1.set_values("hr0-100", 0, range(100)) ok = True def check_length_hook(args): (master, response) = args LOGGER.debug("expected: %d - actual: %d", check_length_hook.expected_length, len(response)) check_length_hook.test.assertEqual(check_length_hook.expected_length, len(response)) check_length_hook.test = self hooks.install_hook("modbus_rtu.RtuMaster.after_recv", check_length_hook) for x in (5, 204): try: check_length_hook.expected_length = x self.master.execute(1, modbus_tk.defines.READ_HOLDING_REGISTERS, 0, 100, expected_length=x) except: pass else: ok = False hooks.uninstall_hook("modbus_rtu.RtuMaster.after_recv", check_length_hook) self.assert_(ok)
def main(): """main""" logger = modbus_tk.utils.create_logger("console") try: def on_before_connect(args): master = args[0] print("on_before_connect", master._host, master._port) hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect) def on_after_recv(args): response = args[1] print("on_after_recv", len(response), "bytes received") hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv) # Connect to the slave master = modbus_tcp.TcpMaster() master.set_timeout(5.0) logger.info("connected") logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3)) #send some queries #logger.info(master.execute(1, cst.READ_COILS, 0, 10)) #logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8)) #logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3)) #logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12)) #logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1)) #logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54)) #logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1])) #logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12))) except modbus_tk.modbus.ModbusError as exc: logger.error("%s- Code=%d", exc, exc.get_exception_code())
def main(): """main""" logger = modbus_tk.utils.create_logger("console", level=logging.DEBUG) def on_after_recv(data): logger.info(data) master, bytes_data = data # logger.info(bytes_data) # logger.info(master) hooks.install_hook('modbus.Master.after_recv', on_after_recv) try: def on_before_connect(args): master = args[0] logger.info(args[0]) logger.debug("on_before_connect {0} {1}".format( master._host, master._port)) hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect) def on_after_recv(args): response = args[1] logger.debug("on_after_recv {0} bytes received".format( len(response))) hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv) # Connect to the slave master = modbus_tcp.TcpMaster() master.set_timeout(5.0) logger.info("connected") logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 100)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='f')) # Read and write floats # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[3.14], data_format='>f') # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f')) # send some queries # logger.info(master.execute(1, cst.READ_COILS, 0, 10)) # logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8)) # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12)) # logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1)) # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54)) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1])) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12))) except modbus_tk.modbus.ModbusError as exc: logger.error("%s- Code=%d", exc, exc.get_exception_code())
def main(): """main""" logger = modbus_tk.utils.create_logger("console", level=logging.DEBUG) def on_after_recv(data): master, bytes_data = data logger.info(bytes_data) hooks.install_hook('modbus.Master.after_recv', on_after_recv) try: def on_before_connect(args): master = args[0] logger.debug("on_before_connect {0} {1}".format(master._host, master._port)) hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect) def on_after_recv(args): response = args[1] logger.debug("on_after_recv {0} bytes received".format(len(response))) hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv) # Connect to the slave master = modbus_tcp.TcpMaster() master.set_timeout(5.0) logger.info("connected") logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='f')) # Read and write floats # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[3.14], data_format='>f') # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f')) # send some queries # logger.info(master.execute(1, cst.READ_COILS, 0, 10)) # logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8)) # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12)) # logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1)) # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54)) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1])) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12))) except modbus_tk.modbus.ModbusError as exc: logger.error("%s- Code=%d", exc, exc.get_exception_code())
def main(): """main""" logger = modbus_tk.utils.create_logger("console") def on_after_recv(data): master, bytes_data = data print(bytes_data) hooks.install_hook('modbus.Master.after_recv', on_after_recv) try: def on_before_connect(args): master = args[0] print("on_before_connect", master._host, master._port) hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect) def on_after_recv(args): response = args[1] print("on_after_recv", len(response), "bytes received") hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv) # Connect to the slave master = modbus_tcp.TcpMaster() master.set_timeout(5.0) logger.info("connected") logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 3)) # send some queries # logger.info(master.execute(1, cst.READ_COILS, 0, 10)) # logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8)) # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 100, 3)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12)) # logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1)) # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54)) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1])) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12))) except modbus_tk.modbus.ModbusError as exc: logger.error("%s- Code=%d", exc, exc.get_exception_code())
def install_hook(cls, hook_name, method): """Helper method for installing hooks. This is necessary to ensure child methods are called if implemented.""" install_hook(hook_name, getattr(cls, method))
def main(): """main""" logger = modbus_tk.utils.create_logger("console", level=logging.DEBUG) def on_after_recv(data): master, bytes_data = data logger.info(bytes_data) hooks.install_hook('modbus.Master.after_recv', on_after_recv) try: def on_before_connect(args): master = args[0] logger.debug("on_before_connect {0} {1}".format( master._host, master._port)) hooks.install_hook("modbus_tcp.TcpMaster.before_connect", on_before_connect) def on_after_recv(args): response = args[1] logger.debug("on_after_recv {0} bytes received".format( len(response))) hooks.install_hook("modbus_tcp.TcpMaster.after_recv", on_after_recv) # Connect to the slave master = modbus_tcp.TcpMaster(host='10.0.0.1', port=502) master.set_timeout(5.0) logger.info("connected") # master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 10) # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=4096, output_value=arrayManualModePower[0], data_format='>f') # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=4098, output_value=arrayManualModePower[1], data_format='>f') # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=4100, output_value=arrayManualModePower[2], data_format='>f') # master.execute(1, cst.WRITE_SINGLE_REGISTER, 4096, output_value=arrayManualModePower[0]) # master.execute(1, cst.WRITE_SINGLE_REGISTER, 4097, output_value=arrayManualModePower[1]) # master.execute(1, cst.WRITE_SINGLE_REGISTER, 4098, output_value=arrayManualModePower[2]) master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=arrayManualMode) print(arrayManualMode) print(arrayManualModePower) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2)) ## # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='f')) # Read and write floats # master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[3.14], data_format='>f') # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 2, data_format='>f')) # send some queries # logger.info(master.execute(1, cst.READ_COILS, 0, 10)) # logger.info(master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 8)) # self, slave, function_code, starting_address, quantity_of_x = 0, output_value = 0, data_format = "", expected_length = -1, write_starting_address_FC23 = 0): # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 16, 1)) # logger.info(master.execute(1, cst.READ_INPUT_REGISTERS, 4097, 1)) # logger.info(master.execute(1, cst.READ_HOLDING_REGISTERS, 100, 12)) # logger.info(master.execute(1, cst.WRITE_SINGLE_COIL, 7, output_value=1)) # logger.info(master.execute(1, cst.WRITE_SINGLE_REGISTER, 100, output_value=54)) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_COILS, 0, output_value=[1, 1, 0, 1, 1, 0, 1, 1])) # logger.info(master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 100, output_value=xrange(12))) except modbus_tk.modbus.ModbusError as exc: logger.error("%s- Code=%d", exc, exc.get_exception_code())
def _do_install_hook(self, args): """install a function as a hook""" hook_name = args[1] fct_name = args[2] hooks.install_hook(hook_name, self._hooks_fct[fct_name])
data_collector = SystemDataCollector(5) #create the thread in charge of calling the data collector system_monitor = WorkerThread(data_collector.collect) #create the modbus TCP simulator and one slave #and one block of analog inputs simu = Simulator(TcpServer()) slave = simu.server.add_slave(1) slave.add_block("Temp", ANALOG_INPUTS, 0, 10) slave.add_block("switch", modbus_tk.defines.COILS, 100, 10) switch_block = slave._get_block("switch") print "switch block" print switch_block install_hook('modbus.ModbusBlock.setitem', setblock_hook) # modbus.Slave.handle_read_coils_request # modbus.Slave.handle_read_discrete_inputs_request # modbus.Slave.handle_read_holding_registers_request # modbus.Slave.handle_read_input_registers_request try: LOGGER.info("'quit' for closing the server") #start the data collect system_monitor.start() #start the simulator! will block until quit command is received simu.start() except Exception, excpt: