2019年8月13日星期二

IoT 第一步!Wifi 開關電燈,動手做,設定及編寫程式 ( 三 )

【上一回】IoT 第一步!Wifi 開關電燈,理論及實踐,為何選用 MQTT ( 二 )


用兩回合幻想及分析,等到不耐煩?這是最終回,完成這項目。

流程︰
  1. 購置零件及注意事項
  2. 程式碼及提示
  3. 安裝及設定 Arduino IDE
  4. 在 Raspberry pi 安裝 Mosquitto
  5. Android 手機安裝 Apps
  6. 組裝電路 ( 附 Fritzing 圖解 )
  7. 測試

注意事項︰


用 220V 交流電!一個失誤可致命!你必須知道自己做甚麼,本人不會負責讀者的人身安全!

———————————簡易的分隔線————————————

購置零件 ( Material list )︰




沒燈片也可以,Relay 作用如一個 ON/OFF switch,所以隨便接一個 DC 的 LED 也可以測試。

然後是一些連接用配件︰


86 型暗盒 可以不用買,只是用來試尺寸,驗證能不能塞一下。

銲接及改裝用工具︰
用作 Broker 的電腦︰

注意事項 ( 裝修及改裝時必須了解 )︰


根據家居實際情況,燈制通常沒有拉零線,只有燈的位置才有零線,所以智能燈制有分「單火」及「零火」。

因此,裝修時,記得拉一條零線去燈制。


———————————簡易的分隔線————————————

程式碼及提示:


以下是 程式碼及 cheatsheet,有信心不看之後教學,可以嘗試挑戰,我很歡迎挑戰困難的人。

MEMO

  1. linklt7697 and Mosquitto broker MUST in a same network.
  2. You can reserve a fix IP for Mosquitto broker in DHCP Service.
  3. Just for fun.

For more information, such as circuit diagram, material list, please visit following blog: https://javatoybox.blogspot.com/2019/08/iot-wifi-3.html

