-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartHomeControl.ino
More file actions
84 lines (75 loc) · 2.1 KB
/
SmartHomeControl.ino
File metadata and controls
84 lines (75 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "harish";
const char* password = "harish23";
#define ORG "iip4gk"
#define DEVICE_TYPE "vizag"
#define DEVICE_ID "1234"
#define TOKEN "harish1234"
String command;
char server[] = ORG ".messaging.internetofthings.ibmcloud.com";
char topic[] = "iot-2/cmd/home/fmt/String";
char authMethod[] = "use-token-auth";
char token[] = TOKEN;
char clientId[] = "d:" ORG ":" DEVICE_TYPE ":" DEVICE_ID;
//Serial.println(clientID);
WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int payloadLength);
PubSubClient client(server, 1883, callback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(D1,OUTPUT);
wifiConnect();
mqttConnect();
}
void loop() {
if (!client.loop()) {
mqttConnect();
}
delay(100);
}
void wifiConnect() {
Serial.print("Connecting to "); Serial.print(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("nWiFi connected, IP address: "); Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!client.connected()) {
Serial.print("Reconnecting MQTT client to "); Serial.println(server);
while (!client.connect(clientId, authMethod, token)) {
Serial.print(".");
delay(500);
}
initManagedDevice();
Serial.println();
}
}
void initManagedDevice() {
if (client.subscribe(topic)) {
Serial.println("subscribe to cmd OK");
} else {
Serial.println("subscribe to cmd FAILED");
}
}
void callback(char* topic, byte* payload, unsigned int payloadLength) {
Serial.print("callback invoked for topic: "); Serial.println(topic);
for (int i = 0; i < payloadLength; i++) {
//Serial.println((char)payload[i]);
command += (char)payload[i];
}
Serial.println(command);
if(command == "LIGHTON"){
digitalWrite(D1,HIGH);
Serial.println("Light is Switched ON");
}
else if(command == "LIGHTOFF"){
digitalWrite(D1,HIGH);
Serial.println("Light is Switched OFF");
}
command ="";
}