MQTT: Arduino Simple Read Write

From OnnoWiki
Revision as of 06:56, 11 May 2017 by Onnowpurbo (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

sumber: http://m2mio.tumblr.com/post/30048662088/a-simple-example-arduino-mqtt-m2mio


Connect. Send. Store. Use.

Connect:  The Arduino will connect via MQTT to the m2m broker.
Send:  Sensor data is sent to the broker/platform and command data is sent to the Arduino.
Store:  If formatted correctly, any MQTT traffic going to the broker will be stored for retrieval in the future.
Use:  The platform provides a simple, RESTful API for client applications to make use of their stored data.

Arduino - Hardware

Parts List

  • Arduino Device (in this example an Uno)
  • Arduino Ethernet Shield
  • Photocell
  • Resistors (10k, 330 ohm)
  • LED
  • Wires

Arduino - Software / MQTT

Empat (4) tugas Arduino

  • Gather light sensor readings periodically
  • Publish sensor readings via MQTT
  • Listen for commands via MQTT
  • Control the LED based on a setpoint

An MQTT client is created in the setup function.

Every loop, the following happens:

  • The MQTT client connects (if it is not already connected).
  • Based on the “sensing mode” the application decides how to drive the LED. It could be OFF, ON or SENSE. In the SENSE case a light reading is taken and the LED is driven according to a hardcoded setpoint.
  • In the SENSE case, if 5 seconds have elapsed since the last reading a new reading is published via MQTT.

When connecting an MQTT client a callback function is specified to handle any incoming MQTT messages on the subscribed topic(s). In this function we check for commands in the proper JSON format and adjust our mode if the command specifies a new mode.

An interesting update to this app would be to handle receiving commands to change hardcoded values such as time we wait between publishing light readings or the “light”/“dark” setpoint.

Below is the Arduino code. Note: This requires both the Ethernet library and MQTT Client Library to be installed in your Arduino library folder. See an example here on how to install Arduino libraries. (it’s easy!)


#include <SPI.h>
#include <PubSubClient.h>
#include <Ethernet.h>

/*
 * LightSensorMqttDemo
 *
 * A simple m2m.io platform demo for Arduino.
 */

#define MQTT_SERVER "192.168.0.100"

// MAC Address of Arduino Ethernet Sheild (on sticker on shield)
byte MAC_ADDRESS[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x31, 0xB8 };
IPAddress ip(192, 168, 0, 4);
IPAddress server(192, 168, 0, 100);

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

// Pin 13 is the LED output pin
int ledPin = 13;
// Analog 2 is the input pin
int lightPinIn = 2;

// defines and variable for sensor/control mode
#define MODE_OFF    0  // not sensing light, LED off
#define MODE_ON     1  // not sensing light, LED on
#define MODE_SENSE  2  // sensing light, LED controlled by software
int senseMode = 0;

unsigned long time;

char message_buff[100];

void setup()
{
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);
  
  // init serial link for debugging
  Serial.begin(9600);
  
  if (Ethernet.begin(MAC_ADDRESS) == 0)
  {
      Serial.println("Failed to configure Ethernet using DHCP");
      return;
  }
}

void loop()
{
  if (!client.connected())
  {
      // clientID, username, MD5 encoded password
      // arduino-mqtt, mqtt-spt, e10adc3949ba59abbe56e057f20f883e (123456)
      // arduino-mqtt (bisa tanpa username & password, sebagai anonymous)
      client.connect("arduino-mqtt");
      client.publish("arduino/lightsensor", "I'm alive!");
      client.subscribe("arduino/lightsensor");
  }
  
  switch (senseMode) {
    case MODE_OFF:
      // light should be off
      digitalWrite(ledPin, LOW);
      break;
    case MODE_ON:
      // light should be on
      digitalWrite(ledPin, HIGH);
      break;
    case MODE_SENSE:
      // light is adaptive to light sensor
       
      // read from light sensor (photocell)
      int lightRead = analogRead(lightPinIn); 

      // if there is light in the room, turn off LED
      // else, if it is "dark", turn it on
      // scale of light in this circit is roughly 0 - 900
      // 500 is a "magic number" for "dark"
      if (lightRead > 500) {
        digitalWrite(ledPin, LOW);
      } else {
        digitalWrite(ledPin, HIGH);
      }
      
      // publish light reading every 5 seconds
      if (millis() > (time + 5000)) {
        time = millis();
        String pubString = "{\"report\":{\"light\": \"" + String(lightRead) + "\"}}";
        pubString.toCharArray(message_buff, pubString.length()+1);
        //Serial.println(pubString);
       client.publish("arduino/lightsensor", message_buff);
      }
      
      
  }
  
  // MQTT client loop processing
  client.loop();
} 

// handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  int i = 0;  

  //Serial.println("Message arrived:  topic: " + String(topic));
  //Serial.println("Length: " + String(length,DEC));
  
  // create character buffer with ending null terminator (string)
  for(i=0; i<length; i++) {
    message_buff[i] = payload[i];
  }
  message_buff[i] = '\0';
  
  String msgString = String(message_buff);
  
  //Serial.println("Payload: " + msgString);
  
  if (msgString.equals("{\"command\":{\"lightmode\": \"OFF\"}}")) {
    senseMode = MODE_OFF;
  } else if (msgString.equals("{\"command\":{\"lightmode\": \"ON\"}}")) {
    senseMode = MODE_ON;
  } else if (msgString.equals("{\"command\":{\"lightmode\": \"SENSE\"}}")) {
    senseMode = MODE_SENSE;
  }
}



Referensi