def testSerialAsyncioClient(self, mock_gather, mock_event_loop, method, framer): """ Test that AsyncModbusSerialClient instantiates AsyncioModbusSerialClient for asyncio scheduler. :return: """ loop = asyncio.get_event_loop() loop.is_running.side_effect = lambda: False loop, client = AsyncModbusSerialClient(schedulers.ASYNC_IO, method=method, port=SERIAL_PORT, loop=loop, baudrate=19200, parity='E', stopbits=2, bytesize=7) assert (isinstance(client, AsyncioModbusSerialClient)) assert (isinstance(client.framer, framer)) assert (client.port == SERIAL_PORT) assert (client.baudrate == 19200) assert (client.parity == 'E') assert (client.stopbits == 2) assert (client.bytesize == 7) client.stop() loop.stop()
def testSerialTwistedClient(self, method, framer): """ Test the serial twisted client client initialize """ from serial import Serial with patch("serial.Serial") as mock_sp: from twisted.internet import reactor from twisted.internet.serialport import SerialPort with patch('twisted.internet.reactor') as mock_reactor: protocol, client = AsyncModbusSerialClient(schedulers.REACTOR, method=method, port=SERIAL_PORT, proto_cls=ModbusSerClientProtocol) assert (isinstance(client, SerialPort)) assert (isinstance(client.protocol, ModbusSerClientProtocol)) assert (0 == len(list(client.protocol.transaction))) assert (isinstance(client.protocol.framer, framer)) assert (client.protocol._connected) def handle_failure(failure): assert (isinstance(failure.exception(), ConnectionException)) d = client.protocol._buildResponse(0x00) d.addCallback(handle_failure) assert (client.protocol._connected) client.protocol.close() protocol.stop() assert (not client.protocol._connected)
def testSerialTwistedClient(self, method, framer): """ Test the serial tornado client client initialize """ from serial import Serial with patch("serial.Serial") as mock_sp: from twisted.internet import reactor from twisted.internet.serialport import SerialPort with patch('twisted.internet.reactor') as mock_reactor: protocol, client = AsyncModbusSerialClient(schedulers.REACTOR, method=method, port=SERIAL_PORT, proto_cls=ModbusSerClientProtocol) assert (isinstance(client, SerialPort)) assert (isinstance(client.protocol, ModbusSerClientProtocol)) assert (0 == len(list(client.protocol.transaction))) assert (isinstance(client.protocol.framer, framer)) assert (client.protocol._connected) def handle_failure(failure): assert (isinstance(failure.exception(), ConnectionException)) d = client.protocol._buildResponse(0x00) d.addCallback(handle_failure) assert (client.protocol._connected) client.protocol.close() protocol.stop() assert (not client.protocol._connected)
def testSerialTornadoClient(self, method, framer): """ Test the serial tornado client client initialize """ from serial import Serial with maybe_manage(sys.platform in ('darwin', 'win32'), patch.object(Serial, "open")): protocol, future = AsyncModbusSerialClient(schedulers.IO_LOOP, method=method, port=SERIAL_PORT) client = future.result() assert (isinstance(client, AsyncTornadoModbusSerialClient)) assert (0 == len(list(client.transaction))) assert (isinstance(client.framer, framer)) assert (client.port == SERIAL_PORT) assert (client._connected) def handle_failure(failure): assert (isinstance(failure.exception(), ConnectionException)) d = client._build_response(0x00) d.add_done_callback(handle_failure) assert (client._connected) client.close() protocol.stop() assert (not client._connected)
def testSerialAsyncioClientPython2(self): """ Test Serial asynchronous asyncio client exits on python2 :return: """ with pytest.raises(SystemExit) as pytest_wrapped_e: AsyncModbusSerialClient(schedulers.ASYNC_IO, method="rtu", port=SERIAL_PORT) assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 1
def testSerialTornadoClient(self, method, framer): """ Test the serial tornado client client initialize """ protocol, future = AsyncModbusSerialClient(schedulers.IO_LOOP, method=method, port=SERIAL_PORT) client = future.result() assert(isinstance(client, AsyncTornadoModbusSerialClient)) assert(0 == len(list(client.transaction))) assert(isinstance(client.framer, framer)) assert(client.port == SERIAL_PORT) assert(client._connected) def handle_failure(failure): assert(isinstance(failure.exception(), ConnectionException)) d = client._build_response(0x00) d.add_done_callback(handle_failure) assert(client._connected) client.close() protocol.stop() assert(not client._connected)
def testSerialTornadoClient(self, method, framer): """ Test the serial tornado client client initialize """ protocol, future = AsyncModbusSerialClient(schedulers.IO_LOOP, method=method, port=SERIAL_PORT) client = future.result() assert(isinstance(client, AsyncTornadoModbusSerialClient)) assert(0 == len(list(client.transaction))) assert(isinstance(client.framer, framer)) assert(client.port == SERIAL_PORT) assert(client._connected) def handle_failure(failure): assert(isinstance(failure.exception(), ConnectionException)) d = client._build_response(0x00) d.add_done_callback(handle_failure) assert(client._connected) client.close() protocol.stop() assert(not client._connected)
:param response: The response to process """ log.info(response.getBit(0)) log.info(response.getBit(1)) log.info(response.getBit(2)) reactor.callLater(CLIENT_DELAY, self.fetch_holding_registers) def error_handler(self, failure): """ Handle any twisted errors :param failure: The error to handle """ log.error(failure) if __name__ == "__main__": proto, client = AsyncModbusSerialClient( schedulers.REACTOR, method="rtu", port=SERIAL_PORT, baudrate=115200, # parity='O', # bytesize=8, # stopbits=1, # timeout=2, proto_cls=ExampleProtocol) #client.inter_char_timeout = 0.1 proto.start() # proto.stop()
adress_register = 0x0 # 起始寄存器 length_data = 0x40 # 数据长度 HEX= adress_gateway = 0x1 # 云盒地址 rr = await client.read_holding_registers(adress_register, length_data, unit=adress_gateway) print('rr: %s' % repr(rr.registers)) print(len(rr.registers)) # assert(rq.function_code < 0x80) # 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 Exception as e: log.exception(e) client.transport.close() await asyncio.sleep(1) if __name__ == '__main__': # ----------------------------------------------------------------------- # # For testing on linux based systems you can use socat to create serial # ports # ----------------------------------------------------------------------- # # socat -d -d PTY,link=/tmp/ptyp0,raw,echo=0,ispeed=9600 PTY, # link=/tmp/ttyp0,raw,echo=0,ospeed=9600 loop, client = ModbusClient(schedulers.ASYNC_IO, port='COM2', baudrate=115200, method="rtu") loop.run_until_complete(start_async_test(client.protocol)) loop.close()
d.addCallbacks(self.start_next_cycle, self.error_handler) def start_next_cycle(self, response): """ Write values of coils, trigger next cycle :param response: The response to process """ print(response) log.info(response.getBit(0)) log.info(response.getBit(1)) log.info(response.getBit(2)) reactor.callLater(CLIENT_DELAY, self.fetch_holding_registers) def error_handler(self, failure): """ Handle any twisted errors :param failure: The error to handle """ log.error(failure) if __name__ == "__main__": proto, client = AsyncModbusSerialClient(schedulers.REACTOR, method="rtu", baudrate=sys.argv[2], port=sys.argv[1], timeout=2, proto_cls=ExampleProtocol) proto.start() # proto.stop()
arguments = { 'read_address': 1, 'read_count': 8, 'write_address': 1, 'write_registers': [20]*8, } log.debug("Read write registers simulataneously") rq = await client.readwrite_registers(unit=UNIT, **arguments) rr = await client.read_holding_registers(1, 8, unit=UNIT) assert(rq.function_code < 0x80) # 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 Exception as e: log.exception(e) client.transport.close() await asyncio.sleep(1) if __name__ == '__main__': # ----------------------------------------------------------------------- # # For testing on linux based systems you can use socat to create serial # ports # ----------------------------------------------------------------------- # # socat -d -d PTY,link=/tmp/ptyp0,raw,echo=0,ispeed=9600 PTY, # link=/tmp/ttyp0,raw,echo=0,ospeed=9600 loop, client = ModbusClient(schedulers.ASYNC_IO, port='/tmp/ptyp0', baudrate=9600, method="rtu") loop.run_until_complete(start_async_test(client.protocol)) loop.close()
d.addCallbacks(self.start_next_cycle, self.error_handler) def start_next_cycle(self, response): """ Write values of coils, trigger next cycle :param response: The response to process """ log.info(response.getBit(0)) log.info(response.getBit(1)) log.info(response.getBit(2)) reactor.callLater(CLIENT_DELAY, self.fetch_holding_registers) def error_handler(self, failure): """ Handle any twisted errors :param failure: The error to handle """ log.error(failure) if __name__ == "__main__": proto, client = AsyncModbusSerialClient(schedulers.REACTOR, method="rtu", port=SERIAL_PORT, timeout=2, proto_cls=ExampleProtocol) proto.start() # proto.stop()
d.addCallbacks(self.start_next_cycle, self.error_handler) def start_next_cycle(self, response): """ Write values of coils, trigger next cycle :param response: The response to process """ log.info(response.getBit(0)) log.info(response.getBit(1)) log.info(response.getBit(2)) reactor.callLater(CLIENT_DELAY, self.fetch_holding_registers) def error_handler(self, failure): """ Handle any twisted errors :param failure: The error to handle """ log.error(failure) if __name__ == "__main__": import time proto, client = AsyncModbusSerialClient(schedulers.REACTOR, method="rtu", port=SERIAL_PORT, timeout=2, proto_cls=ExampleProtocol) proto.start() time.sleep(10) # Wait for operation to complete # proto.stop()
if __name__ == "__main__": # ----------------------------------------------------------------------- # # Create temporary serial ports using SOCAT # socat -d -d PTY,link=/tmp/ptyp0,raw,echo=0,ispeed=9600 PTY, # link=/tmp/ttyp0,raw,echo=0,ospeed=9600 # Default framer is ModbusRtuFramer # ----------------------------------------------------------------------- # # Rtu protocol, future = AsyncModbusSerialClient(schedulers.IO_LOOP, method="rtu", port="/tmp/ptyp0", baudrate=9600, timeout=2) # Asci # from pymodbus.transaction import ModbusAsciiFramer # protocol, future = AsyncModbusSerialClient(schedulers.IO_LOOP, # method="ascii", # port="/dev/ptyp0", # framer=ModbusAsciiFramer, # baudrate=9600, # timeout=2) # Binary # from pymodbus.transaction import ModbusBinaryFramer # protocol, future = AsyncModbusSerialClient(schedulers.IO_LOOP,
parser = argparse.ArgumentParser() parser.add_argument("serialPort", help="The serial port device to use") parser.add_argument("--httpListenPort", help="The port for the HTTP server to listen on", type=int, default=8080) parser.add_argument("--verbose", help="Use verbose logging", action="store_true") args = parser.parse_args() logging.basicConfig() log = logging.getLogger() if args.verbose: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) log.info("Listening on port {}, using device {}".format(args.httpListenPort, args.serialPort)) loop, client = AsyncModbusSerialClient(schedulers.ASYNC_IO, port=args.serialPort, baudrate=19200, method="rtu") modbus = Modbus(client.protocol) handler = HttpHandler(modbus) app = web.Application() app.add_routes([ web.get("/", handler.handle_root), web.get("/summary", handler.get_summary), web.get("/mode/{flag}", handler.get_mode_status), web.post("/mode/{flag}", handler.set_mode_status), web.post("/setSetting/{setting}/{value}", handler.set_setting) ]) try: loop.run_until_complete(web._run_app(app, port=args.httpListenPort)) finally: loop.close()