ESP32. MQTT. Broker. Publish. Subscribe. ThingSpeak

9.- App Publish and moves a Servo in ESP32.

p117B_mqtt_Extension_Servo.aia (73.6 KB)

  • Publish juan/mensaje = “increases” —> increases grado +5
  • Publish juan/mensaje = “decreases” —> decreases grado -5
  • Publish juan/mensaje = 90* —> Move Servo to those position

// Juan A. Villalpando.
// http://kio4.com/arduino/117_Wemos_MQTT.htm

//#include <ESP8266WiFi.h> // Para el ESP8266
#include <WiFi.h> // Para el ESP32
WiFiClient WIFI_CLIENT;
#include <PubSubClient.h>
PubSubClient MQTT_CLIENT;

const char* ssid = "Nombre_Red_Wifi";
const char* password = "Clave_Wifi";

// Servo.
#include <Servo.h>
Servo myservo;
#define servoPin  27 // El servo en pin 27
int grado = 90;
String message = "";

void setup() {
  Serial.begin(115200);
  delay(10);
  myservo.attach(servoPin);
  Serial.println();
  Serial.print("Connecting with ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.print("WiFi conected. IP: ");
Serial.println(WiFi.localIP());

// Setting Callback.
  MQTT_CLIENT.setCallback(callback);
}

// What to do when it receives the data. 
void callback(char* recibido, byte* payload, unsigned int length) {
  Serial.print("Message received: ");
  Serial.print(recibido);
  Serial.print("   ");
  message = "";
  for (int i=0;i<length;i++) {
    message += (char)payload[i];
  }
   Serial.println(message);
   if (message == "increases") {grado = grado + 5; myservo.write(grado);}
   if (message == "decreases") {grado = grado - 5; myservo.write(grado);}
   if (message.indexOf("*") != -1)  { // if message contain *
   message = message.substring(0, message.length() - 1); // Delete last char *
   grado = message.toInt();
   myservo.write(grado);
   }
}
 
void loop() {
  if (!MQTT_CLIENT.connected()) {
    reconnect();
  }

  // PUBLISH topic.
  // Does not Publish.
  
  MQTT_CLIENT.loop(); // Check Subscription.

}

// Reconecta con MQTT broker
void reconnect() {
MQTT_CLIENT.setServer("broker.hivemq.com", 1883);  
//MQTT_CLIENT.setServer("mqtt.eclipse.org", 1883);
MQTT_CLIENT.setClient(WIFI_CLIENT);

// Trying connect with broker.
while (!MQTT_CLIENT.connected()) {
Serial.println("Trying to connect with Broker MQTT.");
MQTT_CLIENT.connect("JuanAntonio"); // it isn't necessary..
MQTT_CLIENT.subscribe("juan/mensaje"); // HERE SUBSCRIBE.

// Wait to try to reconnect again...
delay(3000);
}

Serial.println("Conectado a MQTT.");
}
  • It is convenient that the Servo is powered by an external power supply.

10.- Mobile chat.

p117B_mqtt_Extension_Chat.aia (73.8 KB)

oooooooooooooo000oooooooooooooo

1 Like

11.- ThingSpeak Broker. ESP32 uploads random numbers to ThingSpeak.

  • It is necessary to register with an email account: ThingSpeak.
  • For users of the free option, the message update interval limit remains limited at 15 seconds.
  • New Channel.
    Field1 = aleatorio.

  • ESP32 generates a random number every 15 seconds and uploads it to ThingSpeak.

  • Library ThingSpeak.

  • Sketch / Include Library / Manage Libraries… ThingSpeak

// Juan A. Villalpando.
// http://kio4.com/arduino/117_Wemos_MQTT.htm

// #include <ESP8266WiFi.h> // Para ESP8266
#include <WiFi.h> // Para ESP32
WiFiClient WIFI_CLIENT;
#include <ThingSpeak.h>

const char* ssid = "Nombre_de_tu_Red_Wifi";
const char* password = "Clave_Wifi";  

unsigned long Channel_ID = 746330;
const char * WriteAPIKey = "SVRKZNDDNS9TÑÑÑÑ";
unsigned long tiempo_actual = 0;

void setup() {
  Serial.begin(115200);

  WiFi.mode(WIFI_STA);   
  ThingSpeak.begin(WIFI_CLIENT);

  Serial.println();
  Serial.print("Connecting with ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }
  
  Serial.println("");
  Serial.print("WiFi conected. IP: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  if((millis()-tiempo_actual)>= 16000){ // Each 16 seconds upload.
          int alea = random(0,90);
          tiempo_actual = millis();
          // Send alea to field1.
          int x = ThingSpeak.writeField(Channel_ID, 1, alea, WriteAPIKey);
          if(x == 200){ Serial.println("Upload correct: " + String(alea));}
          else{ Serial.println("Upload failed: " + String(alea)); }
  }
}
1 Like

12.- From App Inventor on/off a Lamp in ThingSpeak.

Remember: updates are every 15 seconds or more.

  • This example does not use ESP32.

  • Channel Settings / Field2 --> lamp
  • Add Widgets --> Lamp

2 Likes

13.- App Inventor sends a number to ThingSpeak and gets last value. WebViewer.

Remember: updates are every 15 seconds or more.

p117_thingspeak_valor.aia (3.2 KB)

esp32_thing22

1 Like

14.- App Inventor Publish, sends values by Extension to ThingSpeak.

  • Now with extension.
  • Subscribe doesn’t work for me.

Subscribe: channels/Channel ID/subscribe/fields/field1/ReadAPIKey

Publish: channels/Channel ID/publish/fields/field1/WriteAPIKey

last value: https://api.thingspeak.com/channels/746330/fields/field1/last

1 Like

15.- Others Dashboards.

https://mydevices.com/cayenne/signup/

https://accounts.adafruit.com/settings/profile

http://www.hivemq.com/demos/websocket-client/

1 Like

great job
muy buena explicacion de todo, hice unas pruebas con cloudmqtt con un wemos d1 esp8266 y funciona perfecto todo.
la extension es muy buena.
gracias por toda la informacion.

16.- Basic example of Subscribe and Publish to HiveMQ.

Normally MQTT is used in IoT, example: a sensor in a hardware sends a short message to a Broker and in real time an app receives it, or an app sends a short message to a Broker and this information is received by a hardware that performs a certain function.

We are going to see a basic example of Publish and Subscribe in the HiveMQ Broker.
We will not use hardware, only the application and the Broker.

  • Do this example! No registration required.

https://www.hivemq.com/

p117B_mqtt_Extension_Hivemq.aia (73.6 KB)






esp32_mqtt6
esp32_mqtt7

17.- Example with Slider.

p117Bi_mqtt_Extension_Hivemq_Slider.aia (83.7 KB)

1 Like

18 .- AccelerometerSensor Publish and Subscribe x, y, z. Send and receive the three variables. HiveMQ.

p117B_mqtt_Extension_Hivemq_Acele.aia (72.0 KB)

AcceleratorSensor "Publish" in HiveMQ xAccel,yAccel,zAccel with topic: juan/acelerometer
and "Subscribe" juan/acelerometer, receive: xAccel,yAccel,zAccel

1 Like

why port at hivemq not same with port at mit app?
if i write at hivemq, host : broker.hivemq.com. , at mit app must be broker: broker.hivemq.com . it right?

the topic at publish should be title that my project right?

https://www.hivemq.com/public-mqtt-broker/

please help me how to get updated data on mqtt server
Hello friend I'm studying the mqtt protocol
my project is to turn the room lights on and off with every button publish and subscribe
publish to send data values and subscribe to receive data but there is a problem when the application is disconnected with the subscriber data broker not being successfully updated
if anyone in the mqtt extension can request a request to the broker to update the missed data, I really need advice. thanks

I use the following extension
Ullis Roboter Seite/AI2 MQTT

@Moh_Khafil_A

You have posted the same on Kodular Community. Are you working with Kodular or App Inventor ?

sorry I just want to receive input and suggestions from different forums , because the two platforms are almost the same implementation . is this against the rules? thanks

You didn't answer my question...

not working this porject with Cellular data

You should explain a "little bit" what you are doing.
There are several examples, I tried n. 18 and is working ok:

  • press connect to broker
  • press subscribe
  • press start accel
  • after a few seconds press stop accel
    ( this example is sending too much data to the broker and hivemq asks not to "abuse" their free broker )

The first 3 labels show the "accel data" read from your phone.
The last 3 labels show the same data read back from the broker

P.S.
I added also a status label just to see what's going on, during connection and subscription

P.P.S.
You can also "interact" withe the phone using the hivemq mqtt web client ( just subscribe or publish to the same topic as set in the aia, which is juan/acelerometer )