-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseConF.pas
1759 lines (1558 loc) · 46.6 KB
/
BaseConF.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 BaseConF;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, variants, Controls, Forms, StdCtrls, ComCtrls, DbCtrls, Spin,
ExtCtrls, Buttons, Dialogs, Grids, synaser, tlntsend, blcksock,
{libusboop, libusb,} StatusF, CustomCommandF{, MenuH};
type
tIntegerArray = array of integer;
tStringArray = array of string;
tVariantArray = array of variant;
ConnectAction = (ANo, AQuery, AReset);
eConnectionKind = (cNone = -1, cSerial, cUSB, cTelNet, cVXI);
eDeviceKind = (dGenerator, dDetector, dTempController);
eReadMode = (rBuffer, rSimultaneous, rRealTime);
Buffer = array of double;
pBuffer = ^Buffer;
tSSA = array of ansistring;
pSSA = ^tSSA;
rConfig = record
CfgFolder, WorkConfig, ParamFile, DefaultGens, DefaultDets, DefaultTemps: shortstring;
LoadParamsOnStart, SaveParamsOnExit, AutoReport, AutoComment,
AutoReadingConst, AutoReadingSweep, AutoReadingStep, KeepLog: boolean;
OnConnect: ConnectAction;
ReadingTime: longint;
end;
rParams = record
Amplitude, Offset, Frequency, SweepStartF, SweepStopF, SweepRate, StepStartF,
StepStopF, StepF, StepStartA, StepStopA, StepA, AxisLimit: double;
Impedance, CurrFunc, AmplUnit, SweepType, SweepDir, Modulation, SampleRate, TimeConstant,
Sensitivity, CloseReserve, WideReserve, InputRange,
XAxis, ReadingsMode, Display1, Display2, Ratio1, Ratio2, Show1, Show2: shortint;
ACOn, AutoSweep, GenFreq: boolean;
TransferPars: array [0..19] of boolean;
UpdateInterval, ReadingTime, TimeStep, Delay: longint;
GeneratorPort, DetectorPort, LastGenerator, LastDetector: shortstring;
end;
pDevice = ^tDevice;
tDevice = record
Manufacturer, Model: string;
Commands: tSSA;
ParSeparator, CommSeparator, Terminator, InitString: string;
//Connection: eConnectionKind;
Timeout: longword;
case Connection: eConnectionKind of
// cNone: ();
cSerial: (Parity, StopBits: byte;
SoftFlow, HardFlow: boolean;
BaudRate, DataBits: longword);
cTelNet: (Host, Port: string[15]);
cVXI: (Address: string[32]);
end;
eUnits = (
uNone = -1, uVPeak, uVRms, udBm
);
{ tConnectionForm }
tConnectionForm = class(tForm)
btApply: TButton;
btnConnect: TButton;
btnDisconnect: TButton;
btnTest: TButton;
btQuery: TSpeedButton;
btReset: TSpeedButton;
btStatus: TSpeedButton;
btStop: TButton;
btCustomCommand: TSpeedButton;
cbPortSelect: TComboBox;
seRecvTimeout: TSpinEdit;
Label3: TLabel;
Label8: TLabel;
StatusBar: TStatusBar;//THintRedirStatusBar;
procedure btnConnectClick(Sender: TObject); virtual;
procedure btCustomCommandClick(Sender: TObject);
procedure btnDisconnectClick(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure btQueryClick(Sender: TObject); virtual; abstract;
procedure btResetClick(Sender: TObject);
procedure btStatusClick(Sender: TObject);
protected
DisplayMessages: boolean; //only for connect procedures
procedure CreateSocket(Sender: TObject);
private
TestResult: string;
fTimeOuts: longword;
function GetCurDev: pDevice;
procedure SetTOE(AValue: longword);
public
ConnectionKind: eConnectionKind;
CommCS: tRTLCriticalSection;
SerPort: tBlockSerial;
TelNetClient: tTelNetSend;
//Session: tVisaSession;
//UsbContext : tLibUsbContext;
ParamsApplied: boolean;
CommandString: shortstring;
DeviceIndex: longint;
DeviceKind: eDeviceKind;
SupportedDevices: array of tDevice;
AmplitudeUnits: array [-1..2] of string;
MinDelay, RealTimeWaitPoints: longword;
property TimeOutErrors: longword read fTimeOuts write SetTOE;
property CurrentDevice: pDevice read GetCurDev;
procedure SetCursorAll(Cur: tCursor);
procedure GetSupportedDevices(Kind: eDeviceKind);
procedure GetDeviceParams; virtual; abstract;
procedure InitDevice;
function RequestIdentity(TimeOut: longword): string;
function ConnectSerial: longint; virtual;
function ConnectTelNet: longint; virtual;
function ConnectVXI: longint; virtual;
function ConnectUSB: longint; virtual;
function AutoConnect: longint; virtual;
procedure AfterConnect; virtual;
procedure EnableControls(Enable: boolean); virtual; abstract;
function GetCommandName(c: variant): string;
function CommandSupported(c: variant): boolean;
procedure AddCommand(c: variant{tCommand}; Query: boolean = false);
procedure AddCommand(c: variant{tCommand}; Query: boolean; s: string);
procedure AddCommand(c: variant{tCommand}; Query: boolean; i: longint);
procedure AddCommand(c: variant{tCommand}; Query: boolean; var a: tIntegerArray);
procedure AddCommand(c: variant{tCommand}; Query: boolean; var a: tStringArray);
procedure AddCommand(c: variant{tCommand}; Query: boolean; var a: tVariantArray); //supports ordinal, float, string
procedure AddCommand(c: variant{tCommand}; Query: boolean; x: double; Units: eUnits = uNone);
procedure PassCommands; //Sometimes there's a framing error when communicating with devices. (In call ClearCommError) I added a crutch to synaser to ignore it as it seems not to affect communications
procedure Purge;
function RecvString: string;
function RecvString(TimeOut: longword): string;
procedure SaveState(FileStream: tFileStream);
function RestoreState(FileStream: tFileStream): integer;
function RestoreState(FileName: string): integer;
procedure EnsureValidItemIndices;
end;
procedure WriteProgramLog(Log: string; Force: boolean = false);
procedure WriteProgramLog(i: longint; Force: boolean = false);
procedure WriteProgramLog(i: int64; Force: boolean = false);
procedure WriteProgramLog(d: double; Force: boolean = false);
procedure SeparateIndices(Source: string; sa: TStrings; var ia: tStringArray);
function strf(x: double): string;
function strf(x: longint): string;
function strf(x: int64): string;
function valf(s: string): integer;
function vald(s: string): double;
function CopyFromTo(Origin: string; Start, Stop: string): string;
function CopyFromTo(Origin: string; SearchStart: integer; Start, Stop: string): string;
function CopyDelFromTo(var Origin: string; Start, Stop: string): string;
// function SubstrCount(const aString, aSubstring: string): Integer;
const
iDefaultDevice = 0;
spConnection = 0;
spDevice = 1;
spTimeOuts = 2;
spStatus = 3;
GenCaption = 'Управление генератором';
DetCaption = 'Управление детектором';
TempCaption = 'Управление термоконтроллером';
StartCaption = 'Начать снятие';
PauseCaption = 'Приостановить';
ContinueCaption = 'Продолжить';
IndexDelim = ' - ';
CfgExt = '.cfg';
PrExt = '.pr';
LogExtensions: array[0..2] of string = ('.genlog', '.detlog', '.templog');
ChartZoomFactor = 2;
var
ProgramLog: TFileStream;
LogCS: TRTLCriticalSection;
Config: RConfig;
Params: RParams;
implementation
uses
sockets, LConvEncoding, Math, EditBtn, StrUtils, DeviceF, OptionF, MainF;
function strf(x: double): string; inline;
begin
str(x, Result);
end;
function strf(x: longint): string; inline;
begin
str(x, Result);
end;
function strf(x: int64): string;
begin
str(x, Result);
end;
function valf(s: string): integer; inline;
begin
val(s, Result);
end;
function vald(s: string): double; inline;
begin
val(s, Result);
end;
function CopyFromTo(Origin: string; Start, Stop: string): string;
var
p1, p2: integer;
begin
p1:= Pos(Start, Origin) + 1;
p2:= Pos(Stop, Origin);
Result:= Copy(Origin, p1, p2 - p1);
end;
function CopyFromTo(Origin: string; SearchStart: integer; Start, Stop: string
): string;
var
p1, p2, i, l: integer;
begin
Delete(Origin, 1, SearchStart - 1);
l:= length(Start);
{if l > 1 then
inc(l); }
p1:= Pos(Start, Origin) + l;
//Delete(Origin, 1, p1 - 1);
//p1:= Pos(Start, Origin) + l;
p2:= Pos(Stop, Origin);
i:= 2;
while p2 < p1 do
begin
p2:= NPos(Stop, Origin, i);
inc(i);
if i > 100 then
break;
end;
Result:= Copy(Origin, p1, p2 - p1);
end;
function CopyDelFromTo(var Origin: string; Start, Stop: string): string;
var
p1, p2: integer;
begin
p1:= Pos(Start, Origin) + 1;
p2:= Pos(Stop, Origin);
Result:= Copy(Origin, p1, p2 - p1);
Delete(Origin, 1, p2 + length(Stop) - 1);
end;
{function SubstrCount(const aString, aSubstring: string): Integer;
var
lPosition: Integer;
begin
Result := 0;
lPosition := PosEx(aSubstring, aString);
while lPosition <> 0 do
begin
Inc(Result);
lPosition := PosEx(aSubstring, aString, lPosition + Length(aSubstring));
end;
end; }
procedure WriteProgramLog(Log: string; Force: boolean = false); inline;
begin
if Config.KeepLog or Force then
try
EnterCriticalSection(LogCS);
Log+= LineEnding;
ProgramLog.Write(Log[1], length(Log));
finally
LeaveCriticalSection(LogCS);
end;
end;
procedure WriteProgramLog(i: longint; Force: boolean = false); inline;
begin
WriteProgramLog(strf(i), Force);
end;
procedure WriteProgramLog(i: int64; Force: boolean = false); inline;
begin
WriteProgramLog(strf(i), Force);
end;
procedure WriteProgramLog(d: double; Force: boolean = false); inline;
begin
WriteProgramLog(strf(d), Force);
end;
procedure SeparateIndices(Source: string; sa: TStrings; var ia: tStringArray);
var
s: string;
i: integer;
begin
sa.Clear;
sa.AddText(Source);
setlength(ia, sa.Count);
for i:= 0 to sa.Count - 1 do
begin
s:= sa[i];
if pos(IndexDelim, s) <> 0 then
begin
ia[i]:= CopyDelFromTo(s, '', IndexDelim);
sa[i]:= s;
end
else
begin
ia[i]:= strf(i);
end;
end;
end;
procedure tConnectionForm.btnConnectClick(Sender: TObject);
var
Result: integer;
Crutch: integer absolute Result;
begin
SetCursorAll(crHourGlass);
btnDisconnectClick(Sender);
if cbPortSelect.ItemIndex >= 0 then
begin
if pos('Ethernet', cbPortSelect.Text) <> 0 then
Result:= ConnectTelNet
else
Result:= ConnectSerial;
end;
if ConnectionKind <> cNone then
begin
StatusBar.Panels[spDevice].Text:= CurrentDevice^.Model;
StatusBar.Panels[spStatus].Text:= '';
case DeviceKind of
dGenerator: Caption:= GenCaption + ' ' + CurrentDevice^.Model;
dDetector: Caption:= DetCaption + ' ' + CurrentDevice^.Model;
dTempController: Caption:= TempCaption + ' ' + CurrentDevice^.Model;
end;
end;
if (Result = 0) {$IFDEF D+} or debug {$ENDIF} then
begin
Crutch:= cbPortSelect.ItemIndex; //because it loads port too
GetDeviceParams;
try
if FileExists(MainForm.FullCfgDir + Config.ParamFile) then
RestoreState(MainForm.FullCfgDir + Config.ParamFile)
else
writeprogramlog('File ' + MainForm.FullCfgDir + Config.ParamFile + ' not found');
except
on E: Exception do
ShowMessage(E.Message);
end;
AfterConnect;
cbPortSelect.ItemIndex:= Crutch;
end
else
WriteProgramLog('Подключение - результат: ' + strf(Result));
SetCursorAll(crDefault);
end;
procedure tConnectionForm.btnDisconnectClick(Sender: TObject);
begin
ParamsApplied:= false;
if assigned(SerPort) then
begin
if SerPort.InstanceActive then
begin
SerPort.Purge;
SerPort.CloseSocket;
end;
freeandnil(SerPort);
end;
if assigned(TelNetClient) then
begin
freeandnil(TelNetClient);
end;
EnableControls(false);
ConnectionKind:= cNone;
DeviceIndex:= iDefaultDevice;
StatusBar.Panels[spDevice].Text:= CurrentDevice^.Model; //why? iunno. whats yo case anyway, m8? why do you care? i dont. look at me, im nick wilde and i dont care. just look at how much i dont care. its astonishing. one could even say its un-'care'-cteristic of me to care so little. get it? actually, i dont care if you get it. buzz off. get off ma case, pal! or else!
StatusBar.Panels[spConnection].Text:= 'Нет подключения';
case DeviceKind of
dGenerator: Caption:= GenCaption;
dDetector: Caption:= DetCaption;
dTempController: Caption:= TempCaption;
end;
end;
procedure tConnectionForm.btnTestClick(Sender: TObject);//проверку на правильность настройки
begin
if ConnectionKind = cNone then
begin
ShowMessage('Подключение отсутствует');
exit;
end;
TestResult:= RequestIdentity(seRecvTimeout.Value);
if not IsEmptyStr(TestResult, [' ']) then
ShowMessage('Подключено к ' + TestResult);
end;
procedure tConnectionForm.btStatusClick(Sender: TObject);
begin
if StatusForm.Visible then
StatusForm.Hide;
StatusForm.Form:= pointer(Self);
StatusForm.Show;
end;
procedure tConnectionForm.CreateSocket(Sender: TObject); //this was supposed to solve winxp telnet delay problem
var
Socket: TSocket;
f: longint;
begin
Socket:= TelNetClient.Sock.Socket;
writeprogramlog(Socket);
f:= 1;
f:= fpsetsockopt(Socket, IPPROTO_TCP, TCP_NODELAY, @f, Sizeof(f));
WriteprogramLog(f);
f:= socketerror;
case f of
ESockEBADF: WriteprogramLog('badf');
ESockENOTSOCK: WriteprogramLog('notsock');
ESockEFAULT: WriteprogramLog('fault');
else
WriteprogramLog('err ' + strf(f));
end;
end;
procedure tConnectionForm.btResetClick(Sender: TObject);
begin
Purge;
EnterCriticalSection(CommCS);
AddCommand(cReset);
PassCommands;
LeaveCritiCalSection(CommCS);
end;
procedure tConnectionForm.btCustomCommandClick(Sender: TObject);
begin
if CustomCommandForm.Visible then
CustomCommandForm.Hide;
CustomCommandForm.Form:= pointer(Self);
CustomCommandForm.Show;
end;
procedure tConnectionForm.SetTOE(AValue: longword);
begin
StatusBar.Panels[spTimeouts].Text:= 'Таймаутов: ' + strf(AValue);
WriteProgramLog('Timeout receiving string');
fTimeOuts:= AValue;
end;
procedure tConnectionForm.SetCursorAll(Cur: tCursor);
var
i, j: Integer;
begin
Cursor := Cur;
for i := 0 to ControlCount - 1 do
begin
if (Controls[i].ClassType <> TBitBtn) then
Controls[i].Cursor := Cur;
if Controls[i] is tPanel then
with Controls[i] as tPanel do
begin
for j := 0 to ControlCount - 1 do
begin
if (Controls[j].ClassType <> TBitBtn) then
Controls[j].Cursor := Cur;
// showmessage(Controls[j].name);
end;
end;
end;
end;
function tConnectionForm.GetCurDev: pDevice;
begin
Result:= @SupportedDevices[DeviceIndex];
end;
procedure tConnectionForm.GetSupportedDevices(Kind: eDeviceKind);
var
i, j: integer;
sg: tStringGrid;
begin
case Kind of
dGenerator: sg:= DeviceForm.sgGenCommands;
dDetector: sg:= DeviceForm.sgDetCommands;
dTempController: sg:= DeviceForm.sgTempCommands;
end;
with sg do
begin
setlength(SupportedDevices, ColCount); //0th is defdevice
//idefdev
for i:= 1 to high(SupportedDevices) do
begin
with SupportedDevices[i] do
begin
Manufacturer:= Cells[i, longint(hManufacturer)];
Model:= Cells[i, longint(hModel)];
CommSeparator:= Cells[i, longint(hCommSeparator)];
ParSeparator:= Cells[i, longint(hParSeparator)];
InitString:= Cells[i, longint(hInitString)];
case Cells[i, longint(hTerminator)] of
'CR': Terminator:= CR;
'LF': Terminator:= LF;
'CRLF': Terminator:= CRLF;
end;
TimeOut:= valf(Cells[i, longint(hTimeout)]);
case Cells[i, longint(hInterface)] of
TelnetString:
begin
Connection:= cTelNet;
Host:= Cells[i, longint(hIPAdress)];
Port:= Cells[i, longint(hPort)];
end;
VXIString:
begin
Connection:= cVXI;
Host:= Cells[i, longint(hIPAdress)];
Port:= Cells[i, longint(hPort)];
end;
USBString:
begin
Connection:= cUSB;
end;
SerialString:
begin
Connection:= cSerial;
BaudRate:= valf(Cells[i, longint(hBaudRate)]);
DataBits:= valf(Cells[i, longint(hDataBits)]);
StopBits:= DeviceForm.cbStopBits.Items.IndexOf(Cells[i, integer(hStopBits)]);
Parity:= DeviceForm.cbParity.Items.IndexOf(Cells[i, integer(hParity)]);
case DeviceForm.cbHandshake.Items.IndexOf(Cells[i, integer(hHandshake)]) of
0:
begin
SoftFlow:= false;
HardFlow:= false;
end;
1:
begin
SoftFlow:= true;
HardFlow:= false;
end;
2:
begin
SoftFlow:= false;
HardFlow:= true;
end;
3:
begin
SoftFlow:= true;
HardFlow:= true;
end;
end;
end;
end;
//writeprogramlog(strf(baudrate)+''+ strf(databits)+''+ strf(stopbits));
setlength(Commands, RowCount - SGHeaderLength);
for j:= 0 to RowCount - SGHeaderLength - 1 do
Commands[j]:= Cells[i, j + SGHeaderLength];
{writeprogramlog(model, true); //this checks if commands are matched correctly
for j:= 0 to high(Commands) do
writeProgramLog(getcommandname(j) + ' ' + Commands[j], true);}
end;
end;
end;
end;
procedure tConnectionForm.InitDevice;
var
s: string;
begin
s:= CurrentDevice^.InitString;
if IsEmptyStr(s, [' ']) then
exit;
s+= CurrentDevice^.Terminator;
WriteProgramLog('Строка на устройство ' + TestResult);
WriteProgramLog(s);
WriteProgramLog('');
case ConnectionKind of
//cNone: ;
cSerial:
begin
SerPort.SendString(s); //cts????
end;
cUSB: ;
cTelNet:
begin
end;
cVXI: ;
end;
end;
function tConnectionForm.RequestIdentity(TimeOut: longword): string;
begin
Purge;
case ConnectionKind of
cNone: Result:= '';
cSerial:
begin
if SerPort.InstanceActive then { TODO 3 -cImprovement : unify? }
begin
EnterCriticalSection(CommCS);
AddCommand(cIdentify, true);
PassCommands;
Result:= RecvString(TimeOut);
if Result = '' then
Result:= RecvString(TimeOut);
LeaveCriticalSection(CommCS);
//if SerPort.CanRead(seRecvTimeout.Value) then
end;
end;
cTelNet:
begin
EnterCriticalSection(CommCS);
AddCommand(cIdentify, true);
PassCommands;
Result:= RecvString(TimeOut);
LeaveCriticalSection(CommCS);
end;
cUSB:
begin
end;
cVXI:
begin
EnterCriticalSection(CommCS);
AddCommand(cIdentify, true);
PassCommands;
Result:= RecvString(TimeOut);
LeaveCriticalSection(CommCS);
end;
end;
end;
function tConnectionForm.ConnectSerial: longint;
var
P: char;
i: integer;
s: string;
enc: boolean;
begin
WriteProgramLog('Подключение...');
DeviceIndex:= iDefaultDevice;
TestResult:= '';
ConnectionKind:= cSerial;
SerPort:= TBlockSerial.Create;
SerPort.ConvertLineEnd:= true;
SerPort.DeadLockTimeOut:= 4000;
//SerPort.RaiseExcept:= true;
SerPort.TestDsr:= true;
try
SerPort.Connect(cbPortSelect.Text);
if SerPort.LastError = 0 then
begin
for i:= 1 to high(SupportedDevices) do
begin
DeviceIndex:= i;
SerPort.RaiseExcept:= false; //because this resets in recvstring
with CurrentDevice^ do
if Connection = cSerial then
begin
s:= 'Попытка подключения к ' + Model;
StatusBar.Panels[spStatus].Text:= s;
StatusBar.Update;
WriteProgramLog(s);
case Parity of
0: P:= 'N'; //none, odd, even, mark, space
1: P:= 'O';
2: P:= 'E';
3: P:= 'M';
4: P:= 'S';
end;
SerPort.Config(BaudRate, DataBits, P, StopBits, SoftFlow, HardFlow);
InitDevice;
TestResult:= RequestIdentity(seRecvTimeout.Value);
WriteProgramLog('Ответ устройства: ' + TestResult);
if not IsEmptyStr(TestResult, [' ']) then
begin
if (pos(Manufacturer, TestResult) > 0) and (pos(Model, TestResult) > 0) then
begin
Result:= 0;
WriteProgramLog('Успешно');
break;
end
else
begin
Result:= -2; //not found
DeviceIndex:= iDefaultDevice;
end;
end
else
begin
Result:= -1; //no answer
DeviceIndex:= iDefaultDevice;
end;
end
else
begin
Result:= -3; //none with this interface
DeviceIndex:= iDefaultDevice;
end;
end;
end
else
begin
Result:= -4 //synaser error
end;
if SerPort.InstanceActive and (Result = 0) then
begin
StatusBar.Panels[spConnection].Text:= 'Подключено к ' + cbPortSelect.Text;
Result:= 0;
TimeOutErrors:= 0;
EnableControls(true);
SerPort.RaiseExcept:= true;
case Config.OnConnect of
AQuery: btQueryClick(Self);
AReset: btResetClick(Self);
end;
CurrentDevice^.Port:= cbPortSelect.Text;
CurrentDevice^.TimeOut:= seRecvTimeOut.Value;
end
else
begin
StatusBar.Panels[spConnection].Text:= 'Нет подключения';
case Result of
-1: StatusBar.Panels[spStatus].Text:= 'Устройство не ответило';
-2: StatusBar.Panels[spStatus].Text:= 'Устройство ' + TestResult + ' не опознано';
-3: StatusBar.Panels[spStatus].Text:= 'Нет совместимых устройств - COM';
-4: //problems with encoding from win drivers
begin
s:= SerPort.LastErrorDesc;
s:= ConvertEncodingToUTF8(s, GuessEncoding(s), enc);
StatusBar.Panels[spStatus].Text:= 'Ошибка подключения: ' + s;
end;
end;
if DisplayMessages then
ShowMessage(StatusBar.Panels[spStatus].Text);
WriteProgramLog(StatusBar.Panels[spStatus].Text);
SerPort.CloseSocket;
ConnectionKind:= cNone;
freeandnil(SerPort);
if Result = 0 then
Result:= -5; //this should never happen; instance not active
exit;
end;
except
on E:Exception do
begin
WriteProgramLog(E.Message, true);
WriteProgramLog(SerPort.LastError, true);
WriteProgramLog('LB' + SerPort.LineBuffer, true);
ShowMessage(E.Message);
SerPort.CloseSocket;
ConnectionKind:= cNone;
freeandnil(SerPort);
Result:= -6; //driver error: receive framing error
end;
end;
end;
function tConnectionForm.ConnectTelNet: longint;
var
i: integer;
s: string;
enc: boolean;
begin
DeviceIndex:= iDefaultDevice;
TestResult:= '';
ConnectionKind:= cTelNet;
TelNetClient:= tTelNetSend.Create;
TelNetClient.Sock.RaiseExcept:= false;
try
for i:= 1 to high(SupportedDevices) do
begin
DeviceIndex:= i;
with CurrentDevice^ do
if Connection = cTelNet then
begin
s:= 'Попытка подключения к ' + Model;
StatusBar.Panels[spStatus].Text:= s;
StatusBar.Update;
WriteProgramLog(s);
WriteProgramLog(Host + ':' + Port);
TelNetClient.TermType:= '';
TelNetClient.TargetHost:= Host;
TelNetClient.TargetPort:= Port;
TelNetClient.Timeout:= TimeOut;
//TelNetClient.Sock.OnCreateSocket:= @CreateSocket; no noticable effect
TelNetClient.Login;
InitDevice;
TestResult:= RequestIdentity(seRecvTimeout.Value);
WriteProgramLog('Ответ устройства: ' + TestResult);
if not IsEmptyStr(TestResult, [' ']) then
begin
if (pos(Manufacturer, TestResult) > 0) and (pos(Model, TestResult) > 0) then
begin
Result:= 0;
DeviceIndex:= i;
break;
end
else
begin
Result:= -2; //not found
DeviceIndex:= iDefaultDevice;
end;
end
else
begin
Result:= -1; //no answer
DeviceIndex:= iDefaultDevice;
end;
end
else
begin
Result:= -3; //no compatible devices
DeviceIndex:= iDefaultDevice;
end;
end;
if TelNetClient.Sock.LastError <> 0 then
begin
TelNetClient.Sock.RaiseExcept:= true;
Result:= -4 //synaser error
end;
if Result = 0 then
begin
StatusBar.Panels[spConnection].Text:= CurrentDevice^.Host;
TimeOutErrors:= 0;
EnableControls(true);
TelNetClient.Sock.RaiseExcept:= true;
case Config.OnConnect of
AQuery: btQueryClick(Self);
AReset: btResetClick(Self);
end;
CurrentDevice^.TimeOut:= seRecvTimeOut.Value;
end
else
begin
StatusBar.Panels[spConnection].Text:= 'Нет подключения';
case Result of
-1: StatusBar.Panels[spStatus].Text:= 'Устройство не ответило';
-2: StatusBar.Panels[spStatus].Text:= 'Устройство ' + TestResult + ' не опознано';
-3: StatusBar.Panels[spStatus].Text:= 'Нет совместимых устройств - TelNet';
-4:
begin
s:= TelNetClient.Sock.LastErrorDesc;
s:= ConvertEncodingToUTF8(s, GuessEncoding(s), enc);
StatusBar.Panels[spStatus].Text:= 'Ошибка подключения: ' + s;
end;
end;
if DisplayMessages then
ShowMessage(StatusBar.Panels[spStatus].Text);
WriteProgramLog(StatusBar.Panels[spStatus].Text);
ConnectionKind:= cNone;
freeandnil(TelNetClient);
end;
except
on E:Exception do
begin
WriteProgramLog(E.Message, true);
WriteProgramLog(TelNetClient.Sock.LastError, true);
WriteProgramLog(TelNetClient.Sock.LineBuffer, true);
ShowMessage(E.Message);
TelNetClient.Sock.CloseSocket;
ConnectionKind:= cNone;
freeandnil(TelNetClient);
Result:= -6; //driver error
end;
end;
end;
function tConnectionForm.ConnectVXI: longint;
var
i: integer;
begin
{ DeviceIndex:= iDefaultDevice;
ConnectionKind:= cVXI;
Session:= tVisaSession.Create(nil);
for i:= 1 to high(SupportedDevices) do
with SupportedDevices[i] do
if Connection = cVXI then
begin
WriteProgramLog('Попытка подключения к ' + Manufacturer + ' ' + Model);
Session.Address:= Address;
Session.ConnectTimeout:= Timeout;
Session.Active:= true;
InitDevice;
TestResult:= RequestIdentity;
WriteProgramLog('Ответ устройства: ' + TestResult);
if not IsEmptyStr(TestResult, [' ']) then
if (pos(Manufacturer, TestResult) > 0) and (pos(Model, TestResult) > 0) then
begin
DeviceIndex:= i;
break;
end;
end;
if DeviceIndex <> iDefaultDevice then
begin
StatusBar.Panels[spConnection].Text:= CurrentDevice^.Host;
Result:= 0;
case Config.OnConnect of
AQuery: btQueryClick(Self);
AReset: btResetClick(Self);
end;
CurrentDevice^.TimeOut:= seRecvTimeOut.Value;
end
else
begin
StatusBar.Panels[spStatus].Text:= 'Устройство не опознано';
ShowMessage('Устройство не опознано');
ConnectionKind:= cNone;
freeandnil(Session);
Result:= -1;
end; }
end;
function tConnectionForm.ConnectUSB: longint;
var
i, USBDeviceCount: integer;
// USBDevices: PPlibusb_device ;
//portpath: TDynByteArray;
Address, Bus, Port: byte;
// Descriptor: libusb_device_descriptor;
begin
{DeviceIndex:= iDefaultDevice;
ConnectionKind:= cUSB;