-
Notifications
You must be signed in to change notification settings - Fork 0
/
umain.pas
1325 lines (1153 loc) · 39.4 KB
/
umain.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
//-----------------------------------------------------------------------------
// USB / Serial, Multi Channel Timer Programmer Console.
// Main window.
//
// Copyright (C) 2020 SriKIT contributors.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
// Last updated: Dilshan Jayakody [24th Nov 2020]
//
// Update log:
// [24/11/2020] - Initial version - Dilshan Jayakody.
//-----------------------------------------------------------------------------
unit umain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
Buttons, ComCtrls, ualarm, ucommon, LCLType, uabout, utimeconfig, Clipbrd,
Menus, LazSerial, LazSynaSer, userial;
type
{ TfrmMain }
TfrmMain = class(TForm)
beSep1: TBevel;
beSep2: TBevel;
beSep3: TBevel;
beSep4: TBevel;
beSep5: TBevel;
beSep6: TBevel;
cmbPortName: TComboBox;
imglMenu: TImageList;
comDrv: TLazSerial;
lblMaxChannels: TLabel;
lblMaxTimers: TLabel;
lblPortName: TLabel;
dlgOpenFile: TOpenDialog;
mnuAddTimer: TMenuItem;
mnuDelTimer: TMenuItem;
mnuPaste: TMenuItem;
mnuSelect: TMenuItem;
mnuClear: TMenuItem;
N2: TMenuItem;
mnuSep1: TMenuItem;
pnlStatus: TPanel;
pnlToolbar: TPanel;
btnConnect: TSpeedButton;
btnInfo: TSpeedButton;
btnDisconnect: TSpeedButton;
btnAddTimer: TSpeedButton;
btnDelTimer: TSpeedButton;
btnSetSysTime: TSpeedButton;
btnSync: TSpeedButton;
btnSave: TSpeedButton;
btnOpen: TSpeedButton;
btnClear: TSpeedButton;
dlgSaveFile: TSaveDialog;
mnuMainPopup: TPopupMenu;
progMain: TProgressBar;
scrTimerList: TScrollBox;
tmrSerial: TTimer;
tmrInit: TTimer;
tmrDelete: TTimer;
procedure btnAddTimerClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure btnDelTimerClick(Sender: TObject);
procedure btnDisconnectClick(Sender: TObject);
procedure btnInfoClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnSetSysTimeClick(Sender: TObject);
procedure btnSyncClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure fmTimerOnValueChanged(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure mnuMainPopupPopup(Sender: TObject);
procedure mnuPasteClick(Sender: TObject);
procedure mnuSelectClick(Sender: TObject);
procedure SetButtonState(isItemsExist : Boolean);
procedure ShowSystemTimeWindow(sysTime: TTimeInfo);
procedure SetConnectionState();
procedure tmrDeleteTimer(Sender: TObject);
procedure tmrInitTimer(Sender: TObject);
procedure tmrSerialTimer(Sender: TObject);
private
alarmUid : Int64;
valueChanged: Boolean;
currentFileName: string;
timerName: string;
channelResetCount: byte;
currentDevCmd: TDeviceCommand;
commandDevRetry: Word;
responseData: string;
responseLen: Word;
FMaxChannelCount: byte;
FMaxTimerCount: byte;
activeAlarmCount: byte;
currentAlarmPos: byte;
tempTimeInfo: TAlarmInfo;
FClipboardFormat: TClipboardFormat;
fmSystemTime : TfrmTimeConfig;
function ConvByteToStr(inData: Byte) : string;
procedure SaveDevNameToMRU(devName: string);
procedure LoadMRUList();
procedure OnHandShakeComplete(isTimeout: Boolean);
procedure OnDeviceInfoAvailable(isTimeout: Boolean; infoData: string);
procedure OnGetAlarmCount(isTimeout: Boolean; infoData: string);
procedure OnGetSystemTime(isTimeout: Boolean; infoData: string);
procedure OnGetAlarmStartTime(isTimeout: Boolean; infoData: string);
procedure OnGetAlarmEndTime(isTimeout: Boolean; infoData: string);
procedure OnSetAlarmCount(isTimeout: Boolean);
procedure OnSetSystemTime(isTimeout: Boolean);
procedure OnSetAlarmStartTime(isTimeout: Boolean);
procedure OnSetAlarmEndTime(isTimeout: Boolean);
procedure OnTimeout(cmdID: TDeviceCommand; var ignore: Boolean);
public
alarmList : TList;
property MaxChannel : byte read FMaxChannelCount write FMaxChannelCount;
property TimerCount : byte read FMaxTimerCount write FMaxTimerCount;
property ClipboardRegFormat : TClipboardFormat read FClipboardFormat write FClipboardFormat;
function AddTimer(alarmData: TAlarmInfo; maxChannelCount: Byte) : TfmTimer;
procedure DeleteTimerAsync(timer: string);
procedure DeleteTimer(timer: string);
procedure SetChangeFlag(isChanged : Boolean);
procedure OpenConfigurationFile(filename: string);
procedure PasteNewTimer();
procedure DuplicateTimer(alarmData: TAlarmInfo);
procedure DeviceHandShake();
procedure DeviceInfo();
procedure GetAlarmCount();
procedure GetSystemTime();
procedure GetAlarmStartTime(alarmID : Byte);
procedure GetAlarmEndTime(alarmID : Byte);
procedure SetAlarmCount(alarmCount: Byte);
procedure SetSystemTime(year: Byte; month: Byte; date: Byte; hour: Byte; minutes: Byte; seconds: Byte);
procedure SetAlarmStartTime(alarmID: Byte; channelID: Byte; year: Byte; month: Byte; date: Byte; hour: Byte; minutes: Byte; seconds: Byte);
procedure SetAlarmEndTime(alarmID: Byte; year: Byte; month: Byte; date: Byte; hour: Byte; minutes: Byte; seconds: Byte);
function CheckDeviceConnection() : boolean;
end;
const
DEFAULT_CHANNEL_COUNT: byte = 1;
DEFAULT_TIMER_COUNT: byte = 8;
MRU_CONFIG_FILE_NAME: string = 'timerprog.mru';
DEFAULT_FILE_NAME: string = 'untitled.tpf';
CLIPBOARD_FORMAT: string = 'application/x-timerprog';
FILE_ID_BYTE: Byte = $21;
DEV_RETRY_COUNT: Word = 5;
var
frmMain: TfrmMain;
resourcestring
srDeleteNoItems = 'Select timer configuration(s) to delete';
srDeleteConfirm = 'Delete selected alarm configuration(s)?';
srMaxAlarm = 'Maximum number of alarm configurations reached';
srMaxLoad = 'Only the maximum number of alarm configurations are loaded';
srFileSaveError = 'An error occurred while saving the file';
srFileOpenError = 'An error occurred while openning the file';
srUnsupportedFile = 'Unsupported file or corrupted file';
srClearConfirmation = 'Clear all alarm configuration(s) and start new session?';
srChannelReset = ' timer channel(s) got reset to the maximum channel limit';
srUnsavedData = 'Existing configuration is changed!' + LineEnding + 'Continue without saving the existing configuration?';
srCommunicationError = 'Communication error';
srComPortNotDefined = 'Communication port is not specified';
srDevieNotResponsive = 'Connected device is not responsive';
srDeviceNotConnected = 'Connection to the device is not available';
srDataCorrupted = 'Received data is invalid or corrupted';
srInvalidAlarmConfig = 'Invalid timer configuration(s) detected';
implementation
{$R *.lfm}
{ TfrmMain }
function TfrmMain.CheckDeviceConnection() : boolean;
begin
result := comDrv.Active;
if(not result) then
begin
// Device connection is not available.
SetConnectionState();
MessageDlg(Application.Title, srDeviceNotConnected, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
end
end;
procedure TfrmMain.SetConnectionState();
begin
btnDisconnect.Enabled := comDrv.Active;
btnConnect.Enabled := not btnDisconnect.Enabled;
btnSetSysTime.Enabled := btnDisconnect.Enabled;
btnSync.Enabled := btnDisconnect.Enabled;
end;
procedure TfrmMain.SetButtonState(isItemsExist : Boolean);
begin
btnDelTimer.Enabled := isItemsExist;
btnSave.Enabled := isItemsExist;
btnClear.Enabled := isItemsExist;
mnuDelTimer.Enabled := isItemsExist;
mnuSelect.Enabled := isItemsExist;
end;
procedure TfrmMain.tmrDeleteTimer(Sender: TObject);
begin
tmrDelete.Enabled := false;
DeleteTimer(timerName);
end;
procedure TfrmMain.tmrInitTimer(Sender: TObject);
begin
tmrInit.Enabled := false;
// Send handshake request to the device.
DeviceHandShake();
end;
procedure TfrmMain.SetChangeFlag(isChanged : Boolean);
begin
valueChanged := isChanged;
self.Caption := Application.Title;
if(isChanged) then
begin
// Place mark on title bar if the content is changed.
self.Caption := self.Caption + '*';
end;
end;
procedure TfrmMain.DeleteTimerAsync(timer: string);
begin
timerName := timer;
tmrDelete.Enabled := true;
end;
procedure TfrmMain.DeleteTimer(timer: string);
var
selPos: Word;
tmpAlarmItem: TfmTimer;
begin
selPos := 0;
// Looking for the specified timer name.
while(selPos < alarmList.Count) do
begin
tmpAlarmItem := TfmTimer(alarmList.Items[selPos]);
if((tmpAlarmItem <> nil) and (tmpAlarmItem.Name = timer)) then
begin
// Delete current timer from the list.
Application.ProcessMessages;
FreeAndNil(tmpAlarmItem);
alarmList.Delete(selPos);
// Reset value changed flag.
SetChangeFlag((alarmList.Count > 0));
break;
end;
inc(selPos);
end;
// changed UI button state based on available alarm configurations.
SetButtonState((alarmList.Count > 0));
end;
procedure TfrmMain.PasteNewTimer();
var
clipboardBuffer: TMemoryStream;
alarmInfo: TAlarmInfo;
begin
if(alarmList.Count < TimerCount) then
begin
// Check current clipboard format and try to load data.
if(Clipboard.HasFormat(ClipboardRegFormat)) then
begin
try
clipboardBuffer := TMemoryStream.Create;
// Get alarm information from clipboard.
Clipboard.GetFormat(ClipboardRegFormat, clipboardBuffer);
clipboardBuffer.Position := 0;
alarmInfo := LoadAlarmInfoFromStream(clipboardBuffer);
// Create new timer panel and apply values.
AddTimer(alarmInfo, MaxChannel);
// Reset value changed flag and UI button state.
SetChangeFlag(true);
SetButtonState(true);
finally
FreeAndNil(clipboardBuffer);
self.Invalidate;
end;
end;
end
else
begin
// Maximum alarm count is reached.
MessageDlg(Application.Title, srMaxAlarm, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
end;
end;
function TfrmMain.AddTimer(alarmData: TAlarmInfo; maxChannelCount: Byte) : TfmTimer;
var
tempAlarmUnit : TfmTimer;
begin
// Create new alarm panel.
tempAlarmUnit := TfmTimer.Create(self, frmMain);
tempAlarmUnit.Name := 'fmAlarmUnit' + IntToStr(alarmUid);
// Increment UID value to provide unique component names.
inc(alarmUid);
// Add new alarm panel to the end of the list.
if(alarmList.Count > 0) then
begin
if(alarmList.Items[alarmList.Count - 1] <> nil) then
begin
tempAlarmUnit.Top := TfmTimer(alarmList.Items[alarmList.Count - 1]).Top + tempAlarmUnit.Height;
end;
end;
tempAlarmUnit.Align := alTop;
tempAlarmUnit.Parent := scrTimerList;
alarmList.Add(tempAlarmUnit);
// Assign dummy alarm information to the panel.
tempAlarmUnit.SetAlarmInfo(alarmData, maxChannelCount);
tempAlarmUnit.OnValueChanged := @fmTimerOnValueChanged;
// Count number of channel resets.
if(tempAlarmUnit.IsChannelReset()) then
begin
inc(channelResetCount);
end;
result := tempAlarmUnit;
end;
procedure TfrmMain.DuplicateTimer(alarmData: TAlarmInfo);
begin
if(alarmList.Count < TimerCount) then
begin
AddTimer(alarmData, MaxChannel);
// Reset value changed flag and UI button state.
SetChangeFlag(true);
SetButtonState(true);
end
else
begin
// Maximum alarm count is reached.
MessageDlg(Application.Title, srMaxAlarm, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
end;
end;
procedure TfrmMain.btnAddTimerClick(Sender: TObject);
begin
if(alarmList.Count < TimerCount) then
begin
AddTimer(NewAlarmInfo(), MaxChannel);
// Reset value changed flag and UI button state.
SetChangeFlag(true);
SetButtonState(true);
end
else
begin
// Maximum alarm count is reached.
MessageDlg(Application.Title, srMaxAlarm, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
end;
end;
procedure TfrmMain.fmTimerOnValueChanged(Sender: TObject);
begin
SetChangeFlag(true);
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
// Setup status bar values.
lblMaxChannels.Caption := IntToStr(MaxChannel);
lblMaxTimers.Caption := IntToStr(TimerCount);
// Load MRU device names if exists.
LoadMRUList();
if((Application.ParamCount > 0) and (FileExists(Application.Params[1]))) then
begin
// Try to open file specified in commandline arguments.
OpenConfigurationFile(Application.Params[1]);
end
else
begin
// Commandline arguments are not specified.
SetButtonState(false);
end;
end;
procedure TfrmMain.mnuMainPopupPopup(Sender: TObject);
begin
mnuPaste.Enabled := Clipboard.HasFormat(ClipboardRegFormat);
end;
procedure TfrmMain.mnuPasteClick(Sender: TObject);
begin
PasteNewTimer();
end;
procedure TfrmMain.mnuSelectClick(Sender: TObject);
var
selPos: Word;
begin
if(alarmList.Count > 0) then
begin
selPos := 0;
// Get an each timer panel in the scroll-box to mark the checkbox.
while(selPos < alarmList.Count) do
begin
if(alarmList.Items[selPos] <> nil) then
begin
TfmTimer(alarmList.Items[selPos]).chkSelect.Checked := true;
end;
inc(selPos);
end;
scrTimerList.Invalidate;
end;
end;
procedure TfrmMain.btnClearClick(Sender: TObject);
var
selPos: Word;
tmpAlarmItem: TfmTimer;
begin
if((Sender <> nil) and (alarmList.Count > 0)) then
begin
if(MessageDlg(Application.Title, srClearConfirmation, TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = mrNo) then
begin
// Clear operation is canceled by the user.
exit;
end;
end;
if(alarmList.Count > 0) then
begin
selPos := 0;
while(selPos < alarmList.Count) do
begin
// Remove selected panel.
tmpAlarmItem := TfmTimer(alarmList.Items[selPos]);
FreeAndNil(tmpAlarmItem);
// Remove alarm panel reference from the list.
alarmList.Delete(selPos);
Continue;
end;
// Reset value changed flag and UI button state.
SetChangeFlag(false);
SetButtonState(false);
end;
// Reset session based variables.
channelResetCount := 0;
end;
procedure TfrmMain.btnConnectClick(Sender: TObject);
begin
try
if(Trim(cmbPortName.Text) = '') then
begin
// Communication port name is not specified;
MessageDlg(Application.Title, srComPortNotDefined, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
exit;
end;
// Connecting with the specified communication port...
{$IFDEF LINUX}
comDrv.Device := '/dev/' + Trim(cmbPortName.Text);
{$ELSE}
comDrv.Device := Trim(cmbPortName.Text);
{$ENDIF}
comDrv.Open;
btnClearClick(nil);
tmrInit.Enabled := comDrv.Active;
except on E: Exception do
// Communication error has occured.
MessageDlg(Application.Title, (srCommunicationError + LineEnding + E.Message), TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
end;
end;
procedure TfrmMain.btnDelTimerClick(Sender: TObject);
var
selCount, selPos: Word;
tmpAlarmItem: TfmTimer;
begin
if(alarmList.Count > 0) then
begin
selCount := 0;
selPos := 0;
// Count number of selected alarm configurations.
while(selPos < alarmList.Count) do
begin
if((alarmList.Items[selPos] <> nil) and (TfmTimer(alarmList.Items[selPos]).IsSelected())) then
begin
inc(selCount);
end;
inc(selPos);
end;
if(selCount = 0) then
begin
// Items are not available to delete!
MessageDlg(Application.Title, srDeleteNoItems, TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], 0);
end
else
begin
if(MessageDlg(Application.Title, srDeleteConfirm, TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = mrYes) then
begin
// Deleting selected alarm configurations!
selPos := 0;
while(selPos < alarmList.Count) do
begin
if((alarmList.Items[selPos] <> nil) and (TfmTimer(alarmList.Items[selPos]).IsSelected())) then
begin
// Remove selected panel.
tmpAlarmItem := TfmTimer(alarmList.Items[selPos]);
FreeAndNil(tmpAlarmItem);
// Remove alarm panel reference from the list.
alarmList.Delete(selPos);
Continue;
end;
inc(selPos);
end;
// Reset value changed flag.
SetChangeFlag((alarmList.Count > 0));
end;
end;
// changed UI button state based on available alarm configurations.
SetButtonState((alarmList.Count > 0));
end;
end;
procedure TfrmMain.btnDisconnectClick(Sender: TObject);
begin
comDrv.Close;
// Update UI controls based on connection status.
SetConnectionState();
end;
procedure TfrmMain.btnInfoClick(Sender: TObject);
var
fmAbout: TfrmAbout;
begin
// Show application version information.
fmAbout := TfrmAbout.Create(self);
fmAbout.ShowModal;
FreeAndNil(fmAbout);
end;
procedure TfrmMain.OpenConfigurationFile(filename: string);
var
dataStream: TMemoryStream;
alarmRecordCount, alarmPos: Word;
alarmRec: TAlarmInfo;
begin
dataStream := TMemoryStream.Create;
channelResetCount := 0;
try
// Clear existing alarm configuration(s).
btnClearClick(nil);
dataStream.LoadFromFile(filename);
// Check for valid file header.
if(dataStream.ReadByte <> FILE_ID_BYTE) then
begin
// Unsupported file type or corrupted file.
raise Exception.Create(srUnsupportedFile);
end;
alarmRecordCount := dataStream.ReadWord();
alarmPos := 0;
if(alarmRecordCount > TimerCount) then
begin
// Only the maximum number of alarm configurations are loading.
alarmRecordCount := TimerCount;
MessageDlg(Application.Title, srMaxLoad, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
end;
while(alarmRecordCount <> alarmPos) do
begin
// Get alarm record from the file.
alarmRec := LoadAlarmInfoFromStream(dataStream);
AddTimer(alarmRec, MaxChannel);
inc(alarmPos);
end;
// Reset value changed flag and UI button state based on available alarm configuration.
SetChangeFlag(false);
SetButtonState((alarmList.Count > 0));
// Set open file name as default file name.
currentFileName := filename;
// Notify channel reset count to the user.
if(channelResetCount > 0) then
begin
MessageDlg(Application.Title, (IntToStr(channelResetCount) + srChannelReset), TMsgDlgType.mtInformation, [TMsgDlgBtn.mbOK], 0);
end;
except on E : Exception do
// File open / read operation has failed!
MessageDlg(Application.Title, (srFileOpenError + LineEnding + E.Message), TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
end;
FreeAndNil(dataStream);
end;
procedure TfrmMain.btnOpenClick(Sender: TObject);
begin
// Check for any unsaved alarm configuration.
if((valueChanged) and (MessageDlg(Application.Title, srUnsavedData, TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = mrNo))then
begin
// Cancel file open operation as selected by user.
exit;
end;
dlgOpenFile.FileName := DEFAULT_FILE_NAME;
dlgOpenFile.InitialDir := ExtractFilePath(currentFileName);
if(dlgOpenFile.Execute()) then
begin
OpenConfigurationFile(dlgOpenFile.FileName);
end;
end;
procedure TfrmMain.btnSaveClick(Sender: TObject);
var
dataStream: TMemoryStream;
resPos: Word;
tmpAlarmInfo: TAlarmInfo;
begin
if(alarmList.Count > 0) then
begin
// Show save file dialog box.
dlgSaveFile.FileName := ExtractFileName(currentFileName);
dlgSaveFile.InitialDir := ExtractFilePath(currentFileName);
if(dlgSaveFile.Execute()) then
begin
// Save alarm configuration into the specified file.
dataStream := TMemoryStream.Create;
// 1. File ID (1 byte)
dataStream.WriteByte(FILE_ID_BYTE);
// 2. Number of alarm records (2 bytes).
dataStream.WriteWord(alarmList.Count);
// 3. Alarm data values.
resPos := 0;
while(resPos < alarmList.Count) do
begin
tmpAlarmInfo := TfmTimer(alarmList.Items[resPos]).GetAlarmInfo();
SaveAlarmInfoToStream(tmpAlarmInfo, dataStream);
Inc(resPos);
end;
try
// Save data stream into the file.
dataStream.SaveToFile(dlgSaveFile.FileName);
SetChangeFlag(false);
// Set open file name as default file name.
currentFileName := dlgSaveFile.FileName;
except on E : Exception do
// File save operation has failed!
MessageDlg(Application.Title, (srFileSaveError + LineEnding + E.Message), TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
end;
FreeAndNil(dataStream);
end;
end;
end;
procedure TfrmMain.btnSetSysTimeClick(Sender: TObject);
begin
if(CheckDeviceConnection())then
begin
// Get system time of the connected device.
GetSystemTime();
end;
end;
procedure TfrmMain.btnSyncClick(Sender: TObject);
var
alarmPos: Word;
tmpAlarmItem: TfmTimer;
begin
if(CheckDeviceConnection())then
begin
// Verify the error state of the alarm configurations.
alarmPos := 0;
while(alarmPos < alarmList.Count)do
begin
tmpAlarmItem := TfmTimer(alarmList.Items[alarmPos]);
if(not tmpAlarmItem.IsValidConfiguration(alNone, 0)) then
begin
// Validation failure detected.
MessageDlg(Application.Title, srInvalidAlarmConfig, TMsgDlgType.mtWarning, [TMsgDlgBtn.mbOK], 0);
exit;
end;
inc(alarmPos);
end;
// Alarm configuration validations are successful. Program current alarm count into device.
currentAlarmPos := 0;
activeAlarmCount := alarmList.Count;
if(activeAlarmCount > TimerCount) then
begin
// Trim alarm count to the maximum limit.
activeAlarmCount := TimerCount;
end;
btnSync.Enabled := false;
SetAlarmCount(activeAlarmCount);
end;
end;
procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
try
// Close serial communication channel.
if(comDrv.Active) then
begin
comDrv.Close;
end;
finally
SetConnectionState();
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
// Create alarm list.
alarmList := TList.Create;
alarmUid := 0;
channelResetCount := 0;
commandDevRetry := 0;
// Setup default data.
valueChanged := false;
currentFileName := DEFAULT_FILE_NAME;
currentDevCmd := CmdNone;
MaxChannel := DEFAULT_CHANNEL_COUNT;
TimerCount := DEFAULT_TIMER_COUNT;
// Register custom clipboard format.
ClipboardRegFormat := RegisterClipboardFormat(CLIPBOARD_FORMAT);
end;
procedure TfrmMain.tmrSerialTimer(Sender: TObject);
var
isIgnoreCommand: Boolean;
payload: string;
begin
tmrSerial.Enabled := false;
// Check for retry limit.
if(commandDevRetry >= DEV_RETRY_COUNT) then
begin
// Stop retry cycle.
commandDevRetry := 0;
// Raise timeout event.
isIgnoreCommand := true;
OnTimeout(currentDevCmd, isIgnoreCommand);
if(not isIgnoreCommand) then
begin
// Continue to command event with timeout flag.
case currentDevCmd of
CmdHandshake:
OnHandShakeComplete(true);
CmdDevInfo:
OnDeviceInfoAvailable(true, '');
CmdGetAlarmCount:
OnGetAlarmCount(true, '');
CmdGetSysTime:
OnGetSystemTime(true, '');
CmdGetStartAlarmTime:
OnGetAlarmStartTime(true, '');
CmdGetEndAlarmTime:
OnGetAlarmEndTime(true, '');
CmdSetAlarmCount:
OnSetAlarmCount(true);
CmdSetSysTime:
OnSetSystemTime(true);
CmdSetStartAlarmTime:
OnSetAlarmStartTime(true);
CmdSetEndAlarmTime:
OnSetAlarmEndTime(true);
end;
end;
// Exit until next timer trigger.
exit;
end;
responseData := responseData + comDrv.ReadData;
// Check for complete response from device.
if(currentDevCmd <> CmdNone) then
begin
// Check for complete response.
if(Length(responseData) < responseLen) then
begin
// Need to wait for complete response.
inc(commandDevRetry);
tmrSerial.Enabled := true;
end
else if(Length(responseData) = responseLen) then
begin
// Complete response is received from device.
commandDevRetry := 0;
payload := Trim(Copy(responseData, (RESP_LEN_HEADER + 1), (Length(responseData) - RESP_LEN_HEADER)));
// Raise command event.
case currentDevCmd of
CmdHandshake:
OnHandShakeComplete(false);
CmdDevInfo:
OnDeviceInfoAvailable(false, payload);
CmdGetAlarmCount:
OnGetAlarmCount(false, payload);
CmdGetSysTime:
OnGetSystemTime(false, payload);
CmdGetStartAlarmTime:
OnGetAlarmStartTime(false, payload);
CmdGetEndAlarmTime:
OnGetAlarmEndTime(false, payload);
CmdSetAlarmCount:
OnSetAlarmCount(false);
CmdSetSysTime:
OnSetSystemTime(false);
CmdSetStartAlarmTime:
OnSetAlarmStartTime(false);
CmdSetEndAlarmTime:
OnSetAlarmEndTime(false);
end;
end;
end;
end;
function TfrmMain.ConvByteToStr(inData: Byte) : string;
begin
result := UpperCase(IntToHex(inData, 2));
end;
procedure TfrmMain.DeviceHandShake();
begin
currentDevCmd := CmdHandshake;
responseLen := RESP_LEN_HANDSHAKE;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_HANDSHAKE);
tmrSerial.Interval := TIME_HANDHSAKE;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.DeviceInfo();
begin
currentDevCmd := CmdDevInfo;
responseLen := RESP_LEN_DEVICE_INFO;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_DEVICE_INFO);
tmrSerial.Interval := TIME_DEVICE_INFO;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.GetAlarmCount();
begin
currentDevCmd := CmdGetAlarmCount;
responseLen := RESP_LEN_GET_ALARM_COUNT;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_GET_ALARM_COUNT);
tmrSerial.Interval := TIME_GET_ALARM_COUNT;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.GetSystemTime();
begin
currentDevCmd := CmdGetSysTime;
responseLen := RESP_LEN_GET_SYS_TIME;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_GET_SYS_TIME);
tmrSerial.Interval := TIME_GET_SYS_TIME;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.GetAlarmStartTime(alarmID : Byte);
begin
currentDevCmd := CmdGetStartAlarmTime;
responseLen := RESP_LEN_GET_START_ALARM_TIME;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_GET_START_ALARM_TIME + ConvByteToStr(alarmID));
tmrSerial.Interval := TIME_GET_START_ALARM_TIME;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.GetAlarmEndTime(alarmID : Byte);
begin
currentDevCmd := CmdGetEndAlarmTime;
responseLen := RESP_LEN_GET_END_ALARM_TIME;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_GET_END_ALARM_TIME + ConvByteToStr(alarmID));
tmrSerial.Interval := TIME_GET_END_ALARM_TIME;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.SetAlarmCount(alarmCount: Byte);
begin
currentDevCmd := CmdSetAlarmCount;
responseLen := RESP_LEN_SET_ALARM_COUNT;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_SET_ALARM_COUNT + ConvByteToStr(alarmCount));
tmrSerial.Interval := TIME_SET_ALARM_COUNT;
tmrSerial.Enabled := true;
end;
procedure TfrmMain.SetSystemTime(year: Byte; month: Byte; date: Byte; hour: Byte; minutes: Byte; seconds: Byte);
begin
currentDevCmd := CmdSetSysTime;
responseLen := RESP_LEN_SET_SYS_TIME;
responseData := '';
commandDevRetry := 0;
// Send data into device and start timeout / response capture timer.
comDrv.WriteData(DEV_CMD_SET_SYS_TIME + ConvByteToStr(year) + ConvByteToStr(month) + ConvByteToStr(date) + ConvByteToStr(hour) + ConvByteToStr(minutes) + ConvByteToStr(seconds));
tmrSerial.Interval := TIME_SET_SYS_TIME;
tmrSerial.Enabled := true;
end;