def testBasicSyncSerialClient(self, mock_serial): ''' Test the basic methods for the serial sync client''' # receive/send mock_serial.in_waiting = 0 mock_serial.write = lambda x: len(x) mock_serial.read = lambda size: b'\x00' * size client = ModbusSerialClient() client.socket = mock_serial client.state = 0 self.assertEqual(0, client._send(None)) client.state = 0 self.assertEqual(1, client._send(b'\x00')) self.assertEqual(b'\x00', client._recv(1)) # connect/disconnect self.assertTrue(client.connect()) client.close() # already closed socket client.socket = False client.close() self.assertEqual('ModbusSerialClient(ascii baud[19200])', str(client))
def get_data(): # choose the serial client client = ModbusClient(method='rtu', port=args.tty, baudrate=9600, timeout=args.timeout) client.connect() log.debug(client) # read the registers # for information about modbus registers see doc TSMPPT.APP.Modbus.EN.10.2.pdf rr = client.read_holding_registers(0,count=60,unit=1) if rr == None: client.close() log.error("couldn't connect") exit(1) # scaling v_scale = rr.registers[0] + rr.registers[1]/(2**16) i_scale = rr.registers[2] + rr.registers[3]/(2**16) # the stuff we want (the numbers are decimal but the registers are listed in hex) data={} data["batt-voltage" ] = ( rr.registers[24] * float(v_scale )) / (2**15) # 0x18 data["array-voltage" ] = ( rr.registers[27] * float(v_scale )) / (2**15) # 0x1b data["batt-current" ] = ( rr.registers[28] * float(i_scale )) / (2**15) # 0x1c data["array-current" ] = ( rr.registers[29] * float(i_scale )) / (2**15) # 0x1d data["batt-temp" ] = rr.registers[37] # 0x25 data["power-out" ] = ( rr.registers[58] * float(v_scale)*float(i_scale)) / (2**17) # 0x3a data["power-in" ] = ( rr.registers[59] * float(v_scale)*float(i_scale)) / (2**17) # 0x3b # close the client client.close() # debug log.info("got data from mppt via modbus") log.debug(datetime.datetime.now()) for key in keys: log.debug("%-15s : %.2f" % (key, data[key])) return data
def main(): if len(sys.argv) != 4: print( """Usage: ./orno_modbus.py serial_port device_address target_device_address Example: ./orno_modbus.py /dev/ttyUSB0 1 11 If you have only one device you can set the device_address to 0 to change its address. """) sys.exit(0) port = sys.argv[1] address = int(sys.argv[2]) target_address = int(sys.argv[3]) client = ModbusClient(method="rtu", port=port, baudrate=9600) client.connect() request = SendOrnoPassword('00000000', unit=address) client.execute(request) response = client.write_registers(15, [target_address], unit=address) if response: if address: print "Success. Changed address from %d to %d." % (address, target_address) else: print "Success. Changed address to %d." % (target_address) else: print "Address change failed" client.close()
def main(): client = ModbusClient(method='rtu', port='/dev/ttyAMA0', baudrate=38400, parity='N', bytesize=8, stopbits=2, timeout=1) # request modbus register values from device client.connect() start = timer() reg_values = {} for addr, size in SDM630_BLOCKS.items(): resp = client.read_input_registers(addr, size * 2, unit=1) block = resp.registers reg_values.update({ (addr + i): block[i] for i in range(0, len(block)) }) request_time = timer() - start client.close() # close the client # convert modbus register values to float start = timer() mod_values = {} for name, r in SDM630_REGISTER.items(): w0 = reg_values[r.address + 0] w1 = reg_values[r.address + 1] mod_values[name] = struct.unpack('>f', struct.pack('>HH', w0, w1))[0] conversion_time = timer() - start # print all values in order of their modbus address for (name, _) in sorted(SDM630_REGISTER.items(), key = lambda x: x[1].address): v = mod_values[name] u = SDM630_REGISTER[name].unit print("{:40}: {:10.2f} {}".format(name, v, "" if u is None else str(u))) print("request took %.3f seconds" % request_time)
class DAQM9004(Instrument.SerialInstrument): DEFAULT_CHECK_RETURN_COMMAND = False DEFAULT_IDN = re.compile('.*') def __init__(self, *args, **kwargs): kwargs['baudrate'] = 9600 # this is fixed if not 'unit' in kwargs: kwargs['unit'] = DEFAULT_UNIT Instrument.SerialInstrument.__init__(self, *args, **kwargs) def connect(self): self.client = ModbusSerialClient('rtu', port=self.port.port, baudrate=self.port.baudrate, timeout=self.port.timeout) self.client.connect() def readADC(self): response = self.client.read_input_registers(0x0000, 8, unit=self.unit) if isinstance(response, ModbusIOException): raise Instrument.CommandTimeoutError return response.registers def readVolt(self, ): return [val / 4095.0 * 5.0 for val in self.readADC()] def readAmp(self): return [val / 4095.0 * 0.02 for val in self.readADC()]
def run(self): global tCtrl _sample=select(tCtrl.samples,'id',self.id) _protocol=select(tCtrl.protocols,'id',_sample.properties['protocol_id']) _transport=select(tCtrl.transports,'id',_sample.properties['transport_id']) _rule=select(tCtrl.rules,'id',_sample.properties['rule_id']) _method=_protocol.properties['method'] _port=_transport.properties['port'] _para=_transport.properties['para'] _timeout=int(_transport.properties['timeout'])/1000.0 client = ModbusClient(method=_method, port=_port,baudrate= \ Baudrate(_para),bytesize=Bytesize(_para),parity=Parity(_para),\ stopbits=Stopbits(_para),timeout=_timeout) _index=int(_rule.properties['index']) _count=int(_rule.properties['count']) _unit_begin=Begin(_rule.properties['range']) _unit_end=End(_rule.properties['range']) client.connect() self.interval = int(_protocol.properties['period']) while not self.thread_stop: for i in range(_unit_begin,_unit_end): start_ = datetime.utcnow() response=client.read_holding_registers(address=_index, \ count=_count,unit=i) tCtrl.samples[self.index].data[i]=response.registers print response.registers #getRegister(1)/10.0 end_ = datetime.utcnow() print '[cost time] %s' %(end_-start_) time.sleep(self.interval)
def pa #---------------------------------------------------------------------------# #---------------------------------------------------------------------------# # configure the client logging #---------------------------------------------------------------------------# import logging logging.basicConfig() log = logging.getLogger() log.setLevel(logging.INFO) for port in ['/dev/ttyxuart3']: client = ModbusClient(method='rtu', port=port, baudrate=9600, timeout=1, retries=1) client.connect() try: for addr in [3,10]: # for addr in xrange(10,15): print ('Meter Modbus Address: %d' % addr) # regs = client.read_holding_registers(768,120,unit=addr); print regs.registers if regs else None # regs = client.read_holding_registers(128,4,unit=addr); print regs.registers if regs else None regs = client.read_holding_registers(142,8,unit=addr); print regs.registers if regs else None for addr in xrange(5,9): print ('Inverter Modbus Address: %d' % addr) regs = client.read_holding_registers(33,10,unit=addr); print regs.registers if regs else None except AttributeError, e: print 'Device not responding' finally:
def ReadMINTAI08(): print("\nReading MINTAI08.........\n") dataString = '' dataStringActual = '' try: client = ModbusClient(method='rtu', port=portID, baudrate=9600, timeout=2, parity='N') print(client.connect()) if (client.connect()): x = client.read_holding_registers(0, 5, unit=1) print(x) MT1 = ((x.getRegister(0) - int(modbus['offset9'])) * int(modbus['scale9'])) MT2 = ((x.getRegister(1) - int(modbus['offset10'])) * int(modbus['scale10'])) MT3 = ((x.getRegister(2) - int(modbus['offset11'])) * int(modbus['scale11'])) MT4 = ((x.getRegister(3) - int(modbus['offset12'])) * int(modbus['scale12'])) MT5 = ((x.getRegister(4) - int(modbus['offset13'])) * int(modbus['scale13'])) dataString = str(MT1) + ',' + str(MT2) + ',' + str( MT3) + ',' + str(MT4) + ',' + str(MT5) dataStringActual = str(MT1 / 10) + ',' + str(MT2 / 10) + ',' + str( MT3 / 10) + ',' + str(MT4 / 10) + ',' + str(MT5 / 10) print("MINTAI08 Data : " + dataString + '\n') return dataString, dataStringActual except Exception as errMOD: print(errMOD) return dataString, dataStringActual
class TH10S_B( Instrument.SerialInstrument ): DEFAULT_CHECK_RETURN_COMMAND = False DEFAULT_IDN = re.compile( '.*' ) def __init__( self, *args, **kwargs ): kwargs['baudrate'] = 9600 # this is fixed if not 'unit' in kwargs: kwargs['unit'] = DEFAULT_UNIT Instrument.SerialInstrument.__init__( self, *args, **kwargs ) def connect( self ): self.client = ModbusSerialClient('rtu', port=self.port.port, baudrate=self.port.baudrate, timeout=self.port.timeout) self.client.connect() def readADC( self, addr ): response = self.client.read_input_registers(addr, 1, unit=self.unit) if isinstance(response, ModbusIOException): raise Instrument.CommandTimeoutError val = response.registers[0] if val == 0x8000: raise Exception('Probe error') return val def readTemperature( self ): val = self.readADC(0) val = Utils.s2i(Utils.I2s(val)) return round(val*0.1, 1) def readHumidity( self, ): return round(self.readADC(1)*0.1, 1)
def testBasicSyncSerialClient(self, mock_serial): ''' Test the basic methods for the serial sync client''' # receive/send mock_serial.in_waiting = 0 mock_serial.write = lambda x: len(x) mock_serial.read = lambda size: b'\x00' * size client = ModbusSerialClient() client.socket = mock_serial client.state = 0 self.assertEqual(0, client._send(None)) client.state = 0 self.assertEqual(1, client._send(b'\x00')) self.assertEqual(b'\x00', client._recv(1)) # connect/disconnect self.assertTrue(client.connect()) client.close() # rtu connect/disconnect rtu_client = ModbusSerialClient(method='rtu', strict=True) self.assertTrue(rtu_client.connect()) self.assertEqual(rtu_client.socket.interCharTimeout, rtu_client.inter_char_timeout) rtu_client.close() # already closed socket client.socket = False client.close() self.assertEqual('ModbusSerialClient(ascii baud[19200])', str(client))
class SerialRtuChannel(BaseChannel): def __init__(self, network, channel_name, channel_protocol, channel_params, channel_manager, channel_type): self.port = channel_params.get("port", "") self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE) self.parity = channel_params.get("parity", serial.PARITY_NONE) self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS) self.baudrate = channel_params.get("baudrate", 9600) self.timeout = channel_params.get("timeout", 2) self.modbus_client = None BaseChannel.__init__(self, network, channel_name, channel_protocol, channel_params, channel_manager, channel_type) def run(self): self.modbus_client = ModbusSerialClient(method='rtu', port=self.port, baudrate=self.baudrate, stopbits=self.stopbits, parity=self.parity, bytesize=self.bytesize, timeout=self.timeout) try: self.modbus_client.connect() logger.debug("连接串口成功.") except Exception, e: logger.error("连接串口失败,错误信息:%r." % e) self.modbus_client = None
def run_sync_client(): clearScreen() print("Enter 1 to take reading, 0 to quit") running = True while running == True: client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=1, baudrate=9600) client.connect() hr = client.read_holding_registers(7, 3, unit=SLAVE) value = input(":") if value == 0: running = False else: temperature = hr.registers[0] / 10.0 humidity = hr.registers[1] / 10.0 dewpoint = hr.registers[2] / 10.0 print("Temperature : " + str(temperature)) print("Humidity : " + str(humidity)) print("Dew Point : " + str(dewpoint)) # ----------------------------------------------------------------------- # # close the client # ----------------------------------------------------------------------- # client.close()
def getLoadCurrent(): client = ModbusClient(method='rtu', port=PORT, baudrate=BAUDRATE) client.connect() result = client.read_input_registers(0x3100, 15, unit=1) data = float(result.registers[13] / 100.0) client.close() return data
def main(): t = 1 # Linux #client = ModbusSerialClient("rtu", port='/dev/ttyS1', baudrate=9600, timeout=t) # Windows client = ModbusSerialClient("rtu", port='COM4', baudrate=9600, timeout=t) client.connect() start = time.time() #data = client.read_input_registers(0x0000, count=10, unit=0x01) data = client.read_holding_registers(0x0002, count=5, unit=0x01) #print dir(data) print(data.function_code) print(data.registers) stop = time.time() if data: succ = "was successful" else: succ = "failed" print("timeout: %ss, read %s, time spent reading: %fs" % (t, succ, stop - start))
def main(): parser = argparse.ArgumentParser( description='Talk to a voegtlin red-y flow controller') parser.add_argument( 'port', help='The serial interface your Modbus device is connected to.') parser.add_argument('--unit', default=247, type=int, help='The slave address of the Modbus device') args = parser.parse_args() logging.basicConfig() log = logging.getLogger() #log.setLevel(logging.DEBUG) client = ModbusClient(method='rtu', port=args.port, stopbits=2, baudrate=9600) try: client.connect() redy = RedY(unit=args.unit, modbus_client=client) redy.read_all() finally: client.close()
def init_rs485_connection(self): client = ModbusClient(method='rtu', port='/dev/ttyS3', rtscts=True, stopbits = 1, bytesize = 8, baudrate = 115200, timeout=0.1, parity = 'N') client.connect() rs485_mode = serial.rs485.RS485Settings(delay_before_tx = 0, delay_before_rx = 0, rts_level_for_tx=True, rts_level_for_rx=False, loopback=False) client.socket.rs485_mode = rs485_mode return client
def main(): signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) logger = logging.getLogger() logger.setLevel("INFO") logger.addHandler(SystemdHandler()) if not Config.read("/usr/local/etc/ff/ff_le03mp_mqtt.ini"): logging.error('No config file found') sys.exit(1) modbus_client = ModbusClient(method="rtu", port=Config['modbus']['port'], timeout=2, stopbits=2, bytesize=8, parity="N", baudrate=9600) modbus_client.connect() registers = load_registers_description() mqtt_client = mqtt_connect(logger) register_services(registers=registers, mqtt_client=mqtt_client) job_register = Job(interval=timedelta(seconds=int(Config['default']['register_period'])), execute=register_services, registers=registers, mqtt_client=mqtt_client) job_register.start() job_update = Job(interval=timedelta(seconds=int(Config['default']['update_period'])), execute=update_registers, mqtt_client=mqtt_client, modbus_client=modbus_client, registers=registers) job_update.start() while True: try: time.sleep(60) except ProgramKilled: logging.info("Program stopped") job_register.stop() job_update.stop() mqtt_client.disconnect() break
class SyncReader(Reader): def __init__(self): super().__init__() def create_client(self): self.client = ModbusClient(**MODBUS_CLIENT_KWARGS) self.client.connect()
def get_modbus_register_data(client, address, count, u): # print "Reading modbus Address: %s" % address #rq = client.read_holding_registers(1000,7,unit=1) #connection = client.connect() #print(connection) tryit = True while tryit: #result = client.read_holding_registers(1002,1,unit=1) #(address=1000,count=1,unit=1) try: result = client.read_holding_registers( address, count, unit=u) #(address=1000,count=1,unit=1) except: # print "Exception" client.close() client = ModbusSerialClient(method="rtu", port="/dev/rfcomm1", baudrate=9600, stopbits=1, bytesize=8, timeout=1) client.connect() time.sleep(1) else: #if result.isError(): try: r = result.registers[0] tryit = False #result.isError() except: tryit = True #print(result.registers) return r #esult.registers[0]
def run_sync_client(): iteration_counter = 0 success_counter = 0 fail_counter = 0 client = ModbusClient(method='rtu', port='/dev/ttyUSB0', timeout=1, baudrate=115200) client.connect() while (iteration_counter < 10000): time.sleep(2) try: log.debug("Write to a holding register and read back") rq = client.write_register(1, 10, unit=UNIT) rr = client.read_holding_registers(1, 1, unit=UNIT) assert (not rq.isError()) # test that we are not an error # assert(rr.registers[0] == 10) # test the expected value log.debug("Write to multiple holding registers and read back") rq = client.write_registers(1, [10] * 8, unit=UNIT) time.sleep(0.5) # 이것을 넣지 않으면 에러가 뿜뿜. --> 마찬가지... rr = client.read_holding_registers(1, 8, unit=UNIT) assert (not rq.isError()) # test that we are not an error # assert(rr.registers == [10]*8) # test the expected value # arguments = { # 'read_address': 1, # 'read_count': 8, # 'write_address': 1, # 'write_registers': [20]*8, # } # log.debug("Read write registeres simulataneously") # rq = client.readwrite_registers(unit=UNIT, **arguments) # rr = client.read_holding_registers(1, 8, unit=UNIT) # assert(not rq.isError()) # test that we are not an error # assert(rq.registers == [20]*8) # test the expected value # assert(rr.registers == [20]*8) # test the expected value except AssertionError: print('ASSERT ERROR') fail_counter += 1 except pymodbus.exceptions.ModbusIOException: print('REGISTER ERROR') fail_counter += 1 else: success_counter += 1 iteration_counter += 1 print('iteration # : ', iteration_counter, ' success : ', success_counter, ' fail : ', fail_counter, ' rate : ', float(success_counter / iteration_counter) * 100, '%') # ----------------------------------------------------------------------- # # close the client # ----------------------------------------------------------------------- # client.close()
def BootInit(portName): client = ModbusClient(method='rtu', port=portName, stopbits=2, timeout=1, baudrate=115200) client.connect() return client
def connect_rtu(my_port=fn_serial_port_list(), my_timeout=1, my_baudrate=9600): """Connect to first available serial port with RTU protocol""" client = ModbusClient(method='rtu', port=my_port, timeout=my_timeout, baudrate=my_baudrate) client.connect() return client
def run_sync_client(): # ------------------------------------------------------------------------# # choose the client you want # ------------------------------------------------------------------------# # make sure to start an implementation to hit against. For this # you can use an existing device, the reference implementation in the tools # directory, or start a pymodbus server. # # If you use the UDP or TCP clients, you can override the framer being used # to use a custom implementation (say RTU over TCP). By default they use # the socket framer:: # # client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer) # # It should be noted that you can supply an ipv4 or an ipv6 host address # for both the UDP and TCP clients. # # There are also other options that can be set on the client that controls # how transactions are performed. The current ones are: # # * retries - Specify how many retries to allow per transaction (default=3) # * retry_on_empty - Is an empty response a retry (default = False) # * source_address - Specifies the TCP source address to bind to # * strict - Applicable only for Modbus RTU clients. # Adheres to modbus protocol for timing restrictions # (default = True). # Setting this to False would disable the inter char timeout # restriction (t1.5) for Modbus RTU # # # Here is an example of using these options:: # # client = ModbusClient('localhost', retries=3, retry_on_empty=True) # ------------------------------------------------------------------------# # client = ModbusClient('localhost', port=5020) # from pymodbus.transaction import ModbusRtuFramer # client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer) # client = ModbusClient(method='binary', port='/dev/ptyp0', timeout=1) # client = ModbusClient(method='ascii', port='/dev/ptyp0', timeout=1) client = ModbusClient(method='rtu', port='/dev/cu.wchusbserial14310', timeout=1, baudrate=9600) client.connect() # ------------------------------------------------------------------------# # specify slave to query # ------------------------------------------------------------------------# # The slave to query is specified in an optional parameter for each # individual request. This can be done by specifying the `unit` parameter # which defaults to `0x00` # ----------------------------------------------------------------------- # log.debug("Write to a holding register and read back") rr = client.read_holding_registers(0, 8, unit=UNIT) print(rr.registers) # test the expected value client.close()
def get_client(self): client = ModbusClient(method='rtu', port=self.port, timeout=1, stopbits=1, bytesize=8, parity='N', baudrate=9600) client.connect() return client
def modBusInit(): client = ModbusClient(method='rtu', port='/dev/ttyUSB0', baudrate=9600, stopbits=2, bytesize=8, parity='N', timeout=0.5) client.connect() return client
def run_modbus(t): try: # Connect to altonic meter client = ModbusSerialClient(method='rtu', port='/dev/ttyUSB0', stopbits=1, bytesize=8, parity='N', baudrate=9600) client.connect() registers = [0,1,3,17,18] status = [t] # Read the registries, append to status list. for reg in registers: result = client.read_holding_registers(reg, 1, unit=1) status.append(str(result.registers[0])) file = open('sequences.txt','a') file.write('Modbus Read at ' + time.strftime('%H:%M') + '\n') file.close() return status except RuntimeError: return 'Moo' except Exception as e: # Save error in file file = open('error_messages.txt','a') file.write('Error: ' + str(e.message) + ' at ' + time.strftime('%Y-%m-%d %H:%M') + '\n') file.close() try: with timeout(60, exception=RuntimeError): hologram = connect_hologram() if hologram == 'Moo': raise RuntimeError except RuntimeError: os.system('sudo hologram modem disconnect') os.system('sudo reboot') mess = hologram.sendMessage(str(e.message), topics ='ModbusError', timeout=30) os.system('sudo hologram modem disconnect') if mess != 0: os.system('sudo reboot') time.sleep(900) t = time.strftime('%Y-%m-%d %H:%M:%S') status = run_modbus(t) return status
class SerialRtuChannel(BaseChannel): def __init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name): BaseChannel.__init__(self, channel_params, devices_file_name, protocol, mqtt_client, network_name) # 配置项 self.port = channel_params.get("port", "") self.baund = channel_params.get("baund", 9600) self.stopbits = channel_params.get("stopbits", serial.STOPBITS_ONE) self.parity = channel_params.get("parity", serial.PARITY_NONE) self.bytesize = channel_params.get("bytesize", serial.EIGHTBITS) self.timeout = channel_params.get("timeout", 2) self.protocol.set_device_info(self.port, self.baund) # modbus通信对象 self.modbus_client = ModbusSerialClient(method='rtu', port=self.port, baudrate=self.baund, stopbits=self.stopbits, parity=self.parity, bytesize=self.bytesize, timeout=self.timeout) @staticmethod def check_config(channel_params): if "port" not in channel_params or "baund" not in channel_params: return False return BaseChannel.check_config(channel_params) def run(self): # 首先上报设备数据 for device_id in self.devices_info_dict: device_info = self.devices_info_dict[device_id] device_msg = { "device_id": device_info["device_id"], "device_type": device_info["device_type"], "device_addr": device_info["device_addr"], "device_port": device_info["device_port"], "protocol": self.protocol.protocol_type, "data": "" } self.mqtt_client.publish_data(device_msg) try: self.modbus_client.connect() logger.debug("连接串口成功.") except Exception, e: logger.error("连接串口失败,错误信息:%r." % e) self.modbus_client = None return while True: # 该线程保持空转 time.sleep(5)
def create_serial_connection(self): self.pump_control_config = self.config["pumpControl"] port = self.pump_control_config["port"] baud = self.pump_control_config["baud"] timeout = self.pump_control_config["timeout"] client = ModbusSerialClient(method="rtu", port=port, baudrate=baud, timeout=timeout) client.connect() return client
def testSerialClientConnect(self): ''' Test the serial client connection method''' with patch.object(serial, 'Serial') as mock_method: mock_method.return_value = object() client = ModbusSerialClient() self.assertTrue(client.connect()) with patch.object(serial, 'Serial') as mock_method: mock_method.side_effect = serial.SerialException() client = ModbusSerialClient() self.assertFalse(client.connect())
class modbusRTUThread(QThread): inData = pyqtSignal(object) NinReg = 29 NoutReg = 27 stConnec = False ## def __init__(self, port, baud, bytesize, parity, stopbits, timeout): ## QThread.__init__(self) ## self.modbus = ModbusClient(method='rtu', port= port, baudrate= baud, bytesize= bytesize, parity= parity, stopbits= stopbits, timeout = timeout) def __init__(self): # Se inicializa el thread y el timer QThread.__init__(self) self.modbus = ModbusClient(method='rtu', port='/dev/ttyUSB0', baudrate=115200, bytesize=8, parity='E', stopbits=1, timeout=1) self.modbus.connect() time.sleep(2) self.Refresh = QtCore.QTimer(self) self.Refresh.timeout.connect(self.getData) def __del__(self): self.wait() ## def initConnection(self): ## while self.stConnec == False: ## try: ## self.modbus.connect() ## self.stConnec = True ## except: ## pass ## self.run() def run(self): self.Refresh.start(200) def stop(self): self.Refresh.stop() def getData(self): try: print(datetime.datetime.now()) Data = self.modbus.read_holding_registers(0, self.NinReg, unit=2) Registers = [] for k in range(0, self.NinReg): Registers.append(Data.getRegister(k)) self.inData.emit(Registers) outData = self.modbus.write_registers(100, [2]*self.NoutReg, unit=2) print(datetime.datetime.now()) except: print("Falla en comunicacion") Registers = [-1]* self.NinReg self.inData.emit(Registers)
def run_sync_client(): #enabling modbus communication client = ModbusClient(method='rtu', port=MODBUS_DEVICE, timeout=MODBUS_TIMEOUT, baudrate=MODBUS_BAUDRATE) client.connect() MyBoiler.registers = [] id_stop = -1 for mbrange in cfg['modbus']['register_ranges']: id_start = mbrange[0] MyBoiler.registers.extend([None] * (id_start - id_stop - 1)) id_stop = mbrange[1] for i in range(MODBUS_RETRIES): log.debug("Attempt {} to read registers from {} to {}".format( i, id_start, id_stop)) rr = client.read_holding_registers(count=(id_stop - id_start + 1), address=id_start, unit=MODBUS_UNIT) if rr.isError(): log.error(rr.message) MyBoiler.registers.extend([None] * (id_stop - id_start + 1)) else: MyBoiler.registers.extend(rr.registers) break client.close() #parsing registers to push data in Object attributes MyBoiler.browse_registers() log.info("Dumping values\n" + MyBoiler.dump()) #pushing data to influxdb if args.backend and args.backend == 'influxdb': timestamp = int(time.time() * 1000) #milliseconds influx_json_body = [{ "measurement": "diematic", "tags": { "host": "raspberrypi", }, "timestamp": timestamp, "fields": MyBoiler.fetch_data() }] influx_client = InfluxDBClient(cfg['influxdb']['host'], cfg['influxdb']['port'], cfg['influxdb']['user'], cfg['influxdb']['password'], cfg['influxdb']['database']) log.debug("Write points: {0}".format(influx_json_body)) influx_client.write_points(influx_json_body, time_precision='ms')
def __init__(self, com, fmt): client = ModbusSerialClient( method="rtu", port=com, # self.PORT, stopbits=self.STOPBITS, baudrate=self.BAUD_RATE, bytesize=self.BYTESIZE, timeout=self.TIMEOUT, ) client.connect() self.client = client self.fmt = fmt
def CONNECT_TO_METER(): try: client = None METER_PORT = find_tty_usb(ID_VENDOR, ID_PRODUCT) #reading to which port rs485(client) is connected client = ModbusClient(retries = RETRIES, method=COM_METHOD, port=METER_PORT, baudrate=BAUD_RATE, stopbits=STOP_BITS, parity=PARITY, bytesize=BYTE_SIZE, timeout=TIME_OUT) client.connect() return client except Exception as e: lgr.error('Error while connecting client: ', exc_info = True) print "Error while connecting client: \n"+e.__str__()
class IOModeule(): def __init__(self): self.port = None self.client = None self.initialized = False def __del__(self): if self.client is not None: self.client.close() self.client = None def init(self, port): self.port = port self.initialized = False if self.client is not None: self.client.close() self.client = None self.client = ModbusClient(method='rtu', port=self.port, baudrate=9600, timeout=0.5) import serial try: self.client.connect() except serial.SerialException as msg: log.error("cannot open the serial port: {0}".format(msg)) self.client = None self.initialized = False return False self.initialized = True return True def write_relay(self, relay: RelayOut, status: bool): if self.initialized is False: log.debug("IO Module un intialized.") return False rlt = self.client.write_coil(relay, status, unit=UNIT) log.debug(rlt) return True def write_analogy_signal(self, channel: DA_Out, value: float): if self.initialized is False: log.debug("IO Module un intialized.") return False rlt = self.client.write_register()
class SensorModbus(object): def __init__(self): self.serial_connection() #Fungsi Deteksi Serial Ports def serial_ports(self): import sys import glob try: if sys.platform.startswith('win'): # deteksi pada platform windows ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # deteksi pada platfoem linux ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): # deteksi pada platform darwin ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: # Membaca setiap port yang terdeteksi dan menyimpannya ke list try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result except Exception: logging.exception("Exception occurred serial_ports") #Fungsi Menghubungkan ke Koneksi Serial def serial_connection(self): try: for port in self.serial_ports(): if 'ttyUSB' in port: # Mendeteksi ttyUSB terdeteksi self.client = ModbusClient(method='rtu', port=str(port),stopbits=1, bytesize=8, parity='N',baudrate=19200, timeout=5) self.client.connect() except Exception: logging.exception("Exception occurred serial_connect") def temperaturehumidity(self,unit): #Autonics # rawtemperature = self.client.read_input_registers(0,1,unit=1) #Register no 1 in datasheet size 1 words Device ID 1 # temperature = round(rawtemperature.registers[0] * 0.01,2) # rawhumidity = self.client.read_input_registers(1,1,unit=1) #Register no 2 in datasheet size 1 words Device ID 1 # humidity = round(rawhumidity.registers[0] * 0.01,2) #SHT20 rawtemperature = self.client.read_input_registers(3,1,unit=1) #Register no 1 in datasheet size 2 words Decice ID 3 temperature = round(rawtemperature.registers[0] *0.001,2) rawbattery = self.client.read_input_registers(4,1,unit=1) #Register no 3 in datasheet size 2 words Device ID 3 battery = round(rawbattery.registers[0]*0.001,2) return (temperature,battery)
def get_wq(dev, addr): client = ModbusClient(method='rtu', port=dev, timeout=1, stopbits=1, bytesize=8, parity='N', baudrate=9600) client.connect() rr = client.read_input_registers(addr, 1, unit=1) # print(rr.registers[0]); return rr.registers[0]
def CONNECT_TO_METER(): try: client = None METER_PORT = find_tty_usb(ID_VENDOR, ID_PRODUCT) #reading to which port rs485(client) is connected client = ModbusClient(retries = RETRIES, method=COM_METHOD, port=METER_PORT, baudrate=BAUD_RATE, stopbits=STOP_BITS, parity=PARITY, bytesize=BYTE_SIZE, timeout=TIME_OUT) client.connect() return client except Exception as e: print "Could not connect to client: \n" + e.__str__() log_file=open(DATA_BASE_PATH+"RealtimeLOG.txt","a") log_file.write(str(time.time())+" Could not connect to client: \n"+e.__str__()+"\n") log_file.close()
def main(args): global PUMP_TIME global SENSOR_TIME try: PUMP_TIME = int(args[1]) SENSOR_TIME = int(args[2]) print('using custom args. pump time: %d sensor time: %d' % (PUMP_TIME, SENSOR_TIME)) except: PUMP_TIME = 3 SENSOR_TIME = 5 print('using default args. pump time: %d sensor time: %d' % (PUMP_TIME, SENSOR_TIME)) startMeasurement() # Connect to sensor and record data try: client = ModbusClient(method = "rtu", port="/dev/ttyS0",stopbits = 1, bytesize = 8, parity = 'N', baudrate= 9600) # Connect to the serial modbus server connection = client.connect() if connection: recordData(client) # Closes the underlying socket connection client.close() except Exception as error: print('CO2 measurement failed: ' + repr(error)) finally: endMeasurement()
class EPsolarTracerClient: ''' EPsolar Tracer client ''' def __init__(self, unit = 1, serialclient = None, **kwargs): ''' Initialize a serial client instance ''' self.unit = unit if serialclient == None: port = kwargs.get('port', '/dev/ttyXRUSB0') baudrate = kwargs.get('baudrate', 115200) self.client = ModbusClient(method = 'rtu', port = port, baudrate = baudrate, kwargs = kwargs) else: self.client = serialclient def connect(self): ''' Connect to the serial :returns: True if connection succeeded, False otherwise ''' return self.client.connect() def close(self): ''' Closes the underlying connection ''' return self.client.close() def read_device_info(self): request = ReadDeviceInformationRequest (unit = self.unit) response = self.client.execute(request) return response def read_input(self, name): register = registerByName(name) if register.is_coil(): response = self.client.read_coils(register.address, register.size, unit = self.unit) elif register.is_discrete_input(): response = self.client.read_discrete_inputs(register.address, register.size, unit = self.unit) elif register.is_input_register(): response = self.client.read_input_registers(register.address, register.size, unit = self.unit) else: response = self.client.read_holding_registers(register.address, register.size, unit = self.unit) return register.decode(response) def write_output(self, name, value): register = registerByName(name) values = register.encode(value) response = False if register.is_coil(): self.client.write_coil(register.address, values, unit = self.unit) response = True elif register.is_discrete_input(): _logger.error("Cannot write discrete input " + repr(name)) pass elif register.is_input_register(): _logger.error("Cannot write input register " + repr(name)) pass else: self.client.write_registers(register.address, values, unit = self.unit) response = True return response
def main(host, port, mqtt_username, mqtt_password, instance, name, serial_port): modbus = ModbusClient(method='rtu', port=serial_port, baudrate=9600, timeout=1) if not modbus.connect(): logger.error("Cannot connect to modbus") return client = mqtt.Client() client.loop_start() client.connect(host, port, 60) if mqtt_username is not None: client.username_pw_set(mqtt_username, mqtt_password) try: while True: now = int(time()) r = modbus.read_holding_registers(0, 16, unit=1) bat_volt = r.registers[8] * 96.667 * 2**(-15) bat_curr = r.registers[11] * 316.67 * 2**(-15) bat_temp = r.registers[15] client.publish('{}/{}/power'.format(instance, name), "{} {:0.2f}".format(now, bat_volt * bat_curr), 0) client.publish('{}/{}/voltage'.format(instance, name), "{} {:0.2f}".format(now, bat_volt), 0) client.publish('{}/{}/current'.format(instance, name), "{} {:0.2f}".format(now, bat_curr), 0) client.publish('{}/{}/temperature'.format(instance, name), "{} {}".format(now, bat_temp), 0) sleep(5) except KeyboardInterrupt: pass client.disconnect() client.loop_stop() modbus.close()
class SynchronousRtuClient(Runner, unittest.TestCase): """ These are the integration tests for the synchronous serial rtu client. """ def setUp(self): """ Initializes the test environment """ super(Runner, self).setUp() self.initialize(["../tools/reference/diagslave", "-m", "rtu", "/dev/pts/14"]) self.client = ModbusClient(method='rtu', timeout=0.2, port='/dev/pts/13') self.client.connect() def tearDown(self): """ Cleans up the test environment """ self.client.close() super(Runner, self).tearDown()
class SynchronousAsciiClient(Runner, unittest.TestCase): ''' These are the integration tests for the synchronous serial ascii client. ''' def setUp(self): ''' Initializes the test environment ''' super(Runner, self).setUp() # "../tools/nullmodem/linux/run", self.initialize(["../tools/reference/diagslave", "-m", "ascii", "/dev/pts/14"]) self.client = ModbusClient(method='ascii', timeout=0.2, port='/dev/pts/13') self.client.connect() def tearDown(self): ''' Cleans up the test environment ''' self.client.close() super(Runner, self).tearDown()
class ModbusSlaveReader: """ This class uses the pymodbus library to communicate with modbus slaves via serial connection. """ def __init__(self, serial_socket): self.logger = logging.getLogger(__name__) self.client = ModbusClient(method='rtu', port=serial_socket, timeout=1) modbus_client_filter = ModbusClientFilter() logging.getLogger("pymodbus.client.sync").addFilter( modbus_client_filter) def read_register_value(self, slave, register): value = self.client.read_holding_registers(register, 1, unit=slave) self.logger.debug('value read from modbus slave: ' + value) return value def check_connection(self): """Before a timer is made in the ReadSensorScheduler to read the data from the modbus slaves, the connection with the modbus client is checked. """ try: self.client.connect() except: self.logger.warning( 'Unable to connect to modbus network, check serial port') raise return False try: rq = ReportSlaveIdRequest() rr = self.client.execute(rq) assert(rr is None) self.logger.warning('Able to see modbus master on network') return True except: self.logger.warning('Unable to see modbus master on network') return False
def connect(self): _logger.info("AsyncModbusSerialClient.connect()") if self.socket: return True timeout = self.timeout # remember timeout self.timeout = 0 # use non-blocking serial res = ModbusSerialClient.connect(self) self.timeout = timeout if self.socket: self.ioloop.add_handler(self.socket.fileno(), partial(self.dataReceived, self.socket), self.ioloop.READ) return res
def serialinit(): try: client = ModbusClient(method='ascii', port='/dev/ttyMP2', parity='E', timeout=1 ) val = client.connect() if val: print "Connection open to client." return client else: print "Error in Client Connection!" return None except: return None
class communication: def __init__(self): self.client = None def connectToDevice(self, device): """Connection to the client - the method takes the IP address (as a string, e.g. '192.168.1.11') as an argument.""" self.client = ModbusSerialClient(method='rtu',port=device,stopbits=1, bytesize=8, baudrate=115200, timeout=0.2) if not self.client.connect(): print "Unable to connect to %s" % device return False return True def disconnectFromDevice(self): """Close connection""" self.client.close() def sendCommand(self, data): """Send a command to the Gripper - the method takes a list of uint8 as an argument. The meaning of each variable depends on the Gripper model (see support.robotiq.com for more details)""" #make sure data has an even number of elements if(len(data) % 2 == 1): data.append(0) #Initiate message as an empty list message = [] #Fill message by combining two bytes in one register for i in range(0, len(data)/2): message.append((data[2*i] << 8) + data[2*i+1]) #To do!: Implement try/except self.client.write_registers(0x03E8, message, unit=0x0009) def getStatus(self, numBytes): """Sends a request to read, wait for the response and returns the Gripper status. The method gets the number of bytes to read as an argument""" numRegs = int(ceil(numBytes/2.0)) #To do!: Implement try/except #Get status from the device response = self.client.read_holding_registers(0x07D0, numRegs, unit=0x0009) #Instantiate output as an empty list output = [] #Fill the output with the bytes in the appropriate order for i in range(0, numRegs): output.append((response.getRegister(i) & 0xFF00) >> 8) output.append( response.getRegister(i) & 0x00FF) #Output the result return output
def main(): mbAddress = 252 baud = 19200 comPort = '/dev/ttyUSB0' mb = ModbusClient(method='rtu', port=comPort, baudrate=baud, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, bytesize=serial.EIGHTBITS, timeout=3) connection = mb.connect() if connection == False: print "Connection failed\n" quit() else: print "Connection successful\n" TestCommunication(mb, mbAddress)
def run_motor_gui(tkroot): client = ModbusClient(method="rtu", port="/dev/ttyUSB1", stopbits=1, \ bytesize=8, parity='E', baudrate=9600, timeout=0.1) # connect to the serial modbus server connection = client.connect() print("Connection = " + str(connection)) # Create and set up the GUI object root = Toplevel(tkroot) root.title("WIFIS Motor Controller") root.geometry("250x375") #root.protocol("WM_DELETE_WINDOW", on_closing) app = MainApplication(root,client) return client
def CONNECT_TO_METER(self): try: clt = None METER_PORT = self.find_tty_usb(self.ID_VENDOR, self.ID_PRODUCT) #reading to which port rs485(client) is connected clt = ModbusClient(retries=self.RETRIES, method=self.COM_METHOD, port=METER_PORT, baudrate=self.BAUD_RATE, stopbits=self.STOP_BITS, parity=self.PARITY, bytesize=self.BYTE_SIZE, timeout=self.TIME_OUT) self.iftrue = clt.connect() if self.iftrue: print "Connection successful. " + str(clt) return clt except Exception as e: #lgr.error('Error while connecting client: ', exc_info = True) print "Error while connecting client: \n" + e.__str__()
def testBasicSyncSerialClient(self): ''' Test the basic methods for the serial sync client''' # receive/send client = ModbusSerialClient() client.socket = mockSocket() self.assertEqual(0, client._send(None)) self.assertEqual(1, client._send('\x00')) self.assertEqual('\x00', client._recv(1)) # connect/disconnect self.assertTrue(client.connect()) client.close() # already closed socket client.socket = False client.close() self.assertEqual('ascii baud[19200]', str(client))
def run_motor_gui_standalone(): client = ModbusClient(method="rtu", port="/dev/ttyUSB0", stopbits=1, \ bytesize=8, parity='E', baudrate=9600, timeout=0.1) # connect to the serial modbus server connection = client.connect() print("Connection = " + str(connection)) # Create and set up the GUI object root = Tk() root.title("WIFIS Motor Controller") root.geometry("275x375") #root.protocol("WM_DELETE_WINDOW", on_closing) app = MainApplication(root,client) root.mainloop() # closes the underlying socket connection client.close()
#!/usr/bin/python # script to poll growatt PV inverter and spit out values # Andrew Elwell <*****@*****.**> 2013-09-01 from pymodbus.client.sync import ModbusSerialClient as ModbusClient import time result = {} result['timestamp'] = time.time() client = ModbusClient(method='rtu', port='/dev/ttyUSB0', baudrate=9600, stopbits=1, parity='N', bytesize=8, timeout=1) client.connect() # can'r read the whole lot in one pass, so grab each chunk # addr / descriptions lifted from http://code.google.com/p/pvbeancounter/source/browse/trunk_v2/PVSettings/Device_Growatt.xml rr = [] rr = client.read_input_registers(2,3) result['PV_W'], result['PV_V'], result['PV_A'] = rr.registers rr = [] rr = client.read_input_registers(12,3) result['Out_W'], result['AC_Hz'], result['AC_V'] = rr.registers #rr = client.read_input_registers(17, 1) #result['wtf2'] = rr.registers[0] #rr = client.read_input_registers(29,3) #print rr.registers client.close()
Deps: Pyserial, Pymodbus, logging """ import time # For sleep functionality import logging # For detailed error output from pymodbus.client.sync import ModbusSerialClient \ as ModbusClient # Import MODBUS support class comSettings = { "method" : 'rtu', "port" : 'COM3', "stopbits" : 1, "bytesize" : 8, "parity" : 'N', "baudrate" : 9600, "timeout" : 1 } logging.basicConfig() # Setup error logging log = logging.getLogger() # Start logging client = ModbusClient(**comSettings) # Setup connection object client.connect() # Open the MODBUS connection while(True): client.write_register(3,1000,unit=0x01) # Write valve to 100% time.sleep(4) # Sleep 4 seconds client.write_register(3,0,unit=0x01) # Write valve to 0% time.sleep(4) # Sleep 4 seconds client.close() # Close the connection
class TristarPWM(object): """ tristar pwm ts45 or ts60 for data logging, it can read the holding/input register and save to csv file """ def __init__(self, method, port, baudrate, stopbits, parity, timeout, DT=10, COUNT=6, debug_flag=True, log_flag=True, thingspeak_flag=True): self.method = method self.port = port self.baudrate = baudrate self.stopbits = stopbits self.parity = parity self.timeout = timeout self.DT = DT self.COUNT = COUNT self.debug_flag = debug_flag self.log_flag = log_flag self.thingspeak_flag = thingspeak_flag self.register_dict={} def connect(self): """ connect to modbus client """ try: self.client = ModbusClient(method=self.method, port=self.port, baudrate=self.baudrate, stopbits=self.stopbits, parity=self.parity, timeout=self.timeout) self.client.connect() print "connected" except KeyboardInterrupt: self.client.close() def close(self): """ disconnect client """ self.client.close() def read_registers(self): """ read holding registers """ # read the registers from logical address 0 to 0x1e. response = self.client.read_holding_registers(0x00, 0x1e, unit=1) # the stuff we want batt_V = (response.registers[adc_vb_f] * v_scale) / (2**15) batt_sens_V = (response.registers[adc_vs_f] * v_scale) / (2**15) array_V = (response.registers[adc_vx_f] * array_scale) / (2**15) charge_I = (response.registers[adc_ipv_f] * i_scale) / (2**15) load_I = (response.registers[adc_iload_f] * iload_scale) / (2**15) batt_V_slow = (response.registers[vb_f] * v_scale) / (2**15) heatsink_T = response.registers[t_hs] batt_T = response.registers[t_batt] reference_V = (response.registers[v_ref] * v_scale) / (2**15) ah_reset = (response.registers[ah_r_hi]<<8 + \ response.registers[ah_r_lo] ) * ah_scale ah_total = (response.registers[ah_t_hi]<<8 + \ response.registers[ah_t_lo] ) * ah_scale hourmeter = response.registers[hourmeter_hi]<<8 + \ response.registers[hourmeter_lo] alarm_bits = response.registers[alarm_hi]<<8 + \ response.registers[alarm_lo] fault_bits = response.registers[fault] dip_num = response.registers[dip_switch] mode_num = response.registers[control_mode] state_num = response.registers[control_state] pwm_duty = response.registers[d_filt] /230.0 if pwm_duty > 1: pwm_duty = 100.0 # p. 13 0: 0%, >=230: 100% else: pwm_duty *= 100.0 # convert to percentage powerIn = batt_V * charge_I mode = control_mode_turple[mode_num] if mode_num == 0 or mode_num ==2: # charge of diversion state = charge_div_state_turple[state_num] else: # load and lighting mode state = load_light_state_turple[state_num] return {"batt_V":batt_V,"batt_sens_V":batt_sens_V, "array_V":array_V,"charge_I":charge_I,"load_I":load_I, "batt_V_slow":batt_V_slow,"heatsink_T":heatsink_T, "batt_T":batt_T,"reference_V":reference_V, "ah_reset":ah_reset,"ah_total":ah_total, "hourmeter":hourmeter,"alarm_bits":alarm_bits, "fault_bits":fault_bits,"dip_num":dip_num, "mode_num":mode_num,"state_num":state_num, "pwm_duty":pwm_duty,"powerIn":powerIn, "mode":mode,"state":state} def read_modbus(self): """read output from modbus, save them into a list""" assert(self.client is not None), "client not connected" counter = 1 # initialize list batt_V_list = [] batt_sens_V_list = [] array_V_list = [] charge_I_list = [] load_I_list = [] batt_V_slow_list = [] heatsink_T_list = [] batt_T_list = [] pwm_duty_list = [] powerIn_list = [] while counter <= self.COUNT: try: self.register_dict = self.read_registers() except KeyboardInterrupt: print "interrupted" break except: print "port not available" continue # debug if self.debug_flag: print self.register_dict.items() # for key in register_dict: # print key # print register_dict[key] # calculate average batt_V_list.append(self.register_dict["batt_V"]) batt_sens_V_list.append(self.register_dict["batt_sens_V"]) array_V_list.append(self.register_dict["array_V"]) charge_I_list.append(self.register_dict["charge_I"]) load_I_list.append(self.register_dict["load_I"]) batt_V_slow_list.append(self.register_dict["batt_V_slow"]) heatsink_T_list.append(self.register_dict["heatsink_T"]) batt_T_list.append(self.register_dict["batt_T"]) pwm_duty_list.append(self.register_dict["pwm_duty"]) powerIn_list.append(self.register_dict["powerIn"]) # return value counter += 1 time.sleep(self.DT) else: # add time point tid = time.strftime("%Y/%m/%d %H:%M:%S") self.register_dict["tid"] = str(tid) # calculate average self.register_dict["batt_V"] = mean(batt_V_list) self.register_dict["array_V"] = mean(array_V_list) self.register_dict["charge_I"] = mean(charge_I_list) self.register_dict["pwm_duty"] = mean(pwm_duty_list) self.register_dict["heatsinke_T"] = mean(heatsink_T_list) self.register_dict["powerIn"] = mean(powerIn_list) def write_thingspeak(self, field_id, field_var_name): """ write certain fields to thingspeak, while loop """ if self.thingspeak_flag: channel = thingspeak.channel() try: while True: # register_dict = self.read_modbus() self.read_modbus() field_var = [self.register_dict[i] for i in field_var_name] channel.update(field_id, field_var) except KeyboardInterrupt: self.close() else: pass def write_thingspeak_oneshot(self, field_id, field_var_name): """ write certain fields to thingspeak, no loop """ if self.thingspeak_flag: channel = thingspeak.channel() self.read_modbus() field_var = [self.register_dict[i] for i in field_var_name] channel.update(field_id, field_var) else: pass def log_data(self, field_var_name, filename, tid=None): """ log data into a file Changelog 20160308: insert external tid for data to have same tid """ if self.log_flag: filename_new = filename + time.strftime("%Y%m%d") + '.csv' if not os.path.isfile(filename_new): # write new file with header # create new file os.mknod(filename_new) # chmod os.chmod(filename_new, 0o755) fil = open(filename_new, 'w+') # write header # select items to write header = ",".join(field_var_name) fil.write(header+"\n") else: # append if not os.access(filename_new, os.W_OK): # chmod os.chmod(filename_new, 0o755) else: fil = open(filename_new, 'a+') # pass register_dict to file write # check if have external tid if tid is not None: self.register_dict['tid'] = str(tid) field_var = [str(self.register_dict[i]) for i in field_var_name] output_text = ",".join(field_var) # print output_text fil.write(output_text+"\n") fil.close() else: # no log pass
def run_sync_client(): # ------------------------------------------------------------------------# # choose the client you want # ------------------------------------------------------------------------# # make sure to start an implementation to hit against. For this # you can use an existing device, the reference implementation in the tools # directory, or start a pymodbus server. # # If you use the UDP or TCP clients, you can override the framer being used # to use a custom implementation (say RTU over TCP). By default they use # the socket framer:: # # client = ModbusClient('localhost', port=5020, framer=ModbusRtuFramer) # # It should be noted that you can supply an ipv4 or an ipv6 host address # for both the UDP and TCP clients. # # There are also other options that can be set on the client that controls # how transactions are performed. The current ones are: # # * retries - Specify how many retries to allow per transaction (default=3) # * retry_on_empty - Is an empty response a retry (default = False) # * source_address - Specifies the TCP source address to bind to # # Here is an example of using these options:: # # client = ModbusClient('localhost', retries=3, retry_on_empty=True) # ------------------------------------------------------------------------# # client = ModbusClient('localhost', port=5020) # client = ModbusClient(method='ascii', port='/dev/pts/2', timeout=1) client = ModbusClient(method='rtu', port='/dev/ttyS3', baudrate=9600, timeout=1) client.connect() # ----------------------------------------------------------------------- # # example requests # ----------------------------------------------------------------------- # # simply call the methods that you would like to use. An example session # is displayed below along with some assert checks. Note that some modbus # implementations differentiate holding/input discrete/coils and as such # you will not be able to write to these, therefore the starting values # are not known to these tests. Furthermore, some use the same memory # blocks for the two sets, so a change to one is a change to the other. # Keep both of these cases in mind when testing as the following will # _only_ pass with the supplied async modbus server (script supplied). # ----------------------------------------------------------------------- # # 读模块型号 rr = client.read_holding_registers(40001, 1, unit=UNIT) print(rr.registers[0]) # 读两路输入(寄存器地址200,共2个) log.debug("Read discrete inputs") rr = client.read_discrete_inputs(200, 2, unit=UNIT) print(rr.bits) # bit0表示DI1的状态,bit1表示DI2 # 写单个输出DO1(寄存器地址100) log.debug("Write to a Coil and read back") rq = client.write_coil(100, True, unit=UNIT) rr = client.read_coils(100, 1, unit=UNIT) assert(rq.function_code < 0x80) # test that we are not an error assert(rr.bits[0] == True) # test the expected value # ----------------------------------------------------------------------- # # close the client # ----------------------------------------------------------------------- # client.close()
class Com_Modbus: def __init__(self): #logging.basicConfig() #log = logging.getLogger() #log.setLevel(logging.DEBUG) #scan all available com port port_list = self.scan() s = None print "Found ports:" for n,s in port_list: print "____(%d) %s" % (n,s) if s <> None: self.client = ModbusClient(method='ascii', port=s, stopbits = 1, parity = 'E', bytesize = 7, baudrate='9600', timeout=1) connect = self.client.connect() print "Com is connected =",connect print "Init Modbus Comm = ",self.client #Scan all available com port on this machine - return list of connected usb com port def scan(self): # scan for available ports. return a list of tuples (num, name) available = [] for i in range(256): try: s = serial.Serial(i) available.append( (i, s.portstr)) s.close() except serial.SerialException: pass return available def D_AddressRef(self,d_Address): #---------------------------------------------------------------------------# # D_AddressRef #---------------------------------------------------------------------------# #Input address in decimal - then function would convert it to PLC address #Address 0x1000 stand for D register in PLC #Address 0x0258 stand for 600 in decimal #So to write to D600 register in the PLC #The reference address is 0x1258 d_Working = 4096 d_Working = d_Working + d_Address return d_Working #_____________________________________________________________________________# # Usage example #_____________________________________________________________________________# #client.write_register(D_AddressRef(600), 123, unit=2 ) #unit=2 : mean PLC server address = 2 # def write_register(self, address, value, **kwargs): // Extracted from pymodbus\client\common.py # ''' # :param address: The starting address to write to # :param value: The value to write to the specified address # :param unit: The slave unit this request is targeting # :returns: A deferred response handle def Send_register(self,address,data): self.client.write_register(self.D_AddressRef(address), data, unit = 1 ) print 'sent' pass #read back single register def Read_register(self,address): #read_coils(address, count=1, unit=0) register_read = self.client.read_holding_registers(self.D_AddressRef(address),1, unit = 1) if register_read <> None: return register_read.registers[0] else: return None pass #read back multiple register def Read_register_multi(self,address,length): #read_coils(address, count=1, unit=0) register_read = self.client.read_holding_registers(self.D_AddressRef(address),length, unit = 1) print register_read.registers[0] return register_read pass
def connect(): try: client = None client = ModbusClient(retries = 0, method='rtu', port='/dev/ttyUSB1', baudrate=38400, stopbits=1, parity='N', bytesize=8, timeout=1) client.connect() return client except Exception as e: print "Error while connecting client: \n"+e.__str__()