#!/usr/bin/env python3
# coding=utf-8
""" WiBotic Websocket Sample"""

__copyright__ = "Copyright 2018 WiBotic Inc."
__version__ = "0.1"
__email__ = "info@wibotic.com"
__status__ = "Technology Preview"

import asyncio
import websockets
import packettools

class NetApi:
    def __init__(self, websocket_url):
        self.websocket_url = websocket_url
        pass

    async def connect(self):
        async with websockets.connect(self.websocket_url, subprotocols=['wibotic']) as websocket:
            consumer_task = asyncio.ensure_future(self.consumer_handler(websocket))
            producer_task = asyncio.ensure_future(self.producer_handler(websocket))
            done, pending = await asyncio.wait(
                [consumer_task, producer_task],
                return_when=asyncio.FIRST_COMPLETED,
            )
            for task in pending:
                task.cancel()
                
    async def consumer_handler(self, websocket):
        while True:
            message = await websocket.recv()
            await self.consumer(message)
            
    async def producer_handler(self, websocket):
        while True:
            message = await self.producer()
            await websocket.send(message)
            
    async def consumer(self, data):
        # Print all ADC packets and Parameter Updates to the console window
        print(packettools.process_data(data))
        
    async def producer(self):
        await asyncio.sleep(1)
        
        # Send commands to the charger
        print("Changing a parameter...")
        request = packettools.ParamWriteRequest(
            packettools.DeviceID.TX, 
            packettools.ParamID.ChargeEnable,
            True
        );

	    # Example of requesting a parameter value
        #print("Request a parameter value...")
        #request = packettools.ParamReadRequest(
        #    packettools.DeviceID.TX, 
        #    packettools.ParamID.ChargeEnable
        #);
        
        # Return the request as bytes to get sent out
        return bytes(request.as_packet())

if __name__ == "__main__":
    WIBOTIC_CHARGER_WS_URL = "ws://192.168.2.20/ws"
    test = NetApi(WIBOTIC_CHARGER_WS_URL)
    asyncio.get_event_loop().run_until_complete(
        test.connect()
    )
    print("Disconnected")
