Pengenalan Komunikasi M2M (Machine to Machine) Via MQTT

1. Apa itu komunikasi M2M (Machine to Machine)?

Komunikasi machine to machine (M2M) adalah komunikasi langsung antar perangkat menggunakan sebuah kanal (channel) komunikasi yang terhubung menggunakan kabel (wired) maupun nirkabel (wireless).

https://en.wikipedia.org/wiki/Machine_to_machine

2. M2M menggunakan HiveMQ

Telah dibahas pada artikel sebelumnya mengenai MQTT HiveMQ. MQTT ini berperan sebagai hub (penghubung) dari beberapa perangkat, hal ini memungkinkan perangkat-perangkat untuk bertukar informasi satu sama lain. Pada artikel ini akan dibahas bagaimana caranya dua perangkat arduino MKR1000 untuk saling berkomunikasi melalui HiveMQ, berikut adalah alat dan bahan yang diperlukan.

  1. Arduino MKR1000 development board @ 2 unit
  2. Arduino IDE
  3. Analog Sensor @ 1 unit
  4. Push Button @1 unit atau lebih
  5. LCD @ 2 unit
  6. LED @ 1 unit atau lebih
  7. PC @ 1 unit
  8. Koneksi WiFi

Untuk percobaan kali ini tentukan peran dari masing-masing board Arduino MKR1000, ada yang berperan sebagai publisher (transmiter/pemancar data) dan subscriber (receiver/penerima data). Pasanglah sensor analog dan push button pada unit publisher dan pasang LED dan LCD pada unit subscriber. Setelah dipasang upload program dibawah ini pada unit publisher.

//Program RDD M2M MQTT Publisher Unit
//RDD Team

#include <WiFi101.h>
#include <PubSubClient.h>
//#include "mkr1000_secrets.h"
#define MSG_BUFFER_SIZE  (50)
#include <Wire.h>
#include "DFRobot_RGBLCD.h"

char msg[MSG_BUFFER_SIZE];
IPAddress ReadIP;
const char* ssid = "RDD Office";
const char* password = "Honeyw3ll1";
const char* mqtt_server = "broker.mqttdashboard.com";

String StrTopic;
String StrPayload;

WiFiClient mkrClient;
PubSubClient client(mkrClient);


const int  lm35Pin = A0;
float lm35Val;
const int numReadings = 10;
int lm35Raw;

const int buttonPin0 = 0;
int buttonPushCounter0 = 0;
int buttonState0 = 0; 
int lastButtonState0 = 0;
int buttonUpdate0;
unsigned long currentMillis,previousMillis;
unsigned long currentMillis1,previousMillis1;
const int colorR = 255;
const int colorG = 255;
const int colorB = 255; 
DFRobot_RGBLCD lcd(16,2);
void setup_wifi() 
{
  delay(10);
  
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  ReadIP = WiFi.localIP();
  Serial.println(ReadIP);
}

void callback(char* topic, byte* payload, unsigned int length) 
{
  StrTopic=topic;
  Serial.print("Message arrived [");
  Serial.print(StrTopic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) 
  {
      StrPayload=StrPayload+(char)payload[i];
  }
  Serial.print(StrPayload);
  Serial.println();

  if (StrTopic == "RDD/Ack_LED0")
  {
    Serial.println("RDD/Ack_LED0");
    if (StrPayload == "OFF") 
    {
      
      lcd.setCursor(0,1);
      lcd.print("LED : OFF");
      Serial.println("LED0 OFF");
    } 
    else if (StrPayload == "ON") 
    {
      
      lcd.setCursor(0,1);
      lcd.print("LED : ON "); 
      Serial.println("LED0 ON");
    }
    else
    {
      
      lcd.setCursor(1,1);
      lcd.print("OFF");  
      Serial.println("LED0 OFF");
    }
    StrPayload="";
  }
}
void reconnect() 
{
 
  while (!client.connected()) 
  {
    Serial.print("Attempting MQTT connection...");
    
    String clientId = "rdd_mkr1000_unit0";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) 
    {
      Serial.println("connected");
      client.publish("RDD/Get_Temp", msg);
      client.subscribe("RDD/Ack_LED0");
    } 
    else 
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}
void setup() {
 Serial.begin(115200);

 lcd.init();
 lcd.setRGB(colorR, colorG, colorB);
 lcd.setCursor(0,0);
 lcd.print("MQTT PUBLISHER");
 lcd.clear();
 delay(2000);

 analogReadResolution(12);
 analogReference(AR_DEFAULT);
 
 pinMode(buttonPin0, INPUT);
 setup_wifi();
 client.setServer(mqtt_server, 1883);
 client.setCallback(callback);
 buttonUpdate0=100;
}

