-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathICSC.cpp
executable file
·698 lines (600 loc) · 19.7 KB
/
ICSC.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
/********************************************************************************
* Copyright (c) 2013, Majenko Technologies and S.J.Hoeksma
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of Majenko Technologies.
********************************************************************************/
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include <ICSC.h>
//Constructor of the class
_ICSC::_ICSC(){
#ifdef ICSC_DYNAMIC
_commandCount=0;
_commands=NULL;
_data=NULL;
#endif
}
//Destructor of the class
_ICSC::~_ICSC(){
#ifdef ICSC_DYNAMIC
free(_data);
free(_commands);
#endif
}
// Initialize the system. Set up the serial port to the right baud rate
// and initialize my variables.
void _ICSC::begin(unsigned char station, unsigned long baud)
{
begin(station, baud, &Serial, -1);
}
void _ICSC::begin(unsigned char station, unsigned long baud, int dePin)
{
begin(station, baud, &Serial, dePin);
}
void _ICSC::begin(unsigned char station, unsigned long baud, HardwareSerial *sdev)
{
begin(station, baud, sdev, -1);
}
#if defined(_USE_USB_FOR_SERIAL_)
void _ICSC::begin(unsigned char station, unsigned long baud, USBSerial *sdev)
{
begin(station, baud, sdev, -1);
}
void _ICSC::begin(unsigned char station, unsigned long baud, USBSerial *sdev, int dePin)
{
_hserial = NULL;
_sserial = NULL;
_userial = sdev;
_userial->begin(baud);
_station = station;
_dePin = dePin;
_baud = baud;
#ifndef ICSC_NO_STATS
_stats.oob_bytes = 0;
_stats.tx_packets = 0;
_stats.tx_bytes = 0;
_stats.rx_packets = 0;
_stats.rx_bytes = 0;
_stats.cs_errors = 0;
_stats.cb_run = 0;
_stats.cb_bad = 0;
#endif
// Reset the state machine
reset();
if (_dePin != -1) {
pinMode(_dePin, OUTPUT);
digitalWrite(_dePin, LOW);
}
}
#endif
void _ICSC::begin(unsigned char station, unsigned long baud, SoftwareSerial *sdev, int dePin) {
_userial = NULL;
_hserial = NULL;
_sserial = sdev;
_sserial->begin(baud);
_station = station;
_dePin = dePin;
_baud = baud;
#ifndef ICSC_NO_STATS
_stats.oob_bytes = 0;
_stats.tx_packets = 0;
_stats.tx_bytes = 0;
_stats.rx_packets = 0;
_stats.rx_bytes = 0;
_stats.cs_errors = 0;
_stats.cb_run = 0;
_stats.cb_bad = 0;
#endif
// Reset the state machine
reset();
if(_dePin != -1) {
pinMode(_dePin, OUTPUT);
digitalWrite(_dePin, LOW);
}
}
void _ICSC::begin(unsigned char station, unsigned long baud, HardwareSerial *sdev, int dePin)
{
_userial = NULL;
_sserial = NULL;
_hserial = sdev;
_hserial->begin(baud);
_station = station;
_dePin = dePin;
_baud = baud;
#ifndef ICSC_NO_STATS
_stats.oob_bytes = 0;
_stats.tx_packets = 0;
_stats.tx_bytes = 0;
_stats.rx_packets = 0;
_stats.rx_bytes = 0;
_stats.cs_errors = 0;
_stats.cb_run = 0;
_stats.cb_bad = 0;
#endif
// Reset the state machine
reset();
if (_dePin != -1) {
pinMode(_dePin, OUTPUT);
digitalWrite(_dePin, LOW);
}
}
void _ICSC::serialFlush()
{
if (_hserial) {
_hserial->flush();
}
}
void _ICSC::serialWrite(unsigned char b)
{
if (_hserial) {
_hserial->write(b);
}
if (_sserial) {
_sserial->write(b);
}
#if defined(_USE_USB_FOR_SERIAL_)
if (_userial) {
_userial->write(b);
}
#endif
}
int _ICSC::serialRead()
{
if (_hserial) {
return _hserial->read();
}
if(_sserial) {
return _sserial->read();
}
#if defined(_USE_USB_FOR_SERIAL_)
if (_userial) {
return _userial->read();
}
#endif
}
int _ICSC::serialAvailable()
{
if (_hserial) {
return _hserial->available();
}
if(_sserial) {
return _sserial->available();
}
#if defined(_USE_USB_FOR_SERIAL_)
if (_userial) {
return _userial->available();
}
#endif
}
// Send a message to a remote station. Origin is the originating station
// "station" is the ID assigned to the remote station, "command" is a
// command code that has been programmed into the remote station.
// "len" is the number of bytes to send in the message (if a
// string is being sent, remember to include the terminating 0). "data" is
// a pointer (cast to a char *) to the data to send.
// The checksum is calculated as the sum of all the variable content of the packet
// modulus 256. I.e., everything except the framing characters SOH/STX/ETX/EOT and
// the checksum itself.
boolean _ICSC::send(unsigned char origin,unsigned char station, char command, unsigned char len, char *data)
{
unsigned char i;
unsigned char cs = 0;
unsigned char del;
#ifdef ICSC_COLLISION_DETECTION
// This is how many times to try and transmit before failing.
unsigned char timeout = 10;
// Let's start out by looking for a colision. If there has been anything seen in
// the last millisecond, then wait for a random time and check again.
while (process()) {
del = rand() % 20;
for (i=0; i<del; i++) {
delay(1);
#ifndef ICSC_NO_STATS
_stats.collision++;
#endif
process();
}
timeout--;
if (timeout == 0) {
// Failed to transmit!!!
#ifndef ICSC_NO_STATS
_stats.tx_fail++;
#endif
return false;
}
}
#endif
assertDE();
// Start of header by writing multiple SOH
for(byte w=0;w<ICSC_SOH_START_COUNT;w++) serialWrite(SOH);
serialWrite(station); // Destination address
cs += station;
serialWrite(origin); // Source address
cs += _station;
serialWrite(command); // Command code
cs += command;
serialWrite(len); // Length of text
cs += len;
serialWrite(STX); // Start of text
for(i=0; i<len; i++) {
serialWrite(data[i]); // Text bytes
cs += data[i];
}
serialWrite(ETX); // End of text
serialWrite(cs);
serialWrite(EOT);
waitForTransmitToComplete();
deassertDE();
#ifndef ICSC_NO_STATS
_stats.tx_packets++;
_stats.tx_bytes += len;
#endif
return true;
}
//Mostly used send, we use our internal station as origin
boolean _ICSC::send(unsigned char station, char command, unsigned char len, char *data)
{
return send(_station,station,command,len,data);
}
// Send a string of data to a remote station.
boolean _ICSC::send(unsigned char station, char command,char *str)
{
return send(station,command,(unsigned char)strlen(str),str);
}
//Wrapper to send a long
boolean _ICSC::send(unsigned char station, char command, long data)
{
return send(station,command,sizeof(data),(char *)&data);
}
//Wrapper to send a int
boolean _ICSC::send(unsigned char station, char command, int data)
{
return send(station,command,sizeof(data),(char *)&data);
}
//Wrapper to send a char
boolean _ICSC::send(unsigned char station, char command, char data)
{
return send(station,command,sizeof(data),(char *)&data);
}
//Broadcast data to all stations
boolean _ICSC::broadcast(char command, unsigned char len, char *data)
{
return send(ICSC_BROADCAST,command,len,data);
}
//BroadCast a string to all Stations
boolean _ICSC::broadcast(char command, char *str)
{
return send(ICSC_BROADCAST,command,(unsigned char)strlen(str),str);
}
//Wrapper for broadcasting a long
boolean _ICSC::broadcast(char command, long data)
{
return send(ICSC_BROADCAST,command,sizeof(data),(char *)&data);
}
//Wrapper for broadcasting a int
boolean _ICSC::broadcast(char command, int data)
{
return send(ICSC_BROADCAST,command,sizeof(data),(char *)&data);
}
//Wrapper for broadcasting a single char
boolean _ICSC::broadcast(char command, char data)
{
return send(ICSC_BROADCAST,command,sizeof(data),(char *)&data);
}
//Reset the state machine and release the data pointer
void _ICSC::reset(){
_recPhase = 0;
_recPos = 0;
_recLen = 0;
_recCommand = 0;
_recCS = 0;
_recCalcCS = 0;
#ifdef ICSC_DYNAMIC
free(_data);
_data=NULL;
#endif
}
// This is the main reception state machine. Progress through the states
// is keyed on either special control characters, or counted number of bytes
// received. If all the data is in the right format, and the calculated
// checksum matches the received checksum, AND the destination station is
// our station ID, then look for a registered command that matches the
// command code. If all the above is true, execute the command's
// function.
boolean _ICSC::process()
{
char inch;
unsigned char i;
unsigned char cbok = 0;
if (!serialAvailable()) return false;
while(serialAvailable()) {
inch = serialRead();
// Record the timestamp of this byte, so that we know how long since we last
// saw any activity on the line
_lastByteSeen = millis();
switch(_recPhase) {
// Case 0 looks for the header. Bytes arrive in the serial interface and get
// shifted through a header buffer. When the start and end characters in
// the buffer match the SOH/STX pair, and the destination station ID matches
// our ID, save the header information and progress to the next state.
case 0:
memcpy(&_header[0],&_header[1],5);
_header[5] = inch;
if ((_header[0] == SOH) && (_header[5] == STX) && (_header[1] != _header[2])) {
_recCalcCS = 0;
_recStation = _header[1];
_recSender = _header[2];
_recCommand = _header[3];
_recLen = _header[4];
for (i=1; i<=4; i++) {
_recCalcCS += _header[i];
}
_recPhase = 1;
_recPos = 0;
//Check if we should process this message
//We reject the message if we are the sender
//We reject if we are not the receiver and message is not a broadcast
if ((_recSender == _station) ||
(_recStation != _station &&
_recStation != ICSC_BROADCAST &&
_recStation != ICSC_SYS_RELAY )) {
reset();
break;
}
if (_recLen == 0) {
_recPhase = 2;
}
#ifdef ICSC_DYNAMIC
else {
_data = (char *)malloc(_recLen);
}
#else
if (_recLen > MAX_MESSAGE) {
_recPhase = 0;
}
#endif
#ifndef ICSC_NO_STATS
} else {
_stats.oob_bytes++;
#endif
}
break;
// Case 1 receives the data portion of the packet. Read in "_recLen" number
// of bytes and store them in the _data array.
case 1:
_data[_recPos++] = inch;
_recCalcCS += inch;
if (_recPos == _recLen) {
_recPhase = 2;
}
break;
// After the data comes a single ETX character. Do we have it? If not,
// reset the state machine to default and start looking for a new header.
case 2:
// Packet properly terminated?
if (inch == ETX) {
_recPhase = 3;
} else {
reset();
}
break;
// Next comes the checksum. We have already calculated it from the incoming
// data, so just store the incoming checksum byte for later.
case 3:
_recCS = inch;
_recPhase = 4;
break;
// The final state - check the last character is EOT and that the checksum matches.
// If that test passes, then look for a valid command callback to execute.
// Execute it if found.
case 4:
cbok = 0;
if (inch == EOT) {
if (_recCS == _recCalcCS) {
// First, check for system level commands. It is possible
// to register your own callback as well for system level
// commands which will be called after the system default
// hook.
switch (_recCommand) {
case ICSC_SYS_PING:
respondToPing(_recSender, _recCommand, _recLen, _data);
break;
#ifndef ICSC_NO_STATS
case ICSC_SYS_QSTAT:
respondToQSTAT(_recSender, _recCommand, _recLen, _data);
break;
#endif
}
#ifdef ICSC_DYNAMIC
for (i=0; i<_commandCount; i++) {
#else
for (i=0; i<MAX_COMMANDS; i++) {
#endif
if ((_commands[i].commandCode == _recCommand ||
_commands[i].commandCode == ICSC_CATCH_ALL )
&& _commands[i].callback)
{
_commands[i].callback(_recSender, _recCommand, _recLen, _data);
#ifndef ICSC_NO_STATS
_stats.cb_run++;
#endif
cbok = 1;
}
}
#ifndef ICSC_NO_STATS
if (cbok == 0) {
_stats.cb_bad++;
}
_stats.rx_packets++;
_stats.rx_bytes += _recLen;
} else {
_stats.cs_errors++;
}
#else
}
#endif
}
//Clear the data
reset();
//Return true, we have processed one command
return true;
break;
}
}
return true;
}
// Add a new command code / function pair into the list of
// registered commands. If there is no room, fail silently.
void _ICSC::registerCommand(char command, callbackFunction func)
{
unsigned char i;
#ifdef ICSC_DYNAMIC
// Check if we should update the function
for (i=0; i<_commandCount; i++) {
if (_commands[i].commandCode == command) {
_commands[i].callback = func;
return;
}
}
// Not Found add a new command
_commandCount++;
_commands = (command_ptr)realloc(_commands,_commandCount * sizeof(command_t));
_commands[i].commandCode=command;
_commands[i].callback = func;
#else
for (i=0; i<MAX_COMMANDS; i++) {
if (_commands[i].commandCode == 0) {
_commands[i].commandCode = command;
_commands[i].callback = func;
return;
}
}
#endif
}
// Look for a registered command and delete it from the
// list if found. If not found, silently fail.
void _ICSC::unregisterCommand(char command)
{
unsigned char i;
#ifdef ICSC_DYNAMIC
for (i=0; i<_commandCount; i++) {
if (_commands[i].commandCode == command) {
_commandCount--;
memcpy(&_commands[i],&_commands[i+1],(_commandCount-i) * sizeof(command_t));
_commands=(command_ptr) realloc(_commands,_commandCount * sizeof(command_t));
return;
}
}
#else
for (i=0; i<MAX_COMMANDS; i++) {
if (_commands[i].commandCode == command) {
_commands[i].commandCode = 0;
_commands[i].callback = NULL;
return;
}
}
#endif
}
// This is a bit of a fudge at the moment as many different versions
// of the different core code from the different chips provides
// different facilities for knowing if the transmission has
// completed.
void _ICSC::waitForTransmitToComplete()
{
if (_dePin == -1) //Skip flush
return;
#ifdef __PIC32MX__
// MPIDE has nothing yet for this. It uses the hardware buffer, which
// could be up to 8 levels deep. For now, let's just delay for 8
// characters worth.
delayMicroseconds((80000000UL/_baud)+1);
#else
#if defined(ARDUINO) && ARDUINO >= 100
#if ARDUINO >= 104
// Arduino 1.0.4 and upwards does it right
serialFlush();
#else
// Between 1.0.0 and 1.0.3 it almost does it - need to compensate
// for the hardware buffer. Delay for 2 bytes worth of transmission.
serialFlush();
delayMicroseconds((20000000UL/_baud)+1);
#endif
#endif
#endif
}
// Control the DE line, if a DEPin has been specified. This will
// always put the DEPin into output mode in case something else has
// tampered with the pin setting in the mean time.
void _ICSC::assertDE()
{
if (_dePin != -1) {
digitalWrite(_dePin, HIGH);
delayMicroseconds(5);
}
}
void _ICSC::deassertDE()
{
if (_dePin != -1) {
digitalWrite(_dePin, LOW);
}
}
// Statistics. Just return a pointer to the internal stats structure.
#ifndef ICSC_NO_STATS
stats_ptr _ICSC::stats()
{
return &_stats;
}
#endif
// System level command responders
// Respond to a PING packet with a PONG packet. Send back whatever data was received.
void _ICSC::respondToPing(unsigned char station, char command, unsigned char len, char *data)
{
send(station, ICSC_SYS_PONG, len, data);
}
// Stat query request - respond with the current stats structure
#ifndef ICSC_NO_STATS
void _ICSC::respondToQSTAT(unsigned char station, char command, unsigned char len, char *data)
{
send(station, ICSC_SYS_RSTAT, sizeof(stats_t), (char *)&_stats);
}
#endif
//function which can be used to validate during a callback
//that the message comes from a BroadCast function
boolean _ICSC::isBroadCast()
{
return _recStation==ICSC_BROADCAST;
}
//A function which can be used to validate during a callback
//that the message comes from a relay function
boolean _ICSC::isRelay()
{
return _recStation==ICSC_SYS_RELAY;
}
// Global object for interraction
_ICSC ICSC;