class ModbusClientRS: def __init__(self): self.client = ModbusClient() def writeRegister(self, address, value): if self.client.is_open(): return self.client.write_single_register(address, value) return None def readRegister(self, address, value): if self.client.is_open(): self.client.read_holding_registers(address, value) def connect(self, host, port): # self.client.debug(True) self.client.host(SERVER_HOST) self.client.port(SERVER_PORT) if not self.client.is_open(): if not self.client.open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) def is_open(self): return self.client.is_open() def disconnect(self): return self.client.close()
def test_unit_id(self): # test valid/invalid cases for debug() c = ModbusClient() self.assertEqual(c.unit_id(), 1, 'default unit_id is 1') self.assertEqual(c.unit_id(42), 42) self.assertEqual(c.unit_id(0), 0) self.assertEqual(c.unit_id(420), None)
class Modbus: def __init__(self, host, port, unit): self.client = ModbusClient(host, port, unit, timeout=3) def __enter__(self): self.client.open() return self def __exit__(self, exc_type, exc_val, exc_tb): self.client.close() def toFloat(self, ushorts): bs = struct.pack('H', ushorts[0]) + struct.pack('H', ushorts[1]) return struct.unpack('f', bs) def openConnect(self): try: if not self.isOpen: self.client.open() except: self.closeConnect() def closeConnect(self): self.client.close() @property def isOpen(self): return self.client.is_open() def getValue(self, addr): return self.toFloat(self.client.read_holding_registers(addr, 2))[0] def getValues(self, tags): return [(tag, self.getValue(tag)) for tag in tags]
def setUp(self): # modbus server self.server = ModbusServer(port=5020, no_block=True) self.server.start() # modbus client self.client = ModbusClient(port=5020) self.client.open()
def test(): c = ModbusClient() # uncomment this line to see debug message # c.debug(True) # define modbus server host, port c.host(SERVER_HOST) c.port(SERVER_PORT) while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) # if open() is ok, read register (modbus function 0x03) if c.is_open(): print c.write_single_register(504, intToUint16(-216)) # sleep 2s before next polling time.sleep(2)
def __enter__(self): # Create a ModbusTCP connection to be used for all our requests try: self._conn = ModbusClient(host=self._host, port=self._port, unit_id=self._unit_id, timeout=self._timeout, debug=self._debug, auto_open=False, auto_close=False) except Exception: logger.exception( "Attempting to create ModbusTCP client raised exception:") raise try: # Make sure we have an open connection to device if self.__open_connection(self._conn_retry): logger.debug( f"Opened ModbusTCP connection to {self._host}:{self._port}/{self._unit_id}" ) else: logger.error( f"Unable to open ModbusTCP connection to {self._host}:{self._port}/{self._unit_id}" ) return None except Exception: logger.error( "Exception while attempting to open ModbusTCP connection:") raise return self
def read(ip): # Initialize modbus c = ModbusClient(host=ip, port=502, auto_open=True, timeout=0.1) # Read the outputs (Returns None if timeout) return(c.read_coils(16, 6))
def __init__(self, host): self.client = ModbusClient(host=host, auto_open=True, auto_close=False) #self.client.debug(True) logger.info("Connecting to %s", self.client.host()) status = self.check_status() if status & 1<<15: # Watchdog ellapsed, try to reset logger.info("Resetting watchdog") self.client.write_single_register(0x1121, 0xbecf) self.client.write_single_register(0x1121, 0xaffe) # Disable the watchdog, if enabled watchdog_timeout = self.client.read_holding_registers(0x1120)[0] if watchdog_timeout > 0: logger.debug("Watchdog timeout: %d", watchdog_timeout) logger.info("Disabling watchdog") self.client.write_single_register(0x1120, 0) (self.num_outputs, self.num_inputs) = self.client.read_holding_registers(0x1012, 2) logger.info("Number of outputs: %d", self.num_outputs) logger.info("Number of inputs: %d", self.num_inputs) self.client.close() # We use auto close for all subsequent calls after initialization self.client.auto_close(True)
def polling_thread(self): self.client = ModbusClient(host=SERVER_HOST, port=SERVER_PORT) isOpen = False # polling loop while True: # keep TCP open if not self.client.is_open(): print("unable to connect to " + SERVER_HOST + ":" + str(SERVER_PORT)) self.client.open() if self.client.is_open(): if not isOpen: print("connected to " + SERVER_HOST + ":" + str(SERVER_PORT)) isOpen = True # do modbus reading on socket reg_list = self.client.read_holding_registers(0, 10) # if read is ok, store result in regs (with thread lock synchronization) if reg_list: with regs_lock: self.regList = list(reg_list) # 1s before next polling time.sleep(0.2)
def __init__(self, ip): self.host = ip self.port = 2121 self.username = "******" self.password = "******" self.localpath = "./" self.modbus_xml = "/data/mgrid/sampler/modbus_map.xml" self.XmlCfg_ftp_path = "/data/mgrid/sampler/XmlCfg" self.__old_str = "&" self.__new_str = "-" # self.__client = ModbusClient(host=self.host, port=502) self.__client = ModbusClient(host=self.host, port=502, debug=True) self.modbus_map_list = [] # 存储modbus_map_list表数据[{},{},{}...] self.MonitorUnitVTU = [] # 存储MonitorUnitVTU表数据[{},{},{}...] self.__conn = connect(host='localhost', port=3306, database="MOTTA_data", user="******", password="******", charset="utf8") self.__cur = self.__conn.cursor() self.__address = 0 self.__register = 1 self.i = 0 self.ftp = None # 设置self.ftp=None的时候 ftp才能自动重新连接上
def baglan(self): self.c = ModbusClient(host=self.host, unit_id=1, timeout=self.timeout, auto_open=True, auto_close=True, port=self.port)
def _read_config(self): self._ip = self._config.get('modbus_server_ip') self._port = self._config.get( 'modbus_port', ModbusTCPSensor.default_config['modbus_port']) self._debug = self._config.get('debug', 0) == 1 self._sample_rate = self._config.get( 'sample_rate', ModbusTCPSensor.default_config['sample_rate']) self._sensors = [] # Load Sensors for sensor in self._config.get('sensors', []): if 0 <= sensor['sensor_id'] < 32: self._sensors.append(sensor) # Load Validation bits self._validation_bits = [] for validation_bit in self._config.get('bits', []): if 0 <= validation_bit['validation_bit_id'] < 256: self._validation_bits.append(validation_bit) self._enabled = len(self._sensors) > 0 try: from pyModbusTCP.client import ModbusClient self._client = ModbusClient(self._ip, self._port, auto_open=True, auto_close=True) self._client.open() self._enabled = self._enabled & True except Exception as ex: self.logger('Error connecting to Modbus server: {0}'.format(ex)) self.logger('ModbusTCPSensor is {0}'.format( 'enabled' if self._enabled else 'disabled'))
def read_all_tags(self): try: c = ModbusClient(host="192.168.2.11", port=502, debug=False) c.open() for name, tag in self.tag_db.items(): mb0 = tag['modbus_start'] -1 mb1 = tag['modbus_stop'] -1 size = 1+mb1-mb0 #print(name, mb0, mb1, size) #print(tag) if 0 <= mb0 < 100000: val = c.read_coils(mb0)[0] elif 100000 <= mb0 < 200000: val = c.read_discrete_inputs(mb0-100000)[0] elif 300000 <= mb0 < 400000: val = c.read_input_registers(mb0-300000, size) if size == 1: val = val[0] elif size == 2: val = utils.word_list_to_long(val, big_endian=False)[0] elif 400000 <= mb0 < 500000: val = c.read_holding_registers(mb0-400000, size ) if size == 1: val = val[0] elif size == 2: val = utils.word_list_to_long(val, big_endian=False)[0] if tag['dtype'] == 'float32': val = utils.decode_ieee(val) #print(name, val) self.settings[name] = val except Exception as err: print("Error in read_all_tags", err) c.close()
def __init__(self): # self.host = input("请输入IP地址:") # self.port = int(input("请输入端口号:")) # self.username = input("请输入用户名:") # self.password = input("请输入密码:") self.host = "192.168.1.30" self.port = 2121 self.username = "******" self.password = "******" self.remote_path = "/data/mgrid/sampler/modbus_map.xml" self.__file = "./modbus_map.xml" self.__old_str = "&" self.__new_str = "-" self.equipid_list = [] self.sigid_list = [] self.reg_addr_list = [] self.name_list = [] self.__client = ModbusClient(host=self.host, port=502, debug=True, auto_open=True) self.__address = 0 self.__register = 50 self.i = 0 self.__conn = connect(host='localhost', port=3306, database="MOTTA_data", user="******", password="******", charset="utf8") self.__cur = self.__conn.cursor() self.float_data = [] # 检测获取到的数据
def onStart(self): Domoticz.Heartbeat(5) if Parameters["Mode2"] == "Debug": Domoticz.Debugging(1) else: Domoticz.Debugging(0) # 从Domoticz重新加载硬件和设备信息 self.reloadFromDomoticz() debug = False if Parameters["Mode2"] == "Debug": debug = True if self.client and self.client.is_open(): self.client.close() self.client = ModbusClient(host=Parameters["Address"], port=Parameters["Port"], auto_open=True, auto_close=False, timeout=1) self.messageThread.start() self.client.mode(2) self.messageQueue.put({ "Type": "Log", "Text": "Heartbeat test message" })
def modbus_devices(register, value): c = ModbusClient(host="164.8.11.147", port=502, auto_open=True) # regs=c.read_holding_registers(33) # print(regs) regs = c.write_single_register(register, value) regs1 = c.read_holding_registers(register) print(regs1)
def __init__(self): ip = rospy.get_param("/robot_ip") self.c = ModbusClient(host=ip, auto_open=True, auto_close=False, port=502, debug=False, unit_id=2) rospy.init_node("joint_pos_pub") self.p = rospy.Publisher('/joint_states', JointState, queue_size=1) name = getpass.getuser() f = open( '/home/%s/catkin_ws/src/delta/arm_driver/yaml/joint_limits.yaml' % name, 'r') d = yaml.load(f) f.close() self.dP = d["PUU_limits"] self.dA = d["Angle_limits"] self.joint_states = JointState() self.joint_states.name = [ 'shoulder', 'elbow', 'wrist1', 'wrist2', 'wrist3', 'wrist4' ]
def onStart(): Domoticz.Log("Domoticz SMA Inverter Modbus plugin start") if 1 not in Devices: Domoticz.Device(Name="Solar Yield", Unit=1, TypeName="kWh", Used=0).Create() if 2 not in Devices: Domoticz.Device(Name="DC Power A", Unit=2, TypeName="Usage", Used=0).Create() if 3 not in Devices: Domoticz.Device(Name="DC Power B", Unit=3, TypeName="Usage", Used=0).Create() if 4 not in Devices: Domoticz.Device(Name="AC Power", Unit=4, TypeName="Usage", Used=0).Create() if 5 not in Devices: Domoticz.Device(Name="Temperature", Unit=5, TypeName="Temperature", Used=0).Create() global client client = ModbusClient(host=Parameters["Address"], port=Parameters["Port"], unit_id=Parameters["Mode1"]) client.open() Domoticz.Heartbeat(int(Parameters["Mode2"]))
def __init__(self, ip, system, port=502): self.c = ModbusClient(host=ip, port=502, auto_open=True) self.c.host(ip) self.c.port(port) self.c.open() self.system = system print("opened")
def __init__(self, *, queue=None, host='127.0.0.1', timeout=1): """ Set up client. ::host:: str - By default client runs on localhost. ::port:: int - Port 502 is constant for ModdbusTCP. """ self.queue = queue self.host = host self.port = 502 self.timeout = timeout self.client = ModbusClient(host=self.host, port=self.port) self.func_read_dict = { 'hr': self.client.read_holding_registers, 'c': self.client.read_coils, 'di': self.client.read_discrete_inputs, 'ir': self.client.read_input_registers, } self.func_write_dict = { 'hr': self.client.write_multiple_registers, 'c': self.client.write_multiple_coils, } self.registers_dict = {} self.reg_current_value = {} self.name_stack = []
class kulucka: def __init__(self): self.bekle = 1 self.host = "212.154.74.164" self.port = 502 self.timeout = 2000 self.c = None self.sonuc = {} def baglan(self): self.c = ModbusClient(host=self.host, unit_id=1, timeout=self.timeout, auto_open=True, auto_close=True, port=self.port) def main(self): self.c.open() regs = self.c.read_holding_registers(12288, 6) if regs: self.parse(regs) else: print("read error") self.c.close() def parse(self, regs): k = 1 for i in range(0, len(regs), 2): sicaklik = regs[i] / 10 nem = regs[i + 1] / 10 self.sonuc["kulucka" + str(k)] = {"sicaklik": sicaklik, "nem": nem} k += 1 print()
def setUp(self): # modbus server self.server = ModbusServer(port=5020, no_block=True) self.server.start() # modbus client self.client = ModbusClient(port=5020) self.client.open()
def connect(self, ip=None): """ Verbinde dich mit einer Heliotherm Wärmepumpe (mit RCG2). Gib dazu die IP-Adresse/den Hostnamen an. Wenn die IP-Adresse schonmal konfiguriert wurde, lasse das Feld einfach leer. """ if ip != None and ip != '' and type(ip) is str: self.IP_Adresse = ip self.savePersistentVariable('IP_Adresse', self.IP_Adresse) self.info('Connecting with {}'.format(self.IP_Adresse)) if not self._connected: try: self.setPerpetualTimer(self._readModbusRegisters, samplerate=self.samplerate) self._c = ModbusClient(host=self.IP_Adresse, port=self.Port, auto_open=True, auto_close=True) if self._c is None: self.error('Could not connect with {}'.format(self.IP_Adresse)) self.status = 'Could not connect with {}'.format(self.IP_Adresse) return False self._c.timeout(10) self.status = 'Trying to connect...' self.start() self._connected = True return True except Exception as e: self.error('Could not connect with {}:\n{}'.format(self.IP_Adresse, e)) self.status = 'Could not connect with {}:\n{}'.format(self.IP_Adresse, e) return False else: self.status = 'Already connected. Disconnect first' return False
def __init__(self, machine, name): builder.SetDeviceName(name) self.com = ModbusClient(host=machine, port=4000, auto_open=True) #4000 self.com.mode(constants.MODBUS_RTU) stat = self.com.open() self.pv_stat = builder.aIn("stat") self.pv_stat.PREC = 1 self.pv_stat.LOPR = 0 self.pv_stat.HOPR = 100 self.pv_temp = builder.aIn("temp") self.pv_temp.PREC = 1 self.pv_temp.LOPR = 0 self.pv_temp.HOPR = 100 self.pv_humi = builder.aIn("humidity") self.pv_humi.PREC = 1 self.pv_humi.LOPR = 0 self.pv_humi.HOPR = 100 self.pv_humi.HSV = "MINOR" self.pv_humi.HHSV = "MAJOR" self.pv_humi.HIGH = 45 self.pv_humi.HIHI = 50 self.pv_flow = builder.aIn("flow") self.pv_flow.PREC = 0 self.pv_flow.LOPR = 0 self.pv_flow.HOPR = 600 self.pv_flow.LOLO = 250 self.pv_flow.LOW = 300 self.pv_flow.HIGH = 480 self.pv_flow.HIHI = 520 self.pv_flow.LSV = "MINOR" self.pv_flow.LLSV = "MAJOR" self.pv_flow.HSV = "MINOR" self.pv_flow.HHSV = "MAJOR" self.stat_pv = builder.boolIn("status", ZNAM="off", ONAM="on", DESC=name) self.stat_pv.ZSV = "MAJOR" self.pv_on = builder.boolOut("on", ZNAM="0", ONAM="1", HIGH=0.1, on_update=self.turnOn) self.pv_off = builder.boolOut("off", ZNAM="0", ONAM="1", HIGH=0.1, on_update=self.turnOff) self.busy = False self.pv_act = builder.boolOut("activity", ZNAM="0", ONAM="1", HIGH=1) self.pv_was_on = builder.boolOut("was_on", ZNAM="0", ONAM="1", HIGH=1.5) self.pv_was_off = builder.boolOut("was_off", ZNAM="0", ONAM="1", HIGH=1.5) self.id_temp = 0 self.id_stat = 1
def __init__(self): self.__client = ModbusClient(host="192.168.1.200", port=502, auto_open=True) self.__address = 0 self.__register = 2 self.__hex_str_list = [] self.__hex_data = [] self.float_list = []
def doWrite(goToPos): c = ModbusClient(host="192.168.1.1", auto_open=True, auto_close=True) if c.write_single_register(1, goToPos): print("write ok") else: print("write error")
def execute_func(): sensor_no = ModbusClient(host="192.40.50.107", port=10010, unit_id=1, auto_open=True) sensor_no.open() regs = sensor_no.read_holding_registers(0, 100) if regs: print(regs) else: print("read error") n = 0 data_count = 0 for n in range(50): data_count = n * 2 regs[data_count], regs[data_count + 1] = regs[data_count + 1], regs[data_count] dec_array = regs data_bytes = np.array(dec_array, dtype=np.uint16) data_as_float = data_bytes.view(dtype=np.float32) time_data = datetime.datetime.now() print(time_data) start = 1 start_range = 50 value = [[num for num in range(start, start + start_range)], [num for num in range(start, start + start_range)], data_as_float] data = np.array(value).T.tolist() # print(data) products = data arr = [] for product in products: vals = {} vals["Sensor No"] = str(int(product[1])) vals["Temp"] = str(product[2]) vals["Time"] = str(time_data) arr.append(vals) myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["Modbus_Database"] mycol = mydb["collection1"] record_data = arr mycol.insert_many(record_data) global documents documents = list(mycol.find({}, {'_id': 0})) print(documents) # myclient.drop_database('Modbus_Database') mycol.delete_many({}) time.sleep(60)
def __init__( self, maxpower=3300, addr_command=63245, addr_time=63243, addr_disPower=63248, addr_chaPower=63246, timeBatt=36000, SERVER_HOST="192.168.0.51", SERVER_PORT=502, PWRNET_API_BASE_URL='http://pwrnet-158117.appspot.com/api/v1/'): self.maxPower = maxpower self.addr_command = addr_command self.addr_time = addr_time self.addr_disPower = addr_disPower self.addr_chaPower = addr_chaPower self.timeBatt = timeBatt # How long to (dis)charge [s]: uint32 self.SERVER_HOST = SERVER_HOST self.SERVER_PORT = SERVER_PORT self.tcpClient = ModbusClient(host=self.SERVER_HOST, port=self.SERVER_PORT, unit_id=247, timeout=2, auto_open=True) self.PWRNET_API_BASE_URL = PWRNET_API_BASE_URL self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) self.handler = RotatingFileHandler('my_log.log', maxBytes=2000, backupCount=10) self.logger.addHandler(self.handler) self.logger.info('Storage class called')
def post(self, uid): ''' POST to control module coil output states (Make the blinkey lights go blinkey) ''' # Parse the form data parser = reqparse.RequestParser() parser.add_argument("type") parser.add_argument("output") parser.add_argument("state") parser.add_argument("ips", action='append') args = parser.parse_args() outputs = ['all_clear', 'emergency', 'lightning', 'a', 'b', 'c'] # Iterate over the outputs and send the state for each one # True = On, False = Off for idx, output in enumerate(outputs): if output == args['output']: for ip in args['ips']: c = ModbusClient(host=ip, port=502, auto_open=True, timeout=1) coil = idx + 16 c.write_single_coil(coil, args['state']) return (200)
def __init__(self, wbu_ip): self.wbu_ip = wbu_ip self.wbu_conn_handle = None # the handle made within the connection upon making the connection try: self.wbu_conn = ModbusClient(host=wbu_ip, port=502) except Error as e: logging.error(f"unable to make the connection to WBU: {e}") sys.exit()
class Traffic: beschikbaar = 0 adress = 0 rood_aan = 0b000100 geel_aan = 0b001000 groen_aan = 0b010000 gedoofd = 0b000000 time1 = time.time() def __init__(self): self.stand = 3 self.c = ModbusClient(host="192.168.3.135", port=502, auto_open=True) def getStatus(self): return self.beschikbaar def setStand(self, modus): self.stand = modus def update_light(self): if self.stand == 3: self.c.write_single_register(self.adress, self.rood_aan) elif self.stand == 1: self.c.write_single_register(self.adress, self.geel_aan) elif self.stand == 0: self.c.write_single_register(self.adress, self.groen_aan) elif self.stand == 4: self.c.write_single_register(self.adress, self.gedoofd) def afsluiten(self): while 1: time2 = time.time() - self.time1 if time2 < 3: self.setStand("geel_knipperen") elif 6 > time2 > 3: self.setStand("geel") elif time2 > 6: self.setStand("rood") break def normaal(self): while 1: time2 = time.time() - self.time1 if time2 < 3: self.setStand(2) #rood elif 13 > time2 > 3: self.setStand(0) #groen elif time2 > 13: self.setStand(4) break def checkError(self): if (self.c.close()): beschikbaar = 0 elif (self.c.open()): beschikbaar = 1
def setUp(self): # modbus server self.server = ModbusServer(port=TestClientServer.port, no_block=True) self.server.start() # modbus client self.client = ModbusClient(port=TestClientServer.port) self.client.open() # to prevent address taken errors TestClientServer.port += 1
def testPCL(): c = ModbusClient(host=getIpPLC(), port=getPortPLC(), auto_open=True) print(c) is_ok = c.write_single_coil(0, 1) print(is_ok) if is_ok: return "is ok" else: return "is not ok"
def doTest(): # TCP auto connect on modbus request, close after it c = ModbusClient(host="192.168.1.1", auto_open=True, auto_close=True) regs = c.read_holding_registers(0, 100) if regs: print(regs) else: print("read error")
def __init__(self): rospy.init_node("RobotArm") ip = rospy.get_param("/robot_ip") self.resetService = rospy.Service('/reset_robot', reset_errors, self.resetErrors) self.powerService = rospy.Service('/power_robot', power, self.powerCallback) self.teachService = rospy.Service("/teach_position", teach_position, self.teachCurrentToolPose) self.c = ModbusClient(host=ip, auto_open=True, auto_close=False, port=502, debug=False, unit_id=2) self.bits = 0 self.name = getpass.getuser()
def polling_thread(): global regs c = ModbusClient(host=SERVER_HOST, port=SERVER_PORT) # polling loop while True: # keep TCP open if not c.is_open(): c.open() # do modbus reading on socket reg_list = c.read_holding_registers(0, 10) # if read is ok, store result in regs (with thread lock synchronization) if reg_list: with regs_lock: regs = list(reg_list) # 1s before next polling time.sleep(1)
def connect(self): self.modbus_c = ModbusClient() self.modbus_c.host(self.client_host) self.modbus_c.port(self.client_port) if not self.modbus_c.is_open(): if not self.modbus_c.open(): text="unable to connect to " + self.client_host + ":" + str(self.client_port) print(text)
def polling_thd(): global regs, cycle_count, good_count, error_count c = ModbusClient(host='localhost', auto_open=True) # polling loop while True: # do modbus reading on socket reg_list = c.read_holding_registers(0, len(regs)) # if read is ok, store result in regs (with thread lock synchronization) with regs_lock: cycle_count += 1 if reg_list: regs = list(reg_list) good_count += 1 else: regs = [None] * 5 error_count += 1 # 1.0s before next polling time.sleep(1.0)
def polling_thread(): global regs, poll_cycle c = ModbusClient(host=args.host, port=args.port, unit_id=args.unit_id) # polling loop while True: # keep TCP open if not c.is_open(): c.open() # do modbus reading on socket reg_list = c.read_holding_registers(20610,20) # if read is ok, store result in regs (with thread lock synchronization) with regs_lock: if reg_list: regs = list(reg_list) poll_cycle += 1 else: poll_cycle = 0 # 1s before next polling time.sleep(0.2)
def __init__(self): self.lock = RLock() self.calibgui = None self.client = ModbusClient() self.register_values_widgets = {} self.counter = 1 self.find_thread = None self.obj_data = None self.stop_signal = False self.__build_ui()
def reader(worker, job): c = ModbusClient(host="localhost", port=502) if not c.is_open() and not c.open(): print("unable to connect to host") if c.is_open(): holdingRegisters = c.read_holding_registers(1, 4) # Imagine we've "energy" value in position 1 with two words energy = (holdingRegisters[0] << 16) | holdingRegisters[1] # Imagine we've "power" value in position 3 with two words power = (holdingRegisters[2] << 16) | holdingRegisters[3] out = {"energy": energy, "power": power} return json.dumps(out) return None
def test_host(self): # test valid/invalid cases for host() c = ModbusClient() self.assertEqual(c.host(), 'localhost', 'default host is localhost') self.assertEqual(c.host('wrong@host'), None) self.assertEqual(c.host('my.good.host'), 'my.good.host') self.assertEqual(c.host('127.0.0.1'), '127.0.0.1') self.assertEqual(c.host('::1'), '::1')
def test_host(self): # test valid/invalid cases for host() c = ModbusClient() self.assertEqual(c.host(), "localhost", "default host is localhost") self.assertEqual(c.host("wrong@host"), None) self.assertEqual(c.host("my.good.host"), "my.good.host") self.assertEqual(c.host("127.0.0.1"), "127.0.0.1") self.assertEqual(c.host("::1"), "::1")
def __init__(self, smarthome, gateway_ip, gateway_port=502, gateway_id=1, update_cycle=60): logger.info("Modbus: init plugin") self._sh = smarthome self._gateway_id = int(gateway_id) self._update_cycle = int(update_cycle) self._keylist = {} #self._client = ModbusTcpClient(gateway_ip,port=gateway_port) self._client = ModbusClient(host=gateway_ip, port=gateway_port, auto_open=True, auto_close=True) self._client.unit_id(2) self._client.debug(True) if not self._client.is_open(): if not self._client.open(): logger.error("Modbus: connection to gateway can not be established") else: logger.info("Modbus: connection to gateway established") self._client.close()
def connect(self): """ (re-) establish a connection to the device. """ if self.dev is None: self.dev = ModbusClient() self.dev.debug(self.debug) self.dev.host(self.host) self.dev.port(self.port) if self.dev.is_open(): return True ret = self.dev.open() if not ret: raise RuntimeError("failed to connect to %s:%s" % (self.host, self.port)) return True
def _read_config(self): self._ip = self._config.get('modbus_server_ip') self._port = self._config.get('modbus_port', ModbusTCPSensor.default_config['modbus_port']) self._debug = self._config.get('debug', 0) == 1 self._sample_rate = self._config.get('sample_rate', ModbusTCPSensor.default_config['sample_rate']) self._sensors = [] for sensor in self._config.get('sensors', []): if 0 <= sensor['sensor_id'] < 32: self._sensors.append(sensor) self._enabled = len(self._sensors) > 0 try: from pyModbusTCP.client import ModbusClient self._client = ModbusClient(self._ip, self._port, auto_open=True, auto_close=True) self._client.open() self._enabled = self._enabled & True except Exception as ex: self.logger('Error connecting to Modbus server: {0}'.format(ex)) self.logger('ModbusTCPSensor is {0}'.format('enabled' if self._enabled else 'disabled'))
class TestClientServer(unittest.TestCase): def setUp(self): # modbus server self.server = ModbusServer(port=5020, no_block=True) self.server.start() # modbus client self.client = ModbusClient(port=5020) self.client.open() def tearDown(self): self.client.close() def test_read_and_write(self): # word space self.assertEqual(self.client.read_holding_registers(0), [0], 'Default value is 0 when server start') self.assertEqual(self.client.read_input_registers(0), [0], 'Default value is 0 when server start') # single read/write self.assertEqual(self.client.write_single_register(0, 0xffff), True) self.assertEqual(self.client.read_input_registers(0), [0xffff]) # multi-write at max size words_l = [randint(0, 0xffff)] * 0x7b self.assertEqual(self.client.write_multiple_registers(0, words_l), True) self.assertEqual(self.client.read_holding_registers(0, len(words_l)), words_l) self.assertEqual(self.client.read_input_registers(0, len(words_l)), words_l) # write over sized words_l = [randint(0, 0xffff)] * 0x7c self.assertEqual(self.client.write_multiple_registers(0, words_l), None) # bit space self.assertEqual(self.client.read_coils(0), [False], 'Default value is False when server start') self.assertEqual(self.client.read_discrete_inputs(0), [False], 'Default value is False when server start') # single read/write self.assertEqual(self.client.write_single_coil(0, True), True) self.assertEqual(self.client.read_coils(0), [True]) self.assertEqual(self.client.read_discrete_inputs(0), [True]) # multi-write at min size bits_l = [getrandbits(1)] * 0x1 self.assertEqual(self.client.write_multiple_coils(0, bits_l), True) self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l) self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)), bits_l) # multi-write at max size bits_l = [getrandbits(1)] * 0x7b0 self.assertEqual(self.client.write_multiple_coils(0, bits_l), True) self.assertEqual(self.client.read_coils(0, len(bits_l)), bits_l) self.assertEqual(self.client.read_discrete_inputs(0, len(bits_l)), bits_l) # multi-write over sized bits_l = [getrandbits(1)] * 0x7b1 self.assertEqual(self.client.write_multiple_coils(0, bits_l), None)
class AmpSwitch(object): def __init__(self, host, port=502, switches=(), debug=False): """ """ self.host = host self.port = port self.debug = debug self.switches = switches self.dev = None self.connect() def __str__(self): return "AmpSwitch(host=%s, port=%s, dev=%s>" % (self.host, self.port, self.dev) def setDebug(self, state): self.debug = state self.connect() def close(self): if self.dev is not None: self.dev.close() self.dev = None def connect(self): """ (re-) establish a connection to the device. """ if self.dev is None: self.dev = ModbusClient() self.dev.debug(self.debug) self.dev.host(self.host) self.dev.port(self.port) if self.dev.is_open(): return True ret = self.dev.open() if not ret: raise RuntimeError("failed to connect to %s:%s" % (self.host, self.port)) return True def readCoils(self): """ Return the state of all our switches. """ self.connect() regs = self.dev.read_coils(0, 16) return regs def setCoils(self, on=(), off=()): """Turn on and off a given set of switches. Argunents --------- on, off : list-like, or a single integer. Notes: ------ The off set is executed first. . There is a command to change all switchees at once, but I have not made it work yet. """ self.connect() if isinstance(on, int): on = on, if isinstance(off, int): off = off, regs0 = self.readCoils() regs1 = regs0[:] for c in off: ret = self.dev.write_single_coil(c, False) regs1[c] = False for c in on: ret = self.dev.write_single_coil(c, True) regs1[c] = True # ret = self.dev.write_multiple_registers(0, regs1) ret = self.readCoils() return ret def chooseCoil(self, n): return self.setCoils(on=n, off=list(range(16)))
DEF_ID_ADDR = 26754 # parse args parser = argparse.ArgumentParser() parser.add_argument('ip_rtu', type=str, help='RTU IPv4 address (like 127.0.0.1)') parser.add_argument('-p', '--port_rtu', type=int, default=502, help='RTU port (default is %d)' % DEF_MB_PORT) parser.add_argument('id_str', type=str, help='ID string') parser.add_argument('-a', '--id_addr', type=int, default=DEF_ID_ADDR, help='ID address (default is %d)' % DEF_ID_ADDR) args = parser.parse_args() # init modbus client c = ModbusClient(host=args.ip_rtu, port=args.port_rtu) # open TCP link if not c.open(): print("unable to connect to " + args.ip_rtu + ":" + str(args.port_rtu)) sys.exit(1) # format id list (8 chars max) id_list = [ord(x) for x in args.id_str.ljust(8)][:8] # do modbus write print('write ID %s at @%d' % (id_list, args.id_addr)) regs = c.write_multiple_registers(args.id_addr, id_list) # print status if regs:
class modBusWriteRead(): def __init__(self,client_host): self.client_host = client_host self.client_port = 502 self.err_list = [] self.connect() #buradan bağlantı yapılacak; def connect(self): self.modbus_c = ModbusClient() self.modbus_c.host(self.client_host) self.modbus_c.port(self.client_port) if not self.modbus_c.is_open(): if not self.modbus_c.open(): text="unable to connect to " + self.client_host + ":" + str(self.client_port) print(text) def write_data_reg(self,address,list): if self.modbus_c.open(): if len(list)>120: sent_list = self.hazirla_dizi_to_write(list) i = 0 hedef_reg_taban = address for list_to_sent in sent_list: hedef_reg = hedef_reg_taban + (i * 120) a = self.modbus_c.write_multiple_registers(hedef_reg, list_to_sent) if a == None or a == False: self.err_list.append(False) i += 1 else: a = self.modbus_c.write_multiple_registers(address, list) if a == None or a == False: self.err_list.append(False) if len(self.err_list) > 0: self.err_list = [] pass # dikkat # print("data göndermede hata oluştu, tekrar deneyin !") def hazirla_dizi_to_write(self,d_list): # eğer gönderilecek değer 120 den büyük ise aşağıdaki fonksiyon 120 lik diziler döndürüyor r_list = [] g_list = [] i = 0 for index in range(len(d_list)): g_list.append(d_list[index]) i += 1 if i > 119: i = 0 r_list.append(g_list) g_list = [] if (len(d_list) - 1) == index and i < 119: r_list.append(g_list) return r_list def read_data_reg(self,address,reg_count,read_float=False ): # burada 16 lık ya da float olarak okunabiliyor if self.modbus_c.is_open(): if read_float == False: plc_list_int = self.modbus_c.read_holding_registers(address, reg_count) return plc_list_int elif read_float == True: plc_list_f_16=self.modbus_c.read_holding_registers(address,reg_count) if plc_list_f_16 is not None: plc_list_float=self.long_to_float(plc_list_f_16) return plc_list_float def long_to_float(self,list_16): list_float=[] list_16.reverse() list_long=utils.word_list_to_long(list_16) for any_long in list_long: list_float.append(utils.decode_ieee(any_long)) list_float.reverse() return list_float
from __future__ import division import atexit import time import sys from math import * from multiprocessing import * from mpu6050_process_1 import MPU6050_Process_1 from mpu6050_process_2 import MPU6050_Process_2 from pyModbusTCP.client import ModbusClient with Manager() as manager: # Open a modbus client try: c = ModbusClient(host="140.116.82.50", port=7654) except ValueError: print("Error with host or port params") c.open() is_ok = c.write_single_register(0, 1) if not is_ok: print("open error") c.open() def exit_handler(): is_ok = c.write_multiple_registers(0, [0, 0, 0, 0, 0]) c.close() # registing exit handler atexit.register(exit_handler)
def __init__(self): self.client = ModbusClient()
print("\nWrote Register") time.sleep(0.5) if __name__ == "__main__": host = input("\nPlease enter IP address [127.0.0.1]: ") port = input("Please enter port [502]: ") if not host: host = "172.16.143.146" if not port: port = 502 c = ModbusClient(timeout=5) c.host(host) c.port(port) for attempt in range(3): print("\nTrying to connect to " + host + ":" + str(port) + "... Attempt " + str(attempt+1)) if c.open(): print("\nSuccessful Connection") failedconnection = False time.sleep(0.5) choice = "" while choice != "q": choice = input("\nPress \n[r] to Read \n[w] to Write \n[q] to Quit: ") if choice == "r": print("\nChose Read") read_regs()
#!/usr/bin/env python # -*- coding: utf-8 -*- # write_bit # write 4 bits to True, wait 2s, write False, restart... from pyModbusTCP.client import ModbusClient import time SERVER_HOST = "localhost" SERVER_PORT = 502 c = ModbusClient() # uncomment this line to see debug message #c.debug(True) # define modbus server host, port c.host(SERVER_HOST) c.port(SERVER_PORT) toggle = True while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT)) # if open() is ok, write coils (modbus function 0x01) if c.is_open():
def test_port(self): # test valid/invalid cases for port() c = ModbusClient() self.assertEqual(c.port(), 502, 'default modbus/TCP port is 502') self.assertEqual(c.port(-1), None) self.assertEqual(c.port(42), 42)
def test_debug(self): # test valid/invalid cases for debug() c = ModbusClient() self.assertEqual(c.debug(), False, 'debug default is off') self.assertEqual(c.debug(False), False) self.assertEqual(c.debug(True), True)
def __init__(self, host, port, unit): self.client = ModbusClient(host, port, unit, timeout=3)
#!/usr/bin/env python # -*- coding: utf-8 -*- import time # min_read_bit # minimal code for read 10 bits on IPv4 192.168.0.200 and print result on stdout from pyModbusTCP.client import ModbusClient c = ModbusClient(host="192.168.0.200", auto_open=True) while True: # read 10 bits at address 20480 bits = c.read_coils(20480, 10) print("bit ad #0 to 9: "+str(bits) if bits else "read error") # sleep 2s time.sleep(2)
from pyModbusTCP.client import ModbusClient import time if __name__ == "__main__": host = input("\nPlease enter IP address [127.0.0.1]: ") port = input("Please enter port [502]: ") if not host: host = "172.16.143.146" if not port: port = 502 c = ModbusClient(timeout=5) c.host(host) c.port(port) print("\nTrying to connect to " + host + ":" + str(port)) if c.open(): print("Opened") print(c.is_open()) if c.close(): print("Closed") print(c.is_open())
from pyModbusTCP.client import ModbusClient import time SERVER_HOST = "192.168.0.104" SERVER_PORT = 502 c = ModbusClient() # uncomment this line to see debug message #c.debug(True) # define modbus server host, port c.host(SERVER_HOST) c.port(SERVER_PORT) while True: # open or reconnect TCP to server if not c.is_open(): if not c.open(): print("unable to connect to "+SERVER_HOST+":"+str(SERVER_PORT)) # if open() is ok, read register (modbus function 0x03) if c.is_open(): print c.write_single_register(544, 220) # sleep 2s before next polling time.sleep(2)