void loop() {
  if (!client.connected()) 
  {
    reconnect();
  }
  client.loop();
  lm35Raw = analogRead(A0);
  lm35Val = (lm35Raw/4095.0)*3.3;
  lm35Val = lm35Val*147.252;
  buttonState0 = digitalRead(buttonPin0);
  currentMillis = millis();
  currentMillis1 = millis();
  if (currentMillis-previousMillis > 200)
  {
    if (buttonState0 != lastButtonState0) 
    {
      if (buttonState0 == HIGH) 
      {
        client.publish("RDD/Set_LED0", "ON");
      }
    }  
    else
    {
        client.publish("RDD/Set_LED0", "OFF");
    }
    
    previousMillis = currentMillis;
    buttonState0 = lastButtonState0;
  }
  if (currentMillis1-previousMillis1 > 2000)
  {
      snprintf (msg, MSG_BUFFER_SIZE , "%.2f",  lm35Val);
      previousMillis1 = currentMillis1;
      client.publish("RDD/Get_Temp", msg);
      lcd.setCursor(0,0);
      lcd.print("Temp:");
      lcd.setCursor(5,0);
      lcd.print(lm35Val);
      lcd.setCursor(11,0);
      lcd.print("^C");
  }
}

Program diatas menggunakan pin D0 sebagai input push button dan A0 sebagai sebagai input sensor analog. Lalu mengirimkan datanya melalui MQTT. LCD pada unit publisher sebagai indikator bahwa perintah sudah diterima / ack (acknowledged) oleh unit subcriber. Setelah upload program publisher, upload-lah program dibawah ini pada unit subscriber.

//Program RDD M2M MQTT Subscriber Unit
//RDD Team


#include <WiFi101.h>
#include <PubSubClient.h>
#include "DFRobot_RGBLCD.h"

#define LED0         5
#define FB_LED0_ON        10
#define FB_LED0_OFF       15
#define LCD_Update        100
#define LCD_OFF           0

const int colorR = 255;
const int colorG = 0;
const int colorB = 0;
char LCD;
char Feedback_LED;
float Temp;
IPAddress ReadIP;
DFRobot_RGBLCD lcd(16,2);
const char* ssid = "RDD Office";
const char* password = "Honeyw3ll1";
const char* mqtt_server = "broker.mqttdashboard.com";

WiFiClient MKRClient;
PubSubClient client(MKRClient);
long lastMsg = 0;
char msg[50];
int value = 0;
String StrTopic;
String StrPayload;
unsigned long currentMillis,previousMillis;
void setup_wifi() {

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

  WiFi.begin(ssid, password);

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

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  ReadIP = WiFi.localIP();
  Serial.println(ReadIP);
}
void callback(char* topic, byte* payload, unsigned int length) 
{
  StrTopic=topic;
  Serial.print("Message arrived [");
  Serial.print(StrTopic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
      StrPayload=StrPayload+(char)payload[i];
  }
  Serial.print(StrPayload);
  Serial.println();

  //Scan Topic
  if (StrTopic == "RDD/Set_LED0")
  {
    if (StrPayload == "OFF") 
    {
      digitalWrite(LED0, LOW);   // Turn the LED off
      Serial.println("LED0 OFF");
      Feedback_LED= FB_LED0_OFF;
    } 
    if (StrPayload == "ON") 
    {
      digitalWrite(LED0, HIGH);  // Turn the LED on
      Serial.println("LED0 ON");
      Feedback_LED= FB_LED0_ON;
    }
    StrPayload="";
  }
  else if (StrTopic == "RDD/Get_Temp")
  {
    Serial.println(StrPayload);
    Temp=StrPayload.toFloat();
    StrPayload="";
    LCD=LCD_Update;
  }
  else
  {
    StrPayload="";
  }
}
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "MKRClient-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      // ... and resubscribe
      client.subscribe("RDD/Set_LED0");
      client.subscribe("RDD/Get_Temp");
    } 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() {
  pinMode(LED0,OUTPUT);
   lcd.init();
   lcd.setRGB(colorR, colorG, colorB);
   lcd.setCursor(0,0);
   lcd.print("MQTT Subscriber");
   Serial.begin(115200);
   setup_wifi();
   client.setServer(mqtt_server, 1883);
   client.setCallback(callback);
   LCD=LCD_Update;
   Feedback_LED = FB_LED0_OFF;
}

void loop() {

  if (!client.connected()) {
  reconnect();
  }
  client.loop();

  if (LCD == LCD_Update)//Update data in LCD screen
  { 
    lcd.setCursor(0,1);
    lcd.print("Temp:");
    lcd.setCursor(5,1);
    lcd.print(Temp);
    lcd.setCursor(11,1);
    lcd.print("^C");
    LCD=LCD_OFF;
  }
  currentMillis = millis();
  if (currentMillis - previousMillis >200)
  {
    if (Feedback_LED == FB_LED0_ON)
    {
      client.publish("RDD/Ack_LED0","ON");
    }
    if (Feedback_LED == FB_LED0_OFF)
    {
      client.publish("RDD/Ack_LED0","OFF");
    }
    previousMillis = currentMillis;
  }

}

Program diatas menggunakan Pin D5 dan LCD. LCD digunakan untuk menampilkan data suhu yang didapatkan dari publisher.

Buka HiveMQ pada web browser dan tambahlah topic subcription sesuai dengan yang ada diprogram. Setelah ditambah maka akan muncul seperti gambar 1.1 dibawah. Coba nyalakan LED pada unit subscriber dengan menekan button pada unit publisher dan juga lihat apakah pembacaan nilai analog pada unit publisher muncul pada layar LCD unit subscriber. Jika kedua hal diatas telah berhasil maka M2M menggunakan HiveMQ telah tercapai.

1.1 HiveMQ

Was this article helpful?

Related Articles

Leave A Comment?