def jobModbusTCP(): global master if hendl: timeNow.delete('1.0', END) timeNow.insert(1.0, time.strftime('%d-%m-%Y %H:%M:%S')) try: jobCi() except: print 'jobModbusTCP CI No connection' master = modbus_tcp.TcpMaster(host=slaveIP, port=int(slavePort)) master.set_timeout(5.0) try: jobDi() except: print 'jobModbusTCP DI No connection' master = modbus_tcp.TcpMaster(host=slaveIP, port=int(slavePort)) master.set_timeout(5.0) try: jobAi() except Exception, e: print 'jobModbusTCP AI No connection', e master = modbus_tcp.TcpMaster(host=slaveIP, port=int(slavePort)) master.set_timeout(5.0) root.update()
def testGarbageData(self): """Send Garbage data and make sure that it doesn't kill everything""" slave1 = self.server.add_slave(1) slave1.add_block("c0-100", modbus_tk.defines.COILS, 0, 100) self.server.set_verbose(True) self.server.start() time.sleep(1.0) master1 = modbus_tcp.TcpMaster() master2 = modbus_tcp.TcpMaster() master1.open() master2.open() master1._send("hello world!") result = master2.execute(1, modbus_tk.defines.WRITE_SINGLE_COIL, 0, output_value=1) self.assertEqual((0, int("ff00", 16)), result) values = slave1.get_values("c0-100", 0, 1) self.assertEqual((1, ), values) master1.close() master2.close()
def __init__(self, protocol, address, id, db): if protocol == "tcp": try: (host, port) = address.split(":") self.modbus = modbus_tcp.TcpMaster(str(host), int(port)) except: self.modbus = modbus_tcp.TcpMaster(address) self.modbus.set_timeout(5.0) elif protocol == "rtu": if SERIAL: args = unicode(address).split(',') kwargs = {} for a in args: key, val = a.split(':') if key == 'port': try: serial_port = int(val) except: serial_port = val else: kwargs[key] = val try: try: s = SERIAL_PORTS[serial_port] except IndexError: SERIAL_PORTS[serial_port] = s = serial.Serial( port=serial_port, **kwargs) self.modbus = modbus_rtu.RtuMaster(s) except Exception, msg: raise Exception("Protocol {0} error! {1}".format( protocol, msg)) else: raise Exception("Protocol {0} is disabled!".format(protocol))
def device_0(f=1): devHost = '127.0.0.1' devPort = int('502') master=modbus_tcp.TcpMaster(host=devHost, port=devPort) master.set_timeout(1) while True: try: time.sleep(1) gc.collect() READ_COILS(master,1,0,'CI0') time.sleep(0.1) READ_DISCRETE_INPUTS(master,1,0,'DI0') time.sleep(0.1) WRITE_SINGLE_COIL(master,1,0,'TU0') time.sleep(0.1) READ_HOLDING_REGISTERS(master,1,0,1,0.1,'HR0','uInt') time.sleep(0.1) except Exception as e: print('TCP Error ', devHost,e) try: print('Try tcp connect ') master=modbus_tcp.TcpMaster(host=devHost, port=devPort) master.set_timeout(1) except Exception as e: print('Try tcp connect error',e) pass pass
def checkSingleDevice(deviceid, deviceinfo): # global count global ps_conf_dict count = 0 threadId = deviceid global stop_flag_file localLogger.info("current device is [" + deviceid + ']:' + str(deviceinfo)) MASTER = modbus_tcp.TcpMaster(host="127.0.0.1", port=12600) # localLogger.info("current device is [" + deviceId + '][m_t_ip]:' + str(type(deviceInfo["m_t_ip"])) ) # localLogger.info("current device is [" + deviceId + '][m_t_port]:' + str(type(deviceInfo["m_t_port"]))) MASTER = modbus_tcp.TcpMaster(host=deviceinfo["m_t_ip"], port=deviceinfo["m_t_port"]) MASTER.set_timeout(5.0) # while not os.path.exists(stop_flag_file): # cursor = pymysql.connect(host=ps_conf_dict["mysql"]["host"], user=ps_conf_dict["mysql"]["user"], # password=ps_conf_dict["mysql"]["password"], db=ps_conf_dict["mysql"]["db"], # port=ps_conf_dict["mysql"]["port"]).cursor(cursor=pymysql.cursors.DictCursor) conn = pymysql.connect(host=ps_conf_dict["mysql"]["host"], user=ps_conf_dict["mysql"]["user"], password=ps_conf_dict["mysql"]["password"], db=ps_conf_dict["mysql"]["db"], port=ps_conf_dict["mysql"]["port"]) cursor = conn.cursor() while True: if os.path.exists(stop_flag_file): break localLogger.info(count) # localLogger.info() localLogger.info("current device is [" + deviceid + ']:' + str(count)) localLogger.info("current device is [" + deviceid + '][m_t_address]:' + str(deviceinfo["m_t_address"])) localLogger.info("current device is [" + deviceid + '][m_t_lenght]:' + str(deviceinfo["m_t_lenght"])) count = count + 1 # value=MASTER.execute(1, cst.READ_HOLDING_REGISTERS, 0, 1) LOGGER.info( MASTER.execute(1, cst.READ_HOLDING_REGISTERS, deviceinfo["m_t_address"], deviceinfo["m_t_lenght"])) current_value = MASTER.execute(1, cst.READ_HOLDING_REGISTERS, deviceinfo["m_t_address"], deviceinfo["m_t_lenght"])[0] rtn = cursor.execute( "insert into e_data(s_id, input_time, value) VALUES(%s, %s, %s)", (deviceid, time.gmtime(time.time()), int(current_value))) conn.commit() #print(rtn) # LOGGER.info(MASTER.execute(1, cst.READ_HOLDING_REGISTERS, 4, 14)) time.sleep(ps_conf_dict["common"]["checkInterval"])
def main(): master = modbus_tcp.TcpMaster(host='192.168.0.202', port=502) master.set_timeout(5.0) master.set_verbose(True) #r = master.execute(1, cst.READ_COIL_REGISTERS, 0, 10) r = master.execute(1, 3, 0, 10) print(r)
def test_write_read_coils(self): """ Objective: Test if we can change values using the modbus protocol. """ master = modbus_tcp.TcpMaster( host="127.0.0.1", port=self.modbus_server.server_port ) master.set_timeout(1.0) set_bits = [1, 0, 0, 1, 0, 0, 1, 1] # write 8 bits master.execute( slave=self.target_slave_id, function_code=cst.WRITE_MULTIPLE_COILS, starting_address=1, output_value=set_bits, ) # read 8 bit actual_bit = master.execute( slave=self.target_slave_id, function_code=cst.READ_COILS, starting_address=1, quantity_of_x=8, ) self.assertSequenceEqual(set_bits, actual_bit)
def test_read_coils(self): """ Objective: Test if we can extract the expected bits from a slave using the modbus protocol. """ self.databus.set_value( "memoryModbusSlave%dBlockA" % self.target_slave_id, [1 for b in range(0, 128)], ) # create READ_COILS request master = modbus_tcp.TcpMaster( host="127.0.0.1", port=self.modbus_server.server_port ) master.set_timeout(1.0) actual_bits = master.execute( slave=self.target_slave_id, function_code=cst.READ_COILS, starting_address=1, quantity_of_x=128, ) # the test template sets all bits to 1 in the range 1-128 expected_bits = [1 for b in range(0, 128)] self.assertSequenceEqual(actual_bits, expected_bits)
def test_modbus_logging(self): """ Objective: Test if modbus generates logging messages as expected. Expected output is a dictionary with the following structure: {'timestamp': datetime.datetime(2013, 4, 23, 18, 47, 38, 532960), 'remote': ('127.0.0.1', 60991), 'data_type': 'modbus', 'session_id': '01bd90d6-76f4-43cb-874f-5c8f254367f5', 'data': {0: {'function_code': 1, 'slave_id': 1, 'request': '0100010080', 'response': '0110ffffffffffffffffffffffffffffffff'}}} """ master = modbus_tcp.TcpMaster(host='127.0.0.1', port=self.modbus_server.server_port) master.set_timeout(1.0) #issue request to modbus server master.execute(slave=1, function_code=cst.READ_COILS, starting_address=1, quantity_of_x=128) #extract the generated logentry log_item = self.log_queue.get(True, 2) #self.assertIn('timestamp', log_item) self.assertIsInstance(log_item['timestamp'], datetime) #we expect session_id to be 36 characters long (32 x char, 4 x dashes) self.assertTrue(len(log_item['session_id']), log_item) self.assertEqual('127.0.0.1', log_item['remote'][0]) self.assertEquals('modbus', log_item['data_type']) #testing the actual modbus data self.assertEquals('0100010080', log_item['data'][0]['request']) self.assertEquals('0110ffffffffffffffffffffffffffffffff', log_item['data'][0]['response'])
def __init__(self): super(MainWin, self).__init__() self.setupUi(self) self.ip_line.setText("192.168.1.5") self.ip_key.clicked.connect(self.ip_connect) self.path1 = 'C:/Caron Engineering/up_picture' self.path2 = 'C:/Caron Engineering/down_picture' self.photoPath = "C:/Caron Engineering/momotest.jpg" self.cap = cv2.VideoCapture() self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 5000) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 5000) self.h = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) self.w = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) self.cap.read() self.HmiWin = HmiWin() self.HmiWin.len_choose_key.clicked.connect(self.len_choose_met) self.HmiWin.hz_choose_key.clicked.connect(self.hz_choose_met) self.HmiWin.auto_key.clicked.connect(self.auto_start_met) self.HmiWin.hold_key.clicked.connect(self.auto_hold_met) self.HmiWin.run_key.clicked.connect(self.run_met) self.HmiWin.next_key.clicked.connect(self.next_met) self.HmiWin.rst_key.clicked.connect(self.rst_met) self.HmiWin.zrn_key.clicked.connect(self.zrn_met) self.HmiWin.signal.connect(self.hmi_close_thread) # 槽函数的使用 self.showPhoto = QPixmap(self.photoPath) self.HmiWin.D_key1.clicked.connect(self.diameter_met1) self.HmiWin.D_key2.clicked.connect(self.diameter_met2) self.HmiWin.H_key1.clicked.connect(self.height_met1) self.HmiWin.H_key2.clicked.connect(self.height_met2) self.HmiWin.ok_key.clicked.connect(self.ok_met) self.diameter1 = 2.98 self.diameter2 = 2.98 self.height1 = 10.0 self.height2 = 10.0 self.T1 = GetPlcDateTread(self) self.T2 = GetCmmDateTread(self) self.T3 = ZrnWaitTread(self) self.T4 = MiscolorTread(self) self.T5 = AutoCompareTread(self) self.master = modbus_tcp.TcpMaster(host=self.ip_line.text(), port=502) self.statusTcp = False self.len_choose_flag = False self.length_int = 0 self.hz_choose_flag = False self.hz_int = 0 self.auto_start_flag = False self.baseValue = 0 self.status = 0 self.HOST = 'localhost' # 主机地址 self.PORT = 1088 # 端口号 self.ADDR = (self.HOST, self.PORT) # 链接地址 self.BUFSIZ = 2048 # 缓存区大小,单位是字节,这里设定了2K的缓冲区 self.PLC_MAX_VER = 1 self.PLC_REQ_MAGIC = 0xC0FEED0C self.PLC_RESP_MAGIC = 0xC0FEED0D self.tcpCliSock = socket(AF_INET, SOCK_STREAM) # 创建一个TCP套接字
def __init__(self, host, port=502, timeout_in_sec=5.0): self.host = host self.port = port self.timeout_in_sec = timeout_in_sec self.client = modbus_tcp.TcpMaster(host, port, timeout_in_sec) self.client.open() logging.info(str(self))
def run(self, *arg, **kwarg): ''' :param apply_interface: 采集驱动任务(Modbus TCP) 建立连接的条件 :param apply_template: 采集驱动任务(Modbus TCP) 设备模板 :return: while 循环 break 条件驱动状态 缓存在redis ''' # print("arg:", arg) # print("kwarg:", kwarg) apply_interface = kwarg["apply_interface"] apply_template = kwarg["apply_template"] self.key = apply_interface["apply_tcp_device"] self.cls = get_subdevicedata_model(self.key) print("start modbus tcp drive ", self.key) try: master = modbus_tcp.TcpMaster( host=apply_interface["apply_tcp_ip"], port=int(apply_interface["apply_tcp_port"]), timeout_in_sec=float(apply_interface["apply_tcp_timeout"])) var_list = self.init_val(apply_template, int(apply_interface["apply_tcp_slave"])) self.loop_start(var_list, master, float(apply_interface["apply_tcp_cycle"])) print("end modbus tcp drive ", self.key) except Exception as e: print(e) finally: if 'master' in locals().keys(): master.close() self.conn.hset(self.key, "drive_enable", 0)
def testSeveralClients(self): """check that the server can serve 15 clients in parallel""" masters = [modbus_tcp.TcpMaster(timeout_in_sec=5.0)] * 15 slave = self.server.add_slave(1) q = Queue.Queue() slave.add_block("a", modbus_tk.defines.HOLDING_REGISTERS, 0, 100) slave.set_values("a", 0, range(100)) self.server.start() time.sleep(1.0) def read_vals(master): try: for i in xrange(100): result = master.execute( 1, modbus_tk.defines.READ_HOLDING_REGISTERS, 0, 100) if result != tuple(range(100)): q.put(1) time.sleep(0.1) except Exception, msg: LOGGER.error(msg) q.put(1)
def read_power_meter(): #mb_port = serial.Serial(port=mbComPort, baudrate=baudrate, bytesize=databit, parity=parity, stopbits=stopbit) master = modbus_tcp.TcpMaster('192.168.43.181', 502) #modbus_rtu.RtuMaster(mb_port) master.set_timeout(mbTimeout / 1000.0) mbId = 4 #[0x1000-0x1001]=VIn_a addr = 0x1000 #4096 v_a = None try: # FC3 rr = master.execute(mbId, cst.READ_INPUT_REGISTERS, addr, 4) print('read value:', rr) # convert to float: # IEEE754 ==> (Hi word Hi Bite, Hi word Lo Byte, Lo word Hi Byte, Lo word Lo Byte) try: v_a_hi = rr[1] v_a_lo = rr[0] v_a = unpack('>f', pack('>HH', v_a_hi, v_a_lo)) print('v_a=', v_a) except Exception as e: #Exception, e: print(e) except Exception as e: #Exception, e: print("modbus test Error: " + str(e)) master._do_close() if v_a == None: v_a = None else: v_a = v_a[0] return v_a
def control_light(status): gate_adr = '192.168.0.201' gate_adr = '192.168.0.200' gate_adr = '101.86.93.63' gate_port = 502 count = 0 sleep_time = 0.1 control_adr = 16 control_channel = 0 control_channel = 1 #Connect to the slave #master = modbus_tcp.TcpMaster(host='192.168.0.7', port=502) master = modbus_tcp.TcpMaster(host= gate_adr, port = gate_port) master.set_timeout(5.0) #this is the api to control the relay #control_channel, there are totally two relays, 0 and 1 #the last parameter is the status of the relay, 0 means open, 1 means close if status=='close': master.execute(control_adr, cst.WRITE_SINGLE_COIL, control_channel, 1, 1) #close channel 1 else: master.execute(control_adr, cst.WRITE_SINGLE_COIL, control_channel, 1, 0) #open channel 1 control_status = master.execute(control_adr, cst.READ_COILS, control_channel, 1 ) time.sleep(sleep_time) return control_status[0]
def __init__(self, name, device_cfg, control_cfg): self.name = name self.EL = EventLogger(name) self.EL.info("STARTING") with open(control_cfg, 'r') as control_cfg: self.control_cfg = yaml.safe_load(control_cfg) with open(device_cfg, 'r') as device_cfg: self.device_cfg = yaml.safe_load(device_cfg) # Load config file to interact with Modbus device self.mode = "GridConnect" # self.control = MicrogridControl.MicrogridControl(logger=self.logger, # dvc=self.dvc, # ctrl_cfg=self.control_cfg, # mode=self.mode) self.modbus_devices = list(self.device_cfg.keys()) self.dvc = self.device_cfg[self.modbus_devices[0]] self.slave = self.dvc['Slave'] addr = self.dvc['Address'] port = self.dvc['Port'] self.debugMode = self.dvc["debugMode"] if self.debugMode: print(f"addr: {addr}\n" f"port: {port}") self.master = modbus_tcp.TcpMaster(addr, port)
def get_data(ip_address, port, slave_id, device_name, measurement_suffix): """Instrument function for pyranometers from Inavitas system. Args: * ip_address (str) : ip address of the TCP device * port (int) : port * slave_id (int) : modbus slave id of the device * device_name (string) : name of device to include in json Modbus Addresses of the device are as follows: == READ 1 == 6 Irradiation 1 uint16 1 """ #Start timer to test for execution time start_time = time.time() #Prepare the modbus stack masterTCP = modbus_tcp.TcpMaster(host=ip_address,port=port) masterTCP.set_timeout(MODBUS_TIMEOUT) masterTCP.set_verbose(True) #Set logging log.debug('Module: %s - Driver: %s - Reading device %s:%s', DRIVER_NAME, device_name, ip_address,port) #Create an ordered list to store the values values = OrderedDict() #Append devicename and timestamp for InfluxDB values['Device_Name'] = device_name values['Measurement_Suffix'] = measurement_suffix values['Date'] = get_timestamp_for_influxdb() # Read first part x = 0 while x < TRY_AMOUNT: try: read1 = masterTCP.execute(slave_id, cst.READ_HOLDING_REGISTERS, 6, 1) log.debug('Module: %s - Read 1 Successful : %s - %s:%s - TRIES:%s', DRIVER_NAME, device_name, ip_address, port, x) x = TRY_AMOUNT except Exception as e: log.error('Module: %s - Read 1 Error : %s - %s:%s - TRIES:%s', DRIVER_NAME, device_name, ip_address, port, x) x += 1 time.sleep(3) if not "read1" in locals(): log.error('Modbus Scan Failed (Read1) : %.4f (DRIVER: %s - DEVICE: %s - UNIT: %s:%s)',(time.time() - start_time),DRIVER_NAME, device_name, ip_address, port) return False #Parse the data for read 1 values['Irradiation'] = float(signed(read1[0])) / 1 #Dont send a negative irradiation if values['Irradiation'] < 0: values['Irradiation'] = float(0.0) log.debug('Modbus Scan Completed in : %.4f (DRIVER: %s - DEVICE: %s - UNIT: %s:%s)',(time.time() - start_time),DRIVER_NAME, device_name, ip_address, port) return values
def rw_device(self, rw="r", var_value=None): value = {} m = modbus_tcp.TcpMaster(self.commif) m.set_timeout(1) if rw == "r": try: # 缺省参数的时候 if not var_value or\ 'StartingAddress' not in var_value\ or 'Quantity' not in var_value: var_value = {'StartingAddress': 0, 'Quantity': 10} md = m.execute(int(self.addr), cst.READ_HOLDING_REGISTERS, var_value['StartingAddress'], var_value['Quantity']) value.update({'modbus_value': md}) self._debug(r'the device value is %r' % value) except Exception as e: self._debug(e) value.update({'error': str(e)}) else: try: md = m.execute(int(self.addr), cst.WRITE_MULTIPLE_REGISTERS, var_value['StartingAddress'], var_value['Quantity'], var_value['value']) value.update({'write_result': md}) self._debug(r'write device result is %r' % value) except Exception as e: self._debug(e) value.update({'error': e}) return value
def main(): master = modbus_tcp.TcpMaster(host='192.168.0.202', port=502) master.set_timeout(5.0) master.set_verbose(True) print('connected') r = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 10) print(r)
def testConnectionErrorNoTimeoutDefined(self): """Check that an error is raised on connection error""" master = modbus_tcp.TcpMaster() try: master.open() except socket.error, message: return
def testSeveralClients(self): """check that the server can serve 15 clients in parallel""" masters = [modbus_tcp.TcpMaster(timeout_in_sec=5.0)] * 15 slave = self.server.add_slave(1) q = Queue.Queue() slave.add_block("a", modbus_tk.defines.HOLDING_REGISTERS, 0, 100) slave.set_values("a", 0, range(100)) self.server.start() time.sleep(1.0) def read_vals(master): try: for i in range(100): result = master.execute(1, modbus_tk.defines.READ_HOLDING_REGISTERS, 0, 100) if result != tuple(range(100)): q.put(1) time.sleep(0.1) except Exception as msg: LOGGER.error(msg) q.put(1) threads = [] for m in masters: threads.append(threading.Thread(target=read_vals, args=(m, ))) for t in threads: t.start() LOGGER.debug("all threads have been started") for t in threads: t.join() LOGGER.debug("all threads have done") self.assert_(q.empty())
def __init__(self, host, port=502): import modbus_tk.modbus_tcp as modbus_tcp self._unit = 1 self._master = modbus_tcp.TcpMaster(host, port) super(PACx200, self).__init__()
def test_modbus_logging(self): """ Objective: Test if modbus generates log messages as expected. Expected output is a dictionary with the following structure: {'timestamp': datetime.datetime(2013, 4, 23, 18, 47, 38, 532960), 'remote': ('127.0.0.1', 60991), 'data_type': 'modbus', 'id': '01bd90d6-76f4-43cb-874f-5c8f254367f5', 'data': {'function_code': 1, 'slave_id': 1, 'request': '0100010080', 'response': '0110ffffffffffffffffffffffffffffffff'}} """ self.databus.set_value( "memoryModbusSlave%dBlockA" % self.target_slave_id, [1 for b in range(0, 128)], ) master = modbus_tcp.TcpMaster( host="127.0.0.1", port=self.modbus_server.server_port ) master.set_timeout(1.0) # issue request to modbus server master.execute( slave=self.target_slave_id, function_code=cst.READ_COILS, starting_address=1, quantity_of_x=128, ) # extract the generated log entries log_queue = conpot_core.get_sessionManager().log_queue conn_log_item = log_queue.get(True, 2) conn_expected_payload = {"type": "NEW_CONNECTION"} self.assertDictEqual(conn_expected_payload, conn_log_item["data"]) modbus_log_item = log_queue.get(True, 2) self.assertIsInstance(modbus_log_item["timestamp"], datetime) self.assertTrue("data" in modbus_log_item) # we expect session_id to be 36 characters long (32 x char, 4 x dashes) self.assertTrue(len(str(modbus_log_item["id"])), modbus_log_item) self.assertEqual("127.0.0.1", modbus_log_item["remote"][0]) self.assertEqual("modbus", modbus_log_item["data_type"]) req = ( "000100000006%s0100010080" % ("01" if self.target_slave_id == 1 else "ff") ).encode() # testing the actual modbus data modbus_expected_payload = { "function_code": 1, "slave_id": self.target_slave_id, "request": req, "response": b"0110ffffffffffffffffffffffffffffffff", } self.assertDictEqual(modbus_expected_payload, modbus_log_item["data"])
def write_Signle_Query(self,UID,function_Code,start_Address,write_Value): try: ## Connects to the slave master = modbus_tcp.TcpMaster(host=self.target_Address,port=self.target_port) response=master.execute(UID,function_Code,start_Address,output_value=write_Value) except modbus_tk.modbus.ModbusError as exc: print "%s- Code=%d"%(exc, exc.get_exception_code()) return response
def Modbus_Client_Open(self , port): print("----- Modbus_Client_Open() -----") print("Connect to Modbus TCP IP : %s" %(str(self.modbus_server_ip))) print("Connect to Modbus TCP Port : %s" %(str(port))) # SOCK_STREAM : TCP/IP self.socketClient = modbus_tcp.TcpMaster(host=str(self.modbus_server_ip),port=int(port)) self.socketClient.set_timeout(5.0)
def read_Query(self,UID,function_Code,start_Address,number_Registers): try: ## Connects to the slave master = modbus_tcp.TcpMaster(host=self.target_Address,port=self.target_port) ## Executes the command response=master.execute(UID,function_Code,start_Address,number_Registers) except modbus_tk.modbus.ModbusError as exc: print "%s- Code=%d"%(exc, exc.get_exception_code()) return response
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 connect(self, ip="localhost", port=502, timeout_in_sec=5.0): logger = modbus_tk.utils.create_logger("console") # Connect to the slave master = modbus_tcp.TcpMaster(host=ip, port=port, timeout_in_sec=timeout_in_sec) master.set_verbose(True) self.master = master logger.info("connected") return True
def main(): master = modbus_tcp.TcpMaster(host='192.168.0.211', port=502) master.set_timeout(5.0) master.set_verbose(True) print('=> ', master) li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] r = master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=li)
def __init__(self, host, port=502): self.host = host self.port = port self.timeout = 1.0 try: self.master = modbus_tcp.TcpMaster(host=self.host, port=self.port) self.master.set_timeout(self.timeout) except Exception as e: print("Exception in PET7015 class constructor\n{}".format(e)) exit(-1)