mqtt_subscriber
unknown
python
4 years ago
1.1 kB
11
Indexable
import asyncio
import websockets
import paho.mqtt.client as mqtt
import time
import requests
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
url = "http://localhost:8000/sensors/readings/"
id = int(msg.topic.split("/")[1])
print(id)
data = {
"sensorstream" : id,
"reading" : msg.payload
}
response = requests.post(url,data=data)
print(response.text)
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
topic = 'SENSORSTREAM/+'
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe(topic)
mqttBroker = "test.mosquitto.org"
client = mqtt.Client("Smartphone")
client.connect(mqttBroker,port=1883)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
Editor is loading...