client.py 1.14 KB
import sys
import asyncio
import json
from configparser import ConfigParser
import websockets
from .read_conf import get_module_object


async def main_loop(conf, module):
    async with websockets.connect(conf['url']) as websocket:
        first = True
        while True:
            await asyncio.sleep(1)
            if first:
                first = False
                d = module.login()
            else:
                d = module.get_data()
            if d:
                raw = json.dumps(d)
                await websocket.send(raw)
                print(f'Send {[raw]}')
            else:
                try:
                    async with asyncio.timeout(2):
                        raw = await websocket.recv()
                        print(f'Receive {[raw]}')
                except asyncio.TimeoutError:
                    pass


async def main_(conf):
    module = get_module_object(conf['module'])
    module.init(conf)
    await main_loop(conf, module)


def main(argv=sys.argv[1:]):
    conf_file = argv[0]
    conf = ConfigParser()
    conf.read(conf_file)
    cf = dict(conf.items('main'))
    obj = main_(cf)
    asyncio.run(obj, debug=True)