post datas to the broker
supposing the IP of the machine running emoncms docker to be 192.168.1.53
, you can post datas from your local network :
mosquitto_pub -h 192.168.1.53 -p 7883 -u "emonpi" -P "emonpimqtt2016" -t 'emon/test/t3' -m 43.67
if you dont have mosquitto_pub installed and are on debian/ubuntu : sudo apt-get install mosquitto-clients
use a python code
Install the paho mqtt library : python3 -m pip install paho-mqtt
Save the following code as test.py
:
"""MQTT post"""
import json
import os
import time
import paho.mqtt.client as mqtt
MQTT_USER = os.getenv("MQTT_USER", default="emonpi")
MQTT_PASSWORD = os.getenv("MQTT_PASSWORD", default="emonpimqtt2016")
MQTT_HOST = os.getenv("MQTT_HOST", default="127.0.0.1").replace("\"", "")
MQTT_PORT = int(os.getenv("MQTT_PORT", default="1883"))
def on_connect(client, userdata, flags, reason_code, propreties): # pylint: disable=unused-argument
"""detect the broker response to the connection request"""
client.connection = True
mqtt.Client.connection = False
def publish_to_mqtt(node, payload):
"""connect to the broker and send a json payload"""
message = {}
message["success"] = True
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.username_pw_set(MQTT_USER, password=MQTT_PASSWORD)
mqttc.on_connect = on_connect
try:
mqttc.connect(MQTT_HOST, port=MQTT_PORT, keepalive=1)
except Exception as e:
message["success"] = False
message["text"] = f'Could not connect to MQTT {e}'
else:
mqttc.loop_start()
while not mqttc.connection :
time.sleep(0.1)
result = mqttc.publish(f'emon/{node}', json.dumps(payload))
if result[0] != 0 :
message["success"] = False
mqttc.disconnect()
message["text"] = mqtt.connack_string(result[0])
return message
message = publish_to_mqtt("test", {"t3": 14})
print(message)
WARNING
The above code requires version 2.0 of paho-mqtt !