forked from seehma/KMC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KukaMatlabConnector.cs
1886 lines (1619 loc) · 84.4 KB
/
KukaMatlabConnector.cs
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
/**
* Kuka Matlab Connector Toolbox
*
* Author: Matthias Seehauser
* matthias@seehauser.at
* http://www.seesle.at
* Date: 01.05.2014
* Institution: MCI - Mechatronics
* http://www.mci.at
*
*
*
*
*
*
*
*
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading.Tasks;
using System.ComponentModel;
/* ===================================================================================================================================== */
/**
* Namespace KukaMatlabConnector
*
*
*/
/* ===================================================================================================================================== */
namespace KukaMatlabConnector
{
/* ------------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* Class ConnectorObject
*
*
*
*/
/* ------------------------------------------------------------------------------------------------------------------------------------------------- */
public class ConnectorObject
{
// enumeration with all available connection states
public enum ConnectionState { init = 1, starting, listening, connecting, running, closeRequest, closing }
// defines the connection state of the class to the robot
ConnectionState robotConnectionState_;
// socket to the robot controller
System.Net.Sockets.Socket serverRobotComListener_;
// port on which the server has to listen
uint robotCommunicationPort_;
// ip address on which the server has to listen
System.Net.IPAddress robotListenIPAddress_;
// path to valid xml document which has to be sent to the robot in the specific cycle
String pathToCommandXMLDocument_;
// xml container which are send to the controller and coming from it
System.Xml.XmlDocument commandXML_;
System.Xml.XmlDocument receiveXML_;
// stopwatches to check if the cycles are fast enough
System.Diagnostics.Stopwatch stopWatch_;
System.Diagnostics.Stopwatch stopWatchReceive_;
System.Diagnostics.Stopwatch stopWatchSend_;
// strings where the command and the actual robot info is saved
String receiveString_;
String sendString_;
// count of the received and send packages, resets after every start of the communication
long receivedPackagesCount_;
long sendPackagesCount_;
// byte buffer for the communication
byte[] comBuffer_ { get; set; }
// communication buffer read pointer
uint comBufferReadPointer_ = 0;
// communication buffer write pointer
uint comBufferWritePointer_ = 0;
// communication buffer size
uint comBufferSize_ = 20480;
// variable to check if the pattern has been found to send the next command to the robot
bool patternFound_ = false;
// pattern which we have to search for
byte pattern_ = 10; // normally 0x0a => CR two times, unique after every xml packet
// thread instance which makes the communication to the robot
System.Threading.Thread kukaListenThread_;
// mutexes which lock the write access to the command and info strings and xml containers
System.Threading.Mutex mutexRobotCommandString_;
System.Threading.Mutex mutexRobotInfoString_;
System.Threading.Mutex mutexRobotCommandXML_;
System.Threading.Mutex mutexRobotInfoXML_;
// socket which contains the connection to the robot controller
System.Net.Sockets.Socket comRobotHandler_ = null;
// current correction values in cartesian and axis values
double RKorr_X_, RKorr_Y_, RKorr_Z_, RKorr_A_, RKorr_B_, RKorr_C_;
double AKorr_1_, AKorr_2_, AKorr_3_, AKorr_4_, AKorr_5_, AKorr_6_;
// if set to true no correction is allowed
bool lockCorrectionCommands_;
// variables to save the statistical times
long communicationTimeMilliSeconds_;
long communicationTimeTicks_;
long delayedPackagesCount_;
long delayedPackagesMilliSecondsComm_;
long delayedPackagesMilliSecondsSend_;
long delayedPackagesMilliSecondsReceive_;
long delayedPackagesTicksComm_;
// signals the connected application that the wrapper is waiting for the next robot info data
bool nextCycleStarted_;
// TextLogger
public TextLogger.TextLogger logger_;
// ------------------------------------------------------------------------------------------------------------------
// buffer and other variables for synchron mode writing
// ------------------------------------------------------------------------------------------------------------------
bool synchronModeRKorrActive_; // true if the RKorr synchron mode is active
bool synchronModeAKorrActive_; // true if the AKorr synchron mode is active
const uint synchronKorrBufferSize_ = 255; // buffer size of synchron mode buffer
uint synchronKorrBufferReadPointer_; // read pointer of synchron mode buffer
uint synchronKorrBufferWritePointer_; // write pointer of synchron mode buffer
synchronKorrBufferStruct[] synchronKorrBuffer_ ; // pointer to synchron mode buffer
// declaration of synchron mode buffer
public struct synchronKorrBufferStruct
{
public double Korr1; // filled with AKorr1 in case of AKorr mode active and RKorrX in case of RKorr mode active
public double Korr2; // filled with AKorr2 in case of AKorr mode active and RKorrY in case of RKorr mode active
public double Korr3; // filled with AKorr3 in case of AKorr mode active and RKorrZ in case of RKorr mode active
public double Korr4; // filled with AKorr4 in case of AKorr mode active and RKorrA in case of RKorr mode active
public double Korr5; // filled with AKorr5 in case of AKorr mode active and RKorrB in case of RKorr mode active
public double Korr6; // filled with AKorr6 in case of AKorr mode active and RKorrC in case of RKorr mode active
public synchronKorrBufferStruct(double extKorr1, double extKorr2, double extKorr3, double extKorr4, double extKorr5, double extKorr6)
{
Korr1 = extKorr1;
Korr2 = extKorr2;
Korr3 = extKorr3;
Korr4 = extKorr4;
Korr5 = extKorr5;
Korr6 = extKorr6;
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief Constructor of connector object
*
* @param pathToCommandXMLDocument ... here you will have to give the path for the command xml document; the easiest way is to place it in
* the same directory as the dll is then you only have to enter the name here; otherwise give the full
* path;
* listenIPAddress ... IP-Address as string where the wrapper has to listen for the robot connection; normally its an LAN adapter
* address; try to figure it out with Windows Start Button -> Run -> cmd Enter; then enter ipconfig and press
* Enter => search for the local area network adapter an its ip address
* listenPort ... Normally this value has to be set to 6008 if not other set in KUKA Config XML file on controller (INIT directory)
*
* @retval none...
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
public ConnectorObject(String pathToCommandXMLDocument, String listenIPAddress, uint listenPort)
{
int iError = 0;
// ------------------------------------------------
// initialize all other needed instances
// ------------------------------------------------
logger_ = new TextLogger.TextLogger( 255 ); // 255 is buffer size of logger
// ------------------------------------------------------------------------
// initialize all communication variables and check if valid (if possible)
// ------------------------------------------------------------------------
if ((listenPort > 1024) && (listenPort < 65535))
{
robotCommunicationPort_ = listenPort;
}
else
{
robotCommunicationPort_ = 6008;
}
// check if the ipAddress is correct otherwise write a logMessage and exit
try
{
robotListenIPAddress_ = System.Net.IPAddress.Parse(listenIPAddress);
}
catch
{
makeLoggingEntry("please give a correct IP-address...");
iError = 1;
}
// --------------------------------------------------
// initialize comBuffer and according variables
// --------------------------------------------------
comBufferReadPointer_ = 0;
comBufferWritePointer_ = 0;
comBuffer_ = new byte[comBufferSize_];
// ---------------------------------------------------------------------------------------------------
// check if the path is correct otherwise take a file located in the same folder as the client is
// ---------------------------------------------------------------------------------------------------
if ((pathToCommandXMLDocument != null) && (pathToCommandXMLDocument.Length != 0))
{
pathToCommandXMLDocument_ = pathToCommandXMLDocument;
}
else
{
pathToCommandXMLDocument_ = "commanddoc.xml";
}
// -----------------------------------------
// initialize the connection states
// -----------------------------------------
robotConnectionState_ = new ConnectionState();
setRobotConnectionState(ConnectionState.init);
// -----------------------------------------
// initialize the stop watches
// -----------------------------------------
stopWatch_ = new System.Diagnostics.Stopwatch();
stopWatchReceive_ = new System.Diagnostics.Stopwatch();
stopWatchSend_ = new System.Diagnostics.Stopwatch();
// -----------------------------------------
// reset all statistical variables
// -----------------------------------------
receivedPackagesCount_ = 0;
sendPackagesCount_ = 0;
communicationTimeMilliSeconds_ = 0;
communicationTimeTicks_ = 0;
delayedPackagesCount_ = 0;
// allow commands from initial state
lockCorrectionCommands_ = false;
// -----------------------------------------
// reset synchron mode flags
// -----------------------------------------
synchronModeAKorrActive_ = false;
synchronModeRKorrActive_ = false;
synchronKorrBufferReadPointer_ = 0;
synchronKorrBufferWritePointer_ = 0;
synchronKorrBuffer_ = new synchronKorrBufferStruct[synchronKorrBufferSize_];
// ------------------------------------------------------------------------------------
// initilize all mutexes
// ------------------------------------------------------------------------------------
mutexRobotCommandString_ = new System.Threading.Mutex(false, "robotCommandString");
mutexRobotInfoString_ = new System.Threading.Mutex(false, "robotInfoString");
mutexRobotCommandXML_ = new System.Threading.Mutex(false, "robotCommandXML");
mutexRobotInfoXML_ = new System.Threading.Mutex(false, "robotInfoXML");
// -----------------------------------------------
// initialize the xml container
// -----------------------------------------------
receiveXML_ = new System.Xml.XmlDocument();
commandXML_ = new System.Xml.XmlDocument();
// -----------------------------------------------------------------
// try to load the given xml document for commands
// -----------------------------------------------------------------
commandXML_ = getXMLCommandDocument(pathToCommandXMLDocument_);
if (commandXML_ == null)
{
makeLoggingEntry("could not find command XML-file...");
iError = 2;
}
// ---------------------------------------------------------------
// only return constructor done if everything is done correctly
// ---------------------------------------------------------------
if (iError == 0)
{
makeLoggingEntry("constructor done...");
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief initializes the thread which handles the communication to the robot
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
public uint initializeRobotListenThread()
{
uint returnal = 0;
// try to figure out if the task is allready running
if( kukaListenThread_ == null)
{
// set connection state of task to starting
setRobotConnectionState(ConnectionState.starting);
// reset all statistic variables
receivedPackagesCount_ = 0;
sendPackagesCount_ = 0;
delayedPackagesCount_ = 0;
// create thread instance and set the threadpriority to the highest value
kukaListenThread_ = new System.Threading.Thread(new System.Threading.ThreadStart(kukaListener), 10000000);
kukaListenThread_.Priority = System.Threading.ThreadPriority.Highest;
kukaListenThread_.Start();
returnal = 0;
}
else if (kukaListenThread_.IsAlive != true)
{
// set connection state of task to starting
setRobotConnectionState(ConnectionState.starting);
// reset all statistic variables
receivedPackagesCount_ = 0;
sendPackagesCount_ = 0;
delayedPackagesCount_ = 0;
// create thread instance and set the threadpriority to the highest value
kukaListenThread_ = new System.Threading.Thread(new System.Threading.ThreadStart(kukaListener), 10000000);
kukaListenThread_.Priority = System.Threading.ThreadPriority.Highest;
kukaListenThread_.Start();
returnal = 1;
}
else
{
returnal = 2;
}
return (returnal);
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief trys to get the xml document which has to be send to the robot
*
* @param path ... string with the path to the document
*
* @retval new XmlDocument Instance
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private System.Xml.XmlDocument getXMLCommandDocument(String pathToXMLDocument)
{
System.Xml.XmlDocument localXMLDocument;
localXMLDocument = null;
// try to load the xml document
try
{
// load variable with xmlDocument instance
localXMLDocument = new System.Xml.XmlDocument();
// prepare xml answer to the kuka robot
localXMLDocument.PreserveWhitespace = true;
localXMLDocument.Load(pathToXMLDocument);
}
catch
{
localXMLDocument = null;
}
return localXMLDocument;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief starts the server and waits for a connection which has to be established from a client (robot or virtual)
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private System.Net.Sockets.Socket startRobotComServerAndWaitForConnection()
{
System.Net.IPEndPoint localEndPoint;
System.Net.Sockets.Socket localComHandler; // create system socket
localEndPoint = null;
localComHandler = null;
// create an IPEndPoint with the previosly selected IPAddress and communication port
localEndPoint = new System.Net.IPEndPoint(robotListenIPAddress_, (int)robotCommunicationPort_);
// create the TCP/IP socket connection
serverRobotComListener_ = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
serverRobotComListener_.NoDelay = true;
setRobotConnectionState(ConnectionState.listening);
try
{
// open socket and listen on network
serverRobotComListener_.Bind(localEndPoint);
serverRobotComListener_.Listen(1);
// program is suspended while waiting for an incoming connection, bind the first request
makeLoggingEntry("listening for RobotCom on ip:" + robotListenIPAddress_.ToString() + " port:" + robotCommunicationPort_.ToString() + ", wait for connection...");
localComHandler = serverRobotComListener_.Accept();
localComHandler.NoDelay = true;
// no more connections are welcome so close the comListener object
serverRobotComListener_.Close();
if ((localComHandler != null) && (getRobotConnectionState() == ConnectionState.listening))
{
setRobotConnectionState(ConnectionState.connecting);
makeLoggingEntry("connection established! starting communication with RobotCom...");
}
else
{
makeLoggingEntry("connection canceled! good bye...");
}
}
catch
{
makeLoggingEntry("cant open port, please give it another try...");
serverRobotComListener_.Close();
localComHandler = null;
}
return localComHandler;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief robot listen thread starting helper method, connects to the robot and initiates the synchron communication
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private void kukaListener()
{
// prepare sendString for first transport to robot
setCommandString(getCommandInnerXML());
// check if the ipAddress is set
if (robotListenIPAddress_ != null)
{
while ((getRobotConnectionState() == ConnectionState.running) || (getRobotConnectionState() == ConnectionState.starting))
{
// start the server and wait for the connection which has to be established from the kuka robot
// goto ST_SKIPSENS in the kuka robot programm...
comRobotHandler_ = startRobotComServerAndWaitForConnection();
if (comRobotHandler_ != null)
{
// now start the server and periodically receive the robot data and send the prepared XML file
// should stay in the following line till the connection is refused
robotServerLoop(comRobotHandler_);
// when the loop is finished then close the socket
comRobotHandler_.Close();
}
else
{
makeLoggingEntry("could not open the server-robot client connection => check network connection!");
}
}
}
else
{
// otherwise throw an error
makeLoggingEntry("no ip host entry found to connect => check network connection!");
}
makeLoggingEntry("connection closed, server closed, see you next time...");
setRobotConnectionState(ConnectionState.init);
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief server loop which waits for data from robot and answers with XML File
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private void robotServerLoop(System.Net.Sockets.Socket comHandler)
{
// variable declarations
byte[] localIncomingDataByteBuffer; // data buffer for incoming data
byte[] localReceivedFullMessageBytes;
byte[] sendMessage;
int bytesReceived;
String localCommandString;
String localInfoString;
// variable initializations
localReceivedFullMessageBytes = null;
sendMessage = new Byte[2048];
// set state to running
setRobotConnectionState(ConnectionState.running);
// --------------------------------------------------
// now lets start the endles loop
// --------------------------------------------------
while (true)
{
// reset and start the stopwatch to measure the time between two robot info cycles
stopWatch_.Reset();
stopWatch_.Start();
// command the garbage collector to collect at the beginning of each cycle
System.GC.Collect();
// signal to the connected application that the command data is ready to be modified
nextCycleStarted_ = true;
// ------------------------------------------------------------
// wait for data and receive bytes
// ------------------------------------------------------------
try
{
while (patternFound_ == false)
{
String testString;
localIncomingDataByteBuffer = new Byte[2048]; // load byte buffer with instance
bytesReceived = comHandler.Receive(localIncomingDataByteBuffer);
if (bytesReceived == 0)
{
makeLoggingEntry("client closed connection (bytesReceived=0)");
setRobotConnectionState(ConnectionState.closing);
break; // client closed socket
}
testString = System.Text.Encoding.ASCII.GetString(localIncomingDataByteBuffer, 0, bytesReceived);
// start stopwatch for receiving task
stopWatchReceive_.Reset();
stopWatchReceive_.Start();
// fill the received bytes into the local buffer and check if a full message came from robot
localReceivedFullMessageBytes = giveRightByteArray(localIncomingDataByteBuffer, bytesReceived);
}
// increment the packages counter
receivedPackagesCount_++;
// clear the pattern found flag
patternFound_ = false;
}
catch
{
makeLoggingEntry("connection closed from remote host...\n\r");
setRobotConnectionState(ConnectionState.closing);
break;
}
stopWatchReceive_.Stop();
stopWatchSend_.Reset();
stopWatchSend_.Start();
// -------------------------------------------------------------------------------------
// signals the connector that the sending operation just started =>
// the external system has to wait until this variable goes again to true
// -------------------------------------------------------------------------------------
nextCycleStarted_ = false;
// --------------------------------------------------------------
// only try to load the xml stuff when there is data available
// --------------------------------------------------------------
if (localReceivedFullMessageBytes != null)
{
// -------------------------------------------------------------------------
// check if the string is valid and then save it to the locally xml storage
// -------------------------------------------------------------------------
if (checkReceivedMessage(localReceivedFullMessageBytes) == true)
{
try
{
// check if there is synchron AKorr active
doSynchronAKorr();
// check if there is synchron RKorr active
doSynchronRKorr();
// get the sendString variable under mutex protection from getter method
localCommandString = getCommandString();
// get the receiveString variable under mutex protection from getter method
localInfoString = getRobotInfoString();
// mirror the IPO counter you received yet
localCommandString = mirrorInterpolationCounter(localInfoString, localCommandString);
// get bytes out of string
sendMessage = System.Text.Encoding.ASCII.GetBytes(localCommandString);
// send data to robot
comHandler.Send(sendMessage, 0, sendMessage.Length, System.Net.Sockets.SocketFlags.None);
sendPackagesCount_++;
// copy the edited string under mutex protection back
setCommandString(localCommandString);
}
catch
{
makeLoggingEntry("could not send XML string");
}
}
}
stopWatchSend_.Stop();
stopWatch_.Stop();
communicationTimeMilliSeconds_ = stopWatch_.ElapsedMilliseconds;
communicationTimeTicks_ = stopWatch_.ElapsedTicks;
// ----------------------------------------------------------------------------------------------
// count the delayed packages
// ----------------------------------------------------------------------------------------------
if (communicationTimeMilliSeconds_ > 16)
{
delayedPackagesCount_++;
delayedPackagesMilliSecondsComm_ = communicationTimeMilliSeconds_;
delayedPackagesMilliSecondsSend_ = stopWatchSend_.ElapsedTicks;
delayedPackagesTicksComm_ = stopWatch_.ElapsedTicks;
delayedPackagesMilliSecondsReceive_ = stopWatchReceive_.ElapsedTicks;
}
// ----------------------------------------------------------------------------------------------
// close communication channel to robot if state changed to closing
// ----------------------------------------------------------------------------------------------
if ((getRobotConnectionState() == ConnectionState.closeRequest) ||(getRobotConnectionState() == ConnectionState.closing) )
{
setRobotConnectionState(ConnectionState.closing);
break;
}
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief checks if the received message is a valid one. it searches for the Rob xml tag
*
* @param receivedMessageBytes ... byte array with the received message
*
* @retval bool ... false if the rob string was not found, true if it was found
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private bool checkReceivedMessage(byte[] receivedMessageBytes)
{
bool robStringFound = false;
String localReceivedFullMessageString = null;
// copy the received string
localReceivedFullMessageString = System.Text.Encoding.ASCII.GetString(receivedMessageBytes, 0, receivedMessageBytes.Length);
// when loaded try to find the rob node
robStringFound = checkStringIfValid(localReceivedFullMessageString);
// if there is no rob node continue else do the other stuff
if (robStringFound == true)
{
// convert bytes to string and save into variable
setRobotInfoString(localReceivedFullMessageString);
}
else
{
makeLoggingEntry("no robot specific nodes found!");
robStringFound = false;
}
return robStringFound;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief fills the locally byte buffer and checks if during the copy operation the pattern 0x0a 0x0a can be found => end of robot message
*
* @param buffer ... buffer with the message which has been received from the robot
* @param size ... received bytes which have been received from the robot
*
* @retval byte array ... with the found message, null if no full valid message is here
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private byte[] giveRightByteArray(byte[] buffer, long size)
{
byte[] localByteBuffer;
uint localComBufferWritePointer;
uint aktEntryCount;
uint countOuterLoop;
uint countInnerLoop;
bool firstPatternFound_;
// reset all variables, especially pattern found... when we come here in that function we copy the byte buffers and check if an end of one message comes
localByteBuffer = null;
localComBufferWritePointer = 0;
patternFound_ = false;
firstPatternFound_ = false;
countInnerLoop = 0;
countOuterLoop = 0;
aktEntryCount = 0;
// check if size is not equal to zero
if (size != 0)
{
for (countOuterLoop = 0; countOuterLoop < size; countOuterLoop++)
{
// save write pointer
localComBufferWritePointer = comBufferWritePointer_;
// increment write pointer and check if incrementation was right
if (!incrementComBufferWritePointer())
{
// copy byte to old write pointer place
comBuffer_[localComBufferWritePointer] = buffer[countOuterLoop];
// check if the first pattern was before and the current pattern is exactly the same
if ((firstPatternFound_ == true) && (buffer[countOuterLoop] == pattern_) && (patternFound_ == false))
{
// set pattern foudn true => only one message for one method call
patternFound_ = true;
aktEntryCount = getComBufferEntryCount();
// get some memor to do the copy operation
localByteBuffer = new byte[aktEntryCount];
// increment the read pointer to the place where the write pointer stands
for (countInnerLoop = 0; countInnerLoop < aktEntryCount; countInnerLoop++)
{
localByteBuffer[countInnerLoop] = comBuffer_[comBufferReadPointer_];
incrementComBufferReadPointer();
}
}
// set firstPatternFound to false because the string was found and we only have to copy the rest of the message
firstPatternFound_ = false;
if (buffer[countOuterLoop] == pattern_)
{
firstPatternFound_ = true;
}
}
}
}
return localByteBuffer;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief calculates the current count of bytes entered in the buffer => it is the subtraction of write - readpointer and it also checks if
* a buffer wrap happened
*
* @retval uint ... count of received bytes
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private uint getComBufferEntryCount()
{
uint localEntryCount = 0;
int localPointerDiff = 0;
localPointerDiff = Convert.ToInt32(comBufferWritePointer_) - Convert.ToInt32(comBufferReadPointer_);
// check if the pointer difference is positive or negative
if (localPointerDiff > 0)
{
localEntryCount = comBufferWritePointer_ - comBufferReadPointer_;
}
else if (localPointerDiff < 0)
{
localEntryCount = (comBufferSize_ - comBufferReadPointer_) + comBufferWritePointer_;
}
else
{
localEntryCount = 0;
}
return localEntryCount;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief increments the combuffer read pointer, if it is larger than the buffer size after incrementation => set to 0
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private void incrementComBufferReadPointer()
{
comBufferReadPointer_++;
if (comBufferReadPointer_ > (comBufferSize_ - 1))
{
comBufferReadPointer_ = 0;
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief increments the combuffer write pointer, if it is larger than the buffer size after incrementation => set to 0
* if it is equal to the readpointer after incrementation => buffer full back to the old value
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private bool incrementComBufferWritePointer()
{
uint localWritePointer;
bool errReturn = false;
localWritePointer = comBufferWritePointer_;
comBufferWritePointer_++;
if (comBufferWritePointer_ > (comBufferSize_ - 1))
{
comBufferWritePointer_ = 0;
}
// writepointer can not be equal to readpointer after incrementation
if (comBufferWritePointer_ == comBufferReadPointer_)
{
errReturn = true;
comBufferWritePointer_ = localWritePointer;
}
return errReturn;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief increments the synchron AKorr read pointer, if it is larger than the buffer size after incrementation => set to 0
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private void incrementSynchronKorrReadPointer()
{
synchronKorrBufferReadPointer_++;
if (synchronKorrBufferReadPointer_ > (synchronKorrBufferSize_ - 1))
{
synchronKorrBufferReadPointer_ = 0;
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief increments the synchron AKorr write pointer, if it is larger than the buffer size after incrementation => set to 0
* if it is equal to the readpointer after incrementation => buffer full back to the old value
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private bool incrementSynchronKorrWritePointer()
{
uint localWritePointer;
bool errReturn = false;
localWritePointer = synchronKorrBufferWritePointer_;
synchronKorrBufferWritePointer_++;
if (synchronKorrBufferWritePointer_ > (synchronKorrBufferSize_ - 1))
{
synchronKorrBufferWritePointer_ = 0;
}
// writepointer can not be equal to readpointer after incrementation
if (synchronKorrBufferWritePointer_ == synchronKorrBufferReadPointer_)
{
errReturn = true;
synchronKorrBufferWritePointer_ = localWritePointer;
}
return errReturn;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief calculates the current count of AKorr commands entered in the buffer => it is the subtraction of write - readpointer and it also checks if
* a buffer wrap happened
*
* @retval uint ... count of received bytes
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private uint getSynchronKorrBufferEntryCount()
{
uint localEntryCount = 0;
int localPointerDiff = 0;
localPointerDiff = Convert.ToInt32(synchronKorrBufferWritePointer_) - Convert.ToInt32(synchronKorrBufferReadPointer_);
// check if the pointer difference is positive or negative
if (localPointerDiff > 0)
{
localEntryCount = synchronKorrBufferWritePointer_ - synchronKorrBufferReadPointer_;
}
else if (localPointerDiff < 0)
{
localEntryCount = (synchronKorrBufferSize_ - synchronKorrBufferReadPointer_) + synchronKorrBufferWritePointer_;
}
else
{
localEntryCount = 0;
}
return localEntryCount;
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief sends the current AKorr command set in the synchron buffer to the robot
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private void doSynchronAKorr()
{
if (synchronModeAKorrActive_ == true)
{
if (getSynchronKorrBufferEntryCount() != 0)
{
modifyAKorrVariable("AKorr1", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr1.ToString());
modifyAKorrVariable("AKorr2", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr2.ToString());
modifyAKorrVariable("AKorr3", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr3.ToString());
modifyAKorrVariable("AKorr4", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr4.ToString());
modifyAKorrVariable("AKorr5", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr5.ToString());
modifyAKorrVariable("AKorr6", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr6.ToString());
incrementSynchronKorrReadPointer();
}
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief sends the current RKorr command set in the synchron buffer to the robot
*
* @retval none
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private void doSynchronRKorr()
{
if (synchronModeRKorrActive_ == true)
{
if( getSynchronKorrBufferEntryCount() != 0 )
{
modifyRKorrVariable("RKorrX", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr1.ToString());
modifyRKorrVariable("RKorrY", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr2.ToString());
modifyRKorrVariable("RKorrZ", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr3.ToString());
modifyRKorrVariable("RKorrA", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr4.ToString());
modifyRKorrVariable("RKorrB", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr5.ToString());
modifyRKorrVariable("RKorrC", synchronKorrBuffer_[synchronKorrBufferReadPointer_].Korr6.ToString());
incrementSynchronKorrReadPointer();
}
}
}
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
/**
* @brief There is a specific counting value coming from the kuka controller inside the receive string.
* This value has to be sent back so separate it and insert it into the xml send string
*
* @param receive ... the string which comes from the kuka controller
* @param send ... the string which we will send to the controller
*
* @retval string ... the modified string for the controller
*/
/* ----------------------------------------------------------------------------------------------------------------------------------------------- */
private String mirrorInterpolationCounter(String receiveString, String sendString)
{
// tried XML separation first, but it was too slow for realtime comm...
// separate the IPO counter which comes from the robot and save it as string
// +6 because "<IPOC>" has 6 character...
int startIpocReceiveIndex = receiveString.IndexOf("<IPOC>") + 6;
int endIpocReceiveIndex = receiveString.IndexOf("</IPOC>");
string ipocount = receiveString.Substring(startIpocReceiveIndex, endIpocReceiveIndex - startIpocReceiveIndex);
// find the position where this number has to be inserted
int startIpocSendIndex = sendString.IndexOf("<IPOC>") + 6;
int endIpocSendIndex = sendString.IndexOf("</IPOC>");