Using MQTT to communicate arduino, rpi and desktop computers via ethernet.
@wolfgangw - here are my example MQTT programs. Â If you read the linked example about MQTT you will find more links to many more examples.
Firstly I link to a short and nice description of the use of MQTT. It's short and to the point. Recommended if you want a proper introduction to MQTT
https://opensource.com/article/18/6/MQTT
I give my example of this with 2 programs one on an ESP8266 programmed in the Arduino environment, and one on an Rpi programmed in python.  You will need to use an MQTT broker, There are public brokers to link to over the internet, but it is very simple to get a broker up and running on an Rpi, - sudo apt-get install mosquitto - and you will have a running MQTT broker.
Esp8266 program
The esp8266 program (tested on my Wemos mini D1 esp8266 board) has been partially lifted from another program that reads temperature data via i2c from an adafruit MCP9808. Now I don't expect anyone will hook up an MCP9808 if they choose to run this program, but possibly thats good for wolfgang who want to test error conditions over MQTT. No sensor = some sort of error!
To run the program you will of course have to have the adafruit MCP9808 library installed in the Arduino environment. Likewise you will need the chosen MQTT client library to be installed . The library I used can be seen in this link.
https://pubsubclient.knolleary.net
The program does not do much. It sits there waiting to receive MQTT messages with the topics of FenC/Wemos1/Received and then checks the message payload for "T" or "F" or "D" and takes action accordingly. T will initiate it to send the temperature reading from the MCP9808, or an error message if it cannot, all being published to MQTT. F will trigger the sending of a 'fake' temperature reading via MQTT that the Rpi MQTT subscriber to the message can enter the reading received into a database. D will cause the MQTT server to be disconnect to check the auto-reconnection is working. Liberal use is made of using Serial.print() to also send information to the serial console of the Arduino.
#include <Wire.h>
#include "Adafruit_MCP9808.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h> //the client library for mqtt
#include <string.h>
//globals
static char tempstr[10]; //for mqtt messages received
float tempFloat;
float faketemp = 10.01;
// wifi router and password
#define WLAN_SSID "Your Router"
#define WLAN_PASS "Your Password"
#define MQTT_SERVER "The IP address of your server"
/************ Create the MCP9808 temperature sensor object******************/
Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();
/*********** Create an ESP8266 WiFiClient object to connect to the MQTT server ****/
WiFiClient Wclient;
/****** mqtt client *************/
PubSubClient mqttClient(Wclient);
/******* function to connect to mqtt server and subscribe to topics and start mqtt loop *******/
bool mqttConnect()
{
if (mqttClient.connect("wemos1"))
{
// connection succeeded
}
else
{
// cannection failed
Serial.print("mqtt connetion failed "); Serial.println(mqttClient.state());
return false;
}
//subsribe to the desired MQTT messages ***********************
mqttClient.subscribe("FenC/Wemos1/Receiving");
mqttClient.loop();
return true;
}
/****** mqtt message received function **************/
void mqttCallback(char* topic, byte* payload, unsigned int length)
{
char mssg[10] ;
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
mssg[0] = char(payload[0]);
if ( mssg[0] == 'D')
{
mqttClient.disconnect();
Serial.println("mqttClient is disconnected");
}
else if ( mssg[0] == 'T')
{
sendTemp();
}
else if ( mssg[0] == 'F')
{
sendFakeTemp();
}
}
/***************************************************/
void setup()
{
Serial.begin(9600);
delay(10);
Serial.println("MCP9808 demo");
Serial.println(); Serial.println();
// Connect to WiFi ********************************
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: "); Serial.println(WiFi.localIP());
// Make sure Access Point is not used! WiFi.mode(m): set mode to WIFI_AP, WIFI_STA, or WIFI_AP_STA.
WiFi.mode(WIFI_STA);
// set the mqtt server ip address and port *********************
mqttClient.setServer(MQTT_SERVER,1883);
// set the function to be called when an MQTT message is received
mqttClient.setCallback(mqttCallback);
// connect to the MQTT server ***********************************
mqttConnect();
}
void loop()
{
// the PubSubClient library needs to receive a periodic mqttClient.loop() or it will close the mqtt connection.
// delay for a short while before issuing a loop() or reconnect to mqtt - for test purposes this program will
// disconnect from the mqtt server if a message of 'D' is received.
if(mqttClient.connected())
{
// mqtt is connected - just call the loop
mqttClient.loop();
}
else
{
// mqtt is NOT conntected - connect to mqtt, subscribe then call loop
mqttConnect();
}
}
// mqtt message 'T' is received so send the temperature from the MCP9808 i2c temperature sensor
void sendTemp()
{
// Make sure the i2c sensor is found
if (!tempsensor.begin(0x18))
{
//publish error to mqtt
mqttClient.publish("FenC/Wemos1/Error", "Error - no communication with MCP9808" );
//and print to serial console
Serial.println("Couldn't find MCP9808!");
return;
}
Serial.println("Found MCP9808!");
// call the getTemp() function to read the temperature and give the resoluion
// more precision = more ms time taken to read
// mode of reading the MCP9808, the modes are defined in bellow:
// Mode Resolution SampleTime
// 0 0.5°C 30 ms
// 1 0.25°C 65 ms
// 2 0.125°C 130 ms
// 3 0.0625°C 250 ms
// get the temperature from the MCP9808 at resolution 3
tempFloat = getTemp(3);
// publish the temperature
dtostrf(tempFloat,2,2,tempstr);
mqttClient.publish("FenC/Wemos1/Temp", tempstr );
}
/********* read the MCP9808 temp sensor ********/
float getTemp(int resolution)
{
// wake up MCP9808 - power consumption ~200 mikro Ampere
tempsensor.wake(); // wake up, ready to read!
tempsensor.setResolution(resolution); // set the resolution
// Read and print out the temperature
Serial.print("Resolution in mode: ");
Serial.println (tempsensor.getResolution());
float c = tempsensor.readTempC();
Serial.print("Temp: "); Serial.print(c); Serial.println("*C\t");
return c;
}
// mqtt message 'F' is received so publish a fake temperature
void sendFakeTemp()
{
dtostrf(faketemp,2,2,tempstr);
mqttClient.publish("FenC/Wemos1/Temp", tempstr ); // will increment the fake temp by 0.01 each time.
faketemp = faketemp + 0.01;
}
RPI program in next message
I had a bit of bother putting the RPI program into my previous message so here is part 2
Rpi program
You will need to install a MQTT client library for python - sudo pip3 install paho-mqtt
I was going to take snippets from other programs I have running, but I thought I would use sqlite3 instead of my usual mysql or mariadb databases as it means theres no need to install a database which can involve a bit of jiggery pokery, making it easy to run the program Â
The sqlite3 simply creates a file in the same directory as the python program. I have not used sqlite3 before and the use of the connection and cursors was not the same as for mysql in that it appears to need to have the connection and cursor redone each time I update or read the database or I got some errors about the cursor running in a different thread. Anyway the program works well enough for illustration purposed.  The database file 'myData.db' will get created.
The program publishes messages via MQTT with the T, F or D payload, as mentioned above, in sequence 10 times each. The Fake temperature reading given by the esp8266 are inserted into the database. Not much is done with the errors except to print the to the python console. An error is also given if a message is published that wants a response, has not received one within 1 second (or whatever you set the global variable to)
For both programs you will need to insert your own Router/password and IP address etc.Â
And finally a note particularly to wolfgang. Theres much more to MQTT than in my example and you need to look a Quality of Service, Retention, and Last Will and Testament settings.Â
Â
AIso a note on the DHT22 temp sensor you are going to use. This is a slow sensor, so reading it in too fast a sequence will mean you will get plenty of errors. Maybe because I had some cheapo ones, but mine did not record the same temperature when sitting side by side, sometimes by over a degree.
import time
import datetime
import paho.mqtt.client as mqtt #import the client
import sqlite3
broker_address = "The IP address of your MQTT Server"
messageRecievedFlag = False
waitSeconds = 1
# Connect to or create database
cnx = sqlite3.connect("myData.db")
cursor = cnx.cursor()
# create table if it does not exist
cursor.execute("""CREATE TABLE IF NOT EXISTS TableForData
(
location text,
date_time text,
temperature real
)
""")
cnx.commit()
cursor.close()
cnx.close()
# function to update the database
def updateDB(temp):
ts = time.time()
cDate = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
cnx = sqlite3.connect("myData.db")
cursor = cnx.cursor()
try:
cursor.execute("INSERT INTO TableForData(location,date_time,temperature)VALUES(?,?,?)",
("My_Home", cDate, float(temp)))
cnx.commit()
except sqlite3.Error as error:
print("sqlite3 update table error: ", error)
cursor.close()
cnx.close()
# function to display records in myData.db
def displayRecords():
try:
cnx = sqlite3.connect('myData.db')
cursor = cnx.cursor()
sql = """SELECT * from TableForData"""
cursor.execute(sql)
records = cursor.fetchall()
print("Total rows are: ", len(records))
print("Printing each row")
x = 1
for row in records:
print(x)
print("Location: ", row[0])
print("Date_Time: ", row[1])
print("Temperature: ", row[2])
x += 1
cursor.close()
cnx.close()
except sqlite3.Error as error:
print("Failed to read data from sqlite3 table", error)
# function to connection to mqtt
def MyMqttConnection(client, userdata, flags, rc):
m="Connected flags"+str(flags)+"result code "\
+str(rc)+"client1_id "+str(client)
print("Connection flags:",m)
# function to receive message from callback and send resqust response (and get a status return from response)
def MyMqttMessage(client1, userdata, message):
myResp = str(message.payload.decode("utf-8"))
global messageRecievedFlag
# parse topics
myTopics = message.topic.split("/")
#Note - subscribed to FenC/Wemos1/Temp and Fenc/Wemos1/Error
if myTopics[0] == "FenC" and myTopics[1] == "Wemos1":
if myTopics[2] == "Error":
messageRecievedFlag = True
print("FenC/Wemo1 gives error message: ", myResp)
return
elif myTopics[2] == "Temp":
messageRecievedFlag = True
updateDB(myResp)
return
else:
print("Something wrong - Topic FenC/Wemos1/XXXXX not understood")
def closeProgram():
client1.disconnect()
client1.loop_stop()
quit()
#****************************************************************************************
# mqtt
client1 = mqtt.Client("pViao") #create new instance
client1.on_connect = MyMqttConnection #attach connection function to callback
client1.on_message = MyMqttMessage #attach the MyMqttMessage function to callback
client1.connect(broker_address) #connect to broker
# start loop and subsribe to mqtt to receive messages
client1.loop_start() # start the loop
client1.subscribe("FenC/Wemos1/Temp")
client1.subscribe("FenC/Wemos1/Error") # subscribe
try:
for x in range(10):
# publish 'T' to "FenC/Wemos1/Receiving"
messageRecievedFlag = False
client1.publish('FenC/Wemos1/Receiving', 'T')
time.sleep(waitSeconds)
if messageRecievedFlag == False:
print("FenC/Wemos has not responded in the timeframe")
# publish 'F' to "FenC/Wemos1/Receiving"
messageRecievedFlag = False
client1.publish('FenC/Wemos1/Receiving', 'F')
time.sleep(waitSeconds)
if messageRecievedFlag == False:
print("FenC/Wemos has not responded in the timeframe")
# publish 'F' to "FenC/Wemos1/Receiving"
client1.publish('FenC/Wemos1/Receiving', 'D')
time.sleep(2)
displayRecords()
closeProgram()
except KeyboardInterrupt:
print("Interupt by contolC")
closeProgram()
Wow, Byron, wow. I expected something, but wow!
Thank you so much man. I guess if this is not helpful, then noone can ever help. 🤣Â
I saw your message coming in, but when I tried to open I received a 401. So last message came in first.
Anyway... it may take some while until I get through with that. But wow, thank you.
Wolfgang
If I am not here, then I am most probably somewhere else
I haven't got much time last two days to get deep into your code. Murphy's Law beat me hard, when my computer was litteraly broken and I had to order a new one. Now weekend I guess will take most of my time to make the new one in a way I am used to it.
I anyway had little time to dive through your example, try to understand and I guess - so far I can judge until now - that this is usefull for me.Â
Thanks again and have a nice weekend.
Wolfgang
If I am not here, then I am most probably somewhere else
I've had a quick look at your code, and the first thing I saw stood out like a sore thumb.
Your "mqttConnect(...)" function is very unsafe, and IMO, not suitable for a safe and secure MQTT network.
When programming functions, the key is that they do one thing, and do that one thing well. This particular function is attempting to do three things (connect, subscribe and loop).
Now for the function itself, you have an if statement in there doing absolutely nothing, and you do not check any of the return codes of each function when you call this function. Also note that your function only returns type boolean for the three internal function operations, but what's worse is that the status function itself actually returns an integer type, not a boolean type, and can return any one of 10 integer results that you never check for.
Let's have a look at the function in question:
/******* function to connect to mqtt server and subscribe to topics and start mqtt loop *******/ bool mqttConnect() {  if (mqttClient.connect("wemos1"))    {      // connection succeeded    }  else    {      // cannection failed      Serial.print("mqtt connetion failed "); Serial.println(mqttClient.state());      return false;    }  //subsribe to the desired MQTT messages ***********************  mqttClient.subscribe("FenC/Wemos1/Receiving");  mqttClient.loop();  return true; }
As I said, there is an if statement for connection succeeded, but it does nothing, and makes no sense to be used like this anyway. I think it is better to write such a function (if you really want one, because "connect()" is already a member function of the library), as follows:
// Possible values for client.state() -4 : MQTT_CONNECTION_TIMEOUT - the server didn't respond within the keepalive time -3 : MQTT_CONNECTION_LOST - the network connection was broken -2 : MQTT_CONNECT_FAILED - the network connection failed -1 : MQTT_DISCONNECTED - the client is disconnected cleanly 0 : MQTT_CONNECTED - the client is connected 1 : MQTT_CONNECT_BAD_PROTOCOL - the server doesn't support the requested version of MQTT 2 : MQTT_CONNECT_BAD_CLIENT_ID - the server rejected the client identifier 3 : MQTT_CONNECT_UNAVAILABLE - the server was unable to accept the connection 4 : MQTT_CONNECT_BAD_CREDENTIALS - the username/password were rejected 5 : MQTT_CONNECT_UNAUTHORIZED - the client was not authorized to connect // Example connection function... int connectToServer(const char* server) { Â Â if (!client.connect(server)) { Â Â Â Â return client.state(); Â Â Â } Â Â return 0; Â }
Then when you come to use it and the others:
int rCode = connectToServer("wemos1"); Â if(rCode != 0) { Â Â Serial.print("Error: - Unable to connect to server: " + String(rCode)); Â Â // Handle error here and/or exit... Â Â return; Â } if(!client.subscribe("FenC/Wemos1/Receiving")) { Â Â Serial.print("Error: - Connection to server has been lost."); Â Â // Handle error here and/or exit... Â Â return; Â } if(!client.loop()) { Â Â Serial.print("Error: - Connection to server has been lost."); Â Â // Handle error here and/or exit... Â Â return; Â }
The connect function can now be properly checked, and it also allows us to connect to a different broker/server at run time. Likewise, the other functions are also independently checked for any error.
The other thing I want to mention, is that one of the main criteria @wolfgangw desired, was to know if something adverse happened to the sensor, and it went offline, for example, if the cable was cut by a tractor, how would one know? Although you did mention the "last will" message, your example does not incorporate it, which I think is mandatory not only for his situation, but recommended for home networking automation, closely followed by "QoS" settings.
I think the whole point of this "last will" feature using MQTT, is that you do not need to handle the sensor errors and publish them to the topic yourself, as it is all automated for you... I think you should only publish temperatures and NaN, and let MQTT do it's thing for hard losses.
In summary, it's probably safer to set up your connection as follows:
if(!client.connect("wemos1", "username", "password", Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â "FenC/Wemos1/Receiving", true, "Sensor is OffLine", true)) { Â Â Serial.print("Error: - Unable to connect to server: " + String(rCode)); Â Â // Handle error here and/or exit... Â Â return; Â }
What do you think?
What do you think?
The code was quickly cobbled together to illustrate mqtt messages going to and fro and as you can see there was hardly any error checking. Â The document I included on the mqtt library for the arduino indicates all the return codes. Â Your suggested amendments are all valid and, as the program is very short I suggest you submit an amended example of the arduino code in case it may help someone.Â
On the subject of secure networks it is worth pointing that out. Â Also to be wary of is the use of the mysql_connector, which I usually use for connecting to my mariadb, which could be the subject of an sql injection attack. Â However all my programs only work with my home network and are not used over any internet connection. Â If anyone is intending to use communications outside of their home network then security should be an important consideration.
And a note to anyone looking at the python program, this is again just a quickly written program for illustrative purposes so don't take it as a finished program. Â It was the first time I used the inbuilt python sqlite3 database so I was interested in seeing what it could do (and it confirmed that I should stick with a proper database for my usual db work 🤨 ). Â Im still working on a much larger program that interacts with mqtt messages with some gui windows, and I may take a different approach to checking if, when a mqtt message is published that is expecting a response, that a response has actually been received.
Thus far I have found, in my home network, the mqtt to be completely reliable and fast so much so that I only use mqtt QOS 0 (i.e. just send and hope 😀). Â I may revise this as I'm now doing a time critical (serval minutes, not u_seconds) program for my heating control.
A final thought for @wolfgangw, the mqtt is a lightweight and fast protocol and is useful for sending info over an ethernet network like temperature readings or sending a command to switch on a light that is triggered by a remote microprocessor etc. Â If your only desire is to store the reading in a database then, of course, you could establish a database connection direct from your esp8266 to update the database with the likes of a mysql_connetor. Â There are libraries for this available for the arduino environment. Â But if you are building an IOT home-brewed solution I think you will find mqtt to be a useful tool with a lot less faffing about than with ip tcp web type libraries as a solution of passing data. Â (but like everything - it depends...) However, now I think of it, @robo-pi wrote something in the past about how he likes to do this stuff with ip udp in a very lightweight way so it maybe worthwhile giving him a ping.
Â
@wolgangw
a further few thoughts for you before I turn in for the night whilst I wait for swimbo to finish watching some silly movie and my thoughts turn to my project. I'm on to doing a gui in python and it sure makes me wish I had a good old visual basic type of program to do this with.
But on to mqtt and @frogandtoad remarks on error handling. The Last Will and Testimony facility is to do with errors in the MQTT pub/sub process where connections are unexpectedly lost. With the arduino mqtt library I used this may not be much use as this lib appears to disconnect by design on a regular basis. The MQTT library I used for the rpi python code expects to be connected until the program closes.
Of course you will still have to report errors like incorrect readings, suspect readings, or the sensor not being available etc via published MQTT messages. A catch all for MQTT pub/sub errors is as per example in the in the rpi receiver program that sets and removes flags to check if the requested response was received. (the code was just a somewhat crude example of using a single global variable for this and can be improved) We must remember that publishing a MQTT message does not mean that a subscriber is expected to pick it up. The last message published can be retained on the broker if you desire for a new subscriber to pick it up when it connects.
And another comment is on the fact that I have had an mqtt broker running on an old rpi2 for some years now. Its not heavily bombarded but it pub/subs messages from a bunch of sensors giving messages on temperature, wind speed, wind direction, rainfall data, plus commands to switch on lights, and front gate opening etc. It's proved to be fast and reliable in this sort of environment so how far you wish to take checking for MQTT pub/sub errors is up to how critical the data is. I log stuff every 15 minutes to the database, but it would not mean much for historic trends if the logging stopped for an hour.
I know you are an experience C# programmer who will bring you own perspective to code written for microprocessors, and I know you have put some comments in some other thread about global variables etc. However for these small programs I think you will find it advantageous not to take the 'big program' thought process to the task. A very pythonic thought it is, but readability for you (or me in my case) it what should rule. Global variables, functions that do three things at once, I happily break best practice rules all the time 😎 .  I suggest to folk, especially beginners, that they should think twice about obfuscating their code with  attempting to do C++ classes when coding in the Arduino environment where simple functions will do. Admittedly as the programs we can fit on our microprocessors gets larger and we put in more sophisticated code one would need to tighten up on ones approach.  But most programs I do, and see other do, in this hobby environment are really quite small.  @frogandtoad is the forums code policeman and a stickler for the rules and I've received several violation tickets from him, but I've yet to pay the fine 😀Â
What do you think?
The code was quickly cobbled together to illustrate mqtt messages going to and fro and as you can see there was hardly any error checking. Â The document I included on the mqtt library for the arduino indicates all the return codes. Â Your suggested amendments are all valid and, as the program is very short I suggest you submit an amended example of the arduino code in case it may help someone.Â
The whole point is that the code you provided is very unsafe, where safety was one of the key points @wolfgangw was inquiring about, and of which you also spoke about in previous posts. As for return codes, the function you wrote with itâs given signature is not even capable of returning any of them, so I was highlighting that for your oversight as well.
Aside from providing all the return codes for the status function, I also provided code examples for how each of the three functions I discussed should be used?
On the subject of secure networks it is worth pointing that out. Â Also to be wary of is the use of the mysql_connector, which I usually use for connecting to my mariadb, which could be the subject of an sql injection attack. Â However all my programs only work with my home network and are not used over any internet connection. Â If anyone is intending to use communications outside of their home network then security should be an important consideration.
Itâs not so much the connector, itâs a host of other setups and or configurations, for example: turning off installation defaults, user access, passwords, encryption, stored procedures and prepared statements to try and avert SQL injection attacks.
And a note to anyone looking at the python program, this is again just a quickly written program for illustrative purposes so don't take it as a finished program. Â It was the first time I used the inbuilt python sqlite3 database so I was interested in seeing what it could do (and it confirmed that I should stick with a proper database for my usual db work :). Â Im still working on a much larger program that interacts with mqtt messages with some gui windows, and I may take a different approach to checking if, when a mqtt message is published that is expecting a response, that a response has actually been received.
Thus far I have found, in my home network, the mqtt to be completely reliable and fast so much so that I only use mqtt QOS 0 (i.e. just send and hope :). Â I may revise this as I'm now doing a time critical (serval minutes, not u_seconds) program for my heating control.
Indeed, MQTT is faster than HTTP requests, and a good choice for home automation. I also think as I mentioned in my previous post, that QoS should be incorporated to guarantee message delivery for obvious safety reasons.
A final thought for @wolfgangw, the mqtt is a lightweight and fast protocol and is useful for sending info over an ethernet network like temperature readings or sending a command to switch on a light that is triggered by a remote microprocessor etc. Â If your only desire is to store the reading in a database then, of course, you could establish a database connection direct from your esp8266 to update the database with the likes of a mysql_connetor. Â There are libraries for this available for the arduino environment. Â But if you are building an IOT home-brewed solution I think you will find mqtt to be a useful tool with a lot less faffing about than with ip tcp web type libraries as a solution of passing data. Â (but like everything - it depends...) However, now I think of it, @robo-pi wrote something in the past about how he likes to do this stuff with ip udp in a very lightweight way so it maybe worthwhile giving him a ping.
It might require a little more setup time (and depending on how far one wants to take home automation), but one may be better off installing Home Assistant, with Node-RED, InfluxDB and a host of other tools to make things easier in the long run.
Cheers.
But on to mqtt and @frogandtoad remarks on error handling. The Last Will and Testimony facility is to do with errors in the MQTT pub/sub process where connections are unexpectedly lost. With the arduino mqtt library I used this may not be much use as this lib appears to disconnect by design on a regular basis. The MQTT library I used for the rpi python code expects to be connected until the program closes.
That disconnection is more to do with the TCP protocol. All the libraries work in the same way really, itâs just that some libraries provide functions to handle such disconnections for you, whereas others expect the user to handle it directly.
Of course you will still have to report errors like incorrect readings, suspect readings, or the sensor not being available etc via published MQTT messages. A catch all for MQTT pub/sub errors is as per example in the in the rpi receiver program that sets and removes flags to check if the requested response was received. (the code was just a somewhat crude example of using a single global variable for this and can be improved) We must remember that publishing a MQTT message does not mean that a subscriber is expected to pick it up. The last message published can be retained on the broker if you desire for a new subscriber to pick it up when it connects
Going back to my previous post, I donât really see this kind of error handling as warranted by each client, or in the spirit of using MQTT. For example, I think a sensor should only implement a last will message upon subscription for hard disconnections, and simply publish temperature readings or a NaN otherwise, thatâs it.
Ideally you want to run a separate client acting as a dashboard subscribed to all of the topics in your home. It can then provide real time monitoring of your devices, provide alerting services and even delegate to another client to handle specific errors.
A very pythonic thought it is, but readability for you (or me in my case) it what should rule.
Everyone should strive for readability, and one of the key points of readability is providing good meaningful identifier, function and class names. Doing so makes ones code self documenting, reducing the need for silly comments, for example:
int t_n[6]; // An array to store tattslotto numbers, vs... int tattslotto_numbers[6];
Global variables, functions that do three things at once, I happily break best practice rules all the time đ .  I suggest to folk, especially beginners, that they should think twice about obfuscating their code with  attempting to do C++ classes when coding in the Arduino environment where simple functions will do.
On the contrary⊠I know you donât like classes, not even in python, but they become essential when programs start to gain complexity, and in fact⊠they make ones code and program logic that much cleaner and easier to understand, let alone easier to debug code, etc⊠there are many advantages to using classes, and they even become necessary to write programs you could never write procedurally.
Admittedly as the programs we can fit on our microprocessors gets larger and we put in more sophisticated code one would need to tighten up on ones approach. Â But most programs I do, and see other do, in this hobby environment are really quite small.
Thatâs not entirely true. Take DB1 for example. Just one of the modules Iâve seen floating around is already around 1,000 lines of code alone, and not at all finished. Weâve discussed the need for classes in the past, and again, IMO, you cannot program a robot of this complexity without classes.
@frogandtoad is the forums code policeman and a stickler for the rules and I've received several violation tickets from him, but I've yet to pay the fine :).Â
Hardly a policeman or stickler⊠I simply point out for the benefit of everyone (especially beginners), when someone posts poor or wrong code or information. Likewise, I am always more than happy to be corrected if I do the same.
Would you stay silent if you saw someone provided an example that connects two AC 400V Active and Neutral wires together?
Silence is Compliance!
My advice to you is to learn how to program using classes in both C++ and Python, and youâll thank me for it in the long run đ
Cheers.
The whole point is that the code you provided is very unsafe, where safety was one of the key points @wolfgangw was inquiring about
I think wolfgang was looking to see how to handle errors that can occur when reading a temperature sensor.  MQTT is a good way of communicating between different microprocessors and computers and introducing MQTT for these  communications means one has to consider the extra errors that may be caused by using the MQTT pub/sub. I have found that MQTT is reliable enough for messaging temperature type data without resorting to higher Quality of Service level provided by MQTT, but they are there to be used if desired.  If you feel that a better example client program should be provided then why not just do so.Â
I know you donât like classes, not even in python,
No, that is not correct.  In python I caution about the creating user classes when they are not necessary which is often done by folks coming to python from other languages.  In python everything is an object. Take the creation of a variable to hold a string. For example if you create  myVar = 'hello'.  and the type dir(myVar) you will see all the methods your newly created object has inherited.  So when I see folks say 'I use classes to break up my code', I say have you considered breaking up your code into separate files.  You can use the functions in a separate file in python by >> import 'myfile' as MF - and then using the functions in that file with MF.myfunction() in the main file.  The namespace in python is very powerful.  Yes python classes can do similar but at the expense of some readability.  Classes are not to be ignored, just not used unnecessarily.  I am in the process of coding a python GUI and I've been getting up to speed with tkinter.  In looking at examples I've seen some that create a class for tkinter, but do nothing about modifying the methods.  tkinter is a class anyway so creating a user class (a subclass) is not necessary.  There are good cases to use classes and I like them very much.
When it comes to C++ however I find that classes make the code a whole magnitude more unreadable for the usually small chunks of code we do for microprocessors.
Thatâs not entirely true. Take DB1 for example.
That was in response to when I said most code written for microprocessors..... Â Most indicates a large majority but not all. Â However you choose the example of the so far published DB1 code. Â I did not count the number of lines but it was an easy readable bit of code that did not appear to warrant the use of classes. Â You indicated you thought is should be broken into classes way back when, but your suggested code improvements did not include a single class. Â I don't think this particular code will grow much as the whole way of working with DB1 appears to be discrete code running on a number of microprocessors that communicate via i2c
It might require a little more setup time (and depending on how far one wants to take home automation), but one may be better off installing Home Assistant, with Node-RED, InfluxDB and a host of other tools to make things easier in the long run.
Yes, each to his own. Â I've played about with them but these frameworks don't appeal to me, good though they are, as I prefer a more home brewed solution.
Would you stay silent if you saw someone provided an example that connects two AC 400V Active and Neutral wires together?
Â
Now you are being silly.
The whole point is that the code you provided is very unsafe, where safety was one of the key points @wolfgangw was inquiring about
I think wolfgang was looking to see how to handle errors that can occur when reading a temperature sensor. Â MQTT is a good way of communicating between different microprocessors and computers
Yes, he was, but the discussion was also about what if something drastic happens to cause a device to go offline, in which you contributed with the following comments:
<Quote>
But what happens if the whole the rpi to which the temp sensor is attached goes down and fails to report to the heating control? For this I record the time when a temperature reading is received so I can easily periodically check if it has not been updated within a specified timespan. Again no need to have any complicated callbacks of other horrible things as you call them.
If my main heating rpi stops functioning I will freeze. Though I hope the dropping temperature will trigger me to flip the switch to revert to the old wall thermostat control.
</Quote>
...but then you concede by what you've written, that you're not actually using a "last will message" at all, and prefer to rely on your own checking, hence one of the reasons I picked you up on that in your code example.
If you feel that a better example client program should be provided then why not just do so.Â
Again, I already provided you with improved code examples for the three functions discussed, and you are free to incorporate them into your program. Are you expecting me to write a whole program for you? Please have a go, and do share your final code. I'll be more than happy to suggest any improvements - As you noted, this is such a small program, so shouldn't take you more than a couple of hours at most to refactor it.
I know you donât like classes, not even in python,
No, that is not correct. Â In python I caution about the creating user classes when they are not necessary which is often done by folks coming to python from other languages. Â In python everything is an object.
I'm pretty sure you cautioned Robo Pi against using them in tkinter. Perhaps these folks understand and appreciate the power and flexibility of classes with respect to: reduced code, reuse, etc... more than you do?
I'm not sure how this matters in this discussion, but for some additional trivia... did you know that everything in C++ is also an object?
 I am in the process of coding a python GUI and I've been getting up to speed with tkinter.  In looking at examples I've seen some that create a class for tkinter, but do nothing about modifying the methods.
I'm not sure what you mean by "modifying the methods"?
When it comes to C++ however I find that classes make the code a whole magnitude more unreadable for the usually small chunks of code we do for microprocessors.
You are of course entitled to feel that way, but I'd be surprised if anyone viewing the following example (the class will be hidden from view in a header file), would consider it to be more difficult to understand than your procedural example, even for such a short piece of code:
// Example client class... class Client { Â private: Â Â Â String name; Â Â Â String topic; Â Â Â // etc... Â public: Â Â Â Switch(String name) : name(name) {...} Â Â Â int connect(String server) {...} Â Â Â bool subscribe(String topic) {...} Â Â Â bool unsubscribe (String topic) {...} Â Â Â void on() {...} Â Â Â void off() {...} Â Â Â // etc... }; // Example usage of client class... Client kitchenLight("Kitchen Light"); Â kitchenLight.connect("server"); Â kitchenLight.subscribe("lights/kitchen"); Â kitchenLight.on(); Â kitchenLight.off();
Thatâs not entirely true. Take DB1 for example.
That was in response to when I said most code written for microprocessors..... Â Most indicates a large majority but not all. Â However you choose the example of the so far published DB1 code. Â I did not count the number of lines but it was an easy readable bit of code that did not appear to warrant the use of classes. Â You indicated you thought is should be broken into classes way back when, but your suggested code improvements did not include a single class.Â
I used that because you said large! This particular code I mentioned was only one (still incomplete) module, and already growing large (it will probably end up more than 1,000 lines of code when finished). I did suggest code improvements, and I did provide code examples for the existing code. I also suggested breaking it up into classes at the time, but there was no real interest, and not just from you, so I'm not going to write a bunch of classes that no one is interested in, especially when I'm not building DB1 for myself.
Would you stay silent if you saw someone provided an example that connects two AC 400V Active and Neutral wires together?
Now you are being silly.
It was the perfect analogy to counter your policeman/stickler comment, but I've come to expect nothing less from one of the forum's most positive members đ
...but then you concede by what you've written, that you're not actually using a "last will message" at all,
I have not used it up to now, but may do so in my latest more critical program. Â My example was to show MQTT messages going between an esp8266 and a rpi in a simple way and to indicate and provide links to documents containing examples, for a more robust use.
I already provided you with improved code examples
Some simple and obvious improvements you have suggested, but not on the thing you harp on about, namely the last will and QOS. Â I dont think an example of their use is needed as the doc links suffice. Â You have stated that this think this should be provided, but obviously don't feel this should be for you to provide. Â Just more noise.
I'm not sure what you mean by "modifying the methods"?
I mean inheriting the class methods and adding to, or overriding them. Â Isn't this obvious?
I'd be surprised if anyone viewing the following example (the class will be hidden from view in a header file), would consider it to be more difficult to understand than your procedural example
You are of course entitled to feel that way
For a simple example I might agree, but for MQTT where a connection to a broker is established and subscriptions made with 3 or 4 lines code early in the procedural code, then one only needs to use a single line like client1.publish("/lights/kitchen", "on"). Â (well that was python I let you think in C). No need to create a class, instantiate it and then use its methods. Â But no harm done if you choose to write a class for this of course, but why bother for a short bit of code to read a temperature sensor. Â You are, of course, entitled to feel differently.
I'm pretty sure you cautioned Robo Pi against using them in tkinter.
Nope. Â Read the thread again. Â Its not decent to put words into others mouth when you have not bothered to check on their accuracy. Â Naughty boy froggy.
It was the perfect analogyÂ
No, it was silly.
I have not used it up to now, but may do so in my latest more critical program.
Yes, I know... that's why I highlighted it. Let's put it this way... if you don't employ such features, then what benefit are you actually getting out of using MQTT over and above other communication methods? Many tutorial's I've read discuss the need to use these features in a positive sense, and advocate their use for good reasons.
Some simple and obvious improvements you have suggested, but not on the thing you harp on about, namely the last will and QOS. Â I dont think an example of their use is needed as the doc links suffice. Â You have stated that this think this should be provided, but obviously don't feel this should be for you to provide. Â Just more noise.
If I do harp on the need to use these features, then it's for good reason, and backed up by many articles on the subject, let alone many years of experience. Why is it that you're always negative against any suggestions for improvement, without actually having any real facts to back up your opposing views?
Once again, it's not my job to code your programs for you, and unless you are able to contribute with valid responses and reasons, rather than negative responses without reasons, then you're the only person making noise here!
I'd be surprised if anyone viewing the following example (the class will be hidden from view in a header file), would consider it to be more difficult to understand than your procedural example
Ok, you chose not to comment on whether the class example I provided was more clear and understandable, but it clearly is. What you fail to understand about OOP (and this is not language specific), is that it is perfectly suited for use with MQTT and home automation. Why? Because many people who employ MQTT want to have many clients... might have 10 light switches, 3 heaters, 3 television's, 8 camera's, 2 toasters, 4 garage lights, 1 door bell ... you get the picture!
The example client class I created can now be used to create all these clients very easily, and with valid names, and without duplicating any code at all, whereas in your procedural code, you will have to copy and paste every client connection function that you wrote, and your code would grow up to 4 times larger, harder to maintain, understand and debug... I could go on. If you don't see the benefit in that, then you got a lot to learn. But just because you can't see it, you should not be making preemptive negative comments for newbies to keep away from using classes and OOP... that's just plain bad advice!
I'm pretty sure you cautioned Robo Pi against using them in tkinter.
Nope. Â Read the thread again. Â Its not decent to put words into others mouth when you have not bothered to check on their accuracy. Â Naughty boy froggy.
Actually, I did read it, and here is your quote to Robo Pi:
More than once I see classes in python being promoted as useful for breaking down large program files, so I caution that one can do this by simply placing functions in separate files too.
Robo Pi even challenged you on your caution, and then you backed down from what I can see.
No, it was silly.
No, it was the perfect analogy... remember, silence is compliance đ
Yes, I know... that's why I highlighted it
Alluding to MQTT and Last Will etc, yes, I know too, thats why I highlighted it in my post and provided links to docs that show its use. Â It is not necessary to use these features at all though in any professional type of program they would be. Whilst it may have been apposite to re-emphasis if you feel I did not highlight their use sufficiently, your additional continual highlighting is more to grandiose I think.Â
Why is it that you're always negative against any suggestions for improvement
It seems you like to create noise, and as we know, this has be pointed out to you by another before.
Robo Pi even challenged you on your caution, and then you backed down from what I can see.
Robo wondered why I use the word 'caution' which maybe was a poor choice of words I did admit  I explained further with some other backup docs where I was coming from, and Robo came to the conclusion that there was indeed no need to create classes just for the purpose of splitting up python code.  So you have endeavoured to pick a small snippet out a thread that does not show its essence, and wonder why I find some of your posts negative.  Was it to grandiose?
What you fail to understand about OOP (and this is not language specific), is that it is perfectly suited for use with MQTT and home automation.Â
No, I do not fail to understand that OOP is well suited for the use of MQTT and home automation.  I do much of this programming in Python.  Do you not understand that using python one is mostly using OOP as all the python libraries are classes, largely written in C and C++, including the MQTT library.  The only thing not relevant to classes and OOP programming are small user constructed programs in the Arduino environment.  The  Arduino libraries are often C++ classes anyway and user created classes, for the purposes of smallish programs like those to read sensors will, in my opinion, obfuscate the code making it harder to understand.  Period.  You continually fantasise by extrapolating about this beyond what I actually write.  So read the words above, and that which I previously stated in this thread about the use of classes in python and my position on all of this should be perfectly clear.  Well it is to me anyway. 😀  I've no wish to change you mind in anyway and I don't really see why you continually try change mine by alluding to some fantasy about what you think I understand.
No, it was the perfect analogy... remember, silence is compliance
Ok, so let's just say that some code froggy writes I think is rather bad. So bad its like risking electrocution from an incorrectly wired high voltage cable, so one cannot be silent about that or risk putting someone at mortal peril. Â That is silly and your analogy was silly. When trying for an OTT analogy you should endeavour at least to find a humorous example. Â Now if I said some of your posts were like a croaking frog, at least that would have some sort of relatively appropriate analogy with humorous connotations. (assuming you have a sense of humour) 🤔 Â Â
croak croak
Hey guys,
I have no idea, what is this debate for. I was asking Byron, whether he want to give me some code example, which allow me to get into the basics of the MQTT. He did and I am happy.Â
If this is helpful or not, I can not judge yet, because I haven't had time to watch and try much.
Later, when I do, I will do it in my way after study the content and I will use it in a way which is matching to my needs, I think most people would do it in such way.
I asked for help, and I got help. This - in my understanding - is what a forum is standing for.
Wolfgang
If I am not here, then I am most probably somewhere else