/
adsAsynPortDriver.cpp
4755 lines (4258 loc) · 166 KB
/
adsAsynPortDriver.cpp
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
//#define MCB_DEBUG
/*
* adsAsynPortDriver.cpp
*
* Class derived of asynPortDriver for ADS communication with TwinCAT plcs.
* AdsLib written by Beckhoff is used for communication: https://github.com/Beckhoff/ADS
*
* Author: Anders Sandström
* Edited to add bulk reads: Michael Browne
*
* Created January 25, 2018
* Edited December 6, 2019
*/
#define USE_TYPED_RSET // Shut up about rset already!
#include "adsAsynPortDriver.h"
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <inttypes.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>
#include <sys/time.h>
#include <epicsTypes.h>
#include <epicsTime.h>
#include <epicsThread.h>
#include <epicsString.h>
#include <epicsTimer.h>
#include <iocsh.h>
#include <initHooks.h>
#include <epicsExport.h>
#include <dbStaticLib.h>
#include <dbAccess.h>
#include <alarm.h>
static const char *driverName="adsAsynPortDriver";
static adsAsynPortDriver *adsAsynPortObj;
static long oldTimeStamp=0;
static struct timeval oldTime={0};
static int allowCallbackEpicsState=0;
static initHookState currentEpicsState=initHookAtIocBuild;
/** Callback hook for EPICS state.
* \param[in] state EPICS state
* \return void
* Will be called be the EPICS framework with the current EPICS state as it changes.
*/
static void getEpicsState(initHookState state)
{
const char* functionName = "getEpicsState";
static struct timeval start;
struct timeval now, diff;
if(!adsAsynPortObj){
printf("%s:%s: ERROR: adsAsynPortObj==NULL\n", driverName, functionName);
return;
}
asynUser *asynTraceUser=adsAsynPortObj->getTraceAsynUser();
switch(state) {
break;
case initHookAfterInitDevSup:
gettimeofday(&start, NULL);
break;
case initHookAfterInitDatabase:
gettimeofday(&now, NULL);
timersub(&now, &start, &diff);
printf("Database initialization took %ld.%05ld seconds.\n", diff.tv_sec, (long)diff.tv_usec);
break;
case initHookAfterScanInit:
allowCallbackEpicsState=1;
//make all callbacks if data arrived from callback before interrupts were registered (before allowCallbackEpicsState==1)
if(!adsAsynPortObj){
printf("%s:%s: ERROR: adsAsynPortObj==NULL\n", driverName, functionName);
return;
}
adsAsynPortObj->fireAllCallbacksLock();
adsAsynPortObj->bulkOK = 1;
printf("Begin polling PLC!\n");
break;
default:
break;
}
currentEpicsState=state;
asynPrint(asynTraceUser, ASYN_TRACEIO_DRIVER , "%s:%s: EPICS state: %s (%d). Allow ADS callbacks: %s.\n", driverName, functionName,epicsStateToString((int)state),(int)state,allowCallbackEpicsState ? "true" : "false");
}
/** Register EPICS hook function
* \return void
*/
int initHook(void)
{
return(initHookRegister(getEpicsState));
}
/** Callback from ads lib for symbols changed in PLC.
* \param[in] pAddr AmsAddr of the system generating the callback.
* \param[in] pNotification Data structure containing the updated data and timestamp information.
* \param[in] hUser Identification index of the callback parameter.
* \return void
* This function will be called by the ADS lib if the symbol version in the PLC is changed.
*/
static void adsSymbolsChangedCallback(const AmsAddr* pAddr, const AdsNotificationHeader* pNotification, uint32_t hUser)
{
const char* functionName = "adsSymbolsChangedCallback";
if(!adsAsynPortObj){
printf("%s:%s: ERROR: adsAsynPortObj==NULL\n", driverName, functionName);
return;
}
asynUser *asynTraceUser=adsAsynPortObj->getTraceAsynUser();
asynPrint(asynTraceUser, ASYN_TRACE_INFO , "%s:%s: Symbols changed for Ams-port %u.\n", driverName, functionName,pAddr->port);
adsAsynPortObj->invalidateParamsLock(pAddr->port);
adsAsynPortObj->refreshParamsLock(pAddr->port);
}
/** Callback from ads lib for updated data.
* \param[in] pAddr AmsAddr of the system generating the callback.
* \param[in] pNotification Data structure containing the updated data and timestamp information.
* \param[in] hUser Identification index of the callback parameter.
* \return void
* This function will be called by the ADS lib when a registered parameter is updated (changed in PLC).
*/
static void adsDataCallback(const AmsAddr* pAddr, const AdsNotificationHeader* pNotification, uint32_t hUser)
{
const char* functionName = "adsDataCallback";
if(!adsAsynPortObj){
printf("%s:%s: ERROR: adsAsynPortObj==NULL\n", driverName, functionName);
return;
}
asynUser *asynTraceUser=adsAsynPortObj->getTraceAsynUser();
asynPrint(asynTraceUser, ASYN_TRACEIO_DRIVER , "%s:%s:\n", driverName, functionName);
const uint8_t* data = reinterpret_cast<const uint8_t*>(pNotification + 1);
struct timeval newTime;
gettimeofday(&newTime, NULL);
asynPrint(asynTraceUser, ASYN_TRACEIO_DRIVER,"TIME %ld.%06ld\n",(long) newTime.tv_sec, (long) newTime.tv_usec);
long secs_used=(newTime.tv_sec - oldTime.tv_sec); //avoid overflow by subtracting first
long micros_used= ((secs_used*1000000) + newTime.tv_usec) - (oldTime.tv_usec);
oldTime=newTime;
//Ensure hUser is within range
if(hUser>(uint32_t)(adsAsynPortObj->getParamTableSize()-1)){
asynPrint(asynTraceUser, ASYN_TRACE_ERROR, "%s:%s: hUser out of range: %u.\n", driverName, functionName,hUser);
return;
}
//Get paramInfo
adsParamInfo *paramInfo=adsAsynPortObj->getAdsParamInfo(hUser);
if(!paramInfo){
asynPrint(asynTraceUser, ASYN_TRACE_ERROR, "%s:%s: getAdsParamInfo() for hUser %u failed\n", driverName, functionName,hUser);
return;
}
asynPrint(asynTraceUser, ASYN_TRACEIO_DRIVER,"Callback for parameter %s (%d).\n",paramInfo->drvInfo,paramInfo->paramIndex);
asynPrint(asynTraceUser, ASYN_TRACEIO_DRIVER,"hUser 0x%x, data size[b]: %d.\n", hUser,pNotification->cbSampleSize);
asynPrint(asynTraceUser, ASYN_TRACEIO_DRIVER,"time stamp [100ns]: %" PRIuMAX ", since last plc [ms]: %4.2lf, since last ioc [ms]: %4.2lf.\n",
(uintmax_t)pNotification->nTimeStamp,
((double)(pNotification->nTimeStamp-oldTimeStamp))/10000.0,
(((double)(micros_used))/1000.0));
oldTimeStamp=pNotification->nTimeStamp;
//Ensure hUser is equal to parameter index
if(hUser!=(uint32_t)(paramInfo->paramIndex)){
asynPrint(asynTraceUser, ASYN_TRACE_ERROR, "%s:%s: hUser not equal to parameter index (%u vs %d).\n", driverName, functionName,hUser,paramInfo->paramIndex);
return;
}
paramInfo->plcTimeStampRaw=pNotification->nTimeStamp;
paramInfo->lastCallbackSize=pNotification->cbSampleSize;
adsAsynPortObj->adsUpdateParameterLock(paramInfo,data);
}
/** Start cyclic thread for supervision of connection.
* \param[in] drvPvt adsAsynPortDriver object
* \return void
*/
void cyclicThread(void *drvPvt)
{
adsAsynPortDriver *pPvt = (adsAsynPortDriver *)drvPvt;
pPvt->cyclicThread();
}
/** Start bulk read thread.
* \param[in] drvPvt adsAsynPortDriver object
* \return void
*/
void bulkReadThread(void *drvPvt)
{
adsAsynPortDriver *pPvt = (adsAsynPortDriver *)drvPvt;
pPvt->bulkReadThread();
}
/** Constructor for the adsAsynPortDriver class.
* \param[in] portName Asyn port name.
* \param[in] ipAddr Ip address of PLC.
* \param[in] amsaddr Ams Address of PLC.
* \param[in] amsport Default amsport in PLC (851 for first PLC).
* \param[in] paramTableSize Maximum parameter/varaiable count.
* \param[in] priority Asyn prio.
* \param[in] autoConnect Enable auto connect.
* \param[in] defaultSampleTimeMS Default sample of varaible (PLC ams router
* checks if variable changed, if changed then add to send buffer).
* \param[in] maxDelayTimeMS Maximum delay before variable that has changed is
* sent to client (linux). The variable can also be sent sooner if the
* ams router send buffer is filled.
* \param[in] defaultTimeSource Default time stamp source of changed variable:\n
* defaultTimeSource=PLC: The PLC time stamp from when the value was
* changedis used and set as timestamp in the EPICS record
* (if record TSE field is set to -2 (enable asyn timestamp)).
* This is the preferred setting.\n
* defaultTimeSource=EPICS: The time stamp will be made when the
* updated data arrives in the EPCIS client.\n
* Initializes all variables and tries to connect to PLC system.
*/
adsAsynPortDriver::adsAsynPortDriver(const char *portName,
const char *ipaddr,
const char *amsaddr,
unsigned int amsport,
int paramTableSize,
unsigned int priority,
int autoConnect,
int defaultSampleTimeMS,
int maxDelayTimeMS,
int adsTimeoutMS,
ADSTIMESOURCE defaultTimeSource)
:asynPortDriver(portName,
1, /* maxAddr */
#ifndef NO_ADS_ASYN_ASYNPARAMINT64
asynInt64Mask |
#endif
asynInt32Mask | asynFloat64Mask | asynFloat32ArrayMask | asynFloat64ArrayMask | asynDrvUserMask | asynOctetMask | asynInt8ArrayMask | asynInt16ArrayMask | asynInt32ArrayMask, /* Interface mask */
#ifndef NO_ADS_ASYN_ASYNPARAMINT64
asynInt64Mask |
#endif
asynInt32Mask | asynFloat64Mask | asynFloat32ArrayMask | asynFloat64ArrayMask | asynDrvUserMask | asynOctetMask | asynInt8ArrayMask | asynInt16ArrayMask | asynInt32ArrayMask, /* Interrupt mask */
ASYN_CANBLOCK, /* asynFlags. This driver does not block and it is not multi-device, so flag is 0 */
autoConnect, /* Autoconnect */
priority, /* Default priority */
0) /* Default stack size*/
{
const char* functionName = "adsAsynPortDriver";
//Extra Debugging from the beginning: pasynTrace->setTraceMask(pasynUserSelf, 0x11);
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s:\n", driverName, functionName);
pAdsParamArray_= new adsParamInfo*[paramTableSize];
memset(pAdsParamArray_,0,sizeof(*pAdsParamArray_));
adsParamArrayCount_=0;
paramTableSize_=paramTableSize;
ipaddr_=strdup(ipaddr);
amsaddr_=strdup(amsaddr);
amsportDefault_=amsport;
priority_=priority;
autoConnect_=autoConnect;
defaultSampleTimeMS_=defaultSampleTimeMS;
defaultMaxDelayTimeMS_=maxDelayTimeMS;
adsTimeoutMS_=adsTimeoutMS;
connectedAds_=0;
defaultTimeSource_=defaultTimeSource;
routeAdded_=0;
notConnectedCounter_ = 0;
oneAmsConnectionOKold_=0;
//Octet interface
octetAsciiBuffer_.bufferSize = ADS_CMD_BUFFER_SIZE;
octetAsciiBuffer_.bytesUsed=0;
memset(&octetBinaryBuffer_,0,ADS_CMD_BUFFER_SIZE);
octetReturnVarName_=0;
//ADS
adsPort_=0; //handle
remoteNetId_={0,0,0,0,0,0};
amsPortList_.clear();
if(amsportDefault_<=0){
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Invalid default AMS port: %d\n", driverName, functionName,amsportDefault_);
return;
}
addNewAmsPortToList(amsportDefault_);
int nvals = sscanf(amsaddr_, "%hhu.%hhu.%hhu.%hhu.%hhu.%hhu",
&remoteNetId_.b[0],
&remoteNetId_.b[1],
&remoteNetId_.b[2],
&remoteNetId_.b[3],
&remoteNetId_.b[4],
&remoteNetId_.b[5]);
if(nvals!=6){
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: AMS address invalid %s.\n", driverName, functionName,amsaddr_);
return;
}
if (nvals != 6) {
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Invalid AMS address: %s\n", driverName, functionName,amsaddr_);
return;
}
if(paramTableSize_<1){ //If paramTableSize_==1 then only stream device or motor record can use the driver through the "default access" param below.
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: Param table size to small: %d\n", driverName, functionName,paramTableSize_);
return;
}
//Add first param for other access (like motor record or stream device).
int index;
asynStatus status=createParam("Default access",asynParamNotDefined,&index);
if(status!=asynSuccess){
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: createParam for default access failed.\n", driverName, functionName);
return;
}
adsParamInfo *paramInfo=new adsParamInfo();
memset(paramInfo,0,sizeof(adsParamInfo));
paramInfo->recordName=strdup("Any record");
paramInfo->recordType=strdup("No type");
paramInfo->scan=strdup("No scan");
paramInfo->dtyp=strdup("No dtyp");
paramInfo->inp=strdup("No inp");
paramInfo->out=strdup("No out");
paramInfo->drvInfo=strdup("No drvinfo");
paramInfo->asynType=asynParamNotDefined;
paramInfo->paramIndex=index; //also used as hUser for ads callback
paramInfo->plcAdrStr=strdup("No adr str");
pAdsParamArray_[0]=paramInfo;
adsParamArrayCount_++;
if(status!=asynSuccess){
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "%s:%s: createParam for default access failed.\n", driverName, functionName);
return;
}
//* Create the thread that computes the waveforms in the background */
status = (asynStatus)(epicsThreadCreate("adsAsynPortDriverCyclicThread",
epicsThreadPriorityMedium,
epicsThreadGetStackSize(epicsThreadStackMedium),
(EPICSTHREADFUNC)::cyclicThread,this) == NULL);
if(status){
printf("%s:%s: epicsThreadCreate failure\n", driverName, functionName);
return;
}
for (int i = 0; i < MAXBULK; i++)
bulk[i].cnt = 0; // Entry is currently unused!!
bulkTScnt = 0;
if (defaultSampleTimeMS_ < 1000) {
printf("Default Sample Time of %d ms is too small, defaulting to 1Hz.\n",
defaultSampleTimeMS_);
bulk_delay_us = 1000000; // 1 Hz
} else {
printf("Default bulk read time: %d ms\n", defaultSampleTimeMS_);
bulk_delay_us = defaultSampleTimeMS_ * 1000;
}
bulkdatasize = 4 * 1024 * 1024; // This is excessive!
bulkdata = (uint8_t *) malloc(bulkdatasize);
bulkOK = 0;
bulk_elapsed_us = 0;
//* Create the thread that does the bulk reads */
status = (asynStatus)(epicsThreadCreate("adsAsynPortDriverBulkReadThread",
epicsThreadPriorityMedium,
epicsThreadGetStackSize(epicsThreadStackMedium),
(EPICSTHREADFUNC)::bulkReadThread,this) == NULL);
if(status){
printf("%s:%s: epicsThreadCreate failure\n", driverName, functionName);
return;
}
//try to connect, and hang until we succeed!
for (;;) {
if (connect(pasynUserSelf) != asynSuccess) {
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
"%s:%s: connect failed for port %s.\n",
driverName, functionName, portName);
epicsThreadSleep(1.0);
continue;
}
long error = 0;
uint16_t adsState = 0;
if (adsReadStateLock(amsport,&adsState,true,&error) != asynSuccess) {
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
"%s:%s: adsReadStateLock failed for port %s.\n",
driverName, functionName, portName);
disconnect(pasynUserSelf);
continue;
}
if (adsState == ADSSTATE_RUN) {
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
"%s:%s: connection established for port %s.\n",
driverName, functionName, portName);
return;
}
}
}
/** Destructor for the adsAsynPortDriver class.
* Cleanup and deallocation of variables.
*/
adsAsynPortDriver::~adsAsynPortDriver()
{
const char* functionName = "~adsAsynPortDriver";
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s:\n", driverName, functionName);
free(ipaddr_);
free(amsaddr_);
for(int i=0;i<adsParamArrayCount_;i++){
if(!pAdsParamArray_[i]){
continue;
}
adsDelDataCallback(pAdsParamArray_[i],true); //Block error messages
adsReleaseSymbolicHandle(pAdsParamArray_[i],true); //Block error messages
free(pAdsParamArray_[i]->recordName);
free(pAdsParamArray_[i]->recordType);
free(pAdsParamArray_[i]->scan);
free(pAdsParamArray_[i]->dtyp);
free(pAdsParamArray_[i]->inp);
free(pAdsParamArray_[i]->out);
free(pAdsParamArray_[i]->drvInfo);
free(pAdsParamArray_[i]->plcAdrStr);
if(pAdsParamArray_[i]->plcDataIsArray){
free(pAdsParamArray_[i]->arrayDataBuffer);
}
delete pAdsParamArray_[i];
}
delete pAdsParamArray_;
for(amsPortInfo *port : amsPortList_){
delete port;
}
}
/** Cyclic thread for supervision of connection.
* \return void
* Check ads state of all connected ams ports and reconnects if needed.
* At reconnect all symbolic handles and callbacks will be reregistered.
*/
void adsAsynPortDriver::cyclicThread()
{
const char* functionName = "cyclicThread";
double sampleTime=0.5;
while (1){
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s: Sample time [s]= %lf.\n",driverName,functionName,sampleTime);
epicsThreadSleep(sampleTime);
if(!allowCallbackEpicsState){
continue; //Epics not started
}
uint16_t adsState=0;
//Check state of all used ams ports
bool oneAmsConnectionOK=false;
if(connectedAds_){
for(amsPortInfo *port : amsPortList_){
long error=0;
asynStatus stat=adsReadStateLock(port->amsPort,&adsState,true,&error);
bool portConnected=(stat==asynSuccess && adsState == ADSSTATE_RUN);
port->adsStateOld=port->adsState;
if(stat==asynSuccess){
port->adsState=(ADSSTATE)adsState;
}
else{
port->adsState=ADSSTATE_INVALID;
}
port->connectedOld=port->connected;
port->connected=portConnected;
port->paramsOK=portConnected;
oneAmsConnectionOK=oneAmsConnectionOK || portConnected;
if(port->connected && port->refreshNeeded){
refreshParamsLock(port->amsPort);
}
if(port->connectedOld && !port->connected){
invalidateParamsLock(port->amsPort);
port->refreshNeeded=true;
setAlarmPortLock(port->amsPort,COMM_ALARM,INVALID_ALARM);
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,
"%s:%s: connection failed for port %s.\n",
driverName, functionName, portName);
exit(-1);
}
if(!port->connectedOld && port->connected){
adsReadVersion(port);
}
}
}
//Printout state status
for(amsPortInfo *port : amsPortList_){
if(port->connectedOld!=port->connected){
asynPrint(pasynUserSelf, ASYN_TRACE_INFO,"%s:%s: Device \"%s\" %s (Ams-port %u, Ams router version %u.%u.%u).\n",driverName,functionName,port->devName,port->connected ? "connected" : "disconnected",port->amsPort,port->version.version,port->version.revision,port->version.build);
}
if(port->adsStateOld!=port->adsState){
//If Ams-router is a asyn paramter then update
if(port->paramInfo){
if(port->paramInfo->dataSource==ADS_DATASOURCE_AMS_STATE){
void * pData=(void *)&port->adsState;
adsUpdateParameterLock(port->paramInfo,pData,2);
}
}
asynPrint(pasynUserSelf, ASYN_TRACE_INFO,"%s:%s: Ams-port, %u, state change: \"%s\" -> \"%s\".\n",driverName,functionName,port->amsPort,adsStateToString(port->adsStateOld),adsStateToString(port->adsState));
}
}
if(!oneAmsConnectionOK){
notConnectedCounter_++;
if (notConnectedCounter_ < 100 || notConnectedCounter_ % 100 == 0) {
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s: Not connected counter: %d.\n",driverName,functionName,notConnectedCounter_);
}
}
if(oneAmsConnectionOK){
notConnectedCounter_=0;
}
if(!oneAmsConnectionOK && autoConnect_){
if(oneAmsConnectionOKold_){
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR,"%s:%s: No connection! Try to reconnect...\n",driverName,functionName);
}
connectedAds_=0;
if((notConnectedCounter_&2)==2){
asynPrint(pasynUserSelf, ASYN_TRACE_ERROR, "cyclicThread: forcing disconnect.\n");
disconnectLock(pasynUserSelf);
}
}
oneAmsConnectionOKold_=oneAmsConnectionOK;
}
}
/* TBD - Poll at different rates depending on pollClass! */
void adsAsynPortDriver::bulkReadThread()
{
const char* functionName = "bulkReadThread";
struct timeval start, now;
uint32_t bytesRead;
long status;
uint32_t cnt, readSize;
asynUser *asynTraceUser=getTraceAsynUser();
gettimeofday(&now, NULL);
while (1) {
start = now;
adsLock();
for (int i = 0; bulk[i].cnt; i++) {
if (!bulkOK || !bulk[i].cnt) {
break;
}
#ifdef MCB_DEBUG
static int first = 1;
if (first) {
printf("Starting to poll!\n");
first = 0;
}
#endif
bytesRead = 0;
cnt = bulk[i].cnt;
readSize = bulk[i].readSize;
AmsAddr amsServer={remoteNetId_,bulk[i].amsPort};
status = AdsSyncReadWriteReqEx2(adsPort_, &amsServer,
ADSIGRP_SUMUP_READ, cnt,
readSize, bulkdata,
sizeof(bulk[i].sum[0]) * cnt, &bulk[i].sum,
&bytesRead);
if (status) {
printf("Sum read %d failed: status %ld\n", i, status);
continue;
}
uint32_t *stat = (uint32_t *)bulkdata;
uint8_t *srd = bulkdata + cnt * sizeof(uint32_t);
uint64_t nTimeStamp = 0;
/* The first *two* bulk parameters might be the timestamp! */
if (!stat[0] && !stat[1] && bulk[i].sum[0].iGroup == ADSIGRP_SYM_VALBYHND) {
nTimeStamp = ((uint32_t *)srd)[0];
nTimeStamp = (nTimeStamp << 32) | ((uint32_t *)srd)[1];
} else {
/*
* Sigh. now has the time since 1970-01-01 00:00:00 UTC, but
* we want 100ns increments since 1601-01-01!! So we grab the constant
* from adsAsynPortDriverUtils.cpp and convert.
*/
#define SEC_TO_UNIX_EPOCH 11644473600LL
nTimeStamp = now.tv_sec + SEC_TO_UNIX_EPOCH;
nTimeStamp = (nTimeStamp * 1000000 + now.tv_usec) * 10;
}
if (!stat[0])
srd += sizeof(uint32_t);
if (!stat[1])
srd += sizeof(uint32_t);
stat += 2;
for (uint32_t j = 2; j < cnt; j++) {
adsParamInfo *paramInfo=getAdsParamInfo(bulk[i].paramID[j]);
if (!paramInfo){
asynPrint(asynTraceUser, ASYN_TRACE_ERROR,
"%s:%s: getAdsParamInfo() for hUser %u failed\n",
driverName, functionName, bulk[i].paramID[j]);
continue;
}
if (*stat++) {
asynPrint(asynTraceUser, ASYN_TRACE_ERROR,
"%s:%s: bulk read for %s (%d) failed\n",
driverName, functionName, paramInfo->drvInfo, j);
continue;
}
paramInfo->plcTimeStampRaw=nTimeStamp;
paramInfo->lastCallbackSize=paramInfo->plcSize;
adsUpdateParameter(paramInfo, srd);
srd += paramInfo->lastCallbackSize;
}
}
adsUnlock();
gettimeofday(&now, NULL);
bulk_elapsed_us = (now.tv_sec - start.tv_sec) * 1000000 +
(now.tv_usec - start.tv_usec);
#ifdef MCB_DEBUG
printf("ELAPSED: %g\n", bulk_elapsed_us / 1000000.0);
#endif
if (bulk_elapsed_us < bulk_delay_us) {
usleep(bulk_delay_us - bulk_elapsed_us);
gettimeofday(&now, NULL);
}
}
}
/** Report of configured parameters.
* \param[in] fp Output file.
* \param[in] details Details of printout. A higher number results in more
* details.
* \return void
* Check ads state of all connected ams ports and reconnects if needed.
*/
void adsAsynPortDriver::report(FILE *fp, int details)
{
const char* functionName = "report";
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s:\n", driverName, functionName);
if(!fp){
fprintf(fp,"%s:%s: ERROR: File NULL.\n", driverName, functionName);
return;
}
if (details >= 1) {
fprintf(fp, "General information:\n");
fprintf(fp, " Port: %s\n",portName);
fprintf(fp, " Ip-address: %s\n",ipaddr_);
fprintf(fp, " Ams-address: %s\n",amsaddr_);
fprintf(fp, " Default Ams-port : %d\n",amsportDefault_);
fprintf(fp, " Auto-connect: %s\n",autoConnect_ ? "true" : "false");
fprintf(fp, " Priority: %d\n",priority_);
fprintf(fp, " Param. table size: %d\n",paramTableSize_);
fprintf(fp, " Param. count: %d\n",adsParamArrayCount_);
fprintf(fp, " ADS command timeout [ms]: %d\n",adsTimeoutMS_);
fprintf(fp, " Default sample time [ms] %d\n",defaultSampleTimeMS_);
fprintf(fp, " Default max delay time [ms]: %d\n",defaultMaxDelayTimeMS_);
fprintf(fp, " Default time source: %s\n",(defaultTimeSource_==ADS_TIME_BASE_PLC) ? ADS_OPTION_TIMEBASE_PLC : ADS_OPTION_TIMEBASE_EPICS);
fprintf(fp, " NOTE: Several records can be linked to the same parameter.\n");
fprintf(fp,"\n");
}
if(details>=2){
//print all parameters
fprintf(fp,"Parameter details:\n");
for(int i=0; i<adsParamArrayCount_;i++){
if(!pAdsParamArray_[i]){
fprintf(fp,"%s:%s: ERROR: Parameter array null at index %d\n", driverName, functionName,i);
return;
}
adsParamInfo *paramInfo=pAdsParamArray_[i];
fprintf(fp," Parameter %d:\n",i);
if(i==0){
fprintf(fp," Parameter 0 (pasynUser->reason==0) is reserved for Asyn octet interface (Motor Record and Stream Device access).\n");
fprintf(fp,"\n");
continue;
}
fprintf(fp," Param name: %s\n",paramInfo->drvInfo);
fprintf(fp," Param index: %d\n",paramInfo->paramIndex);
fprintf(fp," Param type: %s (%d)\n",asynTypeToString((long)paramInfo->asynType),paramInfo->asynType);
fprintf(fp," Param sample time [ms]: %lf\n",paramInfo->sampleTimeMS);
fprintf(fp," Param max delay time [ms]: %lf\n",paramInfo->maxDelayTimeMS);
fprintf(fp," Param isIOIntr: %s\n",paramInfo->isIOIntr ? "true" : "false");
fprintf(fp," Param asyn addr: %d\n",paramInfo->asynAddr);
fprintf(fp," Param time source: %s\n",(paramInfo->timeBase==ADS_TIME_BASE_PLC) ? ADS_OPTION_TIMEBASE_PLC : ADS_OPTION_TIMEBASE_EPICS);
fprintf(fp," Param plc time: %us:%uns\n",paramInfo->plcTimeStamp.secPastEpoch,paramInfo->plcTimeStamp.nsec);
fprintf(fp," Param epics time: %us:%uns\n",paramInfo->epicsTimestamp.secPastEpoch,paramInfo->epicsTimestamp.nsec);
fprintf(fp," Param array buffer alloc: %s\n",paramInfo->arrayDataBuffer ? "true" : "false");
fprintf(fp," Param array buffer size: %lu\n",paramInfo->arrayDataBufferSize);
fprintf(fp," Param alarm: %d\n",paramInfo->alarmStatus);
fprintf(fp," Param severity: %d\n",paramInfo->alarmSeverity);
fprintf(fp," Param data source: %s\n",paramInfo->dataSource==ADS_DATASOURCE_PLC ? "PLC" : "DRIVER");
fprintf(fp," Plc ams port: %d\n",paramInfo->amsPort);
fprintf(fp," Plc adr str: %s\n",paramInfo->plcAdrStr);
fprintf(fp," Plc adr str is ADR cmd: %s\n",paramInfo->isAdrCommand ? "true" : "false");
fprintf(fp," Plc abs adr valid: %s\n",paramInfo->plcAbsAdrValid ? "true" : "false");
fprintf(fp," Plc abs adr group: 16#%x\n",paramInfo->plcAbsAdrGroup);
fprintf(fp," Plc abs adr offset: 16#%x\n",paramInfo->plcAbsAdrOffset);
fprintf(fp," Plc data type: %s\n",adsTypeToString(paramInfo->plcDataType));
fprintf(fp," Plc data type size: %zu\n",adsTypeSize(paramInfo->plcDataType));
fprintf(fp," Plc data size: %u\n",paramInfo->plcSize);
fprintf(fp," Plc data is array: %s\n",paramInfo->plcDataIsArray ? "true" : "false");
fprintf(fp," Plc data type warning: %s\n",paramInfo->plcDataTypeWarn ? "true" : "false");
fprintf(fp," Ads hCallbackNotify: %u\n",paramInfo->hCallbackNotify);
fprintf(fp," Ads CallbackNotify valid: %s\n",paramInfo->bCallbackNotifyValid ? "true" : "false");
fprintf(fp," Ads hSymbHndle: %u\n",paramInfo->hSymbolicHandle);
fprintf(fp," Ads hSymbHndleValid: %s\n",paramInfo->bSymbolicHandleValid ? "true" : "false");
fprintf(fp," Record name: %s\n",paramInfo->recordName);
fprintf(fp," Record type: %s\n",paramInfo->recordType);
fprintf(fp," Record dtyp: %s\n",paramInfo->dtyp);
fprintf(fp,"\n");
}
}
}
/** Disconencts the PLC with asyn lock.
* \param[in] pasynUser Asyn user.
* \return asynSuccess or asynError.
* Thread safe.
*/
asynStatus adsAsynPortDriver::disconnectLock(asynUser *pasynUser)
{
lock();
asynStatus stat=disconnect(pasynUser);
unlock();
return stat;
}
/** Disconencts the PLC.
* \param[in] pasynUser Asyn user.
* \return asynSuccess or asynError.
*/
asynStatus adsAsynPortDriver::disconnect(asynUser *pasynUser)
{
const char* functionName = "disconnect";
asynPrint(pasynUser, ASYN_TRACE_FLOW, "%s:%s:\n", driverName, functionName);
asynStatus disconnectStatus=adsDisconnect();
if (disconnectStatus){
return asynError;
}
return asynPortDriver::disconnect(pasynUser);
}
/** Refreshes the parameters that need refresh after a reconnect or a
* connection failure to a ams port.
* \return asynSuccess or asynError.
*/
asynStatus adsAsynPortDriver::refreshParams()
{
return refreshParams(0);
}
/** Refreshes all parameters for a specific amsport (with asyn lock()).
* \param[in] amsPort ams port.
* \return asynSuccess or asynError.
* Thread safe.
*/
asynStatus adsAsynPortDriver::refreshParamsLock(uint16_t amsPort)
{
lock();
asynStatus stat=refreshParams(amsPort);
unlock();
return stat;
}
/** Refreshes all parameters for a specific amsport.
* \param[in] amsPort ams port.
* \return asynSuccess or asynError.
*/
asynStatus adsAsynPortDriver::refreshParams(uint16_t amsPort)
{
const char* functionName = "refreshParams";
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s:\n", driverName, functionName);
if(connectedAds_){
if(adsParamArrayCount_>1){
//Renew data notification callbacks
for(int i=1; i<adsParamArrayCount_;i++){ //Skip first param since used for motorrecord or stream device
if(!pAdsParamArray_[i]){
continue;
}
adsParamInfo *paramInfo=pAdsParamArray_[i];
if((amsPort==0 || paramInfo->amsPort==amsPort) && paramInfo->refreshNeeded){
updateParamInfoWithPLCInfo(paramInfo);
}
}
}
//Renew symbols changed notification callbacks
for(amsPortInfo *port : amsPortList_){
if(port->amsPort==amsPort && port->refreshNeeded){
if(port->bCallbackNotifyValid){
adsDelSymbolsChangedCallback(port);
}
adsAddSymbolsChangedCallback(port);
}
}
}
bulkOK = 1;
return asynSuccess;
}
/** Invalidates all parameters for a specific amsport (with asyn lock()).
* \param[in] amsPort ams port.
* \return asynSuccess or asynError.
* Thread safe.
*/
asynStatus adsAsynPortDriver::invalidateParamsLock(uint16_t amsPort)
{
lock();
asynStatus stat=invalidateParams(amsPort);
unlock();
return stat;
}
/** Invalidates all parameters for a specific amsport.
* \param[in] amsPort ams port.
* \return asynSuccess or asynError.
*/
asynStatus adsAsynPortDriver::invalidateParams(uint16_t amsPort)
{
const char* functionName = "invalidateParams";
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s:\n", driverName, functionName);
bulkOK = 0;
if(adsParamArrayCount_>1){
for(int i=1; i<adsParamArrayCount_;i++){ //Skip first param since used for motorrecord or stream device
if(!pAdsParamArray_[i]){
continue;
}
adsParamInfo *paramInfo=pAdsParamArray_[i];
if(amsPort==0 || paramInfo->amsPort==amsPort){
paramInfo->refreshNeeded=true;
}
}
}
for (int i = 0; i < bulkTScnt; i++) {
if (amsPort == 0 || bulkTS[i].amsPort == amsPort)
bulkTS[i].refreshNeeded = 1;
}
for (int i = 0; i < MAXBULK; i++) {
if (bulk[i].cnt == 0) // Quit if unused!
break;
if (amsPort == 0 || bulk[i].amsPort == amsPort)
bulk[i].readSize = 4 * sizeof(uint32_t); // Initialize to just the timestamp!
}
return asynSuccess;
}
/** Connects to a PLC (with asyn lock()).
* \param[in] pasynUser Asyn user
* \return asynSuccess or asynError.
* Thread safe.
*/
asynStatus adsAsynPortDriver::connectLock(asynUser *pasynUser)
{
lock();
asynStatus stat=connect(pasynUser);
unlock();
return stat;
}
/** Connects to a PLC.
* \param[in] pasynUser Asyn user
* \return asynSuccess or asynError.
*/
asynStatus adsAsynPortDriver::connect(asynUser *pasynUser)
{
const char* functionName = "connect";
asynPrint(pasynUser, ASYN_TRACE_FLOW, "%s:%s: %s\n", driverName, functionName, epicsThreadGetNameSelf());
bool err=false;
asynStatus stat = adsConnect();
if (stat!= asynSuccess){
return asynError;
}
if(asynPortDriver::connect(pasynUser)!=asynSuccess){
return asynError;
}
connectedAds_=1;
return err ? asynError : asynSuccess;
}
/** Validates drvInfo string
* \param[in] drvInfo String containing information about the parameter.
* \return asynSuccess or asynError.
* The drvInfo string is what is after the asyn() in the "INP" or "OUT"
* field of an record.
*/
asynStatus adsAsynPortDriver::validateDrvInfo(const char *drvInfo)
{
const char* functionName = "validateDrvInfo";
asynPrint(pasynUserSelf,ASYN_TRACE_FLOW, "%s:%s: drvInfo: %s\n", driverName, functionName,drvInfo);
if(strlen(drvInfo)==0){
asynPrint(pasynUserSelf,ASYN_TRACE_ERROR,"Invalid drvInfo string: Length 0 (%s).\n",drvInfo);
return asynError;
}
//Check '?' mark last or '=' last
const char* read=strrchr(drvInfo,'?');
if(read){
if(strlen(read)==1){
return asynSuccess;
}
}
const char* write=strrchr(drvInfo,'=');
if(write){
if(strlen(write)==1){
return asynSuccess;
}
}
asynPrint(pasynUserSelf,ASYN_TRACE_ERROR,"Invalid drvInfo string (%s).\n",drvInfo);
return asynError;
}
/** Overrides asynPortDriver::drvUserCreate.
* This function is called by the asyn-framework for each record that is linked to this asyn port.
* \param[in] pasynUser Pointer to asyn user structure
* \param[in] drvInfo String containing information about the parameter.
* \param[out] pptypeName
* \param[out] psize size of pptypeName.
* \return asynSuccess or asynError.
* The drvInfo string is what is after the asyn() in the "INP" or "OUT"
* field of an record.
*/
asynStatus adsAsynPortDriver::drvUserCreate(asynUser *pasynUser,const char *drvInfo,const char **pptypeName,size_t *psize)
{
const char* functionName = "drvUserCreate";
static int vcnt = 0;
asynPrint(pasynUser, ASYN_TRACE_FLOW, "%s:%s: drvInfo: %s\n", driverName, functionName,drvInfo);
if(validateDrvInfo(drvInfo)!=asynSuccess){
return asynError;
}
int index=0;
asynStatus status=findParam(drvInfo,&index);
if(status==asynSuccess){
asynPrint(pasynUser, ASYN_TRACE_FLOW, "%s:%s: Parameter index found at: %d for %s. \n", driverName, functionName,index,drvInfo);
if(!pAdsParamArray_[index]){
asynPrint(pasynUser, ASYN_TRACE_ERROR, "%s:%s:pAdsParamArray_[%d]==NULL (drvInfo=%s).", driverName, functionName,index,drvInfo);
return asynError;
}
if(pAdsParamArray_[index]->dataSource==ADS_DATASOURCE_AMS_STATE){ //Local variable (not in PLC) like AMS port state.
return asynPortDriver::drvUserCreate(pasynUser,drvInfo,pptypeName,psize);
}
if(!connectedAds_){
//try to connect without error handling
connect(pasynUser);
}
if(connectedAds_){
status =adsReadParam(pAdsParamArray_[index]);
if(status!=asynSuccess){
return asynError;
}
}
return asynPortDriver::drvUserCreate(pasynUser,drvInfo,pptypeName,psize);
}
if (!vcnt++)
printf("Linking EPICS PVs to PLC variables...\n");
if (vcnt % 1000 == 0)
printf("%d...\n", vcnt);
//Ensure space left in param table
if(adsParamArrayCount_>=(paramTableSize_-1)){
asynPrint(pasynUser, ASYN_TRACE_ERROR, "%s:%s: Parameter table full. Parameter with drvInfo %s will be discarded.", driverName, functionName,drvInfo);
return asynError;
}
// Collect data from drvInfo string and recordpasynUser->reason=index;
adsParamInfo *paramInfo=new adsParamInfo();
memset(paramInfo,0,sizeof(adsParamInfo));
paramInfo->sampleTimeMS=defaultSampleTimeMS_;