-
Notifications
You must be signed in to change notification settings - Fork 0
/
LogModule.pas
589 lines (496 loc) · 14.9 KB
/
LogModule.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
unit LogModule;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs, AxisSource;
type
eLogState = (lInActive, lActive, lPaused);
tLogModule = class;
tLogEvent = procedure(Sender: tLogModule) of object;
tLogEventEC = function(Sender: tLogModule): integer of object; //Error code
{ tLogModule }
tLogModule = class
private
fExtension: string;
fOnCreateFile: TLogEvent;
fOnSaveLog: TLogEventEC;
fHeader: string;
fStub: string;
function GetAndResetHeader: string;
protected//???
FOnBeforeStart: TLogEvent;
FOnContinue: TLogEvent;
FOnPause: TLogEvent;
FOnProcessBuffers: TLogEvent;
FOnStop: TLogEvent;
FState: eLogState;
FOnStateChange, FOnStart: TLogEvent;
StartTime, PauseTime, PauseLength: TDateTime;
TimeCS: tRTLCriticalSection;
function GetTime: TDateTime;
procedure SetState(AValue: eLogState);
public
ExperimentLog: TFileStream;
//Data arrays
CoordinateSources: array of TAxisSource;
srcTime: tAxisSource; //not necessarily time, maybe # of point
ReadPoints, ProcessedPoints: longword; //Points read by the working thread, points passed to data arrays
Filename, FilePath: string; //Set FilePath in OnCreateFile
ReadingsThread: TThread; //Assign the working thread to this
ThreadList: TThreadList; //Pass data through this
DataList: TList;
constructor Create;
destructor Destroy; override;
//Methods you should call
procedure GetExperimentNumber;
function CreateFile: integer;
function SaveFile: integer;
procedure Toggle; //convenient for start/pause buttons
procedure Start;
procedure Stop;
procedure Pause;
procedure Continue;
procedure ProcessBuffers;
procedure Clear;
//Set this in OnCreateFile, as well as FilePath
property Stub: string read fStub write fStub; //this is added to file name
property Extension: string read fExtension write fExtension;
property Header: string read GetAndResetHeader write fHeader; //this is written at the top of output file, it is reset every log automatically
//Events you should assign
property OnBeforeStart: TLogEvent read FOnBeforeStart write FOnBeforeStart; //apply settings, init data arrays
property OnStart: TLogEvent read FOnStart write FOnStart; //start threads
property OnPause: TLogEvent read FOnPause write FOnPause;
property OnContinue: TLogEvent read FOnContinue write FOnContinue;
property OnStop: TLogEvent read FOnStop write FOnStop;
property OnCreateFile: TLogEvent read fOnCreateFile write fOnCreateFile; //here you can modify path, timeformat, stub, extension and header
property OnSaveLog: TLogEventEC read fOnSaveLog write fOnSaveLog;
property OnStateChange: TLogEvent read FOnStateChange write FOnStateChange; //to manage interface
property OnProcessBuffers: TLogEvent read FOnProcessBuffers //receive data from threads and pass to data arrays
write FOnProcessBuffers;
property State: eLogState read FState write SetState;
property ElapsedTime: TDateTime read GetTime;
end;
const
DefaultLogFolder = 'Data';
DefaultLogExtension = '.log';
DefaultTimeFormat = 'yyyy_mm_dd';
var
ExperimentNumber: integer = 1;
ReportNumber: integer = 0;
implementation
uses
BaseConF, MainF;
procedure tLogModule.GetExperimentNumber;
var //Filepath + '\'+ datetime + '_' + stub +'_' + reportnumber + '_' + experimentnumber + extension
st, s1, s2: string;
rec: tUnicodeSearchRec;
begin
if Stub <> '' then
st:= '_' + Stub
else
st:= '';
if Config.AutoReport then
begin
if ReportNumber = 0 then //when a new report needs to be formed
begin
inc(ReportNumber);
MainForm.ReportHeader:= true;
str(ReportNumber, s1);
//\/in case stub is emty - no extra '_'
while FindFirst(FilePath + DirectorySeparator + FileName + st + '_' + s1 + '_*' + Extension, faAnyFile, rec) = 0 do
begin
inc(ReportNumber);
str(ReportNumber, s1);
end;
str(ReportNumber, s1);
str(ExperimentNumber, s2);
findClose(rec);
ExperimentNumber:= 1;
end
else
begin
MainForm.ReportHeader:= false;
str(ReportNumber, s1);
str(ExperimentNumber, s2);
while FileExists(FilePath + DirectorySeparator + FileName + st + '_' + s1 + '_' + s2 + Extension) do
begin
inc(ExperimentNumber);
str(ExperimentNumber, s2);
end;
{while FileExists(FilePath + '\' + Stub + '_' + FileName + '_' + s1 + '.txt') or
FileExists(FilePath + '\' + Stub + '_' + FileName + '_' + s1 + '_1' + Extension) do }
end;
end
else
begin
str(ExperimentNumber, s1);
//\/in case stub is emty - no extra '_'
while FileExists(FilePath + DirectorySeparator + FileName + st + '_' + s1 + Extension) do
begin
inc(ExperimentNumber);
str(ExperimentNumber, s1);
end;
end;
end;
{ tLogModule }
function tLogModule.GetAndResetHeader: string;
begin
Result:= fHeader;
fHeader:= '';
end;
{procedure tLogModule.SetTimeFormat(AValue: string);
begin
try
FormatDateTime(AValue, now);
except
on e: Exception do
begin
ShowMessage('Неверный формат даты');
exit
end;
end;
fTimeFormat:= AValue;
end; }
function tLogModule.GetTime: TDateTime;
begin
Result:= Now - StartTime - PauseLength;
end;
procedure tLogModule.SetState(AValue: eLogState);
begin
FState:= AValue;
if Assigned(OnStateChange) then
onStateChange(Self);
end;
constructor tLogModule.Create;
begin
State:= lInActive;
Threadlist:= TThreadList.Create;
FilePath:= DefaultLogFolder;
end;
destructor tLogModule.Destroy;
begin
Clear;
freeandnil(ThreadList);
end;
function tLogModule.CreateFile: integer;
var
s: string; //crutch bc cant do header[1]
begin
if Assigned(OnCreateFile) then
OnCreateFile(Self);
if Header = '' then
Result:= 2
else
Result:= 0;
if Extension = '' then
Extension:= DefaultLogExtension;
if not DirectoryExists(FilePath) then
if not CreateDir(FilePath) then
begin
WriteProgramLog('Ошибка: невозможно создать папку ''' + FilePath + '''');
FilePath:= '';
end;
GetExperimentNumber;
if Stub <> '' then
FileName:= FileName + '_' + Stub;
if Config.AutoReport then
begin
str(ReportNumber, s);
FileName+= '_' + s;
end;
str(ExperimentNumber, s);
FileName+= '_' + s;
Filename+= Extension;
if FilePath <> '' then
FileName:= FilePath + DirectorySeparator + FileName;
try
if FileExists(FileName) then
begin
ShowMessage('Ошибка: файл ''' + FileName + ''' уже существует ');
{if Config.AutoReport then
inc(ReportNumber)
else
inc(ExperimentNumber);}
exit(3);
end;
ExperimentLog:= TFileStream.Create(FileName, fmCreate)
except
on E:Exception do
begin
ShowMessage('Ошибка: файл ''' + FileName + ''' не создан: ' + E.Message);
exit(1);
end;
end;
s:= Header;
if s <> '' then
ExperimentLog.Write(s[1], length(s));
end;
function tLogModule.SaveFile: integer;
begin
if Assigned(OnSaveLog) then
Result:= OnSaveLog(Self)
else
Result:= -3;
freeandnil(ExperimentLog);
end;
procedure tLogModule.Toggle;
begin
case State of
lInActive: Start;
lActive: Pause;
lPaused: Continue;
end;
end;
procedure tLogModule.Start;
var
Res: integer;
begin
if State = lActive then
Stop;
if Assigned(OnBeforeStart) then
OnBeforeStart(Self);
{btStartPauseLog.Caption:= 'Приостановить'; //to an event onbeforestart
WriteProgramLog('Data collection start');
btClearClick(Self);
if Finished or not ReadingsForm.ParamsApplied then //skip if stepf is already going
begin
Cursor:= crHourGlass;
ReadingsForm.btApplyClick(Self);
sleep(ReadingsForm.eDelay.Value);
end;
Cursor:= crDefault;
ReadingMode:= eReadMode(cbReadingsMode.ItemIndex);
case ReadingMode of
rSimultaneous:
begin
if LogFreq and (not cgTransfer.Checked[ReferenceIndex]) and (not UseGenFreq) then //when logfreq set by mainform
begin
if cgTransfer.CheckEnabled[ReferenceIndex] then
cgTransfer.Checked[ReferenceIndex]:= true
else
begin
ShowMessage('Необходимо логирование опорной чатоты');
WriteProgramLog('Data collection could not start: not logging ref');
btStartPauseLog.Caption:= 'Начать снятие';
exit;
end;
cgTransferItemClick(Self, -1);
end;
if not cgTransfer.Enabled then
begin
ShowMessage('Необходимо логирование опорной чатоты');
WriteProgramLog('Data collection could not start: not logging ref');
btStartPauseLog.Caption:= 'Начать снятие';
exit;
end;
LogTime:= true;
if cgTransfer.Checked[ReferenceIndex] and (not LogFreq)
then LogFreq:= true;
j:= 0;
with cgTransfer do
begin
for i:= 0 to high(ReadPars) do
begin
ReadPars[i]:= false;
Params.TransferPars[i]:= false;
if Checked[i] then
begin
ReadPars[i]:= true;
Params.TransferPars[i]:= true;
ParToRead[j]:= i;
inc(j);
end;
end;
end;
for i:= j to high(ParToRead) do
ParToRead[i]:= -1;
setlength(CoordinateSources, cgTransfer.Items.Count);
for j:= 0 to high(ParToRead) do
begin
if ParToRead[j] < 0 then
break;
CoordinateSources[ParToRead[j]]:= TAxisSource.Create(128);
end;
if CH1Index >= 0 then
srcCH1:= CoordinateSources[CH1Index];
if CH2Index >= 0 then
srcCH2:= CoordinateSources[CH2Index];
end;
rBuffer:
begin
LogTime:= true; //???
if LogFreq then
cbUseGenFreq.Checked:= true;
cbUseGenFreqChange(Self);
setlength(CoordinateSources, 2);
CoordinateSources[0]:= TAxisSource.Create(128);
CoordinateSources[1]:= TAxisSource.Create(128);
srcCH1:= CoordinateSources[0];
srcCH2:= CoordinateSources[1];
end;
end;
if LogTime then
srcTime:= TAxisSource.Create(128);
if LogFreq and UseGenFreq then
srcFreq:= TAxisSource.Create(128);
if LogAmpl then
srcAmpl:= TAxisSource.Create(128);
if ReadingMode = rBuffer then
begin
EnterCriticalSection(CommCS);
AddCommand(dStartStorage);
PassCommands;
LeaveCriticalSection(CommCS);
cbChart1Show.ItemIndex:= cbChart1Show.Items.IndexOf(cbCH1.Text);
cbChart2Show.ItemIndex:= cbChart2Show.Items.IndexOf(cbCH2.Text);
end;
if SampleRate <> 0 then
TimeStep:= 1/SampleRate
else
TimeStep:= 1;
UpdateTimer.Interval:= eUpdateInterval.Value;
UpdateTimer.Enabled:= true;
t:= 0;
ReadPoints:= 0;
}
State:= lActive;
Res:= CreateFile;
if Res <> 0 then
begin
WriteProgramLog('Ошибка при создании файла: ' + strf(Res));
State:= lInActive;
if Assigned(ReadingsThread) then
ReadingsThread.Terminate;
if Assigned(OnStop) then
OnStop(Self);
exit;
end;
PauseLength:= 0;
ReadPoints:= 0;
ProcessedPoints:= 0;
StartTime:= Now;
if Assigned(OnStart) then
OnStart(Self);
{case ReadingMode of //onstart
rBuffer:
ReadingsThread:= tBufferThread.Create(PointsInBuffer);
rSimultaneous:
begin
if OnePointPerStep then
ReadingsThread:= nil //Assigned in stepform
else
ReadingsThread:= tSimultaneousThread.Create;
end;
end; }
end;
procedure tLogModule.Stop;
begin
if State = lInActive then
exit;
WriteProgramLog('Data collection end');
if Assigned(ReadingsThread) then
ReadingsThread.Terminate;
if Assigned(OnStop) then
OnStop(Self);
{UpdateTimer.Enabled:= false; to event OnStop
if (ReadingMode = rBuffer) or (Force and (LogState = lInActive)) then
begin
EnterCriticalSection(CommCS);
AddCommand(dResetStorage);
PassCommands;
LeaveCriticalSection(CommCS);
end;
OnePointPerStep:= false;
if LogState <> lInActive then
begin
if Config.AutoReport then
MainForm.ExportParams(false, ReportHeader);
inc(ExperimentNumber);
end;
btStartPauseLog.Caption:= 'Начать снятие';
//btApply.Enabled:= true;
}
if assigned(ReadingsThread) then
ReadingsThread.WaitFor;
ProcessBuffers;
WriteProgramLog('Сохранение - результат: ' + strf(SaveFile));
State:= lInActive;
freeandnil(ExperimentLog);
freeandnil(ReadingsThread);
end;
procedure tLogModule.Pause;
begin
State:= lPaused;
if assigned(ReadingsThread) then
ReadingsThread.Terminate;
PauseTime:= Now;
if Assigned(OnPause) then
OnPause(Self);
{btStartPauseLog.Caption:= 'Продолжить'; //event onpause
WriteProgramLog('Data collection pause');
UpdateTimer.Enabled:= false;
if ReadingMode = rBuffer then
begin
EnterCriticalSection(CommCS);
AddCommand(dPauseStorage);
PassCommands;
LeaveCriticalSection(CommCS);
end; }
if assigned(ReadingsThread) then
ReadingsThread.WaitFor;
ProcessBuffers;
freeandnil(ReadingsThread);
end;
procedure tLogModule.Continue;
begin
{btStartPauseLog.Caption:= 'Приостановить'; //oncontinue
WriteProgramLog('Data collection resume');
UpdateTimer.Enabled:= true;
if ReadingMode = rBuffer then
begin
EnterCriticalSection(CommCS);
AddCommand(dStartStorage);
PassCommands;
LeaveCriticalSection(CommCS);
end;
case ReadingMode of
rBuffer:
ReadingsThread:= tBufferThread.Create(PointsInBuffer);
rSimultaneous:
begin
if OnePointPerStep then
ReadingsThread:= nil //
else
ReadingsThread:= tSimultaneousThread.Create;
end;
end; }
if Assigned(OnContinue) then
OnContinue(Self);
State:= lActive;
PauseLength+= Now - PauseTime;
end;
procedure tLogModule.ProcessBuffers;
begin
DataList:= ThreadList.LockList;
if Assigned(OnProcessBuffers) then
OnProcessBuffers(Self);
ThreadList.UnlockList;
end;
procedure tLogModule.Clear;
var
i: Integer;
begin
if State <> lInActive then
exit;
if Assigned(ThreadList) then
begin
DataList:= ThreadList.LockList;
Datalist.Clear;
ThreadList.UnlockList;
end;
ProcessedPoints:= 0;
freeandnil(srcTime);
for i:= 0 to high(CoordinateSources) do
freeandnil(CoordinateSources[i]);
end;
end.