forked from stanleyhuangyc/Freematics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datalogger.ino
463 lines (399 loc) · 12.9 KB
/
datalogger.ino
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*************************************************************************
* THIS CODE IS BASED ON OBD-II/MEMS/GPS Data Logger Sketch for Freematics ONE+
* Distributed under BSD license
* Visit http://freematics.com/products/freematics-one-plus for more information
* Originally Developed by Stanley Huang <[email protected]>
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* THIS FORK WAS GENERATED BY PAOLO RIVA - UNIVERSITÀ DEGLI STUDI DI BRESCIA.
* THE CODE WAS WRITTEN ALONG A BACHELOR'S DEGREE THESIS PROJECT DEVELOPED IN EARLY 2023,
* BY THE TITLE "DEVELOPMENT OF AN IOT GATEWAY FOR ELECTRIC VEHICLES TELEMETRY".
* FURTHER DEVELOPMENT HAS BEEN PROVIDED TO THE PROJECT IN A POST-GRADUATE STAGE
* COLLABORATION WITH THE ENERGY LABORATORY AS UNIVERSITY EXPO (ELUX) INTERNAL TO
* UNIVERSITÀ DEGLI STUDI DI BRESCIA.
* PROJECT SUPERVISION PROVIDED BY PHD. PAOLO BELLAGENTE
*
* THE FIRMWARE IS ABLE TO ACCESS VEHICLE DATA THROUGH OBD-II DIAGNOSTIC PORTS.
* THE DATA ACQUIRED IS THEN PROCESSED, SERIALIZED AND SENT TO A STATIC MQTT BROKER.
* THE CODE IS SPECIFICALLY INTENDED FOR FREEMATICS ONE+ DEVICES.
*
**************************************************************************/
#include "FreematicsOBD.h"
#include "config.h"
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <Wire.h>
#include <ArduinoJson.h>
#include <SPIFFS.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
using namespace std;
#define WIFI_TIMEOUT 20000 //ms
//Wi-Fi Environment
char wifiSSID[512] = "";
char wifiPassword[512] = "";
const char* wiFiFilePath = "/wifi.json";
const char* rootPage = "/root.html";
const char* savesuccessPage = "/savesuccess.html";
const char* logoImagePath = "/eluxlogo.png";
WiFiClientSecure espClient;
AsyncWebServer server(80);
//OBD Environment
COBDSPI obd;
uint16_t pids[]= {PID_RPM, PID_SPEED, PID_THROTTLE, PID_ENGINE_REF_TORQUE};
String stamps[4]= {"rpm", "speed", "throttle", "torque_reference_erogation"};
int values[4] = {0,0,0,0};
//JSON Serialization/Deserialization Environment
const int capacity = JSON_OBJECT_SIZE(3*(sizeof(pids)/sizeof(pids[0]))); //Dimension to allocate in order to process JSON serialisation (in Bytes)
DynamicJsonDocument jsondoc(capacity);
//MQTT Environment
PubSubClient client(espClient);
long lastMsg = 0;
const char* client_name = "PRivaClient";
const char* mqtt_server = "lab-elux.unibs.it";
const int port = 50009;
const char* topicToPublish = "/telemetry/obd/car1";
const char* broker_uname = "priva";
const char* broker_pw = "KObM2u96t%&M#e%%ShZ#H!5Ls$0UEN^wXLuegI@*1rudAPeQE";
const char* certificate_path = "/intermediate_ca.pem";
String PROGMEM certificate; //NOTE: The certificate needs to have a \n on top and bottom
//Environment Vars
bool connected = false;
bool firstLoop = true;
unsigned long pack_count = 0;
uint32_t pidErrors = 0;
int packet_interval = 100; //ms
/*
* Load Wi-Fi Configuration
* Loads known Wi-Fi credentials from file
*/
void loadWiFiConfig() {
//Loading file from SPIFFS
File file = SPIFFS.open(wiFiFilePath, "r");
if (!file) {
Serial.println("Error: Unable to open configuration file");
return;
}
//Deserialization from file
StaticJsonDocument<256> jsondocwifi;
deserializeJson(jsondocwifi, file);
const char* loadedSSID = jsondocwifi["ssid"].as<const char*>();
const char* loadedPassword = jsondocwifi["password"].as<const char*>();
//Wi-Fi global credentials update
if (loadedSSID && loadedPassword) {
strncpy(wifiSSID, loadedSSID, strlen(loadedSSID));
strncpy(wifiPassword, loadedPassword, strlen(loadedPassword));
Serial.println("Wi-Fi credentials loaded successfully");
} else {
Serial.println("Error: Wi-Fi credentials missing from file");
}
file.close();
}
/*
* Save Wi-Fi Configuration
* Saves Wi-Fi credentials to file
*/
void saveWiFiConfig(const char* newSSID, const char* newPassword) {
//Local allocation to serialize the credentials
StaticJsonDocument<256> jsonDocument;
jsonDocument["ssid"] = newSSID;
jsonDocument["password"] = newPassword;
//Existing global credentials update
strncpy(wifiSSID, newSSID, strlen(newSSID));
strncpy(wifiPassword, newPassword, strlen(newPassword));
//Credential Serialization to file
File file = SPIFFS.open(wiFiFilePath, "w");
if (!file) {
Serial.println("Error: Unable to save to configuration file");
return;
}
serializeJson(jsonDocument, file);
file.close();
Serial.println("Wi-Fi credentials saved successfully");
}
/*
* Connect to Wi-Fi
* Connects to the Wi-Fi credentials currently loaded globally
*/
void connectToWiFi() {
Serial.printf("Connecting to: %s..", wifiSSID);
WiFi.begin(wifiSSID, wifiPassword);
int counter = 0;
long startTime = millis();
while (millis() - startTime < WIFI_TIMEOUT && WiFi.status() != WL_CONNECTED) {
delay(200);
Serial.print(".");
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nWi-Fi connection estabilished");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
} else {
Serial.printf("\nUnable to connect to %s\n", wifiSSID);
}
}
/*
* Enable Access Point
* Sets up an Access Point and starts the Web Server
* accessible from a static IP
*/
void enableAccessPoint() {
delay(500);
Serial.println("Enabling Access Point...");
WiFi.disconnect();
WiFi.softAP("eLUX_datalogger", "ELUXPRPB2023$");
IPAddress apIP(192, 168, 4, 4);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
server.begin();
Serial.println("Access Point enabled");
delay(1000);
}
/*
* Handle Root Page
* Specifies the behaviour of the Web Server's root page
*/
void handleRootPage(AsyncWebServerRequest *request) {
File configFile = SPIFFS.open(rootPage, "r");
if (!configFile) {
Serial.println("Error: Unable to load HTML file");
return;
}
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, rootPage, String(), false);
response->addHeader("Content-Type", "text/html");
request->send(response);
configFile.close();
}
void handleLogoImage(AsyncWebServerRequest *request) {
File logoFile = SPIFFS.open(logoImagePath, "r");
if (!logoFile) {
Serial.println("Error: Unable to load logo image file");
request->send(404, "text/plain", "File not found");
return;
}
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, logoImagePath, "image/jpeg", false);
request->send(response);
logoFile.close();
}
/*
* Handle Root Page
* Specifies the behaviour of the Web Server's save page
*/
void handleSavePage(AsyncWebServerRequest *request) {
String newSSID = request->arg("ssid");
String newPassword = request->arg("password");
saveWiFiConfig(newSSID.c_str(), newPassword.c_str());
File configFile = SPIFFS.open(savesuccessPage, "r");
if (!configFile) {
Serial.println("Error: Unable to load HTML file");
return;
}
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, savesuccessPage, String(), false);
response->addHeader("Content-Type", "text/html");
request->send(response);
connectToWiFi();
}
/*
* Setup Web Server
* Specifies the behaviour of the Web Server
*/
void setup_WebServer() {
server.on("/", HTTP_GET, handleRootPage);
server.on("/save", HTTP_POST, handleSavePage);
server.on(logoImagePath, HTTP_GET, handleLogoImage);
delay(1000);
}
/*
* Setup Wi-Fi Connection
* Connects the device to a Wi-Fi network loaded from file
*/
void setup_wifi() {
loadWiFiConfig();
delay(250);
connectToWiFi();
}
/*
* OBD Vehicle State Gathering
* Reads and saves the current car state parsing OBD-II frames
*/
void obd_sampling() {
for (byte i = 0; i < sizeof(pids) / sizeof(pids[0]); i++) { //Samples the car state starting from the existing map of PIDS
int value_read;
uint16_t pid = pids[i];
if (obd.readPID(pid, value_read)) {
Serial.println(value_read);
} else { //If the number of errors exceeds a certain value, the OBD connection is reset
pidErrors++;
Serial.print("PID errors: ");
Serial.println(pidErrors);
if (obd.errors >= 3) {
obd.reset();
}
}
values[i] = value_read;
}
}
/*
* Setup MQTT
* Sets the CA Certificate and the server (broker) parameters
*/
void setup_mqtt() {
// Open the certificate file
File file = SPIFFS.open(certificate_path, "r");
if (!file) {
Serial.println("Error: Failed to open certificate file");
return;
}
// Read the certificate byte by byte
while (file.available()) {
certificate += char(file.read());
}
file.close();
//espClient.setCACert(x509CA);
espClient.setCACert(certificate.c_str());
client.setServer(mqtt_server, port);
}
/*
* Setup OBD
* Initializes the OBD connection with the car and retrieves the
* Vehicle identification Number (VIN) to ensure its working state
*/
void setup_obd() {
byte ver = obd.begin();
Serial.print("OBD Firmware Ver. ");
Serial.println(ver);
if (obd.init()) {
Serial.println("OBD initializated correctly");
char buffer[128];
if (obd.getVIN(buffer, sizeof(buffer))) {
Serial.print("VIN: ");
Serial.println(buffer);
}
} else {
Serial.println("OBD initialization failed. Retrying...");
retryOBD();
}
}
/*
* OBD Reconnection
* Attempts to re-initialize the OBD connection
*/
void retryOBD() {
if (obd.init()) return;
}
/*
* MQTT Broker Connection
* Connects the device to the specified MQTT broker
*/
void connect_mqtt() {
// Device loops until the connection is successful
delay(500);
while (!client.connected()) {
Serial.print("Attempting MQTT connection...\n");
if (client.connect(client_name, broker_uname, broker_pw)) {
Serial.println("MQTT broker successfully connected");
} else {
Serial.printf("MQTT connection failed with state %d. Retrying...\n", client.state());
delay(1000);
}
}
}
/*
* Wi-Fi Manager Processing
* Activates the access point and waits for the user to send new Wi-Fi credentials
*/
void processWiFiManager() {
enableAccessPoint();
Serial.print("Waiting for a new Wi-Fi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
}
/***********************************************************************************************
* ESP32 Setup
* Arduino "setup" Framework function called at power up
************************************************************************************************/
void setup()
{
//Delay to avoid unstable power-up
delay(2000);
//USB serial initialization and device startup
Serial.begin(115200);
Serial.print("ESP32 ");
Serial.print(ESP.getCpuFreqMHz());
Serial.print("MHz\n");
//SPIFFS Setup
if(!SPIFFS.begin(true)) {
Serial.println("Error: SPIFFS initialization failed");
return;
}
//WiFi Setup
setup_wifi();
//WiFi Manager and Web Server Setup
setup_WebServer();
#if USE_MQTT
//MQTT Broker Setup
setup_mqtt();
#endif
#if USE_OBD
//OBD Setup
setup_obd();
#endif
delay(250);
}
/************************************************************************************************
* ESP32 Execution
* Arduino "loop" Framework function called cyclically during regular execution
************************************************************************************************/
void loop() {
if (firstLoop) {
firstLoop = false;
if (WiFi.status() != WL_CONNECTED) {
processWiFiManager();
}
} else {
while (WiFi.status() != WL_CONNECTED) {
Serial.println("Wi-Fi connection lost");
connectToWiFi(); //Attempts a Wi-Fi reconnection
}
}
#if USE_MQTT
//MQTT Client-to-Broker Processing
if (!client.connected()) {
Serial.println("MQTT broker connection lost");
connect_mqtt(); //Connette o Riconnette il Client al Broker specificato
}
client.loop(); //Processing In-Out dei pacchetti MQTT
#endif
#if USE_OBD
long timestamp = millis();
Serial.print('[');
Serial.print(timestamp);
Serial.print("] #");
Serial.print(pack_count++);
Serial.print(" ");
//Current vehicle state gathering
obd_sampling();
//Inserimento dati nel JSON Document Pre-Serializzazione
jsondoc["timestamp"] = timestamp;
for (byte i = 0; i < sizeof(pids) / sizeof(pids[0]); i++) {
jsondoc[stamps[i].c_str()] = values[i];
}
//Serializzazione ed invio dei pacchetti al broker MQTT sul topic specificato come variabile globale
if (timestamp - lastMsg > packet_interval) { //100 (0.1s) è l'intervallo di invio pacchetti MQTT
lastMsg = timestamp;
char jsonString[512]; //CHECK DIMENSIONE
serializeJson(jsondoc, jsonString);
Serial.println(jsonString);
client.publish(topicToPublish, jsonString);
}
#endif
}