2023年1月25日 星期三

WiFi模組通訊實作 – ubidots雲端平台

WiFi模組通訊實作 – ubidots雲端平台

利用HUB-5168+Ameba A1_Lite將資料傳送到https://stem.ubidots.com/的雲端。

 

程式列表

MQTT_ubidots_Ameba.ino

#include <WiFi.h>

#include <PubSubClient.h>           //MQTT library

 

// Ameba A1_Lite

#define YelloLED 9 //PA15

 

// HUB 5168

#define GreenLED 3 //PA30

#define BlueLED 9 //PA15

#define relayPin 9 //PA15

 

/* Set these to your desired credentials. */

#define ssid1 " "  // Your WiFi SSID (name)

#define pass1 " "  // Your WiFi password

#define ssid2 " "  // Your WiFi SSID (name)

#define pass2 " "  // Your WiFi password

#define ssid3 " "  // Your WiFi SSID (name)

#define pass3 " "  // Your WiFi Password

#define ssid4 " "  // Your WiFi SSID (name)

#define pass4 " "  // Your WiFi Password

int status  = WL_IDLE_STATUS; // the Wifi radio's status

  

//-----------------------------------------------------------------------------------------------------------

#define Token "BBFF-XmkRnmUIcG7BwTld6Cd1kgNqMxiW3r"  // 資料平台裝置的存取權限碼

#define mqttServer    "industrial.api.ubidots.com"   // new ideaschain dashboard MQTT server

#define mqttPort      1883

char clientId[]   = "ameba_iot";                     // MQTT client ID. it's better to use unique id.

char visibility[] = "Temperature";

char MQTT_USERNAME[]  = Token;      // device access token(存取權杖)

char MQTT_PASSWORD[]  = Token;      // no need password

 

#define MQTT_RECONNECT_INTERVAL 100                  // millisecond

#define MQTT_LOOP_INTERVAL      50                   // millisecond

 

#define subscribeTopic  "/v1.6/devices/ameba_iot"    //

#define publishTopic    "/v1.6/devices/ameba_iot"    //

 

WiFiClient client;

 

// String mqttValue;

long lastTime = 0 , startTime = 0;

String HomeDeviceButton ;

int light_val=20;

 

void mqtt_callback(char* topic, byte* payload, unsigned int msgLength);  // MQTT Callback function header

PubSubClient mqttClient(mqttServer, mqttPort, mqtt_callback, client);

 

void setup(void) {

  pinMode(GreenLED, OUTPUT);

  pinMode(relayPin, OUTPUT);

 

  Serial.begin(115200);

 

  // check for the presence of the shield:

  if (WiFi.status() == WL_NO_SHIELD) {

    Serial.println("WiFi shield not present");

    // don't continue:

    while (true);

  }

 

  Serial.print("Configuring access point...");

  wifiConnect();

 

  // you're connected now, so print out the status:

  printWifiStatus();

 

  if ( WiFi.status() == WL_CONNECTED ) {

    Serial.println("waiting for sync");

    for (int i = 0 ; i < 3 ; i++)

    {

      digitalWrite(relayPin, HIGH);

      delay(500);

      digitalWrite(relayPin, LOW);

      delay(500);

    }

  }

  else

  {

    Serial.println("no network !!   ");

  }

  Serial.println(WiFi.localIP());

  Serial.println("Starting MQTT broker");

  mqtt_nonblock_reconnect();

  startTime = millis();

}

 

void loop(void) {

  char publishPayload[80];

 

  light_val++;

  delay(10000);

  digitalWrite(GreenLED, LOW);

 

  sprintf(publishPayload , "{\"%s\": %d}", visibility, light_val);

 

  mqtt_nonblock_reconnect();

  // Once connected, publish an announcement...

  mqttClient.publish(publishTopic, publishPayload);

  Serial.println(publishPayload);

  mqttClient.loop();

  digitalWrite(GreenLED, HIGH);

  // delay(MQTT_LOOP_INTERVAL);

}

 

void wifiConnect(void) {

  char ssid[20],pass[20],num=0;

  unsigned long WifiConnectingTimeout; //連線逾時時間

 

  // scan for nearby networks:

  Serial.println("** Scan Networks **");

  int numSsid = WiFi.scanNetworks();

  if (numSsid == -1) {

    Serial.println("Couldn't get a wifi connection");

    while (true);

  }

 

  for (int thisNet = 0; thisNet < numSsid; thisNet++) {

    strcpy(ssid, WiFi.SSID(thisNet));

    if(strcmp(ssid, ssid1) == 0)

    {

      strcpy(pass, pass1);

      num=1;

      break;

    }

    else if(strcmp(ssid, ssid2) == 0)

    {

      strcpy(pass, pass2);

      num=2;

      break;

    }

    else if(strcmp(ssid, ssid3) == 0)

    {

      strcpy(pass, pass3);

      num=3;

      break;

    }

    else if(strcmp(ssid, ssid4) == 0)

    {

      strcpy(pass, pass4);

      num=4;

      break;

    }

  }

 

  if (num == 0) {

    Serial.println("Couldn't get a wifi connection");

    while (true);

  }

 

  // Connect to WPA/WPA2 network. Change this line if using open or WEP network:

  Serial.print("Connecting to ");

  Serial.println(ssid);

  WiFi.begin(ssid, pass);

  WifiConnectingTimeout = millis();

  while (WiFi.status() != WL_CONNECTED) {

    Serial.print("Attempting to connect to SSID: ");

    Serial.println(ssid);

    if ((millis() - WifiConnectingTimeout) > 10000) //等待 10

      break;

    delay(500);

    Serial.print(".");

  }

}

 

void printWifiStatus(void) {

  // print the SSID of the network you're attached to:

  Serial.print("SSID: ");

  Serial.println(WiFi.SSID());

 

  // print your WiFi shield's IP address:

  Serial.println("WiFi connected");

  Serial.print("IP Address: ");

  IPAddress ip = WiFi.localIP();

  Serial.println(ip);

 

  // print the received signal strength:

  long rssi = WiFi.RSSI();

  Serial.print("signal strength (RSSI):");

  Serial.print(rssi);

  Serial.println(" dBm");

}

void mqtt_callback(char* topic, byte* payload, unsigned int msgLength) {

  char temp[80];

  sprintf(temp , "Message arrived with Topic [%s]\n  Data Length: [%d], Payload: [", topic, msgLength);

  Serial.print(temp);

  Serial.write(payload, msgLength);

  Serial.println("]");

 

  if (strcmp(subscribeTopic, topic) == 0) {        //主題

    HomeDeviceButton = "";

    for (unsigned int i = 0; i < msgLength; i++) {

      HomeDeviceButton += (char)payload[i];

    }

    // Payload: [On]

    if ( HomeDeviceButton == "On" )

      digitalWrite(relayPin, HIGH);

    else if ( HomeDeviceButton == "Off" )

      digitalWrite(relayPin, LOW);

  }

}

 

boolean mqtt_nonblock_reconnect() {

  boolean doConn = false;

 

  if (! mqttClient.connected()) {

    // attempts to reconnect every [MQTT_RECONNECT_INTERVAL] milliseconds without blocking the main loop.

    long currTime = millis();

    if (currTime - lastTime > MQTT_RECONNECT_INTERVAL) {

      lastTime = currTime;

      doConn = true;

      // boolean isConn = mqttClient.connect(clientId);

      boolean isConn = mqttClient.connect(clientId, MQTT_USERNAME, MQTT_PASSWORD);

      char logConnected[100];

      sprintf(logConnected, "Device [%s] Connect %s !", clientId, (isConn ? "Successful" : "Failed"));

      Serial.println(logConnected);

 

      if (isConn) {

        mqttClient.subscribe(subscribeTopic);  //訂閱主題

      }

    }

  }

  return doConn;

}


執行結果

本範例只是傳輸框架,傳輸遞增資料,實際傳輸可改成感測器資料