def _init_modbus(self, ): """modbusServer初始化 Returns: server -- server服务器 slave -- 从机 """ # 钩子 hooks.install_hook('modbus.Slave.handle_write_multiple_registers_request', self._handle_write_multiple_registers_request) hooks.install_hook('modbus.Slave.handle_write_single_register_request', self._handle_write_single_registers_request) # 初始化 server = modbus_tcp.TcpServer(address='0.0.0.0', port=PORT) # 服务启动 server.start() # 建立从机 slave = server.add_slave(SLAVE_ID) # 建立块 # slave.add_block('0', cst.DISCRETE_INPUTS, 0, 100) # slave.add_block('0', cst.COILS, 0, 100) slave.add_block(SYS_ANALOG_INPUTS_BLOCK_NAME, cst.ANALOG_INPUTS, SYS_ANALOG_INPUTS_BLOCK_ADDRESS, 171) slave.add_block(SYS_HOLDING_REGISTERS_BLOCK_NAME, cst.HOLDING_REGISTERS, SYS_HOLDING_REGISTERS_BLOCK_ADDRESS, 6) # slave.add_block(HIDDEN_HOLDING_REGISTERS_BLOCK_NAME, cst.HOLDING_REGISTERS, 5999, 20) return server, slave
def ModSvrFactory(args): """ modFactory : rtu or tcp server holding several slaves """ logger = logging.getLogger("modbus_tk") _svr = None if args[0]=='-tcp': logger.info("Build TCP Server - {0}:{1}".format(args[2],args[1])) try : # remove extra zeros from ip addr _ip = args[2] _ip = _ip.split('.') _ip = str(int(_ip[0])) + "." + str(int(_ip[1])) + "." + str(int(_ip[2])) + "." + str(int(_ip[3])) _svr = modbus_tcp.TcpServer(int(args[1]), _ip) except Exception as err: logger.error("Error while building TCP Server : {0}".format(err)) elif args[0]=='-rtu': logger.info("Build RTU Server - Port: {0}, Baudrate: {1}, Bytesize: {2}, Parity: {3}, Stopbits : {4}" .format(args[1],args[2],args[3],args[4],args[5])) try: _svr = modbus_rtu.RtuServer(serial.Serial(port=args[1], baudrate=int(args[2]), bytesize=int(args[3]), parity=args[4], stopbits=float(args[5]), xonxoff=0)) except Exception as err: logger.error("Error while building RTU Server : {0}".format(err)) else: logger.error("Wrong arguments") return _svr
def testGetRequestLength(self): """Test than _get_request_length returns the length field of request mbap""" s = modbus_tcp.TcpServer() request = struct.pack(">HHHB", 0, 0, 12, 1) self.assertEqual(s._get_request_length(request), 12) request = struct.pack(">HHH", 0, 0, 129) self.assertEqual(s._get_request_length(request), 129)
def testGetRequestLengthFailsOnInvalid(self): """Test than an error is raised in _get_request_length is the length field of request mbap is not filled""" s = modbus_tcp.TcpServer() request = struct.pack(">HHB", 0, 0, 1) self.assertRaises(modbus_tk.modbus.ModbusInvalidRequestError, s._get_request_length, request) self.assertRaises(modbus_tk.modbus.ModbusInvalidRequestError, s._get_request_length, "")
def create_client(self, block_name): client = modbus_tcp.TcpServer(address=self.host, port=self.port) client.start() server = client.add_slave(self.slave) logger.info('create block_name: %s ,slave: %s ' % (block_name, self.slave)) # server.add_block(block_name, cst.HOLDING_REGISTERS, self.register, 4) self.server = server return self
def start_service(self): self._running = True self.threadrx = threading.Thread(target=self.uart_read_thread) self.threadrx.start() self.threadtx = threading.Thread(target=self.uart_write_thread) self.threadtx.start() self._mdbus = modbus_tcp.TcpServer() self._mdbus.start() self._mdbus1 = self._mdbus.add_slave(1) self._mdbus1.add_block('0', cst.HOLDING_REGISTERS, 0, self._reg_size) self._slave = self._mdbus.get_slave(1) logging.info('MODBUS service is started')
def main(): try: server = modbus_tcp.TcpServer(address='127.0.0.1', port=8502) server.start() sistema = PumpSys(server) while True: sistema.update() time.sleep(0.1) os.system('clear') finally: server.stop()
def __init__(self, listen_Address, listen_Port): ##Creates the server self.server = modbus_tcp.TcpServer(address=listen_Address, port=listen_Port) ##Creates a slave object self.slave = self.server.add_slave(255) ##Adding 10 HOLDING_REGISTERS, values = 0 self.slave.add_block('0', cst.HOLDING_REGISTERS, 1, 10) ##Adding 100 COILS, values = 0 #self.slave.add_block('1', cst.COILS, 1, 100) ##Creates socket, bind and listen self.server._do_init() print "Sensor_L is running..."
def start(self): """Starts modbus' server adapter interface. """ try: self.tcp_server = modbus_tcp.TcpServer() self.tcp_server.start() self.running = True return self.running except: self._logger.error("Some error occurred while \ creating a new tcp_server") self.tcp_server.stop() self.running = False return self.running
def __init__(ad, pt): """ 设置服务器地址、端口号 启动服务器 设置从机集合 """ global __logger__ global __server__ global __slaveList__ __logger__ = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") __server__ = modbus_tcp.TcpServer(address=ad, port=pt) __logger__.info("running...") __logger__.info("enter 'quit' for closing the server") __server__.start() __slaveList__ = list()
def __init__(self, options): self.rtu = None self.mode = options.mode if options.mode == 'rtu': self.rtu = serial.Serial(port=options.serial, baudrate=options.baud) # Simulator.__init__(self, modbus_rtu.RtuServer(self.rtu)) Simulator.__init__(self, ModSimRtuServer(self.rtu)) # timeout is too fast for 19200 self.server._serial.timeout = self.server._serial.timeout * 1.5 elif options.mode == 'tcp': Simulator.__init__( self, modbus_tcp.TcpServer(address='', port=options.port)) else: raise ModSimError('Unknown mode: %s' % (options.mode)) self.server.set_verbose(options.verbose)
def __init__(self, Address, Port, option): ##Option 1 is used to create a server instance if option == 1: #Create the server self.server = modbus_tcp.TcpServer(address=Address,port=Port) #create a slave object self.slave = self.server.add_slave(255) #adding 100 HOLDING_REGISTERS, values = 0 self.slave.add_block('0', cst.HOLDING_REGISTERS, 1, 100) #adding 100 COILS, values = 0 self.slave.add_block('1', cst.COILS, 1, 100) # create socket, bind and listen self.server._do_init() ## Option 2 is used to create a client instance elif option == 2: self.target_Address=Address self.target_port=Port
def main(): slaveid = 1 logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") GPIO.setmode(GPIO.BCM) GPIO.setup(13, GPIO.OUT, initial=GPIO.HIGH) try: # get ip address gw = os.popen("ip -4 route show default").read().split() print("gw", gw) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # gate is 255.255.255.0 s.connect((gw[2], 0)) ipaddr = s.getsockname()[0] print("IP:", ipaddr) s.close() GPIO.output(13, GPIO.LOW) time.sleep(1) server = modbus_tcp.TcpServer(address=ipaddr, port=502) logger.info("esimtech modbus server running...") logger.info("enter 'quit' for closing the server") server.start() slave_1 = server.add_slave(slaveid) slave_1.add_block('HOLDING_REGISTERS', cst.HOLDING_REGISTERS, 0, 16) slave_1.add_block('DISCRETE_INPUTS', cst.DISCRETE_INPUTS, 0, 32) slave_1.add_block('READ_INPUT_REGISTERS', cst.READ_INPUT_REGISTERS, 0, 11) slave_1.add_block('COILS', cst.COILS, 0, 32) pcontroller = modbusserver(server, slaveid) while True: if GPIO.input(7) == GPIO.LOW: pcontroller.sendtomcu() pcontroller.recvmcu() time.sleep(0.01) finally: server.stop() GPIO.cleanup()
def sercreate(self, _slaveid, _localip, _port, _fuc): try: #Create the server #server = modbus_tcp.TcpServer(address=_localip,port=_port) server = modbus_tcp.TcpServer() logger.info("running...") #logger.info("enter 'quit' for closing the server") server.start() print('server start..') slave_1 = server.add_slave(_slaveid) print(_slaveid) #slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 100) slave_1.add_block('0', _fuc, 0, 100) senreader = Senreader_Thread(1, "Thread-1", server) senreader.start() except: print('server create fail')
def main(): try: logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") server = modbus_tcp.TcpServer( address=os.environ.get('SLAVE_IP', '0.0.0.0'), port=int(os.environ.get('SLAVE_PORT', '5022'))) server.start() slaves.create(server, logger) while True: try: time.sleep(1) except Exception as e: print(e) break finally: server.stop() logger.error('Slave stopped.')
def __init__(self): """ 创建字典存放通讯数据 """ self.l3_dict = {} self.wincc_dict = {} self.car_dict = {} self.h3u_dict = {} self.mis_dict = {} self.modbussever = modbus_tcp.TcpServer(port=local_port) # 初始化mosbus self.master = modbus_tcp.TcpMaster(host=h3u_host, port=h3u_port) self.sockt_mis = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 初始化 self.snap7client_one = snap7.client.Client() # 1号行车初始化 self.snap7client_two = snap7.client.Client() # 2#行车初始化 self.one_real_sign = 0 self.one_turn_sign = 0 self.one_stop_sign = 0 self.l2_heart_beat = 0 print(111)
def robotComunicate(): logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") try: # Create the server server = modbus_tcp.TcpServer(address="0.0.0.0", port=8080) # server.set_timeout(5.0) logger.info("running...") logger.info("enter 'quit' for closing the server") server.start() slave_1 = server.add_slave(1) slave_1.add_block('A', cst.HOLDING_REGISTERS, 0, 1) slave_1.set_values('A', 0, 0) numsOfcom = 0 while numsOfcom < 3: slave_1.set_values('A', 0, 1) # 改变在地址0处的寄存器的值 print("==========发送" + str(numsOfcom + 1) + "次数据==========") numsOfcom += 1 time.sleep(1) slave_1.set_values('A', 0, 2) finally: server.stop()
#!/usr/bin/env python # -*- coding: utf_8 -*- import modbus_tk import modbus_tk.modbus_tcp as modbus_tcp import threading import modbus_tk.defines as mdef logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") server = modbus_tcp.TcpServer() #creates a slave with id 0 slave1 = server.add_slave(1) #add 2 blocks of holding registers slave1.add_block("a", mdef.HOLDING_REGISTERS, 0, 100) #address 0, length 100 slave1.add_block("b", mdef.HOLDING_REGISTERS, 200, 20) #address 200, length 20 #creates another slave with id 5 slave5 = server.add_slave(5) slave5.add_block("c", mdef.COILS, 0, 100) slave5.add_block("d", mdef.HOLDING_REGISTERS, 0, 100) #set the values of registers at address 0 slave1.set_values("a", 0, range(100)) server.start()
def setUp(self): self.server = modbus_tcp.TcpServer() self.master = modbus_tcp.TcpMaster()
def _get_server(self): return modbus_tcp.TcpServer()
def main(): """main""" logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") try: #Create the server server = modbus_tcp.TcpServer() logger.info("running...") logger.info("enter 'quit' for closing the server") server.start() slave_1 = server.add_slave(1) slave_1.add_block('0', cst.HOLDING_REGISTERS, 0, 100) while True: cmd = sys.stdin.readline() args = cmd.split(' ') if cmd.find('quit') == 0: sys.stdout.write('bye-bye\r\n') break elif args[0] == 'add_slave': slave_id = int(args[1]) server.add_slave(slave_id) sys.stdout.write('done: slave %d added\r\n' % slave_id) elif args[0] == 'add_block': slave_id = int(args[1]) name = args[2] block_type = int(args[3]) starting_address = int(args[4]) length = int(args[5]) slave = server.get_slave(slave_id) slave.add_block(name, block_type, starting_address, length) sys.stdout.write('done: block %s added\r\n' % name) elif args[0] == 'set_values': slave_id = int(args[1]) name = args[2] address = int(args[3]) values = [] for val in args[4:]: values.append(int(val)) slave = server.get_slave(slave_id) slave.set_values(name, address, values) values = slave.get_values(name, address, len(values)) sys.stdout.write('done: values written: %s\r\n' % str(values)) elif args[0] == 'get_values': slave_id = int(args[1]) name = args[2] address = int(args[3]) length = int(args[4]) slave = server.get_slave(slave_id) values = slave.get_values(name, address, length) sys.stdout.write('done: values read: %s\r\n' % str(values)) else: sys.stdout.write("unknown command %s\r\n" % args[0]) finally: server.stop()
def startTcpListener(self, ): server = modbus_tcp.TcpServer(address=self.hostName, port=int(self.port)) server.start() self.server = server
config = configparser.ConfigParser() config.read('config.ini') # mqtt configure MQTT_ServerIP = config['General']['Datalake_IP'] MQTT_ServerPort = 1883 # int(config['General']['MQTT_ServerPort']) MQTT_SubTopic = config['Algorithm']['topic'] # modbus modbus_ip = config['Modbus']['ip'] modbus_port = 502 # int(config['Modbus']['port']) modbus_slave = int(config['Modbus']['slaveID']) modbus_dataCnt = int(config['Modbus']['data_cnt']) # Create server server = modbus_tcp.TcpServer(address=modbus_ip, port=modbus_port) # Default port = 502 slaver = server.add_slave(modbus_slave) # Slave_ID = 1 data = 0 print("===========================") print("Data lake IP: {}".format(MQTT_ServerIP)) print("S_Topic: {}".format(MQTT_SubTopic)) print("\n===========================") print("Modbus IP: {}".format(modbus_ip)) print("Modbus SlaveID: {}".format(modbus_slave)) print("Modbus Data Count: {}".format(modbus_dataCnt)) ''' mqtt '''
b1 = 0xff80 & j[0] b1 |= (0x000f & j[0]) << 3 b1 |= (0x7000 & j[1]) >> 13 b2 = 0xffff & (j[1] << 3) b2 |= (0x7000 & j[2]) >> 13 slave_1.set_values("ro", addr, [b1, b2]) """ return val if __name__ == "__main__": try: """ Initialize the MODBUS TCP slave """ mb_start = 40001 mb_len = 100 server = modbus_tcp.TcpServer(address='0.0.0.0') server.start() slave_1 = server.add_slave(1) slave_1.add_block('ro', cst.HOLDING_REGISTERS, mb_start, mb_len) # Example: modpoll -0 -m tcp -t 4:float -r 40001 -c 46 192.168.x.x """ Initialize AIO """ # Set to your Adafruit IO key. # Remember, your key is a secret, # so make sure not to publish it when you publish this code! ADAFRUIT_IO_KEY = 'YOUR_AIO_KEY' # Set to your Adafruit IO username. # (go to https://accounts.adafruit.com to find your username) ADAFRUIT_IO_USERNAME = '******' aio = MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) aio.connect()
def main(): """main""" slaveid = 1 logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") try: # get current ipaddr # gw = os.popen("ip -4 route show default").read().split() # s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # # s.settimeout(CHECK_TIMEOUT) # s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # # S.bind(('', UDP_PORT)) # s.connect((gw[2], 0)) # ipaddr = s.getsockname()[0] # print("IP:", ipaddr) # s.close() # time.sleep(1) # ipaddr = "192.168.1.112" ipaddr = os.popen( "ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1" ).read() print("IP:", ipaddr) # Create the server # server = modbus_tcp.TcpServer(address='192.168.1.111') server = modbus_tcp.TcpServer(address=ipaddr) logger.info("esimtech modbus server running...") logger.info("enter 'quit' for closing the server") server.start() slave_1 = server.add_slave(slaveid) slave_1.add_block('HOLDING_REGISTERS', cst.HOLDING_REGISTERS, 0, 16) slave_1.add_block('DISCRETE_INPUTS', cst.DISCRETE_INPUTS, 0, 16) slave_1.add_block('READ_INPUT_REGISTERS', cst.READ_INPUT_REGISTERS, 0, 16) slave_1.add_block('COILS', cst.COILS, 0, 16) # 初始化HOLDING_REGISTERS值 # 命令行读取COILS的值 get_values 1 2 0 5 init_value = 0x0 length = 16 init_value_list = [init_value] * length slave = server.get_slave(1) slave.set_values('HOLDING_REGISTERS', 0, init_value_list) # init mcp23s17 mcp_u1 = MCP23S17(bus=0x00, ce=0x00, deviceID=0x00) mcp_u2 = MCP23S17(bus=0x00, ce=0x00, deviceID=0x01) mcp_u3 = MCP23S17(bus=0x00, ce=0x00, deviceID=0x02) mcp_u1.open() mcp_u2.open() mcp_u3.open() for x in range(0, 16): mcp_u1.setDirection(x, mcp_u1.DIR_INPUT) mcp_u1.setPullupMode(x, mcp_u1.PULLUP_ENABLED) mcp_u2.setDirection(x, mcp_u2.DIR_OUTPUT) # status led mcp_u3.setDirection(13, mcp_u3.DIR_OUTPUT) mcp_u3.setPullupMode(13, mcp_u3.PULLUP_ENABLED) thread_1 = InputLoopThread(server, slaveid, mcp_u1) thread_1.start() thread_2 = OutputLoopThread(server, slaveid, mcp_u2) thread_2.start() thread_3 = StatusHoldingThread(ipaddr, q, mcp_u3) thread_3.start() # block here until get message q.get(True) print("restart program") # restart_program() thread_1.stop() thread_2.stop() thread_3.stop() server.stop() GPIO.cleanup() time.sleep(1) python = sys.executable os.execl(python, python, *sys.argv) # thread_3.join() # while True: # cmd = sys.stdin.readline() # args = cmd.split(' ') # # if cmd.find('quit') == 0: # sys.stdout.write('bye-bye\r\n') # break # # elif args[0] == 'add_slave': # slave_id = int(args[1]) # server.add_slave(slave_id) # sys.stdout.write('done: slave %d added\r\n' % slave_id) # # elif args[0] == 'add_block': # slave_id = int(args[1]) # name = args[2] # block_type = int(args[3]) # starting_address = int(args[4]) # length = int(args[5]) # slave = server.get_slave(slave_id) # slave.add_block(name, block_type, starting_address, length) # sys.stdout.write('done: block %s added\r\n' % name) # # elif args[0] == 'set_values': # slave_id = int(args[1]) # name = args[2] # address = int(args[3]) # values = [] # for val in args[4:]: # values.append(int(val)) # slave = server.get_slave(slave_id) # slave.set_values(name, address, values) # values = slave.get_values(name, address, len(values)) # sys.stdout.write('done: values written: %s\r\n' % str(values)) # # elif args[0] == 'get_values': # slave_id = int(args[1]) # name = args[2] # address = int(args[3]) # length = int(args[4]) # slave = server.get_slave(slave_id) # values = slave.get_values(name, address, length) # sys.stdout.write('done: values read: %s\r\n' % str(values)) # # else: # sys.stdout.write("unknown command %s\r\n" % args[0]) finally: thread_1.stop() thread_2.stop() thread_3.stop() server.stop() GPIO.cleanup()
def __init__(self): self.Logger = utils.create_logger( name="console") # record_format="%(message)s" self.server = modbus_tcp.TcpServer() # address="192.168.8.25"
def setUp(self): self.server = modbus_tcp.TcpServer()
import time import sys import logging import threading import modbus_tk import modbus_tk.defines as cst import modbus_tk.modbus as modbus import modbus_tk.modbus_tcp as modbus_tcp import random LOGGER = modbus_tk.utils.create_logger(name="console", record_format="%(message)s") if __name__ == "__main__": try: SERVER = modbus_tcp.TcpServer(address="127.0.0.1", port=502) # connection set up LOGGER.info("running...") SERVER.start() # server started LOGGER.info("server started") SLAVE1 = SERVER.add_slave(1) SLAVE1.add_block('A', cst.HOLDING_REGISTERS, 0, 4) # add block function LOGGER.info("SLAVE1 add_slave") SLAVE1.set_values('A', 0, 10*[0]) # set value function LOGGER.info("SLAVE1 set_values") finally: SERVER.stop()
logger = modbus_tk.utils.create_logger('console') # import string print('============================================================') print('MODBUS TCP Simulator V1.2 (20200415)') #ipp=input('Please input your server IP, then press "ENTER" : ') #Set host IP ppo = input('Please input your MODBUS/TCP port, then press "ENTER" :' ) #Set MODBUS/TCP port sIP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #auto to get host IP sIP.connect(("8.8.8.8", 80)) print('The MODBUS/TCP server IP= {}, Start!'.format(sIP.getsockname()[0])) print('============================================================') ipp = sIP.getsockname()[0] print('Polls / 4X / 0X ') sIP.close() try: server = modbus_tcp.TcpServer(port=int(ppo), address=ipp, timeout_in_sec=3) master = modbus_tcp.TcpMaster(ipp, int(ppo)) master.set_timeout(3.0) server.start() slaveID1 = server.add_slave(2) slaveID1.add_block('block1', mtk.HOLDING_REGISTERS, 0, 6) slaveID2 = server.add_slave(3) slaveID2.add_block('block2', mtk.COILS, 0, 6) logger.info('MODBUS TCP Server Start!') count = 0 while True: time.sleep(1) count += 1 HV001 = random.randint(0, 65535) HV002 = random.randint(0, 65535) HV003 = random.randint(0, 65535)
def __init__(self): self.slave1 = None self.modbussever = modbus_tcp.TcpServer( port=local_port) # address=''默认表示获取本机地址 self.heart_beat = 0