MQTT: Difference between revisions

From Wildsong
Jump to navigationJump to search
Brian Wilson (talk | contribs)
mNo edit summary
Brian Wilson (talk | contribs)
Line 51: Line 51:
First I tried the Adafruit library and their sample code. It works, but the MQTT server is out there in the cloud
First I tried the Adafruit library and their sample code. It works, but the MQTT server is out there in the cloud
and interfaces with a web page at Adafruit. I want to keep a lid on things.
and interfaces with a web page at Adafruit. I want to keep a lid on things.
Per the article in the Resources section I am trying [https://github.com/knolleary/pubsubclient PubSubClient]
which can be installed from the Library Manager in the Arduino IDE.


== Resources ==
== Resources ==

Revision as of 03:28, 13 June 2020

I was originally looking at MQTT right now in the context of Presence Detection. It turned out that Home Assistant already had a good integration with UniFi so I stopped working on that. Now I am building an ESP8266 Arduino (WeMos D1) light strip controller.

My Mosquitto MQTT Server is in a docker container on Bellman. I can log into that container and run commands to learn more.

Listen for presence messages from anyone. QOS is set to 'at least once'. -d is for debug. -t defines what I listen to, where the "+" is a wildcard.

docker exec -it mosquitto mosquitto_sub -t 'sensors/+/presence' -q 1 -d

Send a message.

docker exec -it mosquitto mosquitto_pub -t 'sensors/unifi/presence' -q 1 -d -m 'Julie arrived'

How should my messages look?

  • PUB Home Assistant will publish desired LED settings.
  • SUB The Arduino will subscribe and adjust the LEDs accordingly.
  • PUB After making changes the Arduino will send current settings. On power up the Arduino will restore the last state of the strip and send status.
  • SUB Home Assistant will subscribe and display the LED settings.

I should be able to mock both sides with a bit of Python.

Python for testing

conda create --name mqtt
conda activate mqtt
conda install -c conda-force paho-mqtt

Here's my very first program. It sends a 1 or a 0 to whatever wants to hear it.

import paho.mqtt.publish as publish
import time

HOST = "192.168.123.2"
state = True
target = "blinker"

while(1):
    print(state)
    publish.single(target, "1" if state else "0", hostname=HOST)
    time.sleep(1)
    state = not state

Arduino

Now I need to make the WeMos D1 listen and respond. First I tried the Adafruit library and their sample code. It works, but the MQTT server is out there in the cloud and interfaces with a web page at Adafruit. I want to keep a lid on things.

Per the article in the Resources section I am trying PubSubClient which can be installed from the Library Manager in the Arduino IDE.

Resources

Books - There are some good books in Safari including "Hands-on MQTT Programming With Python".

https://www.baldengineer.com/mqtt-tutorial.html