Internet of Things หรือ IoT คืออะไร
Internet of Things (IoT) คือ การที่อุปกรณ์อิเล็กทรอนิกส์ต่างๆ สามารถเชื่อมโยงหรือส่งข้อมูลถึงกันได้ด้วยอินเทอร์เน็ต โดยไม่ต้องป้อนข้อมูล การเชื่อมโยงนี้ง่ายจนทำให้เราสามารถสั่งการควบคุมการใช้งานอุปกรณ์อิเล็กทรอนิกส์ต่างๆ ผ่านทางเครือข่ายอินเตอร์เน็ตได้ ไปจนถึงการเชื่อมโยงการใช้งานอุปกรณ์อิเล็กทรอนิกส์ต่างๆ ผ่านทางเครือข่ายอินเตอร์เน็ตเข้ากับการใช้งานอื่นๆ จนเกิดเป็นบรรดา Smart ต่างๆ ได้แก่ Smart Device, Smart Grid, Smart Home, Smart Network, Smart Intelligent Transportation ทั้งหลายที่เราเคยได้ยินนั่นเอง ซึ่งแตกต่างจากในอดีตที่อุปกรณ์อิเล็กทรอนิกส์เป็นเพียงสื่อกลางในการส่งและแสดงข้อมูลเท่านั้น
กล่าวได้ว่า Internet of Things นี้ได้แก่การเชื่อมโยงของอุปกรณ์อัจฉริยะทั้งหลายผ่านอินเทอร์เน็ตที่เรานึกออก เช่น แอปพลิเคชัน แว่นตากูเกิลกลาส รองเท้าวิ่งที่สามารถเชื่อมต่อข้อมูลการวิ่ง ทั้งความเร็ว ระยะทาง สถานที่ และสถิติได้
นอกจากนั้น Cloud Storage หรือ บริการรับฝากไฟล์และประมวลผลข้อมูลของคุณผ่านทางออนไลน์ หรือเราเรียกอีกอย่างว่า แหล่งเก็บข้อมูลบนก้อนเมฆ เป็นอีกสิ่งหนึ่งที่เราใช้งานบ่อยๆแต่ไม่รู้ว่าเป็นหนึ่งในรูปแบบของ Internet of Things สมัยนี้ผู้ใช้นิยมเก็บข้อมูลไว้ในก้อนเมฆมากขึ้น เนื่องจากมีข้อดีหลายประการ คือ ไม่ต้องกลัวข้อมูลสูญหายหรือถูกโจรกรรม ทั้งยังสามารถกำหนดให้เป็นแบบส่วนตัวหรือสาธารณะก็ได้ เข้าถึงข้อมูลได้ทุกที่ทุกเวลาด้วยอุปกรณ์อิเล็กทรอนิกส์ใดๆผ่านเครือข่ายอินเตอร์เน็ต แถมยังมีพื้นที่ใช้สอยมาก มีให้เลือกหลากหลาย ช่วยเราประหยัดค่าใช้จ่ายได้อีกด้วย เนื่องจากเราไม่ต้องเสียเงินซื้ออุปกรณ์จัดเก็บข้อมูล เช่น ฮาร์ดไดร์ฟ หรือ Flash drive ต่างๆ
Q01
- All Over IP Age - WebIO Pi Q01
- All Over IP Age - WebIO Pi
>> ทดสอบ Control Over IP with WebIO Pi
>> การติดตั้ง WebIOpi
Step1:
ดาวน์โหลดไฟล์ WebIOPi-0.7.1.tar.gz โดยใช้คำสั่ง
wget http://sourceforge.net/projects/webiopi/files/WebIOPi-0.7.1.tar.gz
Step2:
แตกไฟล์ WebIOPi-0.7.1.tar.gz โดยใช้คำสั่ง
tar xvzf WebIOPi-0.7.1.tar.gz
Step3:
เข้าไปในโฟลเดอร์ WebIOPi-0.7.1 โดยใชคำสั่ง
cd WebIOPi-0.7.1
Step4:
ดาวน์โหลด Patch เสริม webiopi-pi2bplus.patch โดยใช้คำสั่ง
wget https://raw.githubusercontent.com/doublebind/raspi/master/webiopi-pi2bplus.patch
Step5:
ติดตั้ง Patch webiopi-pi2bplus.patch โดยใช้คำสั่ง
patch -p1 -i webiopi-pi2bplus.patch
Step6: ติดตั้ง
WebIOPi-0.7.1 โดยใชคำสั่ง
sudo ./setup.sh
Step7: Reboot ระบบโดยใชคำสั่ง
sudo reboot
การเริ่มใช้งาน WebIOpi
Step1: เริ่มต้นการทำงาน WebIOpi โดยใชคำสั่ง
sudo /etc/init.d/webiopi start
*หยุดการทำงานโดยการใชคำสั่ง sudo /etc/init.d/webiopi stop
Step2: ไปที่ Rpi IP address:8000 เพื่อทำการ Login โดยใช้ Username และ Password เริ่มต้น Username: webiopi Password:
raspberry
Step3:
เมื่อ login สำเร็จจะปรากฏหน้าเว็บดังนี้
>> เลือก GPIO Header
>> เลือก GPIO Header
Step4: ต่อวงจรดังภาพ
GPIO16 = OUTPUT >> LED
GPIO18 = OUTPUT >> LED
GPIO17 = INPUT Pull up >> bottom
switch
Resistor 220-330 ohm
Step5: ตั้งค่าการทำงานของGPIO
GPIO16 = OUT >> LED
GPIO18 = OUT >> LED
GPIO17 = IN >> bottom switch
Step6: คลิกที่ช่อง GPIO เพื่อเปลี่ยนสถานะ
·
off
·
on
การทำ
Start/Stop WebIOPi
คําสั่งการทํางาน WebIOPi
sudo
/etc/init.d/webiopi start
คําสั่งหยุดการทํางาน WebIOPi
sudo
/etc/init.d/webiopi stop
การทำ Auto start WebIopi at boot
คำสั่งเปิดใช้ Auto Start WebIOPi
sudo update-rc.d webiopi
defaults
คำสั่งยกเลิก Auto Start WebIOPi
sudo update-rc.d webiopi
remove
การแก้ไข configure ของ webiopi
เข้าไปแก้ config ของ WebIO Pi ด้วยคำสั่ง
sudo nano /etc/webiopi/config
Q2 - ALL OVER IP AGE - NODERED
LED OUTPUT CONTROL
ต่อวงจรดังรูป

ทำการเรียกใช้ Node Red โดยเข้าไปที่ Terminal แล้วพิมพ์
node-red-start
ไปที่ browser ที่ Link xxx.xxx.xxx.xxx:1880 โดยใช้ IP ของ Raspberry Pi
เช่น ถ้า IP Raspberry Pi คือ 172.20.10.9 ให้ใส่ Link 172.20.10.9:1880
ที่ช่อง input เลือก inject มา2อัน ตั้งชื่อเป็น On / Off
inject ที่ชื่อว่า On ให้ตั้งค่า Payload Type เป็น number เซทค่าเป็น 1
inject ที่ชื่อว่า Off ให้ตั้งค่า Payload Type เป็น number เซทค่าเป็น 0
ที่ node Raspberry Pi เลือก RPi-GPIO output
Double click ที่ RPi GPIO out แล้วทำการเซท pin เป็น pin 8 (GPIO 14) และเลือก Type เป็น Digital output
ที่ node output เลือก debug มา1อันไว้เพื่อแสดง output
ทำการเชื่อม node ต่างๆเข้าด้วยกันดังรูป
กดปุ่ม Deploy เพื่อเริ่มใช้งาน
Q3 - MQTT PROTOCOL AND IOTS CONCEPT
ทดสอบ iot eclips broker ด้วย MQTT Lens
การติดตั้ง MQTT LENS
Step1: ไปที่เพื่อติดตั้ง
https://sites.google.com/view/523372-embedded-systembydiki/week02/q3-mqtt-protocol-and-iots-concept#h.p_IBT6B-QLRx-v
Step2: ไปที่ chrome://apps/ หรือค้นหาใน start windows คลิก MQTTLens
Step3: เพิ่ม Connections โดยตั้งค่าดังนี้
Connection name >> ตั้งชื่อ
Hostname >> tcp:// iot.eclipse.org
Post >> 1883
แล้วคลิก Create Connection
Step4: กำหนด Subscribe เพื่อสร้าง Channel ในการสื่อสาร
Step5: ส่ง Massage ไปยัง Subscribe ที่ต้องการ โดยระบุ ชื่อ และขอ้ความที่จะส่งแล้ว คลิก Subscribe
ทดสอบ iot eclips broker ด้วย RPi (RPi in Client Mode)
Step1:ติดตั้ง paho-mqtt โดยใชคำสั่ง
sudo pip3 install paho-mqtt
sudo pip install paho-mqtt
Step2: สร้างไฟล์ ชื่อ mqtt-test.py แล้วเขียน Source code ดังนี้
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("$SYS/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface. client.loop_forever()
Step3:ทดสอบด้วยการรัน ไฟล์ mqtt-test.py
ทดสอบ “mosquito broker” ด้วย Wemos D1 R2 mini
Step1: ตรวจเช็ค ip Address เชื่อมต่อ Internet ของ Rpi ด้วยคำสั่ง Ifconfig ดูที่ wlan0
Step2: ติดตั้ง Library PubSubClient ใน Arduiono IDE โดยคลิกที่
Sketch >> Include Library >> Manage Library
Step4: เขียนCodeสำหรับเชื่อมต่อดังนี้ แล้วทำการอัพโหลดลง Wemos
// Test Code
//#include <WiFi.h> // ESP32 Board
#include <ESP8266WiFi.h> // ESP8266, WeMos
#include <PubSubClient.h>
const char* ssid = "iris";
const char* password = "12345678";
// const char* mqtt_server = "iot.eclipse.org";
IPAddress My_mqtt_server(192,168,43,145);
const char* UName = "mymqtt";
const char* PassW = "myraspi";
const char* topic1 = "channel1";
int TestLED = D4;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
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.println("IP address: ");
Serial.println(WiFi.localIP());
pinMode(TestLED, OUTPUT);
}
void callback(char* topic, byte* payload, unsigned int length)
{ Serial.print("Message arrived [");
Serial.print(topic1);
Serial.print("] ");
for (int i = 0; i < length; i++)
{ Serial.print((char)payload[i]);
}
Serial.println();
Serial.print(" ---> ");
Serial.println((char)payload[0]);
if ((char)payload[0] == 'o') digitalWrite(TestLED, HIGH);
if ((char)payload[0] == 'f') digitalWrite(TestLED, LOW);
}
void reconnect()
{ while (!client.connected()) // Loop until we're reconnected
{ Serial.print("Attempting MQTT connection...");
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX); // Create a random client ID
if (client.connect(clientId.c_str(), UName, PassW)) // Attempt to connect
{ Serial.println("connected"); // Once connected, publish an announcement... client.publish(topic1, "Hello World Pk007"); // ... and resubscribe
client.subscribe(topic1);
}
else
{ Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); delay(5000);
}
}
}
void setup()
{ Serial.begin(115200);
setup_wifi();
client.setServer(My_mqtt_server, 1883);
client.setCallback(callback);
pinMode(TestLED, OUTPUT);
}
void loop()
{ if (!client.connected()) reconnect();
client.loop();
long now = millis();
if (now - lastMsg > 2000)
{ lastMsg = now;
++value;
snprintf (msg, 75, "hello world #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish(topic1, msg);
}
}
Step5: ต่อวงจร
Step6: เพิ่ม Connections โดยตั้งค่าดังนี้
Connection name >> ชื่อที่จะตั้ง
Hostname >> 192.168.43.145(wlan0 IP Address)
Post >> 1883
Username >> mymqtt
Password >> myraspi
Step7: กำหนด Subscribe เพื่อสร้าง Channel ในการสื่อสารส่ง Massage ไปยัง Subscribe ที่ต้องการ โดยระบุ ชื่อ และข้อความที่จะส่งแล้วคลิก publish
Subscribe >> channel1
Publish >> channel1
Message >> o,f
Q4 - BLYNK IOT APPLICATION
ทดสอบ Blynk จาก “Blynk Server” ด้วย ESP-32
Step3: New Project แล้วเลือกอุปกรณ์ที่ต้องการเชื่อมต่อ
Step4: ติดตั้ง Library Blynk ที่ Arduino IDE คลิกที่
Sketch >> Include Library >> Manage Library ค้นหา Blynk
Step5: เปิดไฟล์ blynk example ตามอุปกรณ์ที่ใช้
คลิก File >> Examples >> Blynk >> Board_WiFi >> ESP32_wifi
Step6: ทำการแก้ไป ssid ,pass ของ wifi ที่ใช้เชื่อมต่อ และ authToken
หลังจากสร้าง Project authToken จะถูกส่งไปยัง email ที่ใช้ในการlogin
Step7: เลือกฟังก์ชันการทำงานในแอป Blynk แล้วเชื่อม
เลือก Button >> เลือก pin = Gp2 >> Switch >> connect
ทดสอบ Blynk จาก “Blynk Server” ด้วย RPi (RPi in Client Mode)
Step1: ติดตั้ง Blynk Library
Add repositories:
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash –
Install Node.js:
sudo apt-get update && sudo apt-get upgrade
sudo apt-get install build-essential nodejs –y
Install Blynk globally:
sudo npm install -g npm sudo npm
install -g onoff
sudo npm install -g blynk-library
Step2: New Project แล้วเลือกอุปกรณ์ที่ต้องการเชื่อมต่อ() แล้วไปรับ AuthToken
Step3: Run Blynk blynk-client "your auth token"
ติดตั้งและทดสอบ Blynk Broker (RPi in Server Mode)
Step1: ตรวจสอบ java
java –version
Step2: ติดตั้ง java jdk
sudo apt-get install oracle-java8-jdk
step3: Download blynk server ไปที่ https://github.com/blynkkk/blynk-server
เพื่อรับเวอรช์ันล่าสุด
wget "https://github.com/blynkkk/blynk-server/releases/download/v0.41.5/server0.41.5-java8.jar"
step4: Start Blynk Server
java -jar server-0.34.0-java8.jar -dataFolder /home/pi/Blynk
Step5: login app Blynk Custom Mode
username : admin@blynk.cc
password : admin
ip : net วงเดียวกัน
port : ตามไฟล์config เสร็จแล้วเราจะมีEnergy มากกว่า Blynk mode
Step6: ไปที่ https://RapiiIP:9443/admin เพื่อรับAuthToken
Step7: ทำการแก้ไป ssid ,pass ของwifi ที่ใช้เชื่อมต่อ, authToken , Rpi Ip Address ,port
Q5 - SQLITE DATABASE ON A RASPBERRY PI
Step1: ติดตั้ง SQLite
sudo apt-get install sqlite3
Step2: Run Mosquitto broker
mosquitto –d
Step3: Install Flask
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-pip python-flask git-core
sudo pip install flask
Step4: สร้าง Python web server script
mkdir web-server
cd web-server
nano app.py
Source Code
#
# Created by Rui Santos
# Complete project details: https://randomnerdtutorials.com
#
import paho.mqtt.client as mqtt
from flask import Flask, render_template, request
import json
import sqlite3
app = Flask(__name__)
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/esp8266/dhtreadings")
# The callback for when a PUBLISH message is received from the ESP8266.
def on_message(client, userdata, message):
if message.topic == "/esp8266/dhtreadings":
print("DHT readings update")
#print(message.payload.json())
#print(dhtreadings_json['temperature'])
#print(dhtreadings_json['humidity'])
dhtreadings_json = json.loads(message.payload)
# connects to SQLite database. File is named "sensordata.db" without the quotes
# WARNING: your database file should be in the same directory of the app.py file or have the correct path
conn=sqlite3.connect('sensordata.db')
c=conn.cursor()
c.execute("""INSERT INTO dhtreadings (temperature,
humidity, currentdate, currentime, device) VALUES((?), (?), date('now'),
time('now'), (?))""", (dhtreadings_json['temperature'],
dhtreadings_json['humidity'], 'esp8266') )
conn.commit()
conn.close()
mqttc=mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.connect("localhost",1883,60)
mqttc.loop_start()
@app.route("/")
def main():
# connects to SQLite database. File is named "sensordata.db" without the quotes
# WARNING: your database file should be in the same directory of the app.py file or have the
correct path
conn=sqlite3.connect('sensordata.db')
conn.row_factory = dict_factory
c=conn.cursor()
c.execute("SELECT * FROM dhtreadings ORDER BY id DESC LIMIT 20")
readings = c.fetchall()
#print(readings)
return render_template('main.html', readings=readings)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8181, debug=True)
Step5: สร้างดาต้าเบส ชื่อ sensordate.db
sqlite3 sensordata.db
Step6: สร้างตาราง ชื่อ dhtreading
.fullschema
CREATE TABLE dhtreadings(id INTEGER PRIMARY KEY AUTOINCREMENT,
temperature NUMERIC, humidity NUMERIC, currentdate DATE, currentime TIME, device TEXT);
Step7: สร้างหน้าเว็บ Html
mkdir templates
cd templates
nano main.html
Step8: ติดตั้ง DHT และ Adafruit_Sensor
เพื่อโหลด Library หลังจากนั้นแตกไฟล์ทั้งสอง แล้วย้ายไปที่ C:\Users\Administrator\Documents\Arduino\libraries
ให้เปลี่ยน ชื่อ DHT-sensor-library-master เป็น DTH
Step9: coding ESP-8266
Source code
/*****
All the resources for this project:
https://rntlab.com/
*****/
// Loading the ESP8266WiFi library and the PubSubClient library
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
// Uncomment one of the lines bellow for whatever DHT sensor type you're using!
//#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21
(AM2301) #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
// Change the credentials below, so your ESP8266 connects to your router
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "YOUR_RPi_IP_Address";
// Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
// DHT Sensor
const int DHTPin = 14;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);
// Timers auxiliar variables
long now = millis();
long lastMeasure = 0;
char data[80];
// Don't change the function below. This functions connects your ESP8266 to your router
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(".");
}
Serial.println("");
Serial.print("WiFi connected - ESP IP address: ");
Serial.println(WiFi.localIP());
}
// This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
}
// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
/*
YOU NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
To change the ESP device ID, you will have to give a unique name to the ESP8266.
Here's how it looks like now:
if (client.connect("ESP8266Client")) {
If you want more devices connected to the MQTT broker, you can do it like this:
if (client.connect("ESPOffice")) {
Then, for the other ESP:
if (client.connect("ESPGarage")) {
That should solve your MQTT multiple connections problem
THE SECTION IN loop() function should match your device name
*/
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Subscribe or resubscribe to a topic
// You can subscribe to more topics (to control more LEDs in this example)
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
// The setup function sets your DHT sensor, starts the serial communication at a baud rate of 115200
// Sets your mqtt broker and sets the callback function
// The callback function is what receives messages and actually controls the LEDs
void setup() {
dht.begin();
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// For this project, you don't need to change anything in the loop function.
// Basically it ensures that you ESP is connected to your broker
void loop() {
if (!client.connected()) {
reconnect();
}
if(!client.loop())
/*
YOU NEED TO CHANGE THIS NEXT LINE, IF YOU'RE HAVING PROBLEMS WITH MQTT MULTIPLE CONNECTIONS
To change the ESP device ID, you will have to give a unique name to the ESP8266.
Here's how it looks like now:
client.connect("ESP8266Client");
If you want more devices connected to the MQTT broker, you can do it like this:
client.connect("ESPOffice");
Then, for the other ESP:
client.connect("ESPGarage");
That should solve your MQTT multiple connections problem
THE SECTION IN recionnect() function should match your device name
*/
client.connect("ESP8266Client");
now = millis();
// Publishes new temperature and humidity every 30 seconds
if (now - lastMeasure > 10000) {
lastMeasure = now;
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Computes temperature values in Celsius
float hic = dht.computeHeatIndex(t, h, false);
static char temperatureTemp[7];
Step10: ต่อวงจรดังนี้
Step11: Launching the Web Server
cd web-server && sudo python app.py