Skip to content

14. Networking and communications

Individual assignment:

Design, build, and connect wired or wireless node(s) with network or bus addresses

All Network

MQTTLens application web with ESP8266 NodeMcu Publisher and ESP8266 NodeMcu Subscriber.


MQTTLens application

MQTT (Message Queue Telemetry Transport) is an OASIS standard for IoT connectivity. It is a publish/subscribe, extremely simple and lightweight messaging protocol, designed for constrained devices and low-bandwidth, high-latency or unreliable networks.


MQTTLens is a Google Chrome application, which connects to a MQTT broker and is able to subscribe and publish to MQTT topics.


MQTTLens Application


ESP8266 NodeMcu Publisher


ESP8266 NodeMcu Publisher program code

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

String ssid = "XXXX";         //Wifi name
String password = "iiiiiii";  //Wifi password
WiFiClient espClient;
PubSubClient client(espClient);

String mqtt_server = "test.mosquitto.org";
char mqtt_server_array[50];
char message_array[50];
char topic_array[50];

char inChar;
String inString = "",inTopic = "",inMessage = "";
bool actionMqtt, actionModule, flagMqtt = false;

// Process
bool gpio0_state1;
bool out_state1;
bool gpio0_state2;
bool out_state2;

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print(topic);
  Serial.print(",");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  // Analisis de topico
  String topico = String(topic);
  if (topico=="HomeP1204AP/BedRoom/Lamp02"){
    Serial.println("Si es igual topico");
    String mensaje = String((char *)payload);
    Serial.println(mensaje);
    if (mensaje[1]=='N'){
      Serial.println("Mensaje ON");
      digitalWrite(4,HIGH);
      out_state1=HIGH;
    }
    else if (mensaje[1]=='F'){
      Serial.println("Mensaje OFF");
      digitalWrite(4,LOW);
      out_state1=LOW;
    }
    Serial.println("Salio");
  }
}

void clientConnect() {
  // Loop until we're reconnecte
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("HomeP1204AP", "hello world");
      client.subscribe("HomeP1204AP/#");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  mqtt_server.toCharArray( mqtt_server_array, 100 );
  client.setServer(mqtt_server_array, 1883);
  client.setCallback(callback);
  // Process
  pinMode(0,INPUT);
  gpio0_state1 = digitalRead(0);
  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);
  out_state1 = LOW;
}

void loop() {
  if (!client.connected()) {
    clientConnect();
  } else {
    client.loop();
    if (flagMqtt) {
      flagMqtt = false;
      inMessage.toCharArray( message_array, 100 );
      inTopic.toCharArray( topic_array, 100 );
      client.publish(topic_array, message_array);
    }
  }
  bool statep1 = !digitalRead(16);
  if (gpio0_state1 != statep1){
    gpio0_state1 = statep1;
    delay(100);
    if (gpio0_state1){
      // Solte el boton   
    } else {
      // Presione el boton
      out_state1 = !out_state1;
      if (out_state1){
        client.publish("HomeP1204AP/Servo01","ON");
      } else {
        client.publish("HomeP1204AP/Servo01","OFF");
      }
    }
  }
  bool statep2 = !digitalRead(5);
  if (gpio0_state2 != statep2){
    gpio0_state2 = statep2;
    delay(100);
    if (gpio0_state2){
      // Solte el boton   
    } else {
      // Presione el boton
      out_state2 = !out_state2;
      if (out_state2){
        client.publish("HomeP1204AP/Servo02","ON");
      } else {
        client.publish("HomeP1204AP/Servo02","OFF");
      }
    }
  }
}
void serialEvent() {
  while (Serial.available()) {
    inChar = (char)Serial.read();
    switch (inChar){
      case '\r':
        inMessage = inString;
      break;
      case '\n':
        inString = "";
        flagMqtt = true;
      break;
      case ',':
        inTopic = inString;
        inString = "";
      break;
      default:
        inString += inChar;
      break;
    }
  }
}
ESP8266 NodeMcu Subscriber


ESP8266 NodeMcu Subscriber program code

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Servo.h>

String ssid = "XXXX";
String password = "iiiiiiii";
WiFiClient espClient;
PubSubClient client(espClient);

String mqtt_server = "test.mosquitto.org";
char mqtt_server_array[50];
char message_array[50];
char topic_array[50];

char inChar;
String inString = "",inTopic = "",inMessage = "";
bool actionMqtt, actionModule, flagMqtt = false;

// Process
bool gpio0_state;
bool out_state;

int servo01_pin = 14;
Servo myservo01;
int angle01 = 0;

int servo02_pin = 13;
Servo myservo02;
int angle02 = 0;

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print(topic);
  Serial.print(",");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  // Analisis de topico
  String topico = String(topic);
  if (topico=="HomeP1204AP/Servo01"){
    Serial.println("Si es igual topico");
    String mensaje = String((char *)payload);
    Serial.println(mensaje);
    if (mensaje[1]=='N'){
      Serial.println("Mensaje ON");
//      digitalWrite(4,HIGH);
//      out_state=HIGH;
      for(angle01 = 0; angle01 < 180; angle01 += 1) {                          
        myservo01.write(angle01);
        delay(10);                       
      }
    } else if (mensaje[1]=='F'){
      Serial.println("Mensaje OFF");
//      digitalWrite(4,LOW);
//      out_state=LOW;
      for(angle01 = 180; angle01 >= 1; angle01 -= 1) {                                
        myservo01.write(angle01);
        delay(10);                       
      } 
    }
    Serial.println("Salio");
  }
  if (topico=="HomeP1204AP/Servo02"){
    Serial.println("Si es igual topico");
    String mensaje = String((char *)payload);
    Serial.println(mensaje);
    if (mensaje[1]=='N'){
      Serial.println("Mensaje ON");
      for(angle02 = 0; angle02 < 180; angle02 += 1) {                          
        myservo02.write(angle02);
        delay(10);                       
      }
    } else if (mensaje[1]=='F'){
      Serial.println("Mensaje OFF");
      for(angle02 = 180; angle02 >= 1; angle02 -= 1) {                                
        myservo02.write(angle02);
        delay(10);                       
      } 
    }
    Serial.println("Salio");
  }
}

void clientConnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("HomeP1204AP", "hello world");
      client.subscribe("HomeP1204AP/#");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  mqtt_server.toCharArray( mqtt_server_array, 100 );
  client.setServer(mqtt_server_array, 1883);
  client.setCallback(callback);
  // Process
  pinMode(0,INPUT);
  gpio0_state = digitalRead(0);
//  pinMode(4,OUTPUT);
//  digitalWrite(4,LOW);
//  out_state = LOW;
  myservo01.attach(servo01_pin);
  myservo02.attach(servo02_pin);
  myservo01.write(angle01);
  myservo02.write(angle02);
}

void loop() {
  if (!client.connected()) {
    clientConnect();
  } else {
    client.loop();
    if (flagMqtt) {
      flagMqtt = false;
      inMessage.toCharArray( message_array, 100 );
      inTopic.toCharArray( topic_array, 100 );
      client.publish(topic_array, message_array);
    }
  }
  bool state = digitalRead(0);
  if (gpio0_state != state){
    gpio0_state = state;
    delay(100);
    if (gpio0_state){
      // Solte el boton   
    } else {
      // Presione el boton
      out_state = !out_state;
      if (out_state){
        client.publish("HomeP1204AP/BedRoom/Lamp02","ON");
      } else {
        client.publish("HomeP1204AP/BedRoom/Lamp02","OFF");
      }
    }
  }
}
void serialEvent() {
  while (Serial.available()) {
    inChar = (char)Serial.read();
    switch (inChar){
      case '\r':
        inMessage = inString;
      break;
      case '\n':
        inString = "";
        flagMqtt = true;
      break;
      case ',':
        inTopic = inString;
        inString = "";
      break;
      default:
        inString += inChar;
      break;
    }
  }
}

Group assignment:

Send a message between two projects

Download Files