Last active
February 5, 2021 15:15
-
-
Save yoshimax/9e3daa6247e3d71cdaa78f1356559db7 to your computer and use it in GitHub Desktop.
mqtt_websocket_x2_proxy.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# python 3.7.3 can work others will can't ;) | |
import asyncio | |
import logging | |
from asyncio_mqtt import Client, MqttError | |
import websockets | |
ws = "" | |
ws2 = "" | |
logger = logging.getLogger(__name__) | |
async def mqtt_wait(): | |
while True: | |
try: | |
logger.info("Connecting to MQTT") | |
async with Client("192.168.0.101") as client: | |
logger.info("Connection to MQTT open") | |
async with client.unfiltered_messages() as messages: | |
await client.subscribe('m5cp1/fromDevice') | |
async for message in messages: | |
logger.info("Message %s %s", message.topic, message.payload.decode()) | |
mes = str(message.payload.decode()) | |
await ws.send("echo : " + mes) | |
# await asyncio.sleep(2) | |
except MqttError as e: | |
logger.error("Connection to MQTT closed: " + str(e)) | |
except Exception: | |
logger.exception("Connection to MQTT closed") | |
await asyncio.sleep(3) | |
async def accept(websocket, path): | |
global ws | |
ws = websocket | |
while True: | |
data = await websocket.recv() | |
print("receive : " + data) | |
await websocket.send("echo : " + data) | |
await asyncio.sleep(3) | |
async def accept2(websocket, path): | |
global ws2 | |
ws2 = websocket | |
while True: | |
data = await websocket.recv() | |
print("receive : " + data) | |
await websocket.send("echo : " + data) | |
await asyncio.sleep(3) | |
async def websocket_wait(): | |
start_server = websockets.serve(accept, "192.168.0.101", 54011) | |
asyncio.get_event_loop().run_until_complete(start_server) | |
# asyncio.get_event_loop().run_forever() | |
async def websocket_wait2(): | |
start_server = websockets.serve(accept2, "192.168.0.101", 54012) | |
asyncio.get_event_loop().run_until_complete(start_server) | |
#asyncio.get_event_loop().run_forever() | |
def main(): | |
logging.basicConfig(level=logging.DEBUG, | |
format="%(asctime)s %(levelname)s %(message)s", | |
datefmt="%Y-%m-%d %H:%M:%S") | |
# asyncio.run(asyncio.wait([mqtt_wait(), websocket_wait()])) | |
asyncio.run(asyncio.wait([mqtt_wait(), websocket_wait(), websocket_wait2()])) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment