Pyscript MQTT publishing message
I'm working on py-script html page and I want to publish a message via mqtt in a specific topic. I put the python code in the tag
import asyncio
import os
import signal
import time
from gmqtt import Client as MQTTClient
STOP = asyncio.Event()
def on_connect(client, flags, rc, properties):
print('Connected')
client.subscribe('TEST/#', qos=0)
def on_message(client, topic, payload, qos, properties):
print(payload)
def on_disconnect(client, packet, exc=None):
print('Disconnected')
def on_subscribe(client, mid, qos, properties):
print('SUBSCRIBED')
async def main(broker_host):
client = MQTTClient("3232DZQ")
client.on_connect = on_connect
client.on_message = on_message
client.on_disconnect = on_disconnect
client.on_subscribe = on_subscribe
await client.connect(broker_host)
client.publish('TEST/TIME', 'IZISIUIQY', qos=1)
await STOP.wait()
await client.disconnect()
def ask_exit(*args):
STOP.set()
if __name__ == '__main__':
loop = asyncio.new_event_loop()
host = 'broker.hivemq.com'
loop.run_until_complete(main(host))
When I run the python file alone it works fine: python file working fine , but when I put the code in the tags, I doesn't work. The html page that I want to run and publish message via mqtt, points on the python file using the tag pyscript and the attribute src="publish.py"
<!DOCTYPE html>
<html>
<head>
<title>Publish MQTT</title>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
<py-env>
- gmqtt
</py-env>
</head>
<body>
<!--calling publish python code-->
<py-script src="publish.py"></py-script>
</body>
</html>
Comments
Post a Comment