Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
en:iot-open:practical:hardware:sut:esp32:iot_3 [2024/04/21 11:27] – created pczekalskien:iot-open:practical:hardware:sut:esp32:iot_3 [2024/04/28 16:45] (current) – [Suggested Readings and Knowledge Resources] pczekalski
Line 1: Line 1:
-<todo @pczekalski>Dokończyć</todo> 
 ====== IOT3: Connecting to the MQTT and publishing data ====== ====== IOT3: Connecting to the MQTT and publishing data ======
 In the following scenario, you will learn how to connect to the MQTT broker and publish a message. In the following scenario, you will learn how to connect to the MQTT broker and publish a message.
Line 11: Line 10:
   * [[[en:iot-open:practical:hardware:sut:esp32:iot_2|]].   * [[[en:iot-open:practical:hardware:sut:esp32:iot_2|]].
  
-<todo @pczekalski>Tu trzeba dodać bibliotekę do MQTT, pewnie pub-sub client</todo>+There are many implementations of the MQTT protocolbut we will use the following library: 
 +<code ini> 
 +lib_deps =  
 +    knolleary/PubSubClient@^2.8 
 +</code>
  
 ===== Suggested Readings and Knowledge Resources ===== ===== Suggested Readings and Knowledge Resources =====
Line 17: Line 20:
   * [[en:iot-open:hardware2:esp32|]],   * [[en:iot-open:hardware2:esp32|]],
   * [[en:iot-open:practical:hardware:sut:esp32|]],   * [[en:iot-open:practical:hardware:sut:esp32|]],
-  * [[en:iot-open:iotprogramming2:espressif_networking|]].+  * [[en:iot-open:iotprogramming2:espressif_networking|]] 
 +  * [[en:iot-open:networking2:applicationnetworkprotocols|]].
  
 ===== Hands-on Lab Scenario ===== ===== Hands-on Lab Scenario =====
 +Note - this scenario can be used in pair with [[[en:iot-open:practical:hardware:sut:esp32:iot_4|]] to build a publish-subscribe solution using two devices (sender and receiver). You need to book two devices then and develop them in parallel.
  
 ==== Task to be implemented ==== ==== Task to be implemented ====
-Connect to the "internal IoT" WiFI access point as presented in the scenario [[[en:iot-open:practical:hardware:sut:esp32:iot_2|]]—present connection status on the display (for tracing). Once connected to the networking layer, connect to the MQTT broker and present the connection status on the display, then publish an MQTT message. +Connect to the "internal IoT" WiFI access point as presented in the scenario [[[en:iot-open:practical:hardware:sut:esp32:iot_2|]]—present connection status on display. Once connected to the networking layer (WiFi), connect the MQTT client to the MQTT broker and present the connection status on the display, then publish an MQTT message of your choice
-<note warning>MQTT clients are identified by their name, so use a unique one, e.g., the end of the IP address assigned, your unique name, etc. It is essential because if you accidentally use someone else's name then you will mess with messages, and your MQTT client will be instantly disconnected when another one with the same name connects!</note>+<note warning>MQTT clients are identified by their name, so use a unique one, e.g., the end of the IP address assigned, your unique name, etc. It is essential because if you accidentally use someone else's namethen you will mess with messages, and your MQTT client will be instantly disconnected when another one with the same name connects!</note>
  
 ==== Start ==== ==== Start ====
Line 32: Line 37:
  
 === Step 1 === === Step 1 ===
-Include the WiFi management library in your source code: +Once the device is booked, check if your display of choice is visible in the camera's FOV.\\  
-<code c> +Refer to the hardware documentation and ensure an understanding of the network infrastructure you're interfacing with.\\ 
-#include <WiFi.h> +Implement the code to display on the selected device.\\ 
-</code> +Connect to the WiFi in the STA mode (as a client) and ensure the connection is OK and you got an IP from the DHCP server.
-The WiFi library automatically initialises a singleton class, ''WiFi,'' which you can use to set up working mode, read MAC and IP, and perform many other operations.+
  
 === Step 2 === === Step 2 ===
-Declare some constants, including AP SSID and passphrase and a variable to store IP:+Include the MQTT implementation library header in your code:
 <code c> <code c>
-const char* ssid = "REPLACE_WITH_CORRECT_SSID"; +#include <PubSubClient.h>
-const char* pass = "REPLACE_WITH_CORRENT_PASSPHRASE"; +
-IPAddress localIP;+
 </code> </code>
- 
-Both ''ssid'' and ''pass'' are to be obtained from the hardware reference, available here: [[en:iot-open:practical:hardware:sut:esp32|]]. 
- 
  
 === Step 3 === === Step 3 ===
-Set your device in the STA mode and connect to the WiFi AP:+Declare necessary addresses, constants, etc.:
 <code c> <code c>
-  WiFi.mode(WIFI_STA); +IPAddress mqttServer(127,0,0,1); //change it to the MQTT broker IP 
-  WiFi.begin(ssidpass); +#define mqtt_user "mqtt user" 
-  while (WiFi.status() != WL_CONNECTED) { +#define mqtt_password "mqtt password" 
-    //Drop some info on display about connecting +#define mqtt_client_id "some_unique_client_id" 
-    delay(1000); +#define mqtt_topic "/sample/topic/comes/here/change/it/please" 
-  }+#define mqtt_payload "sample payload"
 </code> </code>
- +Refer to the technical documentation (nodesor the supervisor's guidance if working in the interactive mode to obtain the ''mqttServer'' IP addressthe ''mqtt_user'' and ''mqtt_password''.\\ 
-The ''WiFi.begin(...)'' returns the following statuses (value, enumerator: meaning): +**Remember to choose some unique client ID and topic!**
-  * 0, ''WL_IDLE_STATUS:'' temporary status assigned when WiFi.begin() is called +
-  * 1, ''WL_NO_SSID_AVAIL:'' when no SSID are available +
-  * 2, ''WL_SCAN_COMPLETED:'' scan networks is completed +
-  3, ''WL_CONNECTED:'' when connected to a WiFi network +
-  4, ''WL_CONNECT_FAILED:'' when the connection fails for all the attempts +
-  5, ''WL_CONNECTION_LOST:'' when the connection is lost +
-  * 6, ''WL_DISCONNECTED:'' when disconnected from a network+
  
 === Step 4 === === Step 4 ===
-Reading the IP as a ''String'' is as easy as simply calling:+Declare WiFi communication client and MQTT communication client:
 <code c> <code c>
-   localIP = WiFi.localIP();+  WiFiClient espClient; 
 +  PubSubClient client(espClient);
 </code> </code>
-The ''IPAddress'' class contains the ''toString()'' method that formats the IP and returns in standard, dot-separated, four-octet text format.+Note that your clients are not yet online!
  
 === Step 5 === === Step 5 ===
-Explicitly disconnect from the WiFi AP to free resources:+Set MQTT client's configuration (proposed in the ''void setup()'' function:
 <code c> <code c>
-  WiFi.disconnect();  +  ... 
 +  client.setServer(mqttServer,1883); //default port is 1883, change if needed 
 +  ...
 </code> </code>
  
-Some useful WiFi functions are listed below: +=== Step 6 === 
-  * ''WiFi.reconnect()'' - reconnects the connection that was droppednote it uses ''ssid'' and ''pass'' previously specified in the ''WiFi.begin(...)''here you do not provide one.  +Finallyconnect the MQTT client to the MQTT broker and publish a message (sample codeadjust to your case): 
-  * ''WiFi.RSSI()'' - once connected, you can get signal strength as ''int8_t'' integer. +<code c> 
-  * ''WiFi.setHostname(const char * hostname)'' - set host name for the ESP32 chip. Remember to use this function before connecting to the AP+  while (!client.connected()) 
-==== Result validation ==== +    { 
-You should be able to connect to the WiFi and present the dynamically assigned IP address by the DHCP server. <note>Note that due to the dynamic nature of the lab, IP addresses can change both during connection (on lease refresh) or between consecutive connects.</note>+      if (client.connect(mqtt_client_id,mqtt_user,mqtt_password)
 +      { 
 +        // Drop some info on the display that the MQTT broker is connected 
 +        client.publish(mqtt_topic,mqtt_payload); 
 +      } 
 +      else 
 +      { 
 +        int status client.state(); //read error code 
 +        //present it on the display to trace/troubleshoot 
 +      } 
 +    } 
 +</code>
  
 +In the case, the client does not connect to the MQTT broker, the ''client.state();'' returns an int that can be interpreted as below:
 +<code c>
 +
 +// Possible values for client.state()
 +#define MQTT_CONNECTION_TIMEOUT     -4
 +#define MQTT_CONNECTION_LOST        -3
 +#define MQTT_CONNECT_FAILED         -2
 +#define MQTT_DISCONNECTED           -1
 +#define MQTT_CONNECTED               0
 +#define MQTT_CONNECT_BAD_PROTOCOL    1
 +#define MQTT_CONNECT_BAD_CLIENT_ID   2
 +#define MQTT_CONNECT_UNAVAILABLE     3
 +#define MQTT_CONNECT_BAD_CREDENTIALS 4
 +#define MQTT_CONNECT_UNAUTHORIZED    5
 +</code>
 +
 +<note tip>In many code samples, including those provided along with this MQTT client library, there is a ''client.loop();'' function executed in the main ''void loop()'' body. While it is obligatory in the case of the use of asynchronous sending and receiving of the MQTT messages, in the simple case as above, it can be abandoned because ''client.publish(topic,payload);'' makes a blocking call and ensures sending of the message to the MQTT broker.</note>
 +==== Result validation ====
 +You should be able to connect to the WiFi and MQTT broker (verified by the status present on the selected display) and then publish a message (once or periodically). Depending on whether you're fully remote or able to access our networks with an additional device, you need to implement a subscriber (as present in the scenario [[[en:iot-open:practical:hardware:sut:esp32:iot_4|]]) or use MQTT Explorer (or any other application capable of connecting to our MQTT Broker) to observe messages that you publish.
 ===== FAQ ===== ===== FAQ =====
-**I set hostname, but it does appear on the router level.**: There are many possible reasons; one is an active registration in the router (APthat keeps an old IP addressso you need to wait until it expires; other reason is you have changed the hostname when you were connected to the AP.\\ +**My MQTT client disconnects randomly**: The most common reason is you're using non-unique MQTT client name. Please change it to some other (even random generated) and give it another try.\\ 
-**Can use a manually configured IP?**: Actually, you can, but we strongly discourage itThis is because you may accidentally overlap this IP address with some other devicerouter, or other infrastructure, blocking its operation.+**How do I observe messages that I send?**: Use a software client, such as [[http://mqtt-explorer.com/| MQTT Explorer]], if you're able to access the "internal IoT" network (you're in the range of the network). If you're remotethe only way is to book another device and implement a client subscribing to your message, as presented in the scenario [[[en:iot-open:practical:hardware:sut:esp32:iot_4|]]. Our MQTT broker is also visible in the campus network on the wired interfaces so that you can access it, e.g. via EduVPN or from the laboratory computers. Refer to the supervisor for IP and credentials.\\ 
 +**Do need to authorise to publish and subscribe?**: Yes, you doThe supervisor provides the user and password on demandalso presented in the Node's technical documentation.
  
 <WRAP noprint> <WRAP noprint>
en/iot-open/practical/hardware/sut/esp32/iot_3.1713698841.txt.gz · Last modified: 2024/04/21 11:27 by pczekalski
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0