Ejemplo n.º 1
0
def run_with_not_running_loop():

    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
    """
    A loop is created and is passed to ModbusClient factory to be used.
    :return:
    """
    log.debug("Running Async client with asyncio loop not yet started")
    log.debug("------------------------------------------------------")
    loop = asyncio.new_event_loop()
    assert not loop.is_running()
    asyncio.set_event_loop(loop)
    new_loop, client = ModbusClient(schedulers.ASYNC_IO,
                                    host=os.getenv('IP_CLIENT'),
                                    port=5020,
                                    loop=loop)
    loop.run_until_complete(start_async_test(client.protocol))
    loop.close()
    log.debug("--------------RUN_WITH_NOT_RUNNING_LOOP---------------")
    log.debug("")
Ejemplo n.º 2
0
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()
async def env_modbus2mongodb(loop, collection, bus):
    # t = time.time()
    # loop = asyncio.new_event_loop()
    assert loop.is_running()
    asyncio.set_event_loop(loop)
    new_loop, client_conn = ModbusClient(schedulers.ASYNC_IO, host=ads.conn[bus - 1][0], port=ads.conn[bus - 1][1], loop=loop)
    client = client_conn.protocol

    for box in range(ads.busBox[bus - 1], ads.busBox[bus]):  # 云盒编号(0开始)
        rr = await client.read_holding_registers(ads.rgs, ads.len_data, unit=box + 1)

        if not hasattr(rr, 'registers'):
            data_db = {'name': '{:0>2d}{:0>2d}xx'.format(bus, box + 1),
                       'message': rr.message,
                       'err': 'No Data Return',
                       'datetime': datetime.now()}
            result = await collection.insert_one(data_db)
            continue

        data_modbus = rr.registers
        for i in range(ads.box_num[box][0]):  # 二合一编号(0开始)
            pos_two = ads.two_start + ads.two_len * i
            # print('two', data_modbus[pos_two + ads.pos_name], (box+1) * 256 + i+1)
            if data_modbus[pos_two + ads.pos_name] == (box + 1) * 256 + ads.two_start + i + 1:
                data_db = {'name': '{:0>2d}{:0>2d}{:0>2d}'.format(bus, box + 1, i + 1),
                           'two_in_one': {ads.two_type[j]: data_modbus[pos_two + ads.pos_data + j] * ads.two_carry[j]
                                          for j in range(2)},
                           'datetime': datetime.now()}
            else:
                data_db = {'name': '{:0>2d}{:0>2d}{:0>2d}'.format(bus, box + 1, i + 1),
                           'data': data_modbus,
                           'err': 'Unexpected Data Received',
                           'datetime': datetime.now()}
            result = await collection.insert_one(data_db)
            # data_all.append(data_db)

        for i in range(ads.box_num[box][1]):  # 六合一编号
            pos_six = ads.six_start * ads.two_len + ads.six_len * i
            # print('six', data_modbus[pos_six + ads.pos_name], (box+1) * 256 + ads.six_start+i + ads.six_bios+1)
            if data_modbus[pos_six + ads.pos_name] == (box + 1) * 256 + ads.six_start + i + ads.six_bios + 1:
                data_db = {'name': '{:0>2d}{:0>2d}{:0>2d}'.format(bus, box + 1, ads.six_start + i + 1),
                           'six_in_one': {ads.six_type[j]: data_modbus[pos_six + ads.pos_data + j] * ads.six_carry[j]
                                          for j in range(6)},
                           'datetime': datetime.now()}
            else:
                data_db = {'name': '{:0>2d}{:0>2d}{:0>2d}'.format(bus, box + 1, ads.six_start + i + 1),
                           'data': data_modbus,
                           'err': 'Unexpected Data Received',
                           'datetime': datetime.now()}
            result = await collection.insert_one(data_db)
            # data_all.append(data_db)

        await asyncio.sleep(1)
    loop.stop()
Ejemplo n.º 4
0
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("")
Ejemplo n.º 5
0
 async def connect(self, ip, port):
     self.clientip = ip
     self.clientport = port
     if self.simulation_mode:
         self.client = MockModbusClient(self.clientip, self.clientport)
     else:
         try:
             self.client = ModbusClient(self.clientip, self.clientport)
         except AttributeError:
             raise ConnectionException(
                 "Unable to connect to modbus device at "
                 f"{self.clientip}:{self.clientport}.")
Ejemplo n.º 6
0
def run_with_not_running_loop():
    """
    A loop is created and is passed to ModbusClient factory to be used.

    :return:
    """
    log.debug("Running Async client with asyncio loop not yet started")
    log.debug("------------------------------------------------------")
    loop = asyncio.new_event_loop()
    assert not loop.is_running()
    new_loop, client = ModbusClient(schedulers.ASYNC_IO, port=5020, loop=loop)
    loop.run_until_complete(start_async_test(client.protocol))
    loop.close()
    log.debug("--------------RUN_WITH_NOT_RUNNING_LOOP---------------")
    log.debug("")
