import asyncio

from aiohttp import web
import random
SERVER_IP = 'localhost'
SERVER_PORT = 8000

# -----------------------------------------------------------------------------
# HTTP Server Core
# -----------------------------------------------------------------------------
routes = web.RouteTableDef()

@routes.post('/send_cmd')
async def handle_send_cmd(request):
    command = await request.json()
    if command['sensor'] == 'DHT11':
        return web.json_response(dht11_data(command))
    else:
        return web.json_response({"error": "unknown sensor"})

def dht11_data(request):
    temperature = round(random.uniform(20, 30), 1)
    humidity = int(random.uniform(20, 80))
    if request['command'] == 'read_temp':
        return {"temperature": temperature}
    elif request['command'] == 'read_hum':
        return {"humidity": humidity}
    else:
        return {"temperature": temperature, "humidity": humidity}

async def main():    # Start HTTP server
    app = web.Application()
    app.add_routes(routes)
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, host=SERVER_IP, port=SERVER_PORT)
    await site.start()

    print(f"Server running at http://{SERVER_IP}:{SERVER_PORT}")
    await asyncio.Event().wait()

if __name__ == '__main__':
    asyncio.run(main())
