-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchild.ino
More file actions
340 lines (290 loc) · 7.99 KB
/
child.ino
File metadata and controls
340 lines (290 loc) · 7.99 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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>
// Network credentials
const char *ssid = "Dialog 4G";
const char *password = "1234567890";
// Google Geolocation API
const char *server = "www.googleapis.com";
const int port = 443;
const char *endpoint = "/geolocation/v1/geolocate?key=";
// Flame
const int flamePin = D6;
int isFlame = false;
// Buzzer
const int buzzerPin = D5;
int buzzerStartTime = 0;
bool isBuzzerOn = false;
String lastRequest = "";
void setup()
{
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Wait for IP address
while (WiFi.localIP() == INADDR_NONE)
{
delay(1000);
Serial.println("Waiting for IP...");
}
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
pinMode(buzzerPin, OUTPUT);
pinMode(flamePin, INPUT);
}
void loop()
{
int flameState = digitalRead(flamePin);
if (flameState == LOW)
{
digitalWrite(buzzerPin, HIGH);
if (!isFlame)
{
postStateRequest("Fire");
}
isFlame = true;
return;
}
else
{
isFlame = false;
digitalWrite(buzzerPin, LOW);
}
if (Serial.available() && !isFlame)
{
String command = Serial.readStringUntil('\n');
command.trim();
if (command.indexOf("request_") != -1)
{
Serial.println(command);
if (lastRequest != command)
{
if (command != "request_send_location")
{
lastRequest = command;
}
if (command == "request_status_driving")
{
digitalWrite(buzzerPin, LOW);
postStateRequest("Driving");
Serial.println("Status sended");
}
else if (command == "request_status_accident")
{
digitalWrite(buzzerPin, HIGH);
postStateRequest("Accidented");
Serial.println("Status sended");
}
else if (command == "request_status_break")
{
postStateRequest("Breaked");
Serial.println("Status sent");
}
else if (command == "request_status_stopped")
{
digitalWrite(buzzerPin, LOW);
postStateRequest("Stopped");
Serial.println("Status sended");
}
else if (command == "request_send_location")
{
digitalWrite(buzzerPin, LOW);
DynamicJsonDocument response = googleGeoLocation();
double lat = response["location"]["lat"];
double lng = response["location"]["lng"];
double accuracy = response["accuracy"];
if (lat != 0 && lng != 0)
{
postLocationRequest(lat, lng, accuracy);
}
}
}
else if (command == "request_status_accident")
{
digitalWrite(buzzerPin, HIGH);
}
else if (command == "request_status_break")
{
buzzerStartTime++;
if (buzzerStartTime < 100)
{
digitalWrite(buzzerPin, HIGH);
}
else
{
digitalWrite(buzzerPin, LOW);
}
if (buzzerStartTime > 200)
{
buzzerStartTime = 0;
}
Serial.println(buzzerStartTime);
}
}
}
}
DynamicJsonDocument googleGeoLocation()
{
WiFi.mode(WIFI_STA); // Enable station mode for WiFi
HTTPClient http;
DynamicJsonDocument responseJSON(1024); // Return JSON
// Prepare JSON payload
const int capacity = JSON_OBJECT_SIZE(7) + JSON_ARRAY_SIZE(0) + JSON_ARRAY_SIZE(1) + 200;
DynamicJsonDocument jsonDoc(capacity);
jsonDoc["considerIp"] = false;
// Create a nested array for wifiAccessPoints
JsonArray wifiArray = jsonDoc.createNestedArray("wifiAccessPoints");
// Scan for WiFi access points and add them to the payload
int numOfNetworks = WiFi.scanNetworks();
for (int i = 0; i < numOfNetworks; i++)
{
JsonObject wifiObj = wifiArray.createNestedObject();
wifiObj["macAddress"] = WiFi.BSSIDstr(i);
wifiObj["signalStrength"] = WiFi.RSSI(i);
}
String jsonBody;
serializeJson(jsonDoc, jsonBody);
// Start the HTTPS POST request
WiFiClientSecure client;
client.setInsecure();
if (client.connect(server, port))
{
Serial.println("Connected to server");
// Send the POST request with JSON payload
client.print(String("POST ") + endpoint + " HTTP/1.1\r\n");
client.print("Host: " + String(server) + "\r\n");
client.print("Content-Type: application/json\r\n");
client.print("Content-Length: " + String(jsonBody.length()) + "\r\n");
client.print("\r\n");
client.print(jsonBody);
// Check for a successful response
while (client.connected())
{
String line = client.readStringUntil('\n');
if (line == "\r")
{
Serial.println("Headers received");
break;
}
}
String responseBody = "";
// Read the response body
while (client.available())
{
String line = client.readStringUntil('\n');
responseBody += line;
// Serial.println(line);
}
Serial.println(responseBody);
if (responseBody.length() != 0)
{
// Remove first numbers and last numbers
int startIndex = responseBody.indexOf('{');
int endIndex = responseBody.lastIndexOf('}');
String realJSONstring = responseBody.substring(startIndex, endIndex + 1);
// Add to new real JSON variable
DeserializationError error = deserializeJson(responseJSON, realJSONstring);
if (error)
{
Serial.print("JSON parsing error: ");
Serial.println(error.c_str());
client.stop();
}
else
{
Serial.println("JSON parsing complete!");
}
}
// Disconnect from the server
client.stop();
Serial.println("Disconnected from server");
}
else
{
Serial.println("Connection failed");
}
return responseJSON;
}
void postStateRequest(String state)
{
WiFiClientSecure client;
client.setInsecure();
if (client.connect("api.driversafe.tharindu.dev", 443))
{
Serial.println("Connected to server");
// Create the JSON payload
String jsonBody = "{\"speed\":0,\"state\":\"" + state + "\"}";
// Send the POST request
HTTPClient http;
http.begin(client, "api.driversafe.tharindu.dev", 443, "/states/");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(jsonBody);
// Check the HTTP response code
if (httpCode > 0)
{
Serial.print("HTTP response code: ");
Serial.println(httpCode);
// Read the response
String response = http.getString();
Serial.print("Response: ");
Serial.println(response);
}
else
{
Serial.println("Error sending POST request");
}
http.end(); // Close the connection
Serial.println("Disconnected from server");
}
else
{
Serial.println("Connection failed");
}
}
void postLocationRequest(double lat, double lng, double accuracy)
{
WiFiClientSecure client;
client.setInsecure();
if (client.connect("api.driversafe.tharindu.dev", 443))
{
Serial.println("Connected to server");
// Create the JSON payload
DynamicJsonDocument jsonDoc(256);
jsonDoc["lat"] = lat;
jsonDoc["lng"] = lng;
jsonDoc["accuracy"] = accuracy;
String jsonBody;
serializeJson(jsonDoc, jsonBody);
// Send the POST request
HTTPClient http;
http.begin(client, "api.driversafe.tharindu.dev", 443, "/locations/");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(jsonBody);
// Check the HTTP response code
if (httpCode > 0)
{
Serial.print("HTTP response code: ");
Serial.println(httpCode);
// Read the response
String response = http.getString();
Serial.print("Response: ");
Serial.println(response);
}
else
{
Serial.println("Error sending POST request");
}
http.end(); // Close the connection
Serial.println("Disconnected from server");
}
else
{
Serial.println("Connection failed");
}
}