-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSciFyIoT.cpp
More file actions
299 lines (248 loc) · 7.63 KB
/
Copy pathSciFyIoT.cpp
File metadata and controls
299 lines (248 loc) · 7.63 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#include "SciFyIoT.h"
// Static instance pointer for callback wrapper
SciFyIoT* SciFyIoT::instance = nullptr;
// Constructor
SciFyIoT::SciFyIoT() {
authenticated = false;
lastHeartbeat = 0;
lastActivity = 0;
_commandCallback = nullptr;
_statusCallback = nullptr;
_serverUrl = "api.scify-tech.com";
_serverPort = 443;
_serverPath = "/ws";
// Set static instance for callback wrapper
instance = this;
}
// Initialize with default server
void SciFyIoT::begin(const char* ssid, const char* password, const char* apiKey, const char* secret) {
begin(ssid, password, apiKey, secret, "api.scify-tech.com", 443, "/ws");
}
// Initialize with custom server
void SciFyIoT::begin(const char* ssid, const char* password, const char* apiKey, const char* secret,
const char* serverUrl, int serverPort, const char* serverPath) {
Serial.begin(115200);
delay(1000);
Serial.println("[SciFyIoT] Starting...");
_ssid = ssid;
_password = password;
_apiKey = apiKey;
_secret = secret;
_serverUrl = serverUrl;
_serverPort = serverPort;
_serverPath = serverPath;
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
// Connect to WiFi
connectWiFi();
if (WiFi.status() == WL_CONNECTED) {
webSocket.beginSSL(_serverUrl.c_str(), _serverPort, _serverPath.c_str());
webSocket.onEvent(webSocketEventWrapper);
webSocket.setReconnectInterval(5000);
webSocket.enableHeartbeat(15000, 3000, 2);
lastActivity = millis();
Serial.println("[SciFyIoT] Initialized successfully!");
} else {
Serial.println("[SciFyIoT] WiFi connection failed");
}
}
// Main loop processing
void SciFyIoT::loop() {
webSocket.loop();
if (WiFi.status() != WL_CONNECTED) {
connectWiFi();
}
if (authenticated && millis() - lastHeartbeat > heartbeatInterval) {
sendHeartbeat();
lastHeartbeat = millis();
}
checkConnection();
delay(50);
}
// Status methods
bool SciFyIoT::isConnected() {
return webSocket.isConnected();
}
bool SciFyIoT::isAuthenticated() {
return authenticated;
}
bool SciFyIoT::isWiFiConnected() {
return WiFi.status() == WL_CONNECTED;
}
// Connect to WiFi
void SciFyIoT::connectWiFi() {
WiFi.begin(_ssid.c_str(), _password.c_str());
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 30) {
delay(500);
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("[WiFi] Connected");
} else {
Serial.println("[WiFi] Connection failed");
}
}
// Static callback wrapper
void SciFyIoT::webSocketEventWrapper(WStype_t type, uint8_t * payload, size_t length) {
if (instance) {
instance->webSocketEvent(type, payload, length);
}
}
// WebSocket event handler
void SciFyIoT::webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
lastActivity = millis();
switch (type) {
case WStype_DISCONNECTED:
authenticated = false;
digitalWrite(LED_BUILTIN, HIGH);
if (_statusCallback) _statusCallback(false, false);
break;
case WStype_CONNECTED:
authenticated = false;
authenticateDevice();
if (_statusCallback) _statusCallback(true, false);
break;
case WStype_TEXT:
handleWebSocketMessage((char*)payload);
break;
case WStype_ERROR:
Serial.printf("[WS] Error: %s\n", payload);
break;
}
}
// Authenticate with server
void SciFyIoT::authenticateDevice() {
DynamicJsonDocument doc(256);
doc["type"] = "auth";
doc["apiKey"] = _apiKey;
doc["secret"] = _secret;
String message;
serializeJson(doc, message);
webSocket.sendTXT(message);
}
// Handle incoming WebSocket messages
void SciFyIoT::handleWebSocketMessage(const char* message) {
DynamicJsonDocument doc(512);
DeserializationError error = deserializeJson(doc, message);
if (error) return;
String type = doc["type"];
if (type == "auth_success") {
authenticated = true;
digitalWrite(LED_BUILTIN, LOW);
lastHeartbeat = millis();
if (_statusCallback) _statusCallback(true, true);
}
else if (type == "auth_error") {
authenticated = false;
digitalWrite(LED_BUILTIN, HIGH);
if (_statusCallback) _statusCallback(true, false);
}
else if (type == "command" && authenticated) {
String commandId = doc["id"];
String payload = doc["payload"];
bool handled = executeDefaultCommand(payload);
if (!handled && _commandCallback) {
_commandCallback(payload, commandId);
} else if (handled) {
sendAck(commandId, "executed");
} else {
sendAck(commandId, "failed");
}
}
}
// Execute default commands
bool SciFyIoT::executeDefaultCommand(const String& command) {
if (command == "LED_ON") {
digitalWrite(LED_BUILTIN, LOW);
return true;
}
else if (command == "LED_OFF") {
digitalWrite(LED_BUILTIN, HIGH);
return true;
}
else if (command == "STATUS") {
sendSensorData();
return true;
}
else if (command == "RESTART") {
ESP.restart();
return true;
}
return false;
}
// Send acknowledgement
void SciFyIoT::sendAck(const String& commandId, const String& status) {
DynamicJsonDocument doc(256);
doc["type"] = "ack";
doc["commandId"] = commandId;
doc["status"] = status;
doc["timestamp"] = millis();
String message;
serializeJson(doc, message);
webSocket.sendTXT(message);
}
// Send heartbeat
void SciFyIoT::sendHeartbeat() {
if (!authenticated) return;
DynamicJsonDocument doc(128);
doc["type"] = "heartbeat";
doc["timestamp"] = millis();
String message;
serializeJson(doc, message);
webSocket.sendTXT(message);
}
// Send sensor data
void SciFyIoT::sendSensorData(float temperature, float humidity) {
DynamicJsonDocument doc(256);
doc["type"] = "sensor_data";
doc["payload"]["temperature"] = temperature;
doc["payload"]["humidity"] = humidity;
doc["payload"]["uptime"] = millis();
doc["payload"]["free_heap"] = ESP.getFreeHeap();
doc["payload"]["wifi_rssi"] = WiFi.RSSI();
doc["timestamp"] = millis();
String message;
serializeJson(doc, message);
webSocket.sendTXT(message);
}
// Send custom data
void SciFyIoT::sendCustomData(const String& dataType, JsonObject& data) {
DynamicJsonDocument doc(512);
doc["type"] = dataType;
doc["payload"] = data;
doc["timestamp"] = millis();
String message;
serializeJson(doc, message);
webSocket.sendTXT(message);
}
// Send response
void SciFyIoT::sendResponse(const String& commandId, const String& status, const String& data) {
sendAck(commandId, status);
}
// Check connection health
void SciFyIoT::checkConnection() {
if (millis() - lastActivity > connectionTimeout) {
webSocket.disconnect();
authenticated = false;
lastActivity = millis();
}
}
// Set command callback
void SciFyIoT::onCommandReceived(CommandCallback callback) {
_commandCallback = callback;
}
// Set status callback
void SciFyIoT::onStatusChanged(StatusCallback callback) {
_statusCallback = callback;
}
// Restart device
void SciFyIoT::restart() {
ESP.restart();
}
// Enable/disable built-in LED
void SciFyIoT::enableBuiltinLED(bool enable) {
if (enable) {
pinMode(LED_BUILTIN, OUTPUT);
}
}