def run_with_no_loop(): """ ModbusClient Factory creates a loop. :return: """ loop, client = ModbusClient(schedulers.ASYNC_IO, port=5020) loop.run_until_complete(start_async_test(client.protocol)) loop.close()
def run_with_no_loop(): """ ModbusClient Factory creates a loop. :return: """ log.debug("---------------------RUN_WITH_NO_LOOP-----------------") loop, client = ModbusClient(schedulers.ASYNC_IO, port=5020) loop.run_until_complete(start_async_test(client.protocol)) loop.close() log.debug("--------DONE RUN_WITH_NO_LOOP-------------") log.debug("")
def __init__(self, host, port="502", timeout=5, loop=None): # pylint: disable=unpacking-non-sequence LOGGER.debug("creating loop and client") self.loop, self.client = AsyncModbusTCPClient( schedulers.ASYNC_IO, port=port, host=host, loop=loop ) LOGGER.debug("created loop and client") self.timeout = timeout self._time_offset = None
def run_with_already_running_loop(): """ An already running loop is passed to ModbusClient Factory :return: """ log.debug("Running Async client with asyncio loop already started") log.debug("------------------------------------------------------") def done(future): log.info("Done !!!") def start_loop(loop): """ Start Loop :param loop: :return: """ asyncio.set_event_loop(loop) loop.run_forever() loop = asyncio.new_event_loop() t = Thread(target=start_loop, args=[loop]) t.daemon = True # Start the loop t.start() assert loop.is_running() asyncio.set_event_loop(loop) loop, client = ModbusClient(schedulers.ASYNC_IO, port=5020, loop=loop) print(type(loop)) print(type(client)) print(type(client.protocol)) future = asyncio.run_coroutine_threadsafe(start_async_test( client.protocol), loop=loop) future.add_done_callback(done) while not future.done(): time.sleep(0.1) loop.stop() log.debug("--------DONE RUN_WITH_ALREADY_RUNNING_LOOP-------------") log.debug("")
def testTcpTornadoClient(self, mock_iostream, mock_ioloop): """ Test the TCP tornado client client initialize """ protocol, future = AsyncModbusTCPClient(schedulers.IO_LOOP, framer=ModbusSocketFramer(ClientDecoder())) client = future.result() assert(isinstance(client, AsyncTornadoModbusTcpClient)) assert(0 == len(list(client.transaction))) assert(isinstance(client.framer, ModbusSocketFramer)) assert(client.port == 502) assert client._connected assert(client.stream.connect.call_count == 1) assert(client.stream.read_until_close.call_count == 1) 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 run_with_no_loop(): """ ModbusClient Factory creates a loop. :return: """ clientSocket = socket.socket() host = os.getenv('IP_CLIENT') port = 15021 clientSocket.connect((host, port)) message = clientSocket.recv(1024).decode("UTF-8") if message == None: print("Error en autenticacion") return log.debug("---------------------RUN_WITH_NO_LOOP-----------------") loop, client = ModbusClient(schedulers.ASYNC_IO, host=os.getenv('IP_CLIENT'), port=5020) loop.run_until_complete(start_async_test(client.protocol)) loop.close() log.debug("--------DONE RUN_WITH_NO_LOOP-------------") log.debug("")
def run_with_already_running_loop(): """ An already running loop is passed to ModbusClient Factory :return: """ log.debug("Running Async client with asyncio loop already started") log.debug("------------------------------------------------------") def done(future): log.info("Done !!!") def start_loop(loop): """ Start Loop :param loop: :return: """ asyncio.set_event_loop(loop) loop.run_forever() loop = asyncio.new_event_loop() t = Thread(target=start_loop, args=[loop]) t.daemon = True # Start the loop t.start() assert loop.is_running() asyncio.set_event_loop(loop) loop, client = ModbusClient(schedulers.ASYNC_IO, port=5020, loop=loop) future = asyncio.run_coroutine_threadsafe( start_async_test(client.protocol), loop=loop) future.add_done_callback(done) while not future.done(): time.sleep(0.1) loop.stop() log.debug("--------DONE RUN_WITH_ALREADY_RUNNING_LOOP-------------") log.debug("")
def testTcpTwistedClient(self): """ Test the TCP Twisted client :return: """ from twisted.internet import reactor with patch("twisted.internet.reactor") as mock_reactor: def test_callback(client): pass def test_errback(client): pass AsyncModbusTCPClient(schedulers.REACTOR, framer=ModbusSocketFramer(ClientDecoder()), callback=test_callback, errback=test_errback)
from pymodbus.constants import Endian from pymodbus.payload import BinaryPayloadDecoder import asyncio import logging import csv # IP address of the smart meter meter_1_IP = "192.168.0.116" meter_2_IP = "192.168.0.80" async def main(meter_1, meter_2): file_name = "results/thread_two_result.csv" with open(file_name, mode='a') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) print("Executing thread two event loop") while True: await meter_1.read_all(csv_writer) await meter_2.read_all(csv_writer) loop = asyncio.get_event_loop() loop, client1 = ModbusClient(schedulers.ASYNC_IO, host=meter_1_IP, loop=loop) loop, client2 = ModbusClient(schedulers.ASYNC_IO, host=meter_2_IP, loop=loop) meter_1 = smart_meter(meter_1_IP, client1) meter_2 = smart_meter(meter_2_IP, client2) loop.create_task(main(meter_1, meter_2)) loop.run_forever()
) as json_file: data = json.load(json_file) #Only insterested in what this script controls #Decided upon by the OpenHAB group try: data_1 = data[group] except KeyError: logger.error(f"No items found for {group}") things = dict() #Iterate through the Things assigned to this script for key, val in data_1.items(): plug = AeotechZW096() # Give the instance the variables obtained from config.json plug.__dict__ = val # Things is a dictionary where the key is the plug UID # The value is an instnace of the Aeotech class things[plug.UID] = plug # Get the event loop loop = asyncio.get_event_loop() # Create an instance of AsyncModbusTCPClient which is connected to meter 192.168.0.116 loop, client = ModbusClient(schedulers.ASYNC_IO, host=meter_1_IP, loop=loop) logger.info(f"Creating smart meter instance with IP of {meter_1_IP}") # Create an instance of the smart_meter class passing the IP and connection to meter 192.168.0.116 meter_1 = smart_meter(meter_1_IP, client) # Add main() to the event loop as a task passing smart_meter instance and dictionary of AeotechZW096 instances loop.create_task(main(meter_1, things)) logger.info(f"Entering event loop") # Run the loop forever loop.run_forever()
# extra requests # --------------------------------------------------------------------------- # # If you are performing a request that is not available in the client # mixin, you have to perform the request like this instead:: # # from pymodbus.diag_message import ClearCountersRequest # from pymodbus.diag_message import ClearCountersResponse # # request = ClearCountersRequest() # response = client.execute(request) # if isinstance(response, ClearCountersResponse): # ... do something with the response # # --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- # # 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 __name__ == "__main__": protocol, deferred = AsyncModbusTCPClient(schedulers.REACTOR, port=5020) # protocol, deferred = AsyncModbusUDPClient(schedulers.REACTOR, port=5020) # callback=beginAsynchronousTest, # errback=err) deferred.addCallback(beginAsynchronousTest) deferred.addErrback(err)