forked from JOGAsoft/EBC-controller
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.pas
executable file
·3226 lines (2941 loc) · 92.1 KB
/
main.pas
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
unit main;
{$mode objfpc}{$H+}{$I-}
interface
uses
Classes, SysUtils, Forms, Graphics, Dialogs, StdCtrls, EditBtn,
ComCtrls, Menus, Buttons, ActnList, TAGraph, TASeries, Grids,
TAIntervalSources, TATransformations, TATools, LazSerial,
DateUtils, TACustomSeries, SynEdit, StepForm, MyIniFile, math, settings,
typinfo, types, lcltype, connectform, aboutform, ExtCtrls, shortcuthelpform,
LCLTranslator, Spin, i18nutils, Controls;
const
{$ifdef Windows}
cFixedFont = 'Consolas';
{$else}
cFixedFont = 'Liberation Mono';
{$endif}
cVersion = '2.18';
cVersionStr= 'EBC Controller '+cVersion;
cConnectRetries = 10;
cstVoltage = 0;
cstCurrent = 2;
cstPower = 1;
cstTime = 3;
cstCapacity = 4;
cstCapLocal = 5; // Capacity computed on host
cstEnergy = 6;
cstResistance = 8;
cstdV = 9;
cstdA = 10;
//cstDbg1 = 13;
//cstDbg2 = 14;
//cstDbg3 = 15;
cstMax = 10;
cConn = 'Conn';
crcsendpos = 9;
crcrecvpos = 18;
cChanged = 'Changed';
cUnChanged = '';
cA = 'A';
cP = 'W';
cR = 'Ω';
cDefaultCaption = 'EBC Controller';
cNull = '00.00';
cName = 'Name';
cMethod = 'Type';
cCharge = 'Charge';
cChargeCV = 'ChargeCV';
cDischarge = 'Discharge';
cDischargeCP = 'DischargeCP';
cDischargeCR = 'DischargeCR';
cCommand = 'Command';
cStop = 'Stop';
cConnect = 'Connect';
cDisconnect = 'Disconnect';
cAdjust = 'Adjust';
cStart = 'Start';
cCont = 'Cont';
cTestVal = 'TestVal';
cEnableNumCells = 'EnableNumCells';
cDefChargeCurrent = 'DefChargeCurrent';
cDefDischargeCurrent = 'DefDischargeCurrent';
cAutoOff = 'AutoOff';
cVoltInfo = 'CellVoltageInfo';
cModels = 'Models';
cIdent = 'Ident';
cIFactor = 'IFactor';
cUFactor = 'UFactor';
cPFactor = 'PFactor';
cModelName = 'Name_';
cCommandFormat = 'CommandFormat';
cMaxChargeVoltage = 'MaxChargeVoltage';
cMaxChargeCurrent = 'MaxChargeCurrent';
cMaxDischargeCurrent = 'MaxDischargeCurrent';
cDefault = 'Default';
cChargeCurrent = 'ChargeCurrent';
cChkAccept = 'ChkAccept';
cDischargeCurrent = 'DischargeCurrent';
cConstantVoltage = 'ConstantVoltage';
cCells = 'Cells';
cDischargePower = 'DischargePower';
cDischargeResistance = 'DischargeResistance';
cModeCommand = 'ModeCommand';
cCutA = 'CutOffA';
cCutATime = 'CutOffATime';
cCutV = 'CutOffV';
cMaxTime = 'MaxTime';
cIntTime = 'IntegrationTime';
cStartup = 'Startup';
cUseLast = 'UseLast';
cChargeIndex = 'ChargeIndex';
cDischargeIndex = 'DischargeIndex';
cStartSelection = 'StartSelection';
cSelection = 'Selection';
cChkSetting = 'CheckSetting';
cSettings = 'Settings';
cConf = '.conf';
cInit = '.init';
// for using the same directory/conf file for Linux and Windows
{$ifdef Windows}
cSaveDir = 'SaveDir-Win';
cLogDir = 'LogDir-Win';
cStepDir = 'StepFileDir-Win';
cProgFile = 'ProgFile-Win';
cSerial = 'Serial-Win';
{$else}
cSaveDir = 'SaveDir';
cLogDir = 'LogDir';
cStepDir = 'StepFileDir';
cProgFile = 'ProgFile';
cSerial = 'Serial';
{$endif}
cLangCode = 'Lang';
cTabIndex = 'TabIndex';
cReadOnly = 'ReadOnly';
cMonitor = 'Monitor';
cAutoLog = 'AutoLog';
cAutoCsvFileName = 'AutoCsvFileName';
cWinMaximized = 'Maximized';
cWinWidth = 'Width';
cWinHeight = 'Height';
cWinTop = 'Top';
cWinLeft = 'Left';
cAppSec = 'Application';
cMemStepLogHeight = 'MemStepLogHeight';
cMemStepLogWidths = 'MemStepLogWidths';
Resourcestring
cFileExists = 'File Exists';
cFatal = 'Fatal Error';
cError = 'Error';
cCurrentHint = 'Set the charge/discharge current in Ampere';
cCurrent = 'Current';
cPower = 'Power';
cResistance = 'Resistance';
cPowerHint = 'Set the charge/discharge Power in Watt';
cResistanceHint = 'Set the charge/discharge current resistance in Ohm';
cConnectTimeout = 'Unable to connect - timeout';
cChargeLowerCutoff = 'Charge current (%fA) is lower than cutoff current (%fA)';
cCutoffGtoeChargeC = 'Cutoff current (%fA) is greater or equal to charage current (%fA)';
cChargeCurrExeeded = 'Charge current (%fA) exceeds the maximum supported by %s (%fA)';
cChargeVoltageExeeded = 'Charge voltage (%fV) exceeds the maximum supported by %s (%fV)';
cNoChargeProfileSelected = 'no charging profile selected';
cDischargeAmpsExeeded = 'Discharge current (%fA) exceeds the maximum supported by %s (%fA)';
cPacketNotInConfFile = 'packet "%S" not found in config file';
cErrorReadingModelFromSec= '%s while reading Model= from %s (Section %d)';
cNoChargeDischargeProfile= 'No charge/discharge profiles defined in configuration file (%s)';
cIdentModelNotFound = 'Ident for model %d not found in %s';
cNoModelsDefined = 'No models defined in configuration file (%s)';
cNoConnectPackage = 'There is no connect packet defined in configuration file (%s)';
cNoDisconnectPackage = 'There is no disconnect packet defined in configuration file (%s)';
cStepLogCreateErr = 'unable to create step logfile %s (%d)';
cAutoLogNoAutoFileName = 'AutoLog is defined but neither a log file name nor Auto CSV Filename is specified';
cFileOverwrite = 'file %s already exists'+#13+'Overwrite File ?';
cUnableToCreateLogFile = 'unable to create logfile %s (%d)';
cErrorClosingLogfile = 'Error %d while closing logfile)';
cUnableToConnectTo = 'Unable to connect to %s';
cConnectionLost = 'Connection Lost';
cPacketTimeout = 'Timout waiting for a packet from charger device';
cSetBorderName = 'Set border name';
cView = 'View...';
cEdit = 'Edit...';
cCapI = 'CapI: ';
cEneI = 'EneI: ';
cInvalidChecksum = '<%s invalid checksum';
cDecodeCorrentException = 'DecodeCurrent raised %s (%2x%2x)';
cDecodeVoltageException = 'DecodeVoltage raised %s (%2x%2x)';
cTime = 'Time';
cStarted = 'started';
cUnknown = 'unknown';
cConnecting = 'Connecting...';
cNotConnected = 'Not connected';
cConnected = 'Connected';
cCopyError = 'unable to copy'+sLineBreak+'%s'+sLineBreak+'to'+sLineBreak+'%s';
Const
cst_ConnectionState = 0;
cst_ConnectionStatus = 1;
cst_ConnectedModel = 2;
cst_RunMode = 3;
cst_LogFileName = 4;
// Log table headers
// cColumns = ' Step CMD (Ah) (Wh) Time StartV EndV';
cColumns = ' Step | CMD | (Ah) | (Wh) | Time |StartV| EndV | EndA';
cCol: array [1..8] of Integer = (7, 9, 7, 7, 12, 6, 6, 6);
type
TCapacity = (caEBC, caLocal);
TSendMode = (smStart, smAdjust, smCont, smConnect, smDisconnect, smConnStop);
TMethod = (mNone, mCharge, mChargeCV, mDischarge, mDischargeCP, mDischargeCR);
TTestVal = (tvCurrent, tvPower, tvResistance);
TConnState = (csNone, csConnecting, csCapture, csConnected); // csCapture = read settings from instrument
TConnPacket = record
Connect: string;
Disconnect: string;
Stop: string;
end;
TModel = record
Name: string;
IFactor: Extended;
UFactor: Extended;
Ident: Integer;
ConnState: TConnState;
ConnPackets: TConnPacket;
CommandFormat : integer;
MaxChargeVoltage: Extended;
MaxChargeCurrent: Extended;
MaxDischargeCurrent: Extended;
end;
TDeltaValue = record
Time: TDateTime;
SumV: Extended;
SumA: Extended;
Values: Integer;
end;
TCSVData = record
vTime: Integer;
vVoltage,vCurrent,CapacityEBC,CapacityLocal: Extended;
end;
TPacket = record
Name: string;
Command: string;
Method: TMethod;
Start: string;
Adjust: string;
Cont: string;
AutoOff: string;
TestVal: TTestVal;
VoltInfo: Extended;
SupportedModels : TIntegerDynArray;
EnableNumCells : boolean; // for cccv A20/A40
DefChargeCurrent : Extended;
DefDischargeCurrent : Extended;
DefCutoffCurrent : Extended;
end;
TChecks = record
cCurrent: Extended;
cDwellTime: Integer;
cEnergy: Extended;
cCapacity: Extended;
ThresholdTime: TDateTime;
TimerRunning: Boolean;
end;
type TDefaults = record
ChargeI: Extended;
DischargeI: Extended;
ConstantU: Extended;
DischargeP: Extended;
DischargeR: Extended;
Cells: Integer;
ModeName: string;
end;
{ TfrmMain }
TfrmMain = class(TForm)
btnAdjust: TButton;
btnCont: TButton;
btnProg: TButton;
btnStart: TButton;
btnStop: TButton;
btnSkip: TButton;
Chart: TChart;
ChartToolset1: TChartToolset;
ChartToolset1ZoomMouseWheelTool1: TZoomMouseWheelTool;
chkCutCap: TCheckBox;
chkCutEnergy: TCheckBox;
edtDelim: TEdit;
edtTestVal: TFloatSpinEdit;
edtCutEnergy: TFloatSpinEdit;
edtCutCap: TFloatSpinEdit;
edtCutV: TFloatSpinEdit;
edtChargeV: TFloatSpinEdit;
edtCutA: TFloatSpinEdit;
gbSettings: TGroupBox;
gbStatus: TGroupBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
lblCutA: TLabel;
lblChargeV: TLabel;
lblCells: TLabel;
lblCutCap2: TLabel;
lblCutEnergy2: TLabel;
lblCutTime: TLabel;
lblTestVal: TLabel;
lblCapI: TLabel;
lblProgTime: TLabel;
Label10: TLabel;
lblCutCap: TLabel;
lblCutEnergy: TLabel;
lblCutoffV1: TLabel;
lblMin: TLabel;
lblStep: TLabel;
lblStepNum: TLabel;
lblTestUnit: TLabel;
ChartAxisTransformationsCurrent: TChartAxisTransformations;
ChartAxisTransformationsCurrentAutoScaleAxisTransform: TAutoScaleAxisTransform;
ChartAxisTransformationsVoltage: TChartAxisTransformations;
ChartAxisTransformationsVoltageAutoScaleAxisTransform: TAutoScaleAxisTransform;
DateTimeIntervalChartSource: TDateTimeIntervalChartSource;
lblTimer: TLabel;
lsCurrent: TLineSeries;
lsInvisibleCurrent: TLineSeries;
lsInvisibleVoltage: TLineSeries;
lsVoltage: TLineSeries;
MainMenu: TMainMenu;
memLog: TMemo;
memStepLog: TStringGrid;
mm_langEnglish: TMenuItem;
mmm_language: TMenuItem;
mm_Shortcuts: TMenuItem;
mm_LogFileDir: TMenuItem;
mm_skipStep: TMenuItem;
mm_AutoCsvFileName: TMenuItem;
mm_stepEdit: TMenuItem;
mm_stepLoad: TMenuItem;
mmm_Step: TMenuItem;
mm_AutoLog: TMenuItem;
mm_setCsvLogFile: TMenuItem;
GraphStepslogPanel: TPanel;
ChargePannel: TPanel;
DischargePanel: TPanel;
RightPanel: TPanel;
SelectDirectoryDialog1: TSelectDirectoryDialog;
Separator2: TMenuItem;
mm_saveCsv: TMenuItem;
mm_savePng: TMenuItem;
mmm_Data: TMenuItem;
mm_taskBarName: TMenuItem;
mm_Settings: TMenuItem;
mmm_Settings: TMenuItem;
mm_About: TMenuItem;
mmm_Help: TMenuItem;
mmm_File: TMenuItem;
mm_Quit: TMenuItem;
Separator1: TMenuItem;
mm_Disconnect: TMenuItem;
mm_Connect: TMenuItem;
pcProgram: TPageControl;
rgDischarge: TRadioGroup;
rgCharge: TRadioGroup;
sdLogCSV: TSaveDialog;
sdPNG: TSaveDialog;
sdCSV: TSaveDialog;
shaCapI: TShape;
MainStatusBar: TStatusBar;
ChartStepSplitter: TSplitter;
edtCutTime: TSpinEdit;
edtCells: TSpinEdit;
edtCutM: TSpinEdit;
stStepFile: TStaticText;
ReconnectTimer: TTimer;
ConnectionWatchdogTimer: TTimer;
tsConsole: TTabSheet;
tmrWait: TTimer;
tsProgram: TTabSheet;
tbxMonitor: TToggleBox;
tsCharge: TTabSheet;
tsDischarge: TTabSheet;
Serial: TLazSerial;
procedure ConnectionWatchdogTimerTimer(Sender: TObject);
procedure edtCellsChange(Sender: TObject);
procedure edtCellsClick(Sender: TObject);
procedure edtCellsEditingDone(Sender: TObject);
procedure edtCellsKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtCellsKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure edtCellsExit(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure mm_AboutClick(Sender: TObject);
procedure FinalizeLanguageSettings;
procedure SetLanguage(langCode : string);
procedure mm_langClick(Sender: TObject);
procedure mm_AutoCsvFileNameClick(Sender: TObject);
procedure mm_AutoLogClick(Sender: TObject);
procedure mm_ConnectClick(Sender: TObject);
procedure mm_LogFileDirClick(Sender: TObject);
procedure mm_QuitClick(Sender: TObject);
procedure mm_saveCsvClick(Sender: TObject);
procedure mm_savePngClick(Sender: TObject);
procedure mm_setCsvLogFileClick(Sender: TObject);
procedure mm_SettingsClick(Sender: TObject);
procedure mm_ShortcutsClick(Sender: TObject);
procedure mm_stepLoadClick(Sender: TObject);
procedure mm_taskBarNameClick(Sender: TObject);
procedure pcProgramChange(Sender: TObject);
procedure ReconnectTimerTimer(Sender: TObject);
procedure btnAdjustClick(Sender: TObject);
procedure btnContClick(Sender: TObject);
procedure btnProgClick(Sender: TObject);
procedure btnSkipClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
function doProgramCchecks : boolean;
procedure btnStopClick(Sender: TObject);
procedure chkCutCapChange(Sender: TObject);
procedure chkCutEnergyChange(Sender: TObject);
procedure edtCutTimeChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure rgChargeClick(Sender: TObject);
procedure rgDischargeClick(Sender: TObject);
procedure MainStatusBarDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel;
const Rect: TRect);
procedure Splitter1CanOffset(Sender: TObject; var NewOffset: Integer;
var Accept: Boolean);
procedure tbxMonitorChange(Sender: TObject);
procedure tmrWaitTimer(Sender: TObject);
procedure tsChargeEnter(Sender: TObject);
procedure tsDischargeEnter(Sender: TObject);
procedure fatalError(aMessage : string);
private
FRecvStatusIndicator: integer;
FRecvStatusIndicatorInc : integer;
FConfFile: string;
FStartTime: TDateTime;
FStepTime: TDateTime;
FLastTime: TDateTime;
FData: array of TCSVData;
FAppDir: string;
public
FPackets: array of TPacket;
private
fLogFileIsOpen : boolean;
fLogFileName : string;
FPacketIndex: Integer;
FLogFile: Text;
FRunMode: TRunMode;
FChecks: TChecks;
FSampleCounter: Integer;
FLastU: Extended;
FLastI: Extended;
FProgramStep: Integer; // Points to next step after LoadStep
FCurrentStep: Integer; // Points to current/last step
FDefault: TDefaults;
FWaitCounter: Integer;
FInProgram: Boolean;
FEnergy: Extended;
FStartU: Extended;
FCurrentCapacity: array [TCapacity] of Extended; // The capacity (Ah) measured so far from the current cycle
FLastDisCapacity: Extended; // Last capacity from the latest discharge cycle
FCurrentDisCapacity: Extended; // The capacity measured from the current discharge cycle
FBeginWaitVoltage: Extended;
FEndWaitVoltage: Extended;
stText: array of TStaticText;
FModels: array of TModel;
FModel: Integer;
FConn: TConnPacket;
FConnState: TConnState;
FUFactor: Extended;
FIFactor: Extended;
FShowJoule: Boolean;
FShowCoulomb: Boolean;
FDelta: array [0..1] of TDeltaValue;
FDeltaIndex: Integer;
FIntTime: Integer;
FConnectRetryCountdown: Integer;
fLanguageCode: String;
procedure DoHexLog(AText: string);
procedure SerialRec(Sender: TObject);
function InterpretPackage(APacket: string; ANow: TDateTime) : boolean;
procedure DumpSerialData(prefix,postfix: string; snd: string; Pos: Integer);
procedure SendData(snd: string);
function EncodeCurrent(Current: Extended): string;
function EncodePower(Power: Extended): string;
function DecodeCurrent(Data: string): Extended;
function EncodeVoltage(Voltage: Extended): string;
function DecodeVoltage(Data: string): Extended;
function DecodeCharge(Data: string): Extended;
function DecodeTimer(Data: string): Integer;
function EncodeTimer(Data: Integer): string;
procedure SaveCSVLine(var f: Text; ATime: Integer; ACurrent: Extended; AVoltage: Extended; CapacityEBC: Extended; CapacityLocal: Extended);
procedure SaveCSV(AFile: string);
function GetHexPacketFromIni(AIniFile: TMyIniFile; ASection: string; AIdent: string; ADefault: string = ''): string;
procedure LoadPackets;
procedure clearChargeDischargeTypes;
public
function PacketSupportedByCharger(chargerModel, PacketIndex : integer) : boolean;
private
procedure setChargeDischargeTypes(chargerModel : integer);
// function MakePacket(AType: TSendMode): string;
function NewMakePacket(Packet: Integer; AType: TSendMode): string;
procedure SetupChecks;
procedure FixLabels(APacket: Integer);
procedure DoLog(AText: string);
function StartLogging : boolean;
procedure StopLogging;
procedure LoadStep;
function FindPacket(AName: string): Integer;
function GetPointer(ARadioGroup: TRadioGroup): Integer;
function MakePacket2(Packet: Integer; SendMode: TSendMode; TestVal, SecondParam: Extended; ATime: Integer; cutoffCurrent: Extended): string;
function MakeConnPacket(SendMode: TSendMode): string;
procedure EBCBreak(Force: Boolean = False; closeLogFile: Boolean = true); // Force = True terminates even if a program is running.
procedure LogStep;
procedure OffSetting; // Sets labels and button for "off".
procedure LoadSettings;
procedure SaveSettings;
procedure SetSettings;
function GetStepNum: string;
function GetModelIndex(AModel: Integer): Integer;
public
function GetModelIndex(AModel: string): Integer;
private
procedure stTextClick(Sender: TObject);
function GetEnergy(AEnergy: Extended): string;
function GetCharge(ACharge: Extended): string;
procedure FreezeEdits;
procedure UnlockEdits;
procedure RunModeOffOrMonitor;
procedure SetRunMode(ARunMode: TRunMode);
procedure TimerOff;
procedure setStatusLine(Element:integer; txt:string);
// StringGrid for step log helper routines
procedure memStepLogClear;
procedure memStepLogAdd (cmd : string);
procedure memStepLogNewStep; // start a step
procedure memStepLogUpdate (AH,WH,startV,endV,endA : extended; time : TDateTime); // updates values in current step
procedure memStepLogEnd; // end of current step
function memStepLog2csv (Separator : char) : TStringList;
public
end;
var
frmMain: TfrmMain;
implementation
{$R *.lfm}
const
cMemStepLog_step = 0;
cMemStepLog_cmd = 1;
cMemStepLog_AH = 2;
cMemStepLog_WH = 3;
cMemStepLog_time = 4;
cMemStepLog_startV = 5;
cMemStepLog_endV = 6;
cMemStepLog_endA = 7;
function ValOk(ANum: Extended): Boolean;
begin
Result := not (IsNan(ANum));// or IsInf(ANum));
end;
function TextFileCopy(AInFile, AOutFile: string): Boolean;
var
fi, fo: Text;
s: string;
begin
result := false;
try
if FileExists(AInFile) then
begin
AssignFile(fi, AInFile);
AssignFile(fo, AOutFile);
Reset(fi);
ReWrite(fo);
while not Eof(fi) do
begin
ReadLn(fi, s);
WriteLn(fo, s);
end;
Flush(fo);
CloseFile(fi);
CloseFile(fo);
Result := True;
end;
except
Result := False;
end;
end;
function AlignL(AStr: string; ALen: Integer): string;
begin
Result := AStr;
while Length(Result) < ALen do
begin
Result := Result + ' ';
end;
end;
function AlignR(AStr: string; ALen: Integer): string;
begin
Result := AStr;
while Length(Result) < ALen do
begin
Result := ' ' + Result;
end;
end;
function Round1V(U: Extended): Extended;
begin
Result := 1 + Round(U + 0.500);
end;
function Round100mA(I: Extended): Extended;
begin
Result := 0.1 + Round(I * 10 + 0.50) / 10;
end;
function NumEdtOk(AStr: string; out AVal: Extended): Boolean;
var
Code: Integer;
begin
Val(AStr, AVal, Code);
Result := (Code = 0);
end;
function MyFloatStr(AVal: Extended): string;
begin
Result := FloatToStrF(AVal, ffFixed, 18, 3);
end;
function MyTimeToStr(ATime: TDateTime): string;
begin
Result := IntToStr(Trunc(ATime)) + ':' + FormatDateTime('hh:mm:ss', ATime);
end;
function HexToOrd(s: string): Integer;
var
I: Integer;
M: Integer;
begin
Result := 0;
M := 1;
for I := Length(s) downto 1 do
begin
if s[I] in ['0'..'9'] then
begin
Result := Result + M * (Ord(s[I]) - Ord('0'));
end else if s[I] in ['A'..'F'] then
begin
Result := Result + M * (Ord(s[I]) - Ord('A') + 10);
end;
M := M * $10;
end;
end;
function FormatPath(APath: string): string; // Removes "//" or "\\" from paths
var
P: integer;
s: string;
begin
s := PathDelim + PathDelim;
repeat
P := Pos(s, APath);
if P > 0 then
begin
APath := Copy(APath, 1, P - 1) + Copy(APath, P + 1, Length(APath));
end;
until P = 0;
Result := APath;
end;
function checksum(s: string; Pos: Integer): Char; // Seems EBC uses a stupid XOR CRC
var
I: Integer;
begin
Result := #0;
if length(s) < Pos then exit; // AD: sigsegv here when usb disconnects
for I := 2 to Pos - 1 do
Result := Chr(Ord(Result) xor Ord(s[I]));
(* AD: EBC-A20 does not accept start/stop chars as checksum
This happens e.g. for charge @ 4.20/4.22V, 1A and 0.1A cutoff
The Windows software sends $0a and $0f in that case so lets do the same here *)
// looks like the A40 never sends checksums >= 0xf0 so lets do the same
if (byte(result) and $f0 = $f0) then
result := char(byte(result) and $0f);
end;
{ TfrmMain }
procedure TfrmMain.fatalError(aMessage : string);
begin
Application.MessageBox(pchar(aMessage),pchar(cFatal),MB_ICONSTOP);
Application.Terminate;
end;
procedure TfrmMain.SerialRec(Sender: TObject);
var
s: string;
r: string;
N: Integer;
E: TDateTime;
startFound: boolean;
rBuf: string;
begin
r := '';
N := 0;
E := Now;
startFound := false;
rBuf := '';
// AD: wait for start char
repeat
s := Serial.ReadData;
if Length(s) > 0 then
begin
rBuf := rBuf + s;
while (length(s) > 0) and (s[1] <> #$FA) do
delete(s,1,1);
if (length(s) > 0) then
begin
startFound := true;
r := s;
end;
end;
until (startFound) or (MillisecondsBetween(Now, E) > 200);
N := Length(r);
repeat
s := Serial.ReadData;
if Length(s) > 0 then
begin
r := r + s;
rBuf := rBuf + s;
Inc(N, Length(s));
end;
until (N >= 19) or (MillisecondsBetween(Now, E) > 200);
DumpSerialData('<','', rBuf, 0);
while N >= 19 do
begin
s := copy(r,1,19); delete(r,1,19); dec(N,19);
if length(s) = 19 then
begin
if InterpretPackage(s, E) then // false if checksum is invalid
begin
FRecvStatusIndicator := FRecvStatusIndicator + FRecvStatusIndicatorInc;
MainStatusBar.invalidate;
//Application.ProcessMessages;
if FConnState = csConnecting then
begin
FModel := GetModelIndex(Ord(s[17]));
if FModel > -1 then
begin
ReconnectTimer.Enabled:=false;
ConnectionWatchdogTimer.Enabled:=true;
setStatusLine(cst_ConnectionStatus,cConnected);
setStatusLine(cst_ConnectedModel,FModels[FModel].Name);
tbxMonitor.Enabled := True;
rgCharge.Enabled := True;
rgDischarge.Enabled := True;
FConnState := csConnected;
FUFactor := FModels[FModel].UFactor;
FIFactor := FModels[FModel].IFactor;
setChargeDischargeTypes(FModel);
edtChargeV.Enabled:=false;
frmStep.setDevice(FModels[FModel].Name);
if length(frmStep.fileName) > 0 then
if frmStep.Compile(fModel,true) = mrOk then
begin
pcProgram.ActivePage := tsProgram;
btnStart.enabled := true;
end;
end;
end else
begin
ConnectionWatchdogTimer.Enabled:=false;
ConnectionWatchdogTimer.Enabled:=true; // does this reset the timer ?
end;
end
else
doLog(Format(cInvalidChecksum,[r]));
end;
end;
FLastTime := E;
end;
function TfrmMain.InterpretPackage(APacket: string; ANow: TDateTime) : boolean;
var
P, tmp: Extended;
dT: Integer;
T: TDateTime;
chkIsValid : boolean;
chk : char;
TSec : longint;
begin
result := false;
if FSampleCounter > 0 then
begin
dT := MillisecondsBetween(ANow, FLastTime);
end else
dT := 2000;
T := ANow - FStartTime;
TSec := SecondsBetween(ANow,FStartTime);
if (TSec < 0) then tSec := 0;
chkIsValid := frmSettings.cgSettings.Checked[cIgnoreCRC];
if not chkIsValid then
begin
chk := checksum(APacket, crcrecvpos);
chkIsValid := (chk = APacket[crcrecvpos]);
end;
if chkIsValid then
begin
if frmSettings.cgSettings.Checked[cLogRecData] then
DumpSerialData('<','',APacket,crcrecvpos);
result := true;
try
FLastI := DecodeCurrent(Copy(APacket, 3, 2));
except
on e:exception do // was for divide by zero check, only visible under windows, fixed
doLog(format(cDecodeCorrentException,[e.Message,byte(APacket[3]), byte(APacket[4])]));
end;
try
FLastU := DecodeVoltage(Copy(APacket, 5, 2));
except
on e:exception do
doLog(format(cDecodeVoltageException,[e.Message,byte(APacket[5]), byte(APacket[6])]));
end;
FCurrentCapacity[caEBC] := DecodeCharge(Copy(APacket, 7, 2));
FCurrentCapacity[caLocal] := FCurrentCapacity[caLocal] + FLastI * dT / 3600000;
stText[cstVoltage].Caption := MyFloatStr(FLastU) + 'V';
stText[cstCurrent].Caption := MyFloatStr(FLastI) + 'A';
P := FLastU * FLastI;
stText[cstPower].Caption := FloatToStrF(P, ffFixed, 18, 3) + 'W';
//if FCurrentCapacity[caEBC] < 10 then
stText[cstCapacity].Caption := GetCharge(FCurrentCapacity[caEBC]);
//else
// stText[cstCapacity].Caption := 'See device'; // FIXME, AD: fixed GetCharge
stText[cstCapLocal].Caption := GetCharge(FCurrentCapacity[caLocal]) + '(PC)';
tmp := (P * dT) / 3600000;
if ValOk(tmp) then
begin
FEnergy := FEnergy + tmp;
stText[cstEnergy].Caption := GetEnergy(FEnergy);
end;
stText[cstTime].Caption := MyTimeToStr(T);
if FLastI <> 0 then
begin
tmp := FLastU / FLastI;
if ValOk(tmp) then
stText[cstResistance].Caption := MyFloatStr(tmp) + cR;
end;
if FInProgram then
lblProgTime.Caption := TimeToStr(ANow - FStepTime);
if not (FRunMode in [rmNone]) then
begin
SetLength(FData, Length(FData) + 1);
with FData[Length(FData) - 1] do
begin
//vTime := DecodeTimer(Copy(APacket, 15, 2));
// AD: use time from PC
vVoltage := FLastU;
vCurrent := FLastI;
CapacityEBC := FCurrentCapacity[caEBC];
CapacityLocal := FCurrentCapacity[caLocal];
if fLogFileIsOpen then
SaveCSVLine(FLogFile, TSec{vTime}, FLastI, FLastU, FCurrentCapacity[caEBC], FCurrentCapacity[caLocal]);
end;
lsVoltage.AddXY(T, FLastU);
lsInvisibleVoltage.AddXY(0, Round1V(FLastU));
lsCurrent.AddXY(T, FLastI);
lsInvisibleCurrent.AddXY(0, Round100mA(FLastI));
end;
FDelta[FDeltaIndex].SumV := FDelta[FDeltaIndex].SumV + FLastU;
FDelta[FDeltaIndex].SumA := FDelta[FDeltaIndex].SumA + FLastI;
Inc(FDelta[FDeltaIndex].Values);
{ if dT <> 0 then
begin
stText[cstdV].Caption := FloatToStrF((1000000 * (FLastU - lU)) / (dT ), ffFixed, 18, 2) + 'mV/s';
stText[cstdA].Caption := FloatToStrF((1000000 * (FLastI - lI)) / (dT ), ffFixed, 18, 2) + 'mA/s';
end;
}
dT := MillisecondsBetween(FDelta[FDeltaIndex].Time, ANow);
if dT >= FIntTime then if dT <> 0 then
begin
FDelta[FDeltaIndex].SumV := FDelta[FDeltaIndex].SumV / FDelta[FDeltaIndex].Values;
FDelta[FDeltaIndex].SumA := FDelta[FDeltaIndex].SumA / FDelta[FDeltaIndex].Values;
if ValOk(FDelta[FDeltaIndex].SumA) then if ValOk(FDelta[FDeltaIndex].SumV) then
begin
tmp := (FDelta[FDeltaIndex].SumV - FDelta[FDeltaIndex xor $01].SumV) / dT;
if ValOk(tmp) then
begin
stText[cstdV].Caption := FloatToStrF(60000000 * tmp , ffFixed, 18, 2) + 'mV/m';
end;
tmp := (FDelta[FDeltaIndex].SumA - FDelta[FDeltaIndex xor $01].SumA) / dT;
if ValOk(tmp) then
begin
stText[cstdA].Caption := FloatToStrF(60000000 * tmp, ffFixed, 18, 2) + 'mA/m';
end;
// stText[cstDbg1].Caption := IntToStr(FDelta[FDeltaIndex].Values);
// stText[cstDbg2].Caption := FloatToStr(FDelta[FDeltaIndex].SumV);
// stText[cstDbg3].Caption := 'Index: ' + IntToStr(FDeltaIndex) + ' : ' + IntToStr(FDeltaIndex xor $01);
end;
FDeltaIndex := FDeltaIndex xor $01;
FDelta[FDeltaIndex].SumV := 0;
FDelta[FDeltaIndex].SumA := 0;
FDelta[FDeltaIndex].Values := 0;
FDelta[FDeltaIndex].Time := ANow;
end;
Inc(FSampleCounter);
if (FRunMode = rmDischargingCR) and (FSampleCounter mod 3 = 0) then
begin
SendData(NewMakePacket(FPacketIndex, smAdjust));
end;
// AutoOff check
if (not (FRunMode in [rmNone, rmMonitor, rmWait, rmLoop])) and
((APacket[2] = FPackets[FPacketIndex].AutoOff) or ((FSampleCounter > 3) and (FLastI < 0.0001))) then
if FInProgram then EBCBreak(false,false) else EBCBreak;
// Cutoff checks
if (FRunMode = rmCharging) and (FSampleCounter > 3) then
begin
if FLastI < FChecks.cCurrent then
begin
if FChecks.TimerRunning then
begin
DoLog(cTime+': ' + IntToStr(SecondsBetween(FChecks.ThresholdTime, Now)));
if SecondsBetween(FChecks.ThresholdTime, Now) div 60 >= FChecks.cDwellTime then
if FInProgram then EBCBreak(false,false) else EBCBreak;
end else
begin
FChecks.ThresholdTime := Now;
FChecks.TimerRunning := True;
DoLog('Timer '+cStarted+'.');
if FChecks.cDwellTime = 0 then
if FInProgram then EBCBreak(false,false) else EBCBreak;
end;
end;
if FCurrentCapacity[caEBC] > FChecks.cCapacity then
if FInProgram then EBCBreak(false,false) else EBCBreak;
end;
LogStep;
end else
begin
DumpSerialData('<','CRC '+cError+':', APacket, crcrecvpos);
end;
end;
procedure TfrmMain.DumpSerialData(prefix,postfix: string; snd: string; Pos: Integer);
var
s: string;
I: Integer;
begin
s := '';
for I := 1 to Length(snd) do
begin
s := s + LowerCase(IntToHex(Ord(snd[I]),2));
// if I < Length(snd) then s := s + '|';
end;
if (pos > 0) and (pos <= length(snd)) then
DoHexLog(prefix + ' ' + s + ' ' + IntToHex(Ord(checksum(snd, Pos)),2) + ' ' + postfix)
else
DoHexLog(prefix + ' ' + s + ' ' + postfix);
end;