Ejemplo n.º 7
0
 def __init__(self, host, port=502, timeout=3):
     """
     Create a Modbus TCP asynchronous client using its own event loop.
     """
     self._host = host
     self._port = port
     # Timeout before giving up requests so that run loop doesn't get hung up forever
     self._request_timeout = timeout
     _, self._async_client = ModbusClient(schedulers.ASYNC_IO,
                                          host=self._host,
                                          port=self._port)
     # Power values in W
     self.grid_import = float('NaN')
     self.phase_import = [float('NaN') for _ in range(3)]
     self.pv_generation = float('NaN')
     # Lifetime values in kWh
     self.lifetime_production = float('NaN')
     self.lifetime_export = float('NaN')
     self.lifetime_import = float('NaN')
     self.phase_import = [float('NaN'), float('NaN'), float('NaN')]
     self.phase_voltage = [float('NaN'), float('NaN'), float('NaN')]
Ejemplo n.º 8
0
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("")
Ejemplo n.º 9
0
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("")
Ejemplo n.º 10
0
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()
Ejemplo n.º 11
0
# sys               - Used to add the path of the openHAB Package
# smart_meter       - Class used to read the smart meters currently configured
# JSON              - Used to read the config.json file
# AeotechZW096      - Class for the smart plugs being used   
import sys
sys.path.append(r'/home/openhabian/Environments/env_1/openHAB_Proj/')
from openHAB_Proj.smart_meters import smart_meter
from pymodbus.client.asynchronous.tcp import AsyncModbusTCPClient as ModbusClient
from pymodbus.client.asynchronous import schedulers
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
import asyncio
import logging 
import csv

# IP address of the smart meter 
meter_IP = "192.168.0.116"

async def main(meter):
    file_name = "results/thread_five_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 five event loop")
        while True:
            await meter.read_all(csv_writer)

loop = asyncio.get_event_loop()
loop, client = ModbusClient(schedulers.ASYNC_IO,host =meter_IP, loop=loop)
meter = smart_meter(meter_IP,client)
loop.create_task(main(meter))
loop.run_forever()
Ejemplo n.º 12
0

async def countAsyn(collection):
    # collection = await DBconnect()
    all = await collection.count_documents({})
    print("There is/are " + str(all) + " document(s)")


if __name__ == '__main__':

    loop = asyncio.new_event_loop()
    # assert not loop.is_running()
    asyncio.set_event_loop(loop)
    new_loop, client1 = ModbusClient(schedulers.ASYNC_IO,
                                     host='192.168.1.82',
                                     port=1030,
                                     loop=loop,
                                     framer=ModbusFramer)
    new_loop, client2 = ModbusClient(schedulers.ASYNC_IO,
                                     host='192.168.1.82',
                                     port=1031,
                                     loop=loop,
                                     framer=ModbusFramer)
    new_loop, client3 = ModbusClient(schedulers.ASYNC_IO,
                                     host='192.168.1.82',
                                     port=1032,
                                     loop=loop,
                                     framer=ModbusFramer)
    new_loop, client4 = ModbusClient(schedulers.ASYNC_IO,
                                     host='192.168.1.82',
                                     port=1033,
Ejemplo n.º 13
0

async def countAsyn(collection):
    # collection = await DBconnect()
    all = await collection.count_documents({})
    print("There is/are " + str(all) + " document(s)")


if __name__ == '__main__':

    loop = asyncio.new_event_loop()
    # assert not loop.is_running()
    asyncio.set_event_loop(loop)
    new_loop, client = ModbusClient(schedulers.ASYNC_IO,
                                    host='192.168.1.82',
                                    port=1032,
                                    loop=loop,
                                    framer=ModbusFramer)
    DBclient = motor.motor_asyncio.AsyncIOMotorClient(
        'mongodb://192.168.1.10/',
        username='******',
        password='******',
        authSource='admin',
        authMechanism='SCRAM-SHA-256',
        io_loop=loop)
    db = DBclient['cpes']
    collection = db['data_test']
    scheduler = AsyncIOScheduler()

    scheduler.add_job(start_async_test,
                      'interval',
Ejemplo n.º 14
0
    #                                                   username='******',
    #                                                   password='******',
    #                                                   authSource='admin',
    #                                                   authMechanism='SCRAM-SHA-256')
    #
    # db = DBclient['cpes']
    # collection = db['data_test']

    executors1 = {
        'default': ThreadPoolExecutor(20),
        'processpool': ProcessPoolExecutor(5)
    }

    executors2 = {'default': AsyncIOExecutor()}

    loop, client = ModbusClient(schedulers.ASYNC_IO, port=5020)

    scheduler = AsyncIOScheduler()  # executors=executors1
    # scheduler = BackgroundScheduler(executors=executors2)
    # scheduler.add_job(tick, 'interval', seconds=3)
    # scheduler.add_job(createOneAsyn, 'interval', args=[collection], seconds=3)
    scheduler.add_job(start_async_test,
                      'interval',
                      args=[client.protocol],
                      seconds=3)
    scheduler.add_job(countAsyn, 'interval', seconds=3)
    scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    # Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
    try: