· 6 years ago · Apr 26, 2020, 01:26 PM
1#include <Arduino.h>
2#include <ESP8266WiFi.h>
3#include <ESP8266WiFiMulti.h>
4#include <WebSocketsClient.h> // https://github.com/kakopappa/sinric/wiki/How-to-add-dependency-libraries
5#include <ArduinoJson.h> // https://github.com/kakopappa/sinric/wiki/How-to-add-dependency-libraries
6#include <StreamString.h>
7
8#define MyApiKey "" // TODO: Change to your sinric API Key. Your API Key is displayed on sinric.com dashboard
9#define MySSID "" // TODO: Change to your Wifi network SSID
10#define MyWifiPassword "" // TODO: Change to your Wifi network password
11
12#define SWITCH_PIN1 13
13#define SWITCH_PIN2 15
14
15#define HEARTBEAT_INTERVAL 300000 // 5 Minutes
16
17uint64_t heartbeatTimestamp = 0;
18bool isConnected = false;
19
20bool timerStarted = false;
21unsigned long previousMillis = 0;
22
23
24
25void turnOn(String deviceId) {
26 if (deviceId == "5axxxxxxxxxxxxxxxxxxx") // Device ID of first device
27 {
28 Serial.print("Turn on device id: ");
29 Serial.println(deviceId);
30 timerStarted = true; // Set a new flag indicating that the timer was started
31 previousMillis = millis(); // Get the initial time the appliance was turned on
32
33 Serial.println("D2 low");
34 digitalWrite(D2, LOW);
35
36 Serial.println("D3 low");
37 digitalWrite(D3, LOW);
38
39 Serial.flush();
40
41 Serial.println("D2 HIGH");
42 digitalWrite(D2, HIGH);
43
44
45 Serial.println("Lift1 moving up.");
46 }
47}
48
49void turnOff(String deviceId) {
50 if (deviceId == "5axxxxxxxxxxxxxxxxxxx") // Device ID of first device
51 {
52 Serial.print("Turn off Device ID: ");
53 Serial.println(deviceId);
54 }
55 timerStarted = true; // Set a new flag indicating that the timer was started
56 previousMillis = millis(); // Get the initial time the appliance was turned on
57
58 Serial.println("D2 low");
59 digitalWrite(D2, LOW);
60
61 Serial.println("D3 low");
62 digitalWrite(D3, LOW);
63
64 Serial.flush();
65
66 Serial.println("D3 HIGH");
67 digitalWrite(D3, HIGH);
68
69 Serial.println("Lift1 moving down.");
70}
71
72void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
73 switch(type) {
74 case WStype_DISCONNECTED:
75 isConnected = false;
76 Serial.printf("[WSc] Webservice disconnected from sinric.com!\n");
77 break;
78 case WStype_CONNECTED: {
79 isConnected = true;
80 Serial.printf("[WSc] Service connected to sinric.com at url: %s\n", payload);
81 Serial.printf("Waiting for commands from sinric.com ...\n");
82 }
83 break;
84 case WStype_TEXT: {
85 Serial.printf("[WSc] get text: %s\n", payload);
86 // Example payloads
87
88 // For Switch or Light device types
89 // {"deviceId": xxxx, "action": "setPowerState", value: "ON"} // https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html
90
91 // For Light device type
92 // Look at the light example in github
93
94 DynamicJsonDocument json(1024);
95 deserializeJson(json, (char*) payload);
96
97 String deviceId = json ["deviceId"];
98 String action = json ["action"];
99
100 if(action == "setPowerState") { // Switch or Light
101 String value = json ["value"];
102 if(value == "ON") {
103 turnOn(deviceId);
104 } else {
105 turnOff(deviceId);
106 }
107 }
108 else if (action == "SetTargetTemperature") {
109 String deviceId = json ["deviceId"];
110 String action = json ["action"];
111 String value = json ["value"];
112 }
113 else if (action == "test") {
114 Serial.println("[WSc] received test command from sinric.com");
115 }
116 }
117 break;
118 case WStype_BIN:
119 Serial.printf("[WSc] get binary length: %u\n", length);
120 break;
121 }
122}
123
124void wifiSetup() {
125 // Set WIFI module to STA mode
126 WiFi.mode(WIFI_STA);
127
128 // Connect
129 Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
130 WiFi.begin(WIFI_SSID, WIFI_PASS);
131
132 // Wait until connected
133 while (WiFi.status() != WL_CONNECTED) {
134 Serial.print(".");
135 delay(100);
136 }
137 Serial.println();
138
139 // Connected!
140 Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
141}
142
143void setup() {
144 Serial.begin(115200);
145
146 wifiSetup();
147
148 pinMode(D2, OUTPUT); // Initialize the D2 PIN as an output
149 digitalWrite(D2, LOW);
150
151 pinMode(D3, OUTPUT); // Initialize the D3 PIN as an output
152 digitalWrite(D3, LOW);
153
154
155 // server address, port and URL
156 webSocket.begin("iot.sinric.com", 80, "/");
157
158 // event handler
159 webSocket.onEvent(webSocketEvent);
160 webSocket.setAuthorization("apikey", MyApiKey);
161
162 // try again every 5000ms if connection has failed
163 webSocket.setReconnectInterval(5000); // If you see 'class WebSocketsClient' has no member named 'setReconnectInterval' error update arduinoWebSockets
164}
165
166void loop() {
167if (timerStarted && millis() - previousMillis > 5000) { // Check if appliance was turned on for 5s
168 digitalWrite(D2, LOW); // Turn off the relay after 5 seconds
169 digitalWrite(D3, LOW); // Turn off the relay after 5 seconds
170 Serial.println("Turning off relays");
171 timerStarted = false; // Reset flag so it won't keep checking this if statement
172 }
173 webSocket.loop();
174
175 if(isConnected) {
176 uint64_t now = millis();
177
178 // Send heartbeat in order to avoid disconnections during ISP resetting IPs over night. Thanks @MacSass
179 if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
180 heartbeatTimestamp = now;
181 webSocket.sendTXT("H");
182 }
183 }
184}