-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCG_scale.ino
2051 lines (1783 loc) · 60 KB
/
CG_scale.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
------------------------------------------------------------------
CG scale
(c) 2019-2020 by M. Lehmann
------------------------------------------------------------------
*/
#define CGSCALE_VERSION "2.3"
/*
******************************************************************
history:
V2.3 01.03.22 Up to three ESPs can be linked via WLAN. Useful for landing gear scales on engine models
V2.22 28.11.20 fixed RAM problems with JSON
V2.21 27.11.20 bug fixed: recompiled, binary file incorrect
V2.2 01.11.20 Virtual weights built in
V2.12 07.10.20 bug fixed: LR value was displayed in the wrong display position
Voltage for specified battery types deleted
V2.11 18.08.20 code is now compatible with standard OLED displays
and original code base (default pw length = 32)
V2.1 18.07.20 added support for ESP8266 based Wifi Kit 8
(by Pulsar07/ (https://heltec.org/project/wifi-kit-8/)
R.Stransky is a ESP8266 with
a build in OLED 128x32
battery connector with charging management
reset and GPIO0 button
support for a tare button (PIN_TARE_BUTTON)
bug fixed: wifi password now with up to 64 chars
bug fixed: wifi data (ssid/passwd) with special
character (e.g. +) is now supported
for specified battery type, voltage is displayed
using uncompressed html files makes WEB GUI much faster
V2.01 29.01.20 small bug fixes with AVR
V2.0 26.01.20 Webpage rewritten, no bootstrap framework needed
add translation to webpage (en, de)
optimized for measuring with landinggears
updated to ArduinoJson V6
firmware update over web interface
V1.2.1 31.03.19 small bug fixed
values in model database are rounded
mDNS and OTA did not work in AP mode
V1.2 23.02.19 Add OTA (over the air update)
mDNS default enabled
add percentlists for many battery types
memory optimization
V1.1 02.02.19 Supports ESP8266, webpage integrated, STA and AP mode
V1.0 12.01.19 first release
******************************************************************
Software License Agreement (BSD License)
Copyright (c) 2019-2020, Michael Lehmann
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// **** Please UNCOMMENT to choose special hardware *****************
//#define WIFI_KIT_8 //is a ESP8266 based board, with integrated OLED and battery management
// ******************************************************************
// Required libraries, can be installed from the library manager
#include <HX711_ADC.h> // library for the HX711 24-bit ADC for weight scales (https://github.com/olkal/HX711_ADC)
#include <U8g2lib.h> // Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/)
// built-in libraries
#include <EEPROM.h>
#include <Wire.h>
// libraries for ESP8266
#if defined(ESP8266)
#include <FS.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiClientSecure.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <ElegantOTA.h>
#include <ArduinoJson.h>
#endif
// load settings
#if defined(__AVR__)
#include "settings_AVR.h"
#elif defined(ESP8266)
#ifdef WIFI_KIT_8
#include "settings_WIFI_KIT_8.h"
#else
#include "settings_ESP8266.h"
#endif
#endif
// HX711 constructor array (dout pin, sck pint):
HX711_ADC LoadCell[] {HX711_ADC(PIN_LOADCELL1_DOUT, PIN_LOADCELL1_PD_SCK), HX711_ADC(PIN_LOADCELL2_DOUT, PIN_LOADCELL2_PD_SCK), HX711_ADC(PIN_LOADCELL3_DOUT, PIN_LOADCELL3_PD_SCK)};
// webserver constructor
#if defined(ESP8266)
ESP8266WebServer server(80);
IPAddress apIP(ip[0], ip[1], ip[2], ip[3]);
WiFiClientSecure httpsClient;
File fsUploadFile; // a File object to temporarily store the received file
#endif
#include "defaults.h"
struct VirtualWeight {
String name;
float cg;
float weight;
bool enabled = false;
};
struct Model {
float distance[3] = {DISTANCE_X1, DISTANCE_X2, DISTANCE_X3};
#if defined(ESP8266)
char name[MAX_MODELNAME_LENGHT + 1] = "";
float targetCGmin = 0;
float targetCGmax = 0;
uint8_t mechanicsType = 0;
VirtualWeight virtualWeight[MAX_VIRTUAL_WEIGHT];
#endif
};
Model model;
// load default values
uint8_t nLoadcells = NUMBER_LOADCELLS;
float calFactorLoadcell[] = {LOADCELL1_CALIBRATION_FACTOR, LOADCELL2_CALIBRATION_FACTOR, LOADCELL3_CALIBRATION_FACTOR};
float resistor[] = {RESISTOR_R1, RESISTOR_R2};
uint8_t batType = BAT_TYPE;
uint8_t batCells = BAT_CELLS;
float refWeight = REF_WEIGHT;
float refCG = REF_CG;
#if defined(ESP8266)
char device_Name[MAX_SSID_PW_LENGHT + 1] = SSID_AP;
char ssid_STA[MAX_SSID_PW_LENGHT + 1] = SSID_STA;
char password_STA[MAX_SSID_PW_LENGHT + 1] = PASSWORD_STA;
char ssid_AP[MAX_SSID_PW_LENGHT + 1] = SSID_AP;
char password_AP[MAX_SSID_PW_LENGHT + 1] = PASSWORD_AP;
char loadCellURL[3][MAX_SSID_PW_LENGHT + 1] = {"","",""};
bool enableUpdate = ENABLE_UPDATE;
bool enableOTA = ENABLE_OTA;
#endif
// declare variables
float weightLoadCell[] = {0, 0, 0};
float lastWeightLoadCell[] = {0, 0, 0};
float weightTotal = 0;
float CG_length = 0;
float CG_trans = 0;
float batVolt = 0;
unsigned long lastTimeMenu = 0;
unsigned long lastTimeLoadcell = 0;
bool updateMenu = true;
int menuPage = 0;
String errMsg[5];
int errMsgCnt = 0;
const uint8_t *oledFontBig;
const uint8_t *oledFontLarge;
const uint8_t *oledFontNormal;
const uint8_t *oledFontSmall;
#if defined(ESP8266)
String updateMsg = "";
bool wifiSTAmode = true;
float gitVersion = -1;
#endif
// Restart CPU
#if defined(__AVR__)
void(* resetCPU) (void) = 0;
#elif defined(ESP8266)
void resetCPU() {}
#endif
// convert time to string
char * TimeToString(unsigned long t)
{
static char str[13];
int h = t / 3600000;
t = t % 3600000;
int m = t / 60000;
t = t % 60000;
int s = t / 1000;
int ms = t - (s * 1000);
sprintf(str, "%02ld:%02d:%02d.%03d", h, m, s, ms);
return str;
}
// Count percentage from cell voltage
int percentBat(float cellVoltage) {
int result = 0;
int elementCount = DATAPOINTS_PERCENTLIST;
byte batTypeArray = batType - 2;
for (int i = 0; i < elementCount; i++) {
if (pgm_read_float( &percentList[batTypeArray][i][1]) == 100 ) {
elementCount = i;
break;
}
}
float cellempty = pgm_read_float( &percentList[batTypeArray][0][0]);
float cellfull = pgm_read_float( &percentList[batTypeArray][elementCount][0]);
if (cellVoltage >= cellfull) {
result = 100;
} else if (cellVoltage <= cellempty) {
result = 0;
} else {
for (int i = 0; i <= elementCount; i++) {
float curVolt = pgm_read_float(&percentList[batTypeArray][i][0]);
if (curVolt >= cellVoltage && i > 0) {
float lastVolt = pgm_read_float(&percentList[batTypeArray][i - 1][0]);
float curPercent = pgm_read_float(&percentList[batTypeArray][i][1]);
float lastPercent = pgm_read_float(&percentList[batTypeArray][i - 1][1]);
result = float((cellVoltage - lastVolt) / (curVolt - lastVolt)) * (curPercent - lastPercent) + lastPercent;
break;
}
}
}
return result;
}
void printConsole(int t, String msg) {
Serial.print(TimeToString(millis()));
Serial.print(" [");
switch (t) {
case T_BOOT:
Serial.print("BOOT");
break;
case T_RUN:
Serial.print("RUN");
break;
case T_ERROR:
Serial.print("ERROR");
break;
case T_WIFI:
Serial.print("WIFI");
break;
case T_UPDATE:
Serial.print("UPDATE");
break;
case T_HTTPS:
Serial.print("HTTPS");
break;
}
Serial.print("] ");
Serial.println(msg);
}
void initOLED() {
oledDisplay.begin();
printConsole(T_BOOT, "init OLED display: " + String(DISPLAY_WIDTH) + String("x") + String(DISPLAY_HIGHT));
#if DISPLAY_HIGHT > 32
oledFontBig = u8g2_font_helvR18_tn;
oledFontLarge = u8g2_font_helvR12_tr;
oledFontNormal = u8g2_font_helvR10_tr;
oledFontSmall = u8g2_font_5x7_tr;
#elif DISPLAY_HIGHT <= 32
oledFontBig = u8g2_font_helvR14_tr;
oledFontLarge = u8g2_font_helvR10_tr;
oledFontNormal = u8g2_font_6x12_tr;
oledFontSmall = u8g2_font_5x7_tr;
#endif
int ylineHeight = DISPLAY_HIGHT / 3;
oledDisplay.firstPage();
do {
oledDisplay.setFont(oledFontLarge);
#if DISPLAY_HIGHT <= 32
oledDisplay.drawXBMP(5, 0, 18, 18, CGImage);
#else
oledDisplay.drawXBMP(20, 12, 18, 18, CGImage);
#endif
oledDisplay.setFont(oledFontLarge);
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(30, 12);
#else
oledDisplay.setCursor(45, 28);
#endif
oledDisplay.print(F("CG scale"));
oledDisplay.setFont(oledFontSmall);
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(30, 22);
#else
oledDisplay.setCursor(35, 55);
#endif
oledDisplay.print(F("Version: "));
oledDisplay.print(CGSCALE_VERSION);
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(5, 31);
#else
oledDisplay.setCursor(20, 64);
#endif
oledDisplay.print(F("(c) 2020 M.Lehmann"));
} while ( oledDisplay.nextPage() );
}
void printOLED(String aLine1, String aLine2, String aLine3) {
int ylineHeight = DISPLAY_HIGHT / 3;
oledDisplay.firstPage();
do {
oledDisplay.setFont(oledFontNormal);
oledDisplay.setCursor(0, ylineHeight * 1);
oledDisplay.print(aLine1);
oledDisplay.setCursor(0, ylineHeight * 2);
oledDisplay.print(aLine2);
oledDisplay.setCursor(0, DISPLAY_HIGHT);
oledDisplay.print(aLine3);
} while ( oledDisplay.nextPage() );
}
void printScaleOLED() {
// print to display
char buff[8];
int pos_weightTotal = 7;
int pos_CG_length = 28;
if (nLoadcells == 2) {
pos_weightTotal = 17;
pos_CG_length = 45;
if (batType == 0) {
pos_weightTotal = 12;
pos_CG_length = 40;
}
}
oledDisplay.firstPage();
do {
if (errMsgCnt == 0) {
// print battery
if (batType > B_OFF) {
oledDisplay.drawXBMP(88, 1, 12, 6, batteryImage);
if (batType == B_VOLT) {
dtostrf(batVolt, 2, 2, buff);
} else {
dtostrf(batVolt, 3, 0, buff);
oledDisplay.drawBox(89, 2, (batVolt / (100 / 8)), 4);
}
oledDisplay.setFont(oledFontSmall);
oledDisplay.setCursor(123 - oledDisplay.getStrWidth(buff), 7);
oledDisplay.print(buff);
if (batType == B_VOLT) {
oledDisplay.print(F("V"));
} else {
oledDisplay.print(F("%"));
}
}
#if defined(ESP8266)
if (DISPLAY_HIGHT <= 32 && (strlen(loadCellURL[LC1]) || strlen(loadCellURL[LC2]) || strlen(loadCellURL[LC3]))) {
oledDisplay.setFont(oledFontBig);
float weight = 0;
for (int i = LC1; i <= LC3; i++) {
if (i < nLoadcells) {
if(strlen(loadCellURL[i]) == 0){
weight = weightLoadCell[i];
}
}
}
dtostrf(weight, 5, 1, buff);
oledDisplay.setCursor(80 - oledDisplay.getStrWidth(buff), 28);
oledDisplay.print(buff);
oledDisplay.print(F(" g"));
}else{
#endif
// print total weight
if (nLoadcells == 1 ) {
oledDisplay.setFont(oledFontBig);
dtostrf(weightTotal, 5, 1, buff);
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(80 - oledDisplay.getStrWidth(buff), 28);
#else
oledDisplay.drawXBMP(2, pos_weightTotal, 18, 18, weightImage);
oledDisplay.setCursor(93 - oledDisplay.getStrWidth(buff), pos_weightTotal + 17);
#endif
oledDisplay.print(buff);
oledDisplay.print(F(" g"));
}else{
oledDisplay.setFont(oledFontNormal);
dtostrf(weightTotal, 5, 1, buff);
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(1, 18);
oledDisplay.print(F("M = "));
#else
oledDisplay.drawXBMP(2, pos_weightTotal, 18, 18, weightImage);
oledDisplay.setCursor(93 - oledDisplay.getStrWidth(buff), pos_weightTotal + 17);
#endif
oledDisplay.print(buff);
oledDisplay.print(F(" g"));
// print CG longitudinal axis
dtostrf(CG_length, 5, 1, buff);
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(1, 32);
oledDisplay.print(F("CG = "));
#else
oledDisplay.drawXBMP(2, pos_CG_length, 18, 18, CGImage);
oledDisplay.setCursor(93 - oledDisplay.getStrWidth(buff), pos_CG_length + 16);
#endif
oledDisplay.print(buff);
oledDisplay.print(F(" mm"));
}
// print CG transverse axis
if (nLoadcells == 3 ) {
#if DISPLAY_HIGHT <= 32
oledDisplay.setCursor(78, 32);
oledDisplay.print(F("LR="));
dtostrf(CG_trans, 3, 0, buff);
#else
dtostrf(CG_trans, 5, 1, buff);
oledDisplay.drawXBMP(2, 47, 18, 18, CGtransImage);
oledDisplay.setCursor(93 - oledDisplay.getStrWidth(buff), 64);
#endif
oledDisplay.print(buff);
oledDisplay.print(F(" mm"));
}
#if defined(ESP8266)
}
#endif
} else {
oledDisplay.setFont(oledFontSmall);
for (int i = 1; i <= errMsgCnt; i++) {
oledDisplay.setCursor(0, 7 * i);
oledDisplay.print(errMsg[i]);
}
}
} while ( oledDisplay.nextPage() );
}
#ifdef PIN_TARE_BUTTON
void handleTareBtn() {
static unsigned long lastTaraBtn = 0;
if ((millis() - lastTaraBtn) > 20) {
lastTaraBtn = millis();
static int tareBtnCnt = 0;
if (digitalRead(PIN_TARE_BUTTON)) {
tareBtnCnt = 0;
} else {
tareBtnCnt++;
if (tareBtnCnt > 10) {
printOLED("TARE ==>", " tare load cells ...","");
// avoid keybounce
tareBtnCnt = -1000;
tareLoadcells();
delay(2000);
}
}
}
}
#endif
// save calibration factor
void saveCalFactor(int nLC) {
LoadCell[nLC].setCalFactor(calFactorLoadcell[nLC]);
EEPROM.put(P_LOADCELL1_CALIBRATION_FACTOR + (nLC * sizeof(float)), calFactorLoadcell[nLC]);
#if defined(ESP8266)
EEPROM.commit();
#endif
}
void updateLoadcells() {
for (int i = LC1; i <= LC3; i++) {
if (i < nLoadcells) {
LoadCell[i].update();
}
}
}
void tareLoadcells() {
for (int i = LC1; i <= LC3; i++) {
if (i < nLoadcells) {
#if defined(ESP8266)
if(strlen(loadCellURL[i]) == 0){
LoadCell[i].tare();
}
#else
LoadCell[i].tare();
#endif
}
}
}
void printNewValueText() {
Serial.print(F("Set new value:"));
}
// run auto calibration
bool runAutoCalibrate() {
Serial.print(F("\nAutocalibration is running"));
for (int i = 0; i <= 20; i++) {
Serial.print(F("."));
delay(100);
}
// calculate weight
float toWeightLoadCell[] = {0, 0, 0};
toWeightLoadCell[LC2] = ((refCG - model.distance[X1]) * refWeight) / model.distance[X2];
toWeightLoadCell[LC1] = refWeight - toWeightLoadCell[LC2];
if (nLoadcells == 3) {
toWeightLoadCell[LC1] = toWeightLoadCell[LC1] / 2;
toWeightLoadCell[LC3] = toWeightLoadCell[LC1];
}
// calculate calibration factors
for (int i = LC1; i <= LC3; i++) {
calFactorLoadcell[i] = calFactorLoadcell[i] / (toWeightLoadCell[i] / weightLoadCell[i]);
saveCalFactor(i);
}
// finish
Serial.println(F("done"));
}
// check if a loadcell has error
bool getLoadcellError() {
bool err = false;
for (int i = LC1; i <= LC3; i++) {
if (i < nLoadcells) {
if (LoadCell[i].getTareTimeoutFlag()) {
String msg = "ERROR: Timeout TARE Lc" + String(i + 1);
errMsg[++errMsgCnt] = msg + "\n";
#if defined(ESP8266)
printConsole(T_ERROR, msg);
#endif
err = true;
}
}
}
return err;
}
#if defined(ESP8266)
void writeModelData(JsonObject object) {
char buff[8];
String stringBuff;
dtostrf(weightTotal, 5, 1, buff);
stringBuff = buff;
stringBuff.trim();
object["wt"] = stringBuff;
dtostrf(CG_length, 5, 1, buff);
stringBuff = buff;
stringBuff.trim();
object["cg"] = stringBuff;
dtostrf(CG_trans, 5, 1, buff);
stringBuff = buff;
stringBuff.trim();
object["cglr"] = stringBuff;
object["x1"] = model.distance[X1];
object["x2"] = model.distance[X2];
object["x3"] = model.distance[X3];
object["cgmin"] = model.targetCGmin;
object["cgmax"] = model.targetCGmax;
object["mType"] = model.mechanicsType;
JsonArray virtw = object.createNestedArray("virtual");
for (int i=0; i < MAX_VIRTUAL_WEIGHT; i++){
JsonArray virtWeight = virtw.createNestedArray();
virtWeight.add(model.virtualWeight[i].name);
virtWeight.add(model.virtualWeight[i].cg);
virtWeight.add(model.virtualWeight[i].weight);
virtWeight.add(model.virtualWeight[i].enabled);
}
}
// save model to json file
bool saveModelJson(String modelName) {
if (modelName.length() > MAX_MODELNAME_LENGHT) {
return false;
}
DynamicJsonDocument jsonDoc(JSONDOC_SIZE);
if (SPIFFS.exists(MODEL_FILE)) {
// read json file
File f = SPIFFS.open(MODEL_FILE, "r");
auto error = deserializeJson(jsonDoc, f);
f.close();
if (error) {
printConsole(T_ERROR, "save JSON: " + String(error.c_str()));
return false;
}
// check if model exists
if (jsonDoc.containsKey(modelName)) {
writeModelData(jsonDoc[modelName]);
} else {
// otherwise create new
writeModelData(jsonDoc.createNestedObject(modelName));
}
// write to file
if (!error) {
f = SPIFFS.open(MODEL_FILE, "w");
serializeJson(jsonDoc, f);
f.close();
} else {
printConsole(T_ERROR, "save JSON: " + String(error.c_str()));
return false;
}
} else {
// creat new json
writeModelData(jsonDoc.createNestedObject(modelName));
// write to file
if (!jsonDoc.isNull()) {
File f = SPIFFS.open(MODEL_FILE, "w");
serializeJson(jsonDoc, f);
f.close();
} else {
printConsole(T_ERROR, "JSON is null ");
return false;
}
}
return true;
}
// read model data from json file
bool openModelJson(String modelName) {
DynamicJsonDocument jsonDoc(JSONDOC_SIZE);
if (SPIFFS.exists(MODEL_FILE)) {
// read json file
File f = SPIFFS.open(MODEL_FILE, "r");
auto error = deserializeJson(jsonDoc, f);
f.close();
if (error) {
printConsole(T_ERROR, "open JSON: " + String(error.c_str()));
return false;
}
// check if model exists
if (jsonDoc.containsKey(modelName)) {
// load parameters from model
model.distance[X1] = jsonDoc[modelName]["x1"];
model.distance[X2] = jsonDoc[modelName]["x2"];
model.distance[X3] = jsonDoc[modelName]["x3"];
model.targetCGmin = jsonDoc[modelName]["cgmin"];
model.targetCGmax = jsonDoc[modelName]["cgmax"];
model.mechanicsType = jsonDoc[modelName]["mType"];
JsonArray virtw = jsonDoc[modelName]["virtual"];
if(virtw){
for (int i=0; i < MAX_VIRTUAL_WEIGHT; i++){
model.virtualWeight[i].name = virtw[i][0].as<String>();
model.virtualWeight[i].cg = virtw[i][1].as<int>();
model.virtualWeight[i].weight = virtw[i][2].as<int>();
model.virtualWeight[i].enabled = virtw[i][3].as<bool>();
}
}
} else {
printConsole(T_ERROR, "Model name not found");
return false;
}
// save current model name to eeprom
modelName.toCharArray(model.name, MAX_MODELNAME_LENGHT + 1);
EEPROM.put(P_MODELNAME, model.name);
EEPROM.commit();
return true;
}
printConsole(T_ERROR, "Modelfile not exists");
return false;
}
// delete model from json file
bool deleteModelJson(String modelName) {
DynamicJsonDocument jsonDoc(JSONDOC_SIZE);
if (SPIFFS.exists(MODEL_FILE)) {
// read json file
File f = SPIFFS.open(MODEL_FILE, "r");
auto error = deserializeJson(jsonDoc, f);
f.close();
if (error) {
printConsole(T_ERROR, "delete JSON: " + String(error.c_str()));
return false;
}
// check if model exists
if (jsonDoc.containsKey(modelName)) {
jsonDoc.remove(modelName);
} else {
printConsole(T_ERROR, "Model name not found");
return false;
}
// if no models in json, kill it
if (jsonDoc.size() == 0) {
SPIFFS.remove(MODEL_FILE);
} else {
// write to file
if (!jsonDoc.isNull()) {
File f = SPIFFS.open(MODEL_FILE, "w");
serializeJson(jsonDoc, f);
f.close();
} else {
printConsole(T_ERROR, "JSON is null ");
return false;
}
}
return true;
}
printConsole(T_ERROR, "Modelfile not exists");
return false;
}
// send headvalues to client
void getHead() {
String response = ssid_AP;
response += "&";
for (int i = 1; i <= errMsgCnt; i++) {
response += errMsg[i];
}
response += "&";
response += CGSCALE_VERSION;
response += "&";
response += gitVersion;
server.send(200, "text/html", response);
}
// send values to client
void getValue() {
char buff[8];
String response = "";
dtostrf(weightTotal, 5, 1, buff);
response += buff;
response += "g&";
dtostrf(CG_length, 5, 1, buff);
response += buff;
response += "mm&";
dtostrf(CG_trans, 5, 1, buff);
response += buff;
response += "mm&";
if (batType == B_VOLT) {
dtostrf(batVolt, 5, 2, buff);
response += buff;
response += "V";
} else {
dtostrf(batVolt, 5, 0, buff);
response += buff;
response += "%";
}
server.send(200, "text/html", response);
}
// send raw values to client
void getRawValue() {
char buff[8];
String response = "";
dtostrf(weightLoadCell[LC1], 5, 1, buff);
response += buff;
response += "g&";
dtostrf(weightLoadCell[LC2], 5, 1, buff);
response += buff;
response += "g&";
dtostrf(weightLoadCell[LC3], 5, 1, buff);
response += buff;
response += "g&";
if (batType == B_VOLT) {
dtostrf(batVolt, 5, 2, buff);
response += buff;
response += "V";
} else {
dtostrf(batVolt, 5, 0, buff);
response += buff;
response += "%";
}
server.send(200, "text/html", response);
}
// send parameters to client
void getParameter() {
char buff[8];
String response = "";
float weightTotal_saved = 0;
float CG_length_saved = 0;
float CG_trans_saved = 0;
model.targetCGmin = 0;
model.targetCGmax = 0;
DynamicJsonDocument jsonDoc(JSONDOC_SIZE);
if (SPIFFS.exists(MODEL_FILE)) {
// read json file
File f = SPIFFS.open(MODEL_FILE, "r");
auto error = deserializeJson(jsonDoc, f);
f.close();
// check if model exists
if (!error && jsonDoc.containsKey(model.name)) {
weightTotal_saved = jsonDoc[model.name]["wt"];
CG_length_saved = jsonDoc[model.name]["cg"];
CG_trans_saved = jsonDoc[model.name]["cglr"];
model.targetCGmin = jsonDoc[model.name]["cgmin"];
model.targetCGmax = jsonDoc[model.name]["cgmax"];
model.mechanicsType = jsonDoc[model.name]["mType"];
}
}
// parameter list
response += nLoadcells;
response += "&";
for (int i = X1; i <= X3; i++) {
response += model.distance[i];
response += "&";
}
response += refWeight;
response += "&";
response += refCG;
response += "&";
for (int i = LC1; i <= LC3; i++) {
response += calFactorLoadcell[i];
response += "&";
}
for (int i = R1; i <= R2; i++) {
response += resistor[i];
response += "&";
}
response += batType;
response += "&";
response += batCells;
response += "&";
response += ssid_STA;
response += "&";
response += password_STA;
response += "&";
response += ssid_AP;
response += "&";
response += password_AP;
response += "&";
response += model.name;
response += "&";
dtostrf(weightTotal_saved, 5, 1, buff);
response += buff;
response += "g&";
dtostrf(CG_length_saved, 5, 1, buff);
response += buff;
response += "mm&";
dtostrf(CG_trans_saved, 5, 1, buff);
response += buff;
response += "mm&";
response += model.targetCGmin;
response += "&";
response += model.targetCGmax;
response += "&";
response += model.mechanicsType;
response += "&";
response += enableUpdate;
response += "&";
response += enableOTA;
response += "&";
response += device_Name;
for (int i = LC1; i <= LC3; i++) {
response += "&";
response += loadCellURL[LC1];
}
server.send(200, "text/html", response);
}
// send virtual weights to client
void getVirtualWeight() {
String response = "";
DynamicJsonDocument jsonDoc(JSONDOC_SIZE);
JsonArray virtw = jsonDoc.createNestedArray("virtual");
for (int i=0; i < MAX_VIRTUAL_WEIGHT; i++){
JsonArray virtWeight = virtw.createNestedArray();
virtWeight.add(model.virtualWeight[i].name);
virtWeight.add(model.virtualWeight[i].cg);
virtWeight.add(model.virtualWeight[i].weight);
virtWeight.add(model.virtualWeight[i].enabled);
}
serializeJson(jsonDoc["virtual"], response);
server.send(200, "text/html", response);
}
// send available WiFi networks to client
void getWiFiNetworks() {
bool ssidSTAavailable = false;
String response = "";
int n = WiFi.scanNetworks();
if (n > 0) {
for (int i = 0; i < n; ++i) {
response += WiFi.SSID(i);
if (WiFi.SSID(i) == ssid_STA) ssidSTAavailable = true;
if (i < n - 1) response += "&";
}
if (!ssidSTAavailable) {
response += "&";
response += ssid_STA;
}
}
server.send(200, "text/html", response);
}
// save parameters
void saveParameter() {
if (server.hasArg("nLoadcells")) nLoadcells = server.arg("nLoadcells").toInt();
if (server.hasArg("distanceX1")) model.distance[X1] = server.arg("distanceX1").toFloat();
if (server.hasArg("distanceX2")) model.distance[X2] = server.arg("distanceX2").toFloat();
if (server.hasArg("distanceX3")) model.distance[X3] = server.arg("distanceX3").toFloat();
if (server.hasArg("refWeight")) refWeight = server.arg("refWeight").toFloat();
if (server.hasArg("refCG")) refCG = server.arg("refCG").toFloat();
if (server.hasArg("calFactorLoadcell1")) calFactorLoadcell[LC1] = server.arg("calFactorLoadcell1").toFloat();
if (server.hasArg("calFactorLoadcell2")) calFactorLoadcell[LC2] = server.arg("calFactorLoadcell2").toFloat();
if (server.hasArg("calFactorLoadcell3")) calFactorLoadcell[LC3] = server.arg("calFactorLoadcell3").toFloat();
if (server.hasArg("resistorR1")) resistor[R1] = server.arg("resistorR1").toFloat();
if (server.hasArg("resistorR2")) resistor[R2] = server.arg("resistorR2").toFloat();
if (server.hasArg("batType")) batType = server.arg("batType").toInt();
if (server.hasArg("batCells")) batCells = server.arg("batCells").toInt();
if (server.hasArg("ssid_STA")) server.arg("ssid_STA").toCharArray(ssid_STA, MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("password_STA")) server.arg("password_STA").toCharArray(password_STA, MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("ssid_AP")) server.arg("ssid_AP").toCharArray(ssid_AP, MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("password_AP")) server.arg("password_AP").toCharArray(password_AP, MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("mechanicsType")) model.mechanicsType = server.arg("mechanicsType").toInt();
if (server.hasArg("enableUpdate")) enableUpdate = server.arg("enableUpdate").toInt();
if (server.hasArg("enableOTA")) enableOTA = server.arg("enableOTA").toInt();
if (server.hasArg("device_Name")) server.arg("device_Name").toCharArray(device_Name, MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("lc1_URL")) server.arg("lc1_URL").toCharArray(loadCellURL[LC1], MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("lc2_URL")) server.arg("lc2_URL").toCharArray(loadCellURL[LC2], MAX_SSID_PW_LENGHT + 1);
if (server.hasArg("lc3_URL")) server.arg("lc3_URL").toCharArray(loadCellURL[LC3], MAX_SSID_PW_LENGHT + 1);
EEPROM.put(P_NUMBER_LOADCELLS, nLoadcells);
for (int i = LC1; i <= LC3; i++) {
EEPROM.put(P_DISTANCE_X1 + (i * sizeof(float)), model.distance[i]);
saveCalFactor(i);
}
EEPROM.put(P_REF_WEIGHT, refWeight);
EEPROM.put(P_REF_CG, refCG);
for (int i = R1; i <= R2; i++) {
EEPROM.put(P_RESISTOR_R1 + (i * sizeof(float)), resistor[i]);
}
EEPROM.put(P_BAT_TYPE, batType);
EEPROM.put(P_BATT_CELLS, batCells);
EEPROM.put(P_SSID_STA, ssid_STA);