view raw README.md hosted with ❤ by GitHub
# Reference:
# https://blog.gtwang.org/iot/raspberry-pi/raspberry-pi-mosquitto-mqtt-broker-iot-integration/
# update APT Server list
apt-get update
# install mosquitto broker and test client
apt-get install mosquitto mosquitto-clients
# check service is running or not
service mosquitto status
# exit check
:q
# build a "subscriber" for test
mosquitto_sub -t javatoybox/message
# test broker with "publisher"
mosquitto_pub -t javatoybox/message -m "Hello, world!"
/*
reference:
https://docs.labs.mediatek.com/resource/linkit7697-arduino/zh_tw/developer-guide/using-the-wi-fi-library
https://blog.gtwang.org/iot/raspberry-pi/raspberry-pi-mosquitto-mqtt-broker-iot-integration/
https://randomnerdtutorials.com/why-you-shouldnt-always-use-the-arduino-delay-function/
https://swf.com.tw/?p=1021
https://github.com/ArcherHuang/LinkIt_7697/blob/master/Arduino/MQTT_MCS_Control_LED/MQTT_MCS_Control_LED.ino
For more information, such as circuit diagram, material list, please visit following blog:
https://javatoybox.blogspot.com/2019/08/iot-wifi-3.html
*/
#include <LWiFi.h>
#include <PubSubClient.h>
#define WIFI_SSID "YOUR_SSID" // your network SSID (name)
#define WIFI_PASSWORD "WPA/WPA2_PASSWORD" // your network password
#define MQTT_SERVER_IP "<SERVER_IP>"
#define MQTT_SERVER_PORT 1883
#define MQTT_CLIENT_ID "linklt7697_12345678"
#define MQTT_SUB_TOPIC "javatoybox/linkit7697/AC-Light-switch"
int controlPin = 3; //set control pin for on/off relay
int status = WL_IDLE_STATUS; // the Wifi radio's status
WiFiClient mqttClient;
PubSubClient client(mqttClient);
void callback(char* topic, byte* payload, unsigned int length);
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
// set Pin mode
pinMode(controlPin, OUTPUT);
client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
client.setCallback(callback);
connectWifi();
connectMQTT();
}
void loop() {
// check the network connection once every 1 seconds:
// delay(1000);
// check if disconnect WIFI, then reconnect
connectWifi();
connectMQTT();
client.loop();
}
void connectWifi() {
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
delay(5000);
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_SSID);
// Connect to WPA/WPA2 network:
status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// you're connected now, so print out the data:
if (status = WL_CONNECTED){
Serial.println("You're connected to Wifi network");
printWifiData();
}
}
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print your MAC address:
byte mac[6];
char mac_str[18];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
sprintf(mac_str, "%02x:%02x:%02x:%02x:%02x:%02x", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
Serial.println(mac_str);
Serial.println("====================");
}
void connectMQTT() {
// Loop until we're reconnected
while (!client.connected())
{
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(MQTT_CLIENT_ID))
{
Serial.println("connected");
client.subscribe(MQTT_SUB_TOPIC);
}
else
{
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// Callback function
void callback(char* topic, byte* payload, unsigned int length) { //MQTT Relay
Serial.print("Input Message arrived [");
Serial.print(MQTT_SUB_TOPIC);
Serial.print("] ");
Serial.print((char)payload[0]);
if((char)payload[0] == '1'){
digitalWrite(controlPin, HIGH);
}else if((char)payload[0] == '0'){
digitalWrite(controlPin, LOW);
}else{
Serial.print("value error");
}
Serial.println();
}
———————————簡易的分隔線————————————

安裝及設定 Arduino IDE︰


跟官方做法 安裝及設定 LinkIt 7697 及 Arduino IDE ,沒難度。Linux 裝不到 PubSubClient 程式庫,只能忍痛用 Windwos 做。

安裝 PubSubClient 程式庫︰



用 MQTT 需要安裝第三方和式庫。


裝好後,把程式碼貼上,更改一些設定︰
  1. Wifi
  2. MQTT
  3. 針腳
最後,把 LinkIt 7697 接到電腦 USB 上傳。

安裝 PubSubClient 程式庫
https://swf.com.tw/?p=1021

knolleary/pubsubclient
https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_basic/mqtt_basic.ino

———————————簡易的分隔線————————————

在 Raspberry pi 安裝 Mosquitto ︰


看 連結 的教學裝,上面 cheatsheet 有齊所有 command,這裡沒有做保安之類,所以成功後,可以挑戰保安設定。沒玩過樹莓派,可以看 以前教學

樹莓派安裝 Mosquitto 輕量級 MQTT Broker 教學,連接各種物聯網設備
https://blog.gtwang.org/iot/raspberry-pi/raspberry-pi-mosquitto-mqtt-broker-iot-integration/

——————————— 公家 Broker ( start ) ————————————

如果覺得安裝及設定很麻煩,用公家 broker 做測試也可以。當然,說是公家,就是說沒有保安,任何人都可以控制到開關。

MQTT connection settings

Host: broker.hivemq.comTCP Port: 1883Websocket Port: 8000

HiveMQ | Public Broker | MQTT Dashboard
http://www.mqtt-dashboard.com/

——————————— 公家 Broker ( end ) ————————————

Apps store 安裝 "MQTT Dash"︰



MQTT Apps 有很多選擇,當然要知道 MQTT 才懂做設定。Apple 應該都會有這類實用 Apps 可以裝。一理通百理明,不知道 MQTT 是甚麼,請回到 前一篇 找答案。

———————————簡易的分隔線————————————

組裝電路 ( 附 Fritzing 圖解 ) 



大約是這樣組裝,詳細怎銲接,要非常細心銲接 AC 電不能說笑,銲前想清楚有沒有做錯,銲完檢查有沒有銲錯,用之前請測試好幾次,沒問題才好用在日常生活

注意事項︰


用 220V 交流電!一個失誤可致命!你必須知道自己做甚麼,本人不會負責讀者的人身安全!

HLK-5M05 Buck Step Down Power Supply Module︰



把 USB 線剪斷,看 維基 把 5 VDC + 及 GND 弄清楚,銲接在適當腳位。AC 電,看對面正負極,找相對的接腳銲接。

LinkIt 7697 and One 1 Channel 5V Relay Module︰



沒甚麼要特別說明,把 Linkit 7697 插上迷你麵包板,看清楚怎接線。

———————————簡易的分隔線————————————

測試︰



把所有東西結合起來,測試是否成功,如果要用於日常生活,請找個空擴及沒有雜物的位置,開 12 至 24 小時,測試會不會漏電著火

———————————簡易的分隔線————————————

總結︰


看似簡單,實際要做,還需要一定網路基礎、電學基礎及編程基礎,這裡甚麼都沒說明,只會不求甚解地 step by step 做,不會有開發新項目能力。自發補回那些基礎吧,很多基礎,不是三言兩語,一個 blog 能說明全部。

找出問題、研究及學習,作為一個 Maker 是最基本能力,如果社交能力不錯,或許可以求助其他有經驗人仕。

用 220V 交流電!一個失誤可致命!你必須知道自己做甚麼,本人不會負責讀者的人身安全!