2022年12月23日 星期五

WiFi模組通訊實作 – Ideaschain雲端平臺

 WiFi模組通訊實作 – Ideaschain雲端平臺

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

Ideaschain國產免費的雲端平臺,由財團法人資訊工業策進會數位服務創新研究所由開發。


程式列表

MQTT_IdeasChain_Ameba.ino

#include <WiFi.h>

#include <PubSubClient.h>           //MQTT library

 

// HUB 5168

#define GreenLED 3 //PA30

#define BlueLED 9 //PA15

#define relayPin 9 //PA15

 

/* Set these to your desired credentials. */

char ssid1[] = " ";      // your network SSID (name)

char pass1[] = " ";      // your network password

char ssid2[] = " ";      // your network SSID (name)

char pass2[] = " ";      // your network password

char ssid3[] = " ";  //Your WiFi SSID

char pass3[] = " ";  //Your WiFi Password

char ssid4[] = " ";  //Your WiFi SSID

char pass4[] = " ";  //Your WiFi Password

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

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

char mqttServer[]     = "iiot.ideaschain.com.tw";    // new ideaschain dashboard MQTT server

#define mqttPort      1883

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

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

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

 

#define MQTT_RECONNECT_INTERVAL 100                  // millisecond

#define MQTT_LOOP_INTERVAL      50                   // millisecond

 

#define subscribeTopic  "v1/devices/me/attributes"   // Fixed topic. ***DO NOT MODIFY***

#define publishTopic    "v1/devices/me/telemetry"    // Fixed topic. ***DO NOT MODIFY***

 

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

// unsigned long alarmTimeout;

 

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

WiFiClient wifiClient;

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

 

// String mqttValue;

long lastTime = 0 , startTime = 0;

String HomeDeviceButton ;

int PM2p5 = 0;

int PM10p0 = 2;

 

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();

 

  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];

 

  PM2p5++;

  PM10p0++;

  delay(10000);

  digitalWrite(GreenLED, LOW);

 

  // {"PM2.5":"10","PM10":"20"}

  // char publishPayload[] = "{\"PM2.5\":\"10\",\"PM10\":\"20\"}";        // String of stringified JSON Object (key value pairs)

  // String publishPayload = ("{\"PM2.5\":\"10\"" + String((int) PM2p5) + "\",\"PM10\":\"" + String((int) PM10p0));

  sprintf(publishPayload , "{\"PM2.5\":\"%d\",\"PM10\":\"%d\"}", PM2p5,PM10p0);

 

  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;

 

  // 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 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, "HomeDevice [%s] Connect %s !", clientId, (isConn ? "Successful" : "Failed"));

      Serial.println(logConnected);

 

      if (isConn) {

        mqttClient.subscribe(subscribeTopic);  //訂閱 智能插座控制主題

      }

    }

  }

  return doConn;

}


執行結果

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



沒有留言:

張貼留言