-
Notifications
You must be signed in to change notification settings - Fork 0
/
ledTPMS2.ino
332 lines (307 loc) · 11 KB
/
ledTPMS2.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
#include <Arduino.h>
#include <LittleFS.h>
// #define CONFIG_LOG_DEFAULT_LEVEL ESP_LOG_INFO // ESP_IDF only?
#include "esp_log.h"
#define CONFIG_BT_NIMBLE_PINNED_TO_CORE 1
// #define CONFIG_BT_NIMBLE_LOG_LEVEL 2
#include "NimBLEDevice.h"
#include "TireCaps.h" // ----- Define TireCap and the specific tire_caps we wish to monitor. -----
// Web service
#include "Web.h"
// TPMS decoding from valve stem manufacturer BLE broadcast data.
#include "Tpms.h"
tpms_raw raw_cache[40]; // Hourly save = Two tires reporting ~3min
int cache_idx = 0;
#include "LedUtils.h"
#include "WifiTime.h"
#include "LFS_utils.h"
class Scanned : public NimBLEAdvertisedDeviceCallbacks // WHY NOT? NimBLEScanCallbacks
{
public:
void csvPrintRawCache(int tc_idx=-1){
for(int i=0; i<cache_idx; i++){
if(tc_idx<0 || raw_cache[i].tc_idx == tc_idx){
csvPrintRawDat(raw_cache[i], false);
}
}
}
void storeCache(const char* filename=NULL) {
if(filename == NULL) filename = raw_filename;
File file = LittleFS.open(filename, FILE_APPEND);
if (!file) {
log_e("- failed to open file for appending: %s", filename);
return;
}
file.write((const uint8_t *)raw_cache, (cache_idx)*sizeof(raw_cache[0]));
file.close();
file = LittleFS.open(filename, FILE_READ);
log_i("raw_cache saved on LittleFS as: %s", filename);
Serial.printf("Saved raw_cache[%d] FILE: %s SIZE: %d\n", cache_idx, filename, file.size());
file.close();
cache_idx=0;
}
void cacheRawData(const tpms_raw &data){
// if (cache_idx >10) csvPrintRawCache(0);
if (cache_idx >= sizeof(raw_cache)/sizeof(raw_cache[0])) {
storeCache();
}
raw_cache[cache_idx++] = data;
log_i("raw_cache[%d] next %d", sizeof(raw_cache)/sizeof(raw_cache[0]), cache_idx);
}
void onResult(NimBLEAdvertisedDevice* device) override {
if( device->isAdvertisingService(TpmsServiceUuid)
&& device->haveServiceUUID()
&& device->haveManufacturerData()
&& device->getManufacturerData().length()==18) {
// Serial.println(device->toString().c_str());
struct tpms_raw raw(millis());
memcpy (raw.addr, device->getAddress().getNative(), sizeof(raw.addr));
if( device->haveManufacturerData()
&& device->getManufacturerData().length()==18) {
std::string mdat = device->getManufacturerData();
memcpy(raw.data, mdat.c_str(), mdat.length());
};
for(int i=0; i<sizeof(tire_caps)/sizeof(tire_caps[0]); i++){
if(device->getAddress().equals(tire_caps[i].addr)){
raw.tc_idx=i;
struct Tpms tpms= decodeTPMS(raw.data);
tire_caps[i].last_mils = millis();
tire_caps[i].last_psi = tpms.psi;
tire_caps[i].last_deg = tpms.deg;
tire_caps[i].last_bat = tpms.bat;
uint8_t (*rgb)[3];
if(tpms.psi>tire_caps[i].target_psi*tire_caps[i].psi_hi_m) {
rgb=&(tire_caps[i].psi_hi_rgb);
raw.alm |= 0x80; // set PSI high bit.
} else if(tpms.psi<tire_caps[i].target_psi*tire_caps[i].psi_lo_m) {
rgb=&(tire_caps[i].psi_lo_rgb);
raw.alm |= 0x40; // set PSI low bit.
} else {
rgb=&(tire_caps[i].norm_rgb);
raw.alm &= 0x3F; // clear PSI high&low bits.
}
tire_caps[i].last_alm = raw.alm;
// Serial.printf("raw.alm=%02x\n", raw.alm);
lightRGB((*rgb)[0], (*rgb)[1], (*rgb)[2]);
cacheRawData(raw);
log_i("mils: %ld, Name[%d]: %s, addr: %s",
raw.mils, raw.tc_idx, tire_caps[raw.tc_idx].name, hexStrAddr(raw.addr).c_str()
);
if (device->haveManufacturerData()) {
Serial.printf("tc_idx:%d, psi:%0.1f, deg_f:%0.1f, alm:%02x, bat:%d\n",
raw.tc_idx, tpms.psi, tpms.deg_f, raw.alm, tpms.bat);
}
}
}
}
}
};
//WebDoc: https://h2zero.github.io/NimBLE-Arduino/md__new_user_guide.html#autotoc_md45
class TpmsScan {
public:
Scanned tpmsCB;
NimBLEScan *pScan;
int scan_sec = -1;
TpmsScan(int scan_time_sec=180) {
scan_sec=scan_time_sec;
pScan = NimBLEDevice::getScan();
// TRY: results and duplicates
pScan->setMaxResults(0); // do not store the scan results, use callback only.
pScan->setAdvertisedDeviceCallbacks(&tpmsCB); // , true); // want dup events, not just 1st.
}
NimBLEScanResults startScan(int scan_time_sec=NULL, bool cont_scan=true) {
if(scan_time_sec == NULL) scan_time_sec = scan_sec;
log_i("Starting a %d second BLE Scan. Continued=%d", scan_time_sec, cont_scan);
NimBLEScanResults results = pScan->start(scan_time_sec, cont_scan);
return results;
}
void stopScan() {
if(pScan) pScan->stop();
}
void csvPrintRawCache(int tc_idx=-1) {
tpmsCB.csvPrintRawCache(tc_idx);
}
void storeCache(const char* filename=NULL) {
tpmsCB.storeCache(filename);
}
};
TpmsScan *pTpmsScan=NULL;
TaskHandle_t updateLEDTask_handle;
// ----- Touch event handlers -----
bool pleaseStartWeb = false; // Triggered with T2
bool webServerRunning = false;
bool pleaseSaveCache = false; // Triggered with T7
void gotTouch2() {
Serial.println("T2: Start web?");
pleaseStartWeb = true; // Toggle web server
xTaskAbortDelay(updateLEDTask_handle); // LED response
}
uint64_t T7_beg = 0;
float T7_held = -1;
void bad_gotTouch7() {
int last = touchInterruptGetLastStatus(T7);
if (last && T7_beg==0) {
T7_beg = millis();
T7_held = -1;
} else {
T7_held = ( millis() - T7_beg ) / 1000.0;
Serial.printf("T7 held for %0.2f seconds\n", T7_held);
T7_beg=0;
}
}
void gotTouch7(){ // delme? -rea
Serial.printf("T7: Please Save Cache to LittleFS: %s\n", raw_filename);
pleaseSaveCache = true; // LED will breath white before save (red during, then breath green).
xTaskAbortDelay(updateLEDTask_handle); // LED response
}
// ----- LED update task -----
void updateLEDTask(void *pvParams){
uint8_t unset_rgb[3]={15,15,0};
uint8_t (*rgb)[3]=NULL;
rgb = &(unset_rgb);
uint8_t (*warn)[3]=NULL;
uint64_t missed2 = 6*60*1000; // Should get 2 updats within 6 minutes
while(true) {
if(webServerRunning){
lightRGB(3,1,3); // dim magenta
continue;
}
for(int i=0; i<sizeof(tire_caps)/sizeof(TireCap); i++) {
if(tire_caps[i].last_alm) {
rgb=&(tire_caps[i].norm_rgb);
if(tire_caps[i].last_alm && 0x40) rgb=&(tire_caps[i].psi_lo_rgb);
if(tire_caps[i].last_alm && 0x80) rgb=&(tire_caps[i].psi_hi_rgb);
warn = rgb;
if(tire_caps[i].grp_id>=0) {
warn = &(tire_groups[tire_caps[i].grp_id].warn_rgb);
}
break;
}
if(millis() - tire_caps[i].last_mils > missed2) {
if(tire_caps[i].grp_id == 0) { // All of the primary group must check in.
warn = &(unset_rgb);
rgb = &(tire_caps[i].norm_rgb);
break;
}
}
if(tire_caps[i].grp_id == 0 && tire_caps[i].last_mils<1) {
break; // report unset until all primary have reported in.
}
warn = NULL;
if(sizeof(tire_groups)) rgb = &(tire_groups[0].norm_rgb);
}
if (warn){
ledBreath((*warn)[0], (*warn)[1], (*warn)[2]);
if(rgb) lightRGB((*rgb)[0], (*rgb)[1], (*rgb)[2]);
vTaskDelay(2000/portTICK_PERIOD_MS);
continue;
}
if(pleaseSaveCache) {
ledBreath(10,10,10); // breath white
if(pTpmsScan) pTpmsScan->stopScan();
continue;
}
if(pleaseStartWeb) {
ledBreath(30,10,30); // breath magenta
if(pTpmsScan) pTpmsScan->stopScan();
continue;
}
if(rgb) lightRGB((*rgb)[0], (*rgb)[1], (*rgb)[2]);
else {
lightRGB(unset_rgb[0],unset_rgb[1],unset_rgb[2]);
}
// Serial.printf("Touch values: T2=%d, T7=%d\n", touchRead(T2), touchRead(T7));
vTaskDelay(10000/portTICK_PERIOD_MS);
}
}
// ----- setup & loop -----
void setup() {
vTaskDelay(100/portTICK_PERIOD_MS);
// esp_log_level_set("*", ESP_LOG_INFO); // Default all components to INFO level
// esp_log_level_set("NimBLEScan", ESP_LOG_WARN); // Except only WARN for NimBLEScan
// ?? above may only work with ESP-IDF
Serial.begin(115200);
vTaskDelay(100/portTICK_PERIOD_MS);
lightRGB(1,1,0); // dim yellow = while finding WiFi AP
if (wifi_setup()) {
lightRGB(0,1,0) ; // dim green = after finding AP
if (time_setup()) {
ledBreath(0,20,0); // breath green = NTP time found
strftime(raw_filename, sizeof(raw_filename), "/dat/TPMS_%FT%T%Z.dat", &timeinfo);
}
wifi_shutdown();
} else ledBreath(20,20,0); // breath yellow = no WiFi AP(NTP) found
lightRGB(0,0,0); // off
if(getLocalTime(&timeinfo)){
Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}
lfs_setup();
// csvPrintRawFile(raw_filename, 0);
// LittleFS.remove(raw_filename);
// LittleFS.rename("/TPMS_Raw.dat", "/2024-11-10TX.dat");
listDir(LittleFS, "/", 3);
const char* mkdirs[]={"/dat", "/www", "/www/js"};
for(const char* dir: mkdirs){
if(!LittleFS.mkdir(dir)){
Serial.printf("- created LittleFS: %s\n", dir);
}
}
Serial.printf("Current Raw Filename: %s\n", raw_filename); // changed after time_setup()?
Serial.println("Starting NimBLE TPMS Monitor");
// rgbLedWriteOrdered(RGB_PIN, LED_COLOR_ORDER_RGB, 0,0,1);
ledBreath(0,0,20); // blue
NimBLEDevice::init("ledTPMS");
pTpmsScan = new TpmsScan(30);
// ----- Start task updating the LED -----
// xTaskCreatePinnedToCore(
xTaskCreate( // any core
updateLEDTask, // funct
"updateLEDTask", // name
20480, // stack 20k
NULL, // params
2, // pri
&updateLEDTask_handle // task handle
// ,CONFIG_BT_NIMBLE_PINNED_TO_CORE // core number (0 or 1)
);
int threshold = 150;
touchAttachInterrupt(T2, gotTouch2, threshold);
touchAttachInterrupt(T7, gotTouch7, threshold);
}
// the loop function runs over and over again forever
void loop(){
// rgbLedWriteOrdered(RGB_PIN, LED_COLOR_ORDER_RGB, 1,1,1);
pTpmsScan->startScan();
if(pleaseSaveCache){ // set by T7 trigger.
pleaseSaveCache=false;
ledBreath(10,10,0);
lightRGB(1,0,0);
pTpmsScan->storeCache();
ledBreath(0,10,0);
pleaseSaveCache=false;
}
if(pleaseStartWeb){
pTpmsScan->storeCache(); // store cache first.
Serial.println("web_setup");
lightRGB(3,1,3); // dim magenta
pleaseStartWeb=false;
if(wifi_setup()){
webServerRunning = true;
web_setup();
xTaskAbortDelay(updateLEDTask_handle); // LED response
while(true) {
// stop ble?
server.handleClient(); // web server main loop.
if(pleaseStartWeb) break; // Use Touch to toggle WebServer
}
server.close();
webServerRunning = false;
pleaseStartWeb = false;
xTaskAbortDelay(updateLEDTask_handle); // LED response
vTaskDelay(2000/portTICK_PERIOD_MS); // Allow touch events time to clear.
pleaseStartWeb = false;
xTaskAbortDelay(updateLEDTask_handle); // LED response
}
}
lightRGB(0,0,0); // off
// vTaskDelay(secs*1000/portTICK_PERIOD_MS);
}