diff --git a/do_chi_thanh/OpenHAB/HPCC_IOT.md b/do_chi_thanh/OpenHAB/HPCC_IOT.md new file mode 100644 index 00000000..b929cce4 --- /dev/null +++ b/do_chi_thanh/OpenHAB/HPCC_IOT.md @@ -0,0 +1,155 @@ +# IOT Platform OpenHAB và kịch bản triển khai + - Hệ thống được cài đặt trên zone_3 (phòng làm việc của sinh viên). + - Hệ thống gồm 2 Fog Node và 1 Pi3 cài đặt OpenHAB để quản lý các Fog Node. + +## Kịch bản cài đặt + - Hệ thống gồm có: + - 02 Arduino + - 02 Esp 8266 + - 01 Raspberry Pi 3 cài OpenHAB + - 01 cảm biến chuyển động + - 01 cảm biến ánh sáng + - 01 cảm biến nhiệt ẩm + - 03 đèn LED: vàng, đỏ, xanh + - Chương trình điều khiển thực hiện kịch bản bật tắt đèn khi có chuyển động đi qua. + +  - Kịch bản sử dụng + - Khi cảm biến chuyển động phát hiện có chuyển động, chương trình điều khiển sẽ thực hiện bật một trong 3 đèn: đèn xanh khi cường độ sáng lớn (tương ứng giá trị của cảm biến ánh sáng >= 900); đèn đỏ khi cường độ sáng trung bình (giá trị >=500, <900); đèn vàng khi cường độ sáng yếu (giá trị <500) + +## Cài đặt hệ thống + +### Sơ đồ cài đặt +![Image of OpenHAB system](https://github.com/haiquan5396/K59_training/raw/master/HaiQuan/Homeassistant/image/serverRoom.jpg) + + +### Arduino + - Arduino được sử dụng để nhận các giá trị từ cảm biến và đẩy dữ liệu cho ESP 8266 thông qua các chân RX, TX. +### ESP 8266 + - Broker: cài docker image mqtt trên Pi 3 làm một broker tại địa chỉ IP 192.168.60.197 + - docker run -itd --name mosquitto -p 1883:1883 haiquan5396/mqtt + - ESP 8266 chuyển dữ liệu lên/nhận lệnh từ broker thông qua giao thức MQTT (Mosquito) vào các topic publish, subscribe. + +### OpenHAB + - IOT Platform OpenHAB được cài đặt trên Pi 3 nhận dữ liệu/gửi lệnh cho ESP 8266 thông qua các topic subscribe, publish tương ứng. + - Cài đặt MQTT Binding; JSON Binding trên OpenHAB PaperUI. + - Cầu hình broker cho MQTT binding bằng cách thêm 1 file default.service vào thư mục service của OpenHAB: +``` + mybroker.url=tcp://192.168.60.197:1883 +``` + Khi này, các gói tin MQTT sẽ được chuyển đến broker 192.168.60.197 cổng 1883. + - Các Items có trong hệ thống + - 3 đèn tương ứng với 3 Switch (Switch 1 - đèn vàn; Switch 2 - đèn đỏ; Switch 3 - đèn xanh). Mỗi đèn khi được bật/tắt sẽ gửi về 1 topic trên broker 192.168.60.197 (topic publish: zone_3/box_1/led). + - Cảm biến chuyển động (topic subscribe: zone_3/box_1/motion/id_1). + - Cảm biến ánh sáng (topic subscribe: zone_3/box_1/light/id_1 + - Cảm biến nhiệt độ, độ ẩm (topic subscribe: zone_3/box_1/temp/id_1). + +    - Data format: + - Của OpenHAB gửi cho đèn: {"name": "Tên đèn", "value": "giá trị"} +    - Của esp 8266 gắn với arduino cảm biến chuyển động gửi cho broker: {"motion": "giá trị"} +  - Của esp 8266 gắn với arduino cảm biến nhiệt độ, độ ẩm gửi cho broker: {"humidity":"độ ẩm", "temperature":"nhiệt độ"} +        - Của esp 8266 gắn với arduino cảm biến ánh sáng gửi cho broker: {"light": "giá trị"} (giá trị thuộc tập: {0, 1, 2} với 0 ứng với giá trị analog <500; 1 ứng với gíá trị analog >=500 và <900; 2 ứng với giá trị analog >=900) +``` +Switch Switch1 {mqtt=">[mybroker:zone_3/box_1/led:command:ON:{\"vang\"\\:\"ON\"}],>[mybroker:zone_3/box_1                                                                                        /led:command:OFF:{\"vang\"\\:\"OFF\"}]"} + +Switch Switch2 {mqtt=">[mybroker:zone_3/box_1/led:command:ON:{\"do\"\\:\"ON\"}],>[mybroker:zone_3/box_1/led:command:OFF:                                                                                         {\"do\"\\:\"OFF\"}]"} + +Switch Switch3 {mqtt=">[mybroker:zone_3/box_1/led:command:ON:{\"xanh\"\\:\"ON\"}],>[mybroker:zone_3/box_1                                                                                                   /led:command:OFF:{\"xanh\"\\:\"OFF\"}]"} + +Number Temperature "Temperature: [%.1f oC]" {mqtt="<[mybroker:zoner_3/box_1                                                                                                                             /temp/id_1:state:JSONPATH($.temperature)]"} + +Number Humidity "Humidity: [%.1f ]" {mqtt="<[mybroker:zoner_3/box_1/temp/id_1:state:JSONPATH($.humidity)]"} + +Number Motion "Motion: [ %d ]" {mqtt="<[mybroker:zone_3/box_1/motion/id_1:state:JSONPATH($.motion)]"} + +Number Light "Light: [%d ]" {mqtt="<[mybroker:zoner_3/box_1/light/id_1:state:JSONPATH($.light)]"} +``` + - Chương trình điều khiển đọc giá trị trả về từ cảm biến ánh sáng trên broker và ra lệnh cho OpenHAB bật các đèn tương ứng theo kịch bản sử dụng bằng cách sử dụng API của OpenHAB. +``` +from openhab import openHAB +import paho.mqtt.client as mqtt +import json +import time + + +base_url = 'http://localhost:8080/rest' +openhab = openHAB(base_url) + +# fetch all items +items = openhab.fetch_all_items() +# print (items) + +item1 = openhab.get_item("Switch1") +item2 = openhab.get_item("Switch2") +item3 = openhab.get_item("Switch3") + +temp_item = openhab.get_item("Temperature") +light_item = openhab.get_item("Light") +light_state = light_item.state + +topic_sub_sensor = "zone_3/box_1/motion/id_1" +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(topic_sub_sensor) + +# The callback for when a PUBLISH message is received from the server. +def on_message(client, userdata, msg): + print(msg.topic+" "+str(msg.payload)) + global pre_motion + + mes = json.loads(str(msg.payload)) + mes = mes['motion'] + + if (mes == 1 and pre_motion == 0): + # pre_motion = mes + light_state = light_item.state + print (light_state) + if (light_state == 0): # LDRReading < 500 + item1.on() # Bat den vang + time.sleep(0.5) + item2.off() + time.sleep(0.5) + item3.off() + print ("Vang: ON, Do: OFF, Xanh: OFF") + elif (light_state == 1): # LDRReading >= 500 và <900 + item1.off() + time.sleep(0.5) + item2.on() # Bat den do + time.sleep(0.5) + item3.off() + print ("Vang: OFF, Do: ON, Xanh: OFF") + elif (light_state == 2): # LDRReading >= 900 + item1.off() + time.sleep(0.5) + item2.off() + time.sleep(0.5) + item3.on() # Bat den xanh + print ("Vang: OFF, Do: OFF, Xanh: ON") + else: + print ("ERROR!") + exit() + +client = mqtt.Client() +pre_motion = 0 +pre_temp = 0 + +client.on_connect = on_connect +client.on_message = on_message + +client.connect("192.168.60.197", 1883, 60) +client.loop_forever() +``` + - Chương trình sử dụng thư viện paho mqtt để gửi, nhận dữ liệu với broker và thư viện Python-OpenHAB để gọi API của OpenHAB. Chương trình được lặp vô hạn, tại mỗi vòng lặp, các hàm on_connect và on_message subscribe dữ liệu từ broker và xử lý, ra lệnh cho OpenHAB qua API theo kịch bản sử dụng. + +### Các giá trị trả về của cảm biến + - Cảm biến chuyển động: Trả về 0 nếu không phát hiện chuyển động, trả về 1 nếu phát hiện chuyển động + - Cảm biến ánh sáng: Trả về giá trị 0-1023, gía trị càng lớn tức cường độ ánh sáng càng lớn. + - Cảm biến nhiệt độ độ ẩm: Trả về 2 giá trị nhiệt độ (độ C) và độ ẩm (%) + - 03 đèn LED: vàng, đỏ, xanh. + +### NOTE: + - Cách lắp mạch, mã nguồn của Arduino và ESP 8266 có trong file đính kèm. + - OpenHAB API xem trong file OpenHAB_API + diff --git a/do_chi_thanh/OpenHAB/LDR-circuit-improved-1024x729.png b/do_chi_thanh/OpenHAB/LDR-circuit-improved-1024x729.png new file mode 100644 index 00000000..6199bef2 Binary files /dev/null and b/do_chi_thanh/OpenHAB/LDR-circuit-improved-1024x729.png differ diff --git a/do_chi_thanh/OpenHAB/OpenHAB API.xlsx b/do_chi_thanh/OpenHAB/OpenHAB API.xlsx new file mode 100644 index 00000000..feca965c Binary files /dev/null and b/do_chi_thanh/OpenHAB/OpenHAB API.xlsx differ diff --git a/do_chi_thanh/OpenHAB/cam_bien_anh_sang_arduino.ino b/do_chi_thanh/OpenHAB/cam_bien_anh_sang_arduino.ino new file mode 100644 index 00000000..1f927fe3 --- /dev/null +++ b/do_chi_thanh/OpenHAB/cam_bien_anh_sang_arduino.ino @@ -0,0 +1,65 @@ +#include +#include +#include +#include "ArduinoJson.h" + +SoftwareSerial mySerial(10, 11); // RX, TX + +const int DHTPIN = 2; +const int DHTTYPE = DHT11; // Khai bao loai cam bien, co 2 loai la DHT11 va DHT22 +DHT dht(DHTPIN, DHTTYPE); +const int LDR_Pin = A0; + +void setup(){ + Serial.begin(115200); + mySerial.begin(115200); +} + +StaticJsonBuffer<200> jsonBuffer; +JsonObject& json_buffer = jsonBuffer.createObject(); +char buffer_temp[200]; + +int LDRReading = 0; +int temperature = 0; +int humidity = 0; + +void loop() +{ + LDRReading = analogRead(LDR_Pin); + Serial.println(LDRReading); + + if (LDRReading < 500){ + LDRReading = 0; + } + else if (LDRReading >= 500 && LDRReading < 900){ + LDRReading = 1; + } + else{ + LDRReading = 2; + } + + + + humidity = dht.readHumidity(); //Doc do am + temperature = dht.readTemperature(); // Doc nhiet do + Serial.print("Nhiet do: "); + Serial.println(temperature); + Serial.print("Do am: "); + Serial.println(humidity); + Serial.println(); + + json_buffer["light"] = LDRReading; + json_buffer["temperature"] = temperature; + json_buffer["humidity"] = humidity; + + json_buffer.printTo(buffer_temp, sizeof(buffer_temp)); +// Serial.println(buffer_temp); + mySerial.write(LDRReading); // Gui cho Esp8266 + mySerial.write(temperature); + mySerial.write(humidity); +// mySerial.write(buffer_temp); + + delay(1000); + +} + diff --git a/do_chi_thanh/OpenHAB/cam_bien_chuyen_dong_arduino.ino b/do_chi_thanh/OpenHAB/cam_bien_chuyen_dong_arduino.ino new file mode 100644 index 00000000..e328ec66 --- /dev/null +++ b/do_chi_thanh/OpenHAB/cam_bien_chuyen_dong_arduino.ino @@ -0,0 +1,123 @@ +#include +#include +SoftwareSerial mySerial(10, 11); // RX, TX + +int ledXanh = 3; // chọn chân 13 báo hiệu LED +int ledDo = 4; +int ledVang = 5; + +int inputPin = 2; // chọn ngõ tín hiệu vào cho cảm biến chuyển động +int val = 0; + +void setup(){ + pinMode(ledXanh, OUTPUT); + pinMode(ledDo, OUTPUT); + pinMode(ledVang , OUTPUT); + pinMode(inputPin, INPUT); + Serial.begin(9600); + mySerial.begin(115200); +} + + +StaticJsonBuffer<200> jsonBuffer; +JsonObject& json_buffer = jsonBuffer.createObject(); +char buffer_motion[200]; + +void loop(){ + val = digitalRead(inputPin); // đọc giá trị đầu vào. + + + if(mySerial.available() > 0){ + StaticJsonBuffer<200> jsonBufferLed; + String ledString = mySerial.readString(); + Serial.println(ledString); + + int index=0, pre_index=0; + int num_led=3; + int i=0; + String subLedString; + + // Tach tung json trong message + while (i +#include +#include +#include "ArduinoJson.h" + +SoftwareSerial mySerial(10, 11); // RX, TX + +const int DHTPIN = 2; +const int DHTTYPE = DHT11; // Khai bao loai cam bien, co 2 loai la DHT11 va DHT22 +DHT dht(DHTPIN, DHTTYPE); + + +int ledXanh = 3; // chọn chân 13 báo hiệu LED +int ledDo = 4; +int ledVang = 5; + +void setup(){ + Serial.begin(9600); + mySerial.begin(115200); +} + + +int temperature = 0; +int humidity = 0; + +StaticJsonBuffer<200> jsonBuffer; +JsonObject& json_buffer = jsonBuffer.createObject(); +char buffer_temp[200]; + +void loop() +{ + + float h = dht.readHumidity(); //Doc do am + float t = dht.readTemperature(); // Doc nhiet do + Serial.print("Nhiet do: "); + Serial.println(t); + Serial.print("Do am: "); + Serial.println(h); + + json_buffer["temperature"] = t; + json_buffer["humidity"] = h; + + json_buffer.printTo(buffer_temp, sizeof(buffer_temp)); + + mySerial.write(t); // Gui cho esp8266 + mySerial.write(h); // Gui cho esp8266 + mySerial.write(buffer_temp); + Serial.println(); + delay(10); + +} + diff --git a/do_chi_thanh/OpenHAB/connect_arduino_and_esp8266_nodeMCU.PNG b/do_chi_thanh/OpenHAB/connect_arduino_and_esp8266_nodeMCU.PNG new file mode 100644 index 00000000..ec17b832 Binary files /dev/null and b/do_chi_thanh/OpenHAB/connect_arduino_and_esp8266_nodeMCU.PNG differ diff --git a/do_chi_thanh/OpenHAB/connect_arduino_and_motion_sensor.PNG b/do_chi_thanh/OpenHAB/connect_arduino_and_motion_sensor.PNG new file mode 100644 index 00000000..bbee3c43 Binary files /dev/null and b/do_chi_thanh/OpenHAB/connect_arduino_and_motion_sensor.PNG differ diff --git a/do_chi_thanh/OpenHAB/default.items b/do_chi_thanh/OpenHAB/default.items new file mode 100644 index 00000000..c755181a --- /dev/null +++ b/do_chi_thanh/OpenHAB/default.items @@ -0,0 +1,8 @@ +Switch Switch1 {mqtt=">[mybroker:zone_3/box_1/led:command:ON:{\"vang\"\\:\"ON\"}],>[mybroker:zone_3/box_1/led:command:OFF:{\"vang\"\\:\"OFF\"}]"} +Switch Switch2 {mqtt=">[mybroker:zone_3/box_1/led:command:ON:{\"do\"\\:\"ON\"}],>[mybroker:zone_3/box_1/led:command:OFF:{\"do\"\\:\"OFF\"}]"} +Switch Switch3 {mqtt=">[mybroker:zone_3/box_1/led:command:ON:{\"xanh\"\\:\"ON\"}],>[mybroker:zone_3/box_1/led:command:OFF:{\"xanh\"\\:\"OFF\"}]"} +Number Temperature "Temperature: [%.1f oC]" {mqtt="<[mybroker:zoner_3/box_1/temp/id_1:state:JSONPATH($.temperature)]"} +Number Humidity "Humidity: [%.1f ]" {mqtt="<[mybroker:zoner_3/box_1/temp/id_1:state:JSONPATH($.humidity)]"} +Number Motion "Motion: [ %d ]" {mqtt="<[mybroker:zone_3/box_1/motion/id_1:state:JSONPATH($.motion)]"} +Number Light "Light: [%d ]" {mqtt="<[mybroker:zoner_3/box_1/light/id_1:state:JSONPATH($.light)]"} + diff --git a/do_chi_thanh/OpenHAB/default.services b/do_chi_thanh/OpenHAB/default.services new file mode 100644 index 00000000..1e528947 --- /dev/null +++ b/do_chi_thanh/OpenHAB/default.services @@ -0,0 +1 @@ +mybroker.url=tcp://test.mosquitto.org:1883 diff --git a/do_chi_thanh/OpenHAB/default.sitemap b/do_chi_thanh/OpenHAB/default.sitemap new file mode 100644 index 00000000..62176d0d --- /dev/null +++ b/do_chi_thanh/OpenHAB/default.sitemap @@ -0,0 +1,11 @@ +sitemap default label="My first sitemap" +{ + Switch item=Laptop_Thanh label="Thanh's Laptop" + Switch item=Switch1 label="Led vang" + Switch item=Switch2 label="Led do" + Switch item=Switch3 label="Led xanh" + Text item=Temperature label="Temperature" + Text item=Humidity label="Humidity" + Text item=Motion label="Motion" + Text item=Light label="Light" +} diff --git a/do_chi_thanh/OpenHAB/esp8266_cam_bien_chuyen_dong.ino b/do_chi_thanh/OpenHAB/esp8266_cam_bien_chuyen_dong.ino new file mode 100644 index 00000000..aad7829e --- /dev/null +++ b/do_chi_thanh/OpenHAB/esp8266_cam_bien_chuyen_dong.ino @@ -0,0 +1,139 @@ +#include +#include "PubSubClient.h" +#include "ArduinoJson.h" +#include +const byte RX = D1; +const byte TX = D2; + +SoftwareSerial mySerial = SoftwareSerial(RX, TX, false, 256); + +//#define mqtt_server "test.mosquitto.org" +#define mqtt_server "192.168.60.199" +#define mqtt_topic_pub "zone_3/box_1/motion/id_1" +#define mqtt_topic_sub "zone_3/box_1/led" + +//IPAddress staticIP(192,168,60,174); // Phong may +IPAddress staticIP(192,168,60,173); // Phong ngoai +//IPAddress staticIP(192,168,60,172); // Phong can bo + +IPAddress gateway(192,168,60,1); +IPAddress subnet(255,255,255,0); + +const char *ssid = "HPCC_IOT"; /// replace with your wifi ssid and wpa2 key. +const char *pass = "hpcc_iot"; +//const char* ssid = "ThuyHuong"; +//const char* pass = "09061994"; + +WiFiClient ESPclient; +PubSubClient client(ESPclient); + +long lastMsg = 0; +char msg[50]; +int value = 0; + + +//unsigned long time = 0; +void setup_wifi(); + +void setup() +{ + Serial.begin(115200); + mySerial.begin(115200); + setup_wifi(); + client.setServer(mqtt_server, 1883); + client.setCallback(callback); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); +} + +void setup_wifi(){ + delay(10); + Serial.println("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, pass); + WiFi.config(staticIP, gateway, subnet); + + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); +} + +// Ham callback de nhan du lieu +void callback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + + if(strcmp(topic,mqtt_topic_sub)==0){ + payload[length] = '\0'; // Cắt bỏ dữ liệu thừa + char inData[80]; + char payload_string[100]; + strncpy(payload_string, (char*)payload,sizeof(payload_string)); // chuyển về dàng char + Serial.println(payload_string); + mySerial.print(payload_string); + } + Serial.println(); + delay(100); +} + +void reconnect() { + // Loop until we're reconnected + while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + // Create a random client ID + String clientId = "ESP8266Client-"; + clientId += String(random(0xffff), HEX); + // Attempt to connect + if (client.connect(clientId.c_str())) { + Serial.println("connected"); + // Once connected, publish an announcement... + //client.publish(mqtt_topic_pub, "hello world"); + // ... and resubscribe + client.subscribe(mqtt_topic_sub); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // Wait 5 seconds before retrying + delay(5000); + } + } +} + +// Nhan du lieu tu arduino va publish/subscribe len server +int person = 0; +StaticJsonBuffer<200> jsonBuffer; +JsonObject& json_buffer = jsonBuffer.createObject(); +char buffer_motion[200]; + +void loop() +{ + // Kiem tra ket noi + if (!client.connected()){ + reconnect(); + } + + client.loop(); + if(mySerial.available() > 0){ + person = mySerial.read(); + long now = millis(); + if (now - lastMsg > 100){ + lastMsg = now; + + json_buffer["motion"] = person; + json_buffer.printTo(buffer_motion, sizeof(buffer_motion)); + Serial.println(buffer_motion); + client.publish(mqtt_topic_pub, buffer_motion); + + } + } + delay(3000); + +} diff --git a/do_chi_thanh/OpenHAB/ip.txt b/do_chi_thanh/OpenHAB/ip.txt new file mode 100644 index 00000000..e3e15df2 --- /dev/null +++ b/do_chi_thanh/OpenHAB/ip.txt @@ -0,0 +1,47 @@ +laptop : 192.168.60.246 +cam bien nguoi phong ngoai, canh ban: 192.168.60.173 +cam bien nguoi phong ngoai, tren cao: 192.168.60.170 +cam bien nhiet am phong ngoai: 192.168.60.176 + +cam bien nguoi phong can bo: 192.168.60.172 +cam bien nhiet am phong can bo: 192.168.60.171 + +cam bien nguoi phong may: 192.168.60.174 +cam bien nhiet am phong may: 192.168.60.175 + + + + +MAC Adress: + +cam bien nguoi + nhiet do do am phong ngoai canh ban: 2C:3A:E8:0E:BC:D5 + + +Qui uoc dat ten topic : + zone_1: phong server + zone_2: phong can bo + zone_3: phong ngoai + + box_1 : hop tren cao (neu co) + box_2 : hop duoi thap + + temperature_humidity: cam bien nhiet do do am + motion: cam bien nguoi + id_1 : thiet bi so 1 trong hop + id_2 : thiet bi so 2 trong hop + +Dat ten topic : + + cam bien nguoi trong phong can bo : zone_2/box_2/motion/id_1 cong 30004 + cam bien nhiet do do am, phong can bo : zone_2/box_1/temperature_humidity/id_1 cong 30004 + + cam bien nguoi trong phong ngoai, tren cao: zone_1/box_2/motion/id_1 + cam bien nguoi trong phong ngoai, canh ban: zone_1/box_1/motion/id_1 + cam bien nhiet do, do am phong ngoai : zone_1/box_3/temperature_humidity/id_1 + + cam bien nguoi phong server, tren cao : zone_3/box_1/motion/id_1, cong 30004 + cam bien nhiet do, do am phong server : zone_3/box_2/temperature_humidity/id_1, cong 30004 + + + + diff --git a/do_chi_thanh/OpenHAB/mqtt.cfg b/do_chi_thanh/OpenHAB/mqtt.cfg new file mode 100644 index 00000000..8bc9b6bf --- /dev/null +++ b/do_chi_thanh/OpenHAB/mqtt.cfg @@ -0,0 +1,41 @@ +# +# Define your MQTT broker connections here for use in the MQTT Binding or MQTT +# Persistence bundles. Replace with an ID you choose. +# + +# URL to the MQTT broker, e.g. tcp://localhost:1883 or ssl://localhost:8883 +#.url=tcp://:1883 +mybroker.url=tcp://test.mosquitto.org:1883 + +# Optional. Client id (max 23 chars) to use when connecting to the broker. +# If not provided a random default is generated. +#.clientId= + +# Optional. True or false. If set to true, allows the use of clientId values +# up to 65535 characters long. Defaults to false. +# NOTE: clientId values longer than 23 characters may not be supported by all +# MQTT servers. Check the server documentation. +#.allowLongerClientIds=false + +# Optional. User id to authenticate with the broker. +#.user= + +# Optional. Password to authenticate with the broker. +#.pwd= + +# Optional. Set the quality of service level for sending messages to this broker. +# Possible values are 0 (Deliver at most once),1 (Deliver at least once) or 2 +# (Deliver exactly once). Defaults to 0. +#.qos= + +# Optional. True or false. Defines if the broker should retain the messages sent to +# it. Defaults to false. +#.retain= + +# Optional. True or false. Defines if messages are published asynchronously or +# synchronously. Defaults to true. +#.async= + +# Optional. Defines the last will and testament that is sent when this client goes offline +# Format: topic:message:qos:retained
+#.lwt= diff --git a/do_chi_thanh/OpenHAB/openHAB_system.jpg b/do_chi_thanh/OpenHAB/openHAB_system.jpg new file mode 100644 index 00000000..34b27fec Binary files /dev/null and b/do_chi_thanh/OpenHAB/openHAB_system.jpg differ diff --git a/do_chi_thanh/OpenHAB/openhab_light_on_off.py b/do_chi_thanh/OpenHAB/openhab_light_on_off.py new file mode 100644 index 00000000..0582fda2 --- /dev/null +++ b/do_chi_thanh/OpenHAB/openhab_light_on_off.py @@ -0,0 +1,75 @@ +from openhab import openHAB +import paho.mqtt.client as mqtt +import json +import time + + +base_url = 'http://localhost:8080/rest' +openhab = openHAB(base_url) + +# fetch all items +items = openhab.fetch_all_items() +# print (items) + +item1 = openhab.get_item("Switch1") +item2 = openhab.get_item("Switch2") +item3 = openhab.get_item("Switch3") + +temp_item = openhab.get_item("Temperature") +light_item = openhab.get_item("Light") +light_state = light_item.state + +topic_sub_sensor = "zone_3/box_1/motion/id_1" +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(topic_sub_sensor) + +# The callback for when a PUBLISH message is received from the server. +def on_message(client, userdata, msg): + print(msg.topic+" "+str(msg.payload)) + global pre_motion + + mes = json.loads(str(msg.payload)) + mes = mes['motion'] + + if (mes == 1 and pre_motion == 0): + # pre_motion = mes + light_state = light_item.state + print (light_state) + if (light_state == 0): # LDRReading < 500 + item1.on() # Bat den vang + time.sleep(0.5) + item2.off() + time.sleep(0.5) + item3.off() + print ("Vang: ON, Do: OFF, Xanh: OFF") + elif (light_state == 1): # LDRReading >= 500 <600 + item1.off() + time.sleep(0.5) + item2.on() # Bat den do + time.sleep(0.5) + item3.off() + print ("Vang: OFF, Do: ON, Xanh: OFF") + elif (light_state == 2): # LDRReading >= 600 + item1.off() + time.sleep(0.5) + item2.off() + time.sleep(0.5) + item3.on() # Bat den xanh + print ("Vang: OFF, Do: OFF, Xanh: ON") + else: + print ("ERROR!") + exit() + +client = mqtt.Client() +pre_motion = 0 +pre_temp = 0 + +client.on_connect = on_connect +client.on_message = on_message + +client.connect("192.168.60.199", 1883, 60) +client.loop_forever() diff --git a/do_chi_thanh/OpenHAB/wifi_cam_bien_anh_sang.ino b/do_chi_thanh/OpenHAB/wifi_cam_bien_anh_sang.ino new file mode 100644 index 00000000..44d996e6 --- /dev/null +++ b/do_chi_thanh/OpenHAB/wifi_cam_bien_anh_sang.ino @@ -0,0 +1,174 @@ +#include +#include "PubSubClient.h" +#include "ArduinoJson.h" +#include +#include +#include +#include +#include + + +const byte RX = D1; +const byte TX = D2; + +SoftwareSerial mySerial = SoftwareSerial(RX, TX, false, 256); + +//#define mqtt_server "test.mosquitto.org" +#define mqtt_server "192.168.60.199" +#define mqtt_topic_pub "zone_3/box_1/light/id_1" +//#define mqtt_topic_sub "light/switch" +#define mqtt_topic_sub "zone_3/box_1/led" +#define mqtt_topic_check_status "light/status" + + +//IPAddress staticIP(192,168,60,175); // Phong may +//IPAddress staticIP(192,168,60,171); // Phong can bo +IPAddress staticIP(192,168,60,176); // Phong ngoai + +IPAddress gateway(192,168,60,1); +IPAddress subnet(255,255,255,0); + +const char *ssid = "HPCC_IOT"; /// replace with your wifi ssid and wpa2 key. +const char *pass = "hpcc_iot"; +//const char* ssid = "ThuyHuong"; +//const char* pass = "09061994"; +//const char* host = "esp8266-webupdate"; + +//ESP8266WebServer httpServer(80); +//ESP8266HTTPUpdateServer httpUpdater; + +WiFiClient ESPclient; +PubSubClient client(ESPclient); + +long lastMsg = 0; +char msg[50]; +int value = 0; + + +//unsigned long time = 0; +void setup_wifi(); + +void setup() +{ + Serial.begin(115200); + mySerial.begin(115200); + setup_wifi(); +// WiFi.mode(WIFI_STA); + client.setServer(mqtt_server, 1883); + client.setCallback(callback); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); + +// MDNS.begin(host); +// +// httpUpdater.setup(&httpServer); +// httpServer.begin(); +// +// MDNS.addService("http", "tcp", 80); +// Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host); + +} + +void setup_wifi(){ + delay(10); + Serial.println("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, pass); + WiFi.config(staticIP, gateway, subnet); + + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IP address: "); + Serial.println(WiFi.localIP()); +} + +// Ham callback de nhan du lieu +void callback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + + if(strcmp(topic,mqtt_topic_sub)==0){ + payload[length] = '\0'; // Cắt bỏ dữ liệu thừa + char inData[80]; + char payload_string[100]; + strncpy(payload_string, (char*)payload,sizeof(payload_string)); // chuyển về dàng char + Serial.println(payload_string); + mySerial.print(payload_string); + client.publish(mqtt_topic_check_status, payload_string); + } + Serial.println(); +} + +void reconnect() { + // Loop until we're reconnected + while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + // Create a random client ID + String clientId = "ESP8266Client-"; + clientId += String(random(0xffff), HEX); + // Attempt to connect + if (client.connect(clientId.c_str())) { + Serial.println("connected"); + // Once connected, publish an announcement... + //client.publish(mqtt_topic_pub, "hello world"); + // ... and resubscribe + boolean boo = client.subscribe(mqtt_topic_sub); + Serial.println(boo); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // Wait 5 seconds before retrying + delay(5000); + } + } +} + +// Nhan du lieu tu arduino va publish/subscribe len server +int light=0; +int temperature = 0; +int humidity = 0; + +StaticJsonBuffer<200> jsonBuffer; +JsonObject& json_buffer = jsonBuffer.createObject(); +char buffer_weather[200]; + +void loop() +{ +// httpServer.handleClient(); + // Kiem tra ket noi + if (!client.connected()){ + reconnect(); + } + + client.loop(); + if(mySerial.available() > 0){ + light = mySerial.read(); + temperature = mySerial.read(); + humidity = mySerial.read(); + +// Serial.println(light); + long now = millis(); +// if (now - lastMsg > 100){ + lastMsg = now; + + json_buffer["light"] = light; + json_buffer["temperature"] = temperature; + json_buffer["humidity"] = humidity; + + json_buffer.printTo(buffer_weather, sizeof(buffer_weather)); + Serial.println(buffer_weather); + client.publish(mqtt_topic_pub, buffer_weather); + +// } + } + delay(1000); + +} diff --git a/do_chi_thanh/OpenHAB/wifi_cam_bien_nhiet_do_do_am.ino b/do_chi_thanh/OpenHAB/wifi_cam_bien_nhiet_do_do_am.ino new file mode 100644 index 00000000..db621181 --- /dev/null +++ b/do_chi_thanh/OpenHAB/wifi_cam_bien_nhiet_do_do_am.ino @@ -0,0 +1,144 @@ +#include +#include "PubSubClient.h" +#include "ArduinoJson.h" +#include +const byte RX = D1; +const byte TX = D2; + +SoftwareSerial mySerial = SoftwareSerial(RX, TX, false, 256); + +#define mqtt_server "test.mosquitto.org" +#define mqtt_topic_pub "zone_3/box_1/temp/id_1" +//#define mqtt_topic_sub "light/switch" +#define mqtt_topic_sub "zone_3/box_1/led" +#define mqtt_topic_check_status "light/status" + + +IPAddress staticIP(192,168,60,176); +IPAddress gateway(192,168,60,1); +IPAddress subnet(255,255,255,0); + +const char *ssid = "HPCC_IOT"; /// replace with your wifi ssid and wpa2 key. +const char *pass = "hpcc_iot"; +//const char* ssid = "ThuyHuong"; +//const char* pass = "09061994"; + +WiFiClient ESPclient; +PubSubClient client(ESPclient); + +long lastMsg = 0; +char msg[50]; +int value = 0; + + +//unsigned long time = 0; +void setup_wifi(); + +void setup() +{ + Serial.begin(115200); + mySerial.begin(115200); + setup_wifi(); + client.setServer(mqtt_server, 1883); + client.setCallback(callback); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); +} + +void setup_wifi(){ + delay(10); + Serial.println("Connecting to "); + Serial.println(ssid); + + WiFi.begin(ssid, pass); + WiFi.config(staticIP, gateway, subnet); + + while (WiFi.status() != WL_CONNECTED) + { + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.println("WiFi connected"); + Serial.println("IPu address: "); + Serial.println(WiFi.localIP()); +} + +// Ham callback de nhan du lieu +void callback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + + if(strcmp(topic,mqtt_topic_sub)==0){ + payload[length] = '\0'; // Cắt bỏ dữ liệu thừa + char inData[80]; + char payload_string[100]; + strncpy(payload_string, (char*)payload,sizeof(payload_string)); // chuyển về dàng char + Serial.println(payload_string); + mySerial.print(payload_string); +// client.publish(mqtt_topic_check_status, payload_string); + } + Serial.println(); +} + +void reconnect() { + // Loop until we're reconnected + while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + // Create a random client ID + String clientId = "ESP8266Client-"; + clientId += String(random(0xffff), HEX); + // Attempt to connect + if (client.connect(clientId.c_str())) { + Serial.println("connected"); + // Once connected, publish an announcement... + //client.publish(mqtt_topic_pub, "hello world"); + // ... and resubscribe + boolean boo = client.subscribe(mqtt_topic_sub); + Serial.println(boo); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // Wait 5 seconds before retrying + delay(5000); + } + } +} + +// Nhan du lieu tu arduino va publish/subscribe len server +int temperature = 0; +int humidity = 0; + +StaticJsonBuffer<200> jsonBuffer; +JsonObject& json_buffer = jsonBuffer.createObject(); +char buffer_weather[200]; + +void loop() +{ + // Kiem tra ket noi + if (!client.connected()){ + reconnect(); + } + + client.loop(); + if(mySerial.available() > 0){ + temperature = mySerial.read(); + humidity = mySerial.read(); + long now = millis(); + if (now - lastMsg > 10){ + lastMsg = now; + + json_buffer["temperature"] = temperature; + json_buffer["humidity"] = humidity; + + json_buffer.printTo(buffer_weather, sizeof(buffer_weather)); + Serial.println(buffer_weather); + client.publish(mqtt_topic_pub, buffer_weather); + + } + } + delay(100); + +}