forked from amaurial/mergCanBus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergCBUS.cpp
2418 lines (2119 loc) · 68.1 KB
/
MergCBUS.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
#include "MergCBUS.h"
/** \brief
* Constructor
* Create the internal buffers.
* Initiate the memory management and transport object.
*
*/
MergCBUS::MergCBUS(byte num_node_vars,byte num_events,byte num_events_var,byte max_device_numbers)
{
//ctor
messageFilter = 0;
bufferIndex = 0;
#ifdef USE_FLEXCAN
CANbus=FlexCAN(CAN_125KBPS);
#else
Can=MCP_CAN();
#endif
msgBuffer=CircularBuffer();
memory=MergMemoryManagement(num_node_vars,num_events,num_events_var,max_device_numbers);
nodeId=MergNodeIdentification();
nodeId.setSuportedEvents(num_events);
nodeId.setSuportedNodeVariables(num_node_vars);
nodeId.setSuportedEventsVariables(num_events_var);
message=Message();
//skip RESERVED messages
skipMessage(RESERVED);
softwareEnum=false;
//LED vars
greenLed = 255;
yellowLed = 255;
ledGreenState=HIGH;
ledYellowState=LOW;
ledtimer=millis();
//user handler function var
userHandler = 0;
//reset function pointer
resetFunc = 0;
//flag to match if an event is in memory
eventmatch = false;
//pusch button vars
push_button = 255;
pb_state = HIGH;
std_nn = 300;//std node number for a producer
initMemory();
}
/** \brief
* Start the memory reading the EEPROM values
*
*/
void MergCBUS::initMemory(){
memory.read();
loadMemory();
}
/** \brief
* Load the important EPROM memory data to RAM memory.
*/
void MergCBUS::loadMemory(){
nodeId.setNodeNumber(memory.getNodeNumber());
//nodeId.setDeviceNumber(memory.getDeviceNumber());
nodeId.setCanID(memory.getCanId());
nodeId.setFlags(memory.getNodeFlag());
if (nodeId.isSlimMode()){
node_mode = MTYP_SLIM;
#ifdef DEBUGDEF
Serial.println(F("SLIM mode"));
#endif // DEBUGDEF
}else{
node_mode = MTYP_FLIM;
#ifdef DEBUGDEF
Serial.println(F("FLIM mode"));
#endif // DEBUGDEF
}
state_mode = NORMAL;
}
uint16_t MergCBUS::getPromNN(){
return memory.getNodeNumber();
}
uint16_t MergCBUS::getNN(){
return nodeId.getNodeNumber();
}
/** \brief
* Destructor
* Not used.
*/
MergCBUS::~MergCBUS()
{
//dtor
}
/** \brief
* Initiate the CanBus layer.
* Set the port number for SPI communication.
* Set the CBUS rate and initiate the transport layer.
* @param port is the the SPI port number.
* @param rate is the can bus rate. The values defined in the can transport layer are
* CAN_5KBPS 1
* CAN_10KBPS 2
* CAN_20KBPS 3
* CAN_31K25BPS 4
* CAN_40KBPS 5
* CAN_50KBPS 6
* CAN_80KBPS 7
* CAN_100KBPS 8
* CAN_125KBPS 9
* CAN_200KBPS 10
* CAN_250KBPS 11
* CAN_500KBPS 12
* CAN_1000KBPS 13
* @param clock MCP_16MHz or MCP_8MHz
* @param retries is the number of retries to configure the can bus
* @param retryIntervalMilliseconds is the delay in milliseconds between each retry.
*/
bool MergCBUS::initCanBus(uint8_t port,unsigned int rate, const uint8_t clock, unsigned int retries,unsigned int retryIntervalMilliseconds){
unsigned int r = 0;
#ifdef USE_FLEXCAN
CANbus.begin();
#else
Can.set_cs(port);
do {
if (CAN_OK == Can.begin(rate, clock)){
#ifdef DEBUGMSG
Serial.println(F("Can rate set"));
#endif // DEBUGDEF
return true;
}
r++;
delay(retryIntervalMilliseconds);
}while (r < retries);
#ifdef DEBUGMSG
Serial.println(F("Failed to set Can rate"));
#endif // DEBUGDEF
#endif
return false;
}
/** \brief
* Initiate the CanBus layer with rate 125kps.
* Set the port number for SPI communication.
* @param port is the the SPI port number.
* @param clock MCP_16MHz or MCP_8MHz
*/
bool MergCBUS::initCanBus(uint8_t port, const uint8_t clock){
return initCanBus(port, CAN_125KBPS, clock, 20, 30);
}
/** \brief
* Initiate the CanBus layer.
* Set the port number for SPI communication.
* Set the CBUS rate and initiate the transport layer.
* The can shield clock is set default to 16Mhz
* @param port is the the SPI port number.
* @param rate is the can bus rate. The values defined in the can transport layer are
* CAN_5KBPS 1
* CAN_10KBPS 2
* CAN_20KBPS 3
* CAN_31K25BPS 4
* CAN_40KBPS 5
* CAN_50KBPS 6
* CAN_80KBPS 7
* CAN_100KBPS 8
* CAN_125KBPS 9
* CAN_200KBPS 10
* CAN_250KBPS 11
* CAN_500KBPS 12
* CAN_1000KBPS 13
* @param retries is the number of retries to configure the can bus
* @param retryIntervalMilliseconds is the delay in milliseconds between each retry.
*/
bool MergCBUS::initCanBus(uint8_t port,unsigned int rate,unsigned int retries,unsigned int retryIntervalMilliseconds){
return initCanBus(port, rate, MCP_16MHz, retries, retryIntervalMilliseconds );
}
/** \brief
* Initiate the CanBus layer with rate 125kps.
* The can shield clock is set default to 16Mhz
* Set the port number for SPI communication.
* @param port is the the SPI port number.
*/
bool MergCBUS::initCanBus(uint8_t port){
return initCanBus(port, CAN_125KBPS, MCP_16MHz, 20, 30);
}
/** \brief
* Set or unset the bit in the message bit.
* @param pos specifies the bit position @see messageFilter
* @param val if true set bit to 1, else set bit to 0
* @see skipMessage
* @see processMessage
* Internal usage.
*/
void MergCBUS::setBitMessage(byte pos,bool val){
if (val){
bitSet(messageFilter,pos);
}
else{
bitClear(messageFilter,pos);
}
}
/** \brief
* Method that deals with the majority of messages and behavior. Auto enummeration, query requests and config messages.
* If a custom function is set it calls it for every non automatic message.
* @see setUserHandlerFunction
* If the green and yellow leds are set ,it also control the standard their behaviour based on node state.
*/
uint8_t MergCBUS::run(){
controlLeds();
controlPushButton();
uint8_t resp = NO_MESSAGE;
//unsigned int resp1=NO_MESSAGE;
if (state_mode == SELF_ENUMERATION){
unsigned long tdelay = millis() - startTime;
#ifdef DEBUGDEF
Serial.println(F("Processing self ennumeration."));
#endif // DEBUGDEF
if (tdelay > SELF_ENUM_TIME){
#ifdef DEBUGDEF
Serial.println(F("Finishing self ennumeration."));
#endif // DEBUGDEF
finishSelfEnumeration();
}
}
#ifdef USE_FLEXCAN
while (readCanBus(0)){
#else
while (readCanBus()){
#endif
resp = mainProcess();
if (resp != OK ){
if (userHandler != 0){
userHandler(&message,this);
}
}
}
/*
else{
if (readCanBus(0)==true){
resp=mainProcess();
}
if (readCanBus(1)==true){
resp1=mainProcess();
}
if (resp==OK || resp1==OK){
return OK;
}
}
*/
return OK;
}
uint8_t MergCBUS::mainProcess(){
if (message.getRTR()){
//if we are a device with can id
//we need to answer this message
#ifdef DEBUGDEF
Serial.print(F("RTR message received."));
#endif // DEBUGDEF
if (nodeId.getNodeNumber() != 0){
//create the response message with no data
#ifdef DEBUGDEF
Serial.print(F("RTR message received. Sending can id: "));
Serial.println(nodeId.getCanID(),HEX);
#endif // DEBUGDEF
#ifdef USE_FLEXCAN
int i = 0;
CAN_message_t txmsg;
txmsg.id = nodeId.getCanID();
txmsg.len = 0;
txmsg.rtr = 0;
txmsg.ext = 0;
for(i = 0; i<8; i++)
{
txmsg.buf[i] = 0;
}
CANbus.write(txmsg);
#else
Can.sendMsgBuf(nodeId.getCanID(),0,0,mergCanData);
#endif
return OK;
}
}
//message for self enumeration
if (message.getOpc() == OPC_ENUM){
if (message.getNodeNumber() == nodeId.getNodeNumber()){
#ifdef DEBUGDEF
Serial.println(F("Starting message based self ennumeration."));
#endif // DEBUGDEF
doSelfEnnumeration(true);
}
return OK;
}
//do self enumeration
//collect the canid from messages with 0 size
//the state can be a message or manually
if (state_mode == SELF_ENUMERATION){
#ifdef DEBUGDEF
Serial.print(F("other msg size:"));
Serial.println(message.getCanMessageSize());
#endif // DEBUGDEF
if (message.getCanMessageSize() == 0){
#ifdef DEBUGDEF
Serial.println(F("Self ennumeration: saving others can id."));
#endif // DEBUGDEF
if (bufferIndex < SELF_ENUM_BUFFER_SIZE){
buffer[bufferIndex] = message.getCanId();
bufferIndex++;
}
}
return OK;
}
if (state_mode == LEARN && node_mode == MTYP_SLIM){
learnEvent();
return OK;
}
//treat each message individually to interpret the code
#ifdef DEBUGDEF
Serial.print(F("Message type:"));
Serial.print(message.getType());
Serial.print(F("\t OPC:"));
Serial.print(message.getOpc(),HEX);
Serial.print(F("\t STATE:"));
Serial.println(state_mode);
#endif // DEBUGDEF
switch (message.getType()){
case (DCC):
if (dccHandler != 0){
dccHandler(&message,this);
return OK;
}
break;
case (ACCESSORY):
if (nodeId.isConsumerNode()){
return handleACCMessages();
}
break;
case (GENERAL):
if (nodeId.isConsumerNode()){
return handleGeneralMessages();
}
break;
case (CONFIG):
return handleConfigMessages();
break;
default:
return UNKNOWN_MSG_TYPE;
}
return UNKNOWN_MSG_TYPE;
}
/** \brief
* Read the can bus and load the data in the message object.
* @return true if a message in the can bus.
*/
bool MergCBUS::readCanBus(byte buf_num){
byte len = 0;//number of bytes read.
bool resp=false;
byte bufIdxdata = 115;//position in the general buffer. data need 8 bytes
byte bufIdxhead = 110;//position in the general buffer. header need 4 bytes
eventmatch = false;
#ifdef USE_FLEXCAN
int i;
CAN_message_t rxmsg;
if(CANbus.available())
{
resp=CANbus.read(rxmsg);
if (resp)
{
message.clear();
message.setCanMessageSize(rxmsg.len);
for (i=0;i<rxmsg.len;i++)
{
buffer[bufIdxdata+i]=rxmsg.buf[i];
}
message.setDataBuffer(&buffer[bufIdxdata]);
if (rxmsg.rtr==0)
{
message.unsetRTR();
}
else
{
message.setRTR();
}
if (rxmsg.ext)
{
buffer[bufIdxhead+3] = (byte) (rxmsg.id & 0xFF);
buffer[bufIdxhead+2] = (byte) (rxmsg.id >> 8);
buffer[bufIdxhead+1] = (byte) ((rxmsg.id>>16) & 0x03);
buffer[bufIdxhead+1] += (byte) (((rxmsg.id>>16) & 0x1C) << 3);
buffer[bufIdxhead+1] |= 0x08 ;
buffer[bufIdxhead+0] = (byte) ((rxmsg.id>>16) >> 5 );
}
else
{
buffer[bufIdxhead+0] = (byte) ((rxmsg.id & 0x7F ) >> 3 );
buffer[bufIdxhead+1] = (byte) ((rxmsg.id & 0x07 ) << 5);
buffer[bufIdxhead+2] = 0;
buffer[bufIdxhead+3] = 0;
}
message.setHeaderBuffer(&buffer[bufIdxhead]);
message.setPriority((rxmsg.id & 0x600)>>9);
eventmatch=hasThisEvent();
#ifdef DEBUGDEF
// print message
int j=0;
Serial.print("Message: ");
for (j=0;j<rxmsg.len;j++){
Serial.print (rxmsg.buf[j], HEX);
Serial.print("\t");
}
for (j=rxmsg.len;j<8;j++){
Serial.print("-\t");
}
Serial.print("Header: ");
for (j=0;j<4;j++){
Serial.print (buffer[bufIdxhead+j], HEX);
Serial.print("\t");
}
Serial.print("CANid: ");
Serial.print (rxmsg.id & 0x7F);
Serial.print("\t");
Serial.print("D Pri: ");
Serial.print ((rxmsg.id & 0x600)>>9);
Serial.print("\t");
Serial.print("M Pri: ");
Serial.print ((rxmsg.id & 0x180)>>7);
Serial.print("\t");
Serial.print("rtr: ");
Serial.print (rxmsg.rtr);
Serial.print("\t");
Serial.println();
#endif // DEBUGDEF
}
}
#else
resp = readCanBus(&buffer[bufIdxdata],&buffer[bufIdxhead],&len,buf_num);
if (resp){
message.clear();
message.setCanMessageSize(len);
message.setDataBuffer(&buffer[bufIdxdata]);
if (Can.isRTMMessage() == 0){
#ifdef DEBUGDEF
Serial.println(F("readCanBus - unsetRTM"));;
#endif // DEBUGDEF
message.unsetRTR();
}
else{
#ifdef DEBUGDEF
Serial.println(F("readCanBus - setRTM"));
#endif // DEBUGDEF
message.setRTR();
}
message.setHeaderBuffer(&buffer[bufIdxhead]);
//eventmatch=memory.hasEvent(buffer[bufIdxdata],buffer[bufIdxdata+1],buffer[bufIdxdata+2],buffer[bufIdxdata+3]);
eventmatch = hasThisEvent();
}
#endif
return resp;
}
/** \brief
* Read the can bus from the circular buffer and load the data in the message object.
* @return true if a message in the can bus.
*/
bool MergCBUS::readCanBus(){
bool resp;
byte bufidx = 90;//position in the general buffer. data need 8 bytes
eventmatch = false;
resp = msgBuffer.get(&buffer[bufidx]);
if (resp){
message.clear();
message.setCanMessageSize(buffer[bufidx]);
message.setHeaderBuffer(&buffer[bufidx+2]);
message.setDataBuffer(&buffer[bufidx+6]);
if (buffer[bufidx+1] == 0){
#ifdef DEBUGDEF
Serial.println(F("readCanBus - unsetRTM"));
#endif // DEBUGDEF
message.unsetRTR();
}
else{
#ifdef DEBUGDEF
Serial.println(F("readCanBus - setRTM"));
#endif // DEBUGDEF
message.setRTR();
}
//eventmatch=memory.hasEvent(buffer[bufIdxdata],buffer[bufIdxdata+1],buffer[bufIdxdata+2],buffer[bufIdxdata+3]);
eventmatch = hasThisEvent();
}
return resp;
}
/** \brief
* Read the can bus and return the buffer.
* @return number of bytes read;
*/
bool MergCBUS::readCanBus(byte *data,byte *header,byte *length,byte buf_num){
#ifdef USE_FLEXCAN
int i;
CAN_message_t rxmsg;
if(CANbus.available())
{
if (CANbus.read(rxmsg))
{
*length=rxmsg.len;
for (i=0;i<rxmsg.len;i++)
{
data[i]=rxmsg.buf[i];
}
if (rxmsg.ext)
{
header[3] = (byte) (rxmsg.id & 0xFF);
header[2] = (byte) (rxmsg.id >> 8);
header[1] = (byte) ((rxmsg.id>>16) & 0x03);
header[1] += (byte) (((rxmsg.id>>16) & 0x1C) << 3);
header[1] |= 0x08 ;
header[0] = (byte) ((rxmsg.id>>16) >> 5 );
}
else
{
header[0] = (byte) (rxmsg.id >> 3 );
header[1] = (byte) ((rxmsg.id & 0x07 ) << 5);
header[2] = 0;
header[3] = 0;
}
#ifdef DEBUGDEF
// print message
int j=0;
Serial.print("Message: ");
for (j=0;j<rxmsg.len;j++){
Serial.print (rxmsg.buf[j], HEX);
Serial.print("\t");
}
for (j=rxmsg.len;j<8;j++){
Serial.print("-\t");
}
Serial.print("Header: ");
for (j=0;j<4;j++){
Serial.print (header[j], HEX);
Serial.print("\t");
}
Serial.print("CANid: ");
Serial.print (rxmsg.id & 0x7F);
Serial.print("\t");
Serial.print("D Pri: ");
Serial.print ((rxmsg.id & 0x600)>>9);
Serial.print("\t");
Serial.print("M Pri: ");
Serial.print ((rxmsg.id & 0x180)>>7);
Serial.print("\t");
Serial.print("rtr: ");
Serial.print (rxmsg.rtr);
Serial.print("\t");
Serial.println();
#endif // DEBUGDEF
return true;
}
return false;
}
#else
byte resp;
if(CAN_MSGAVAIL == Can.checkReceive()) // check if data coming
{
resp=Can.readMsgBuf(length,data,buf_num);
if (resp == CAN_OK){
Can.getCanHeader(header);
return true;
}
return false;
}
#endif
return false;
}
/** \brief
* Put node in setup mode and send the Request Node Number RQNN
* It is the function that starts the changing from slim to flim
*/
void MergCBUS::doSetup(){
state_mode = SETUP;
prepareMessage(OPC_RQNN);
#ifdef DEBUGDEF
Serial.println(F("Doing setup"));
printSentMessage();;
#endif // DEBUGDEF
sendCanMessage();
}
/** \brief
* Node when going out of service. Send NNREL.
*/
void MergCBUS::doOutOfService(){
prepareMessage(OPC_NNREL);
sendCanMessage();
}
/** \brief
* Initiate the auto enumeration procedure
* Start the timers and send a RTR message.
* @param softEnum True if the self ennumeration started by a software tool by receiving a ENUM message.
*/
void MergCBUS::doSelfEnnumeration(bool softEnum){
bufferIndex = 0;
softwareEnum = softEnum;
state_mode = SELF_ENUMERATION;
#ifdef USE_FLEXCAN
int i = 0;
CAN_message_t txmsg;
txmsg.id = nodeId.getCanID();
txmsg.len = 0;
txmsg.rtr = 1;
txmsg.ext = 0;
for(i = 0; i<8; i++)
{
txmsg.buf[i] = 0;
}
CANbus.write(txmsg);
#else
Can.setPriority(PRIO_LOW,PRIO_MIN_LOWEST);
Can.sendRTMMessage(nodeId.getCanID());
#endif
startTime = millis();
}
/** \brief
* Finish the auto enumeration. Get the lowest available can id and set the Node to NORMAL mode.
* If a software tool started the ennumeration, it return a NNACK message - in revision.
*/
void MergCBUS::finishSelfEnumeration(){
state_mode = NORMAL;
sortArray(buffer,bufferIndex);
//run the buffer and find the lowest can_id
byte cid = 1;
for (int i = 0;i < bufferIndex;i++){
if (cid < buffer[i]){
break;
}
cid++;
}
if (cid > 99){
#ifdef DEBUGDEF
Serial.println(F("Self ennumeration: no can id available."));
#endif // DEBUGDEF
//send and error message
if (softwareEnum){
sendERRMessage(CMDERR_INVALID_EVENT);
}
return;
}
#ifdef DEBUGDEF
Serial.print(F("Self ennumeration: new can id."));
Serial.println(cid);
#endif // DEBUGDEF
memory.setCanId(cid);
nodeId.setCanID(cid);
//TODO: check if it is from software
if (softwareEnum){
prepareMessageBuff(OPC_NNACK,
highByte(nodeId.getNodeNumber()),
lowByte(nodeId.getNodeNumber()) );
#ifdef USE_FLEXCAN
int i = 0;
CAN_message_t txmsg;
txmsg.id = nodeId.getCanID();
txmsg.len = 3;
txmsg.rtr = 0;
txmsg.ext = 0;
for(i = 0; i<txmsg.len; i++)
{
txmsg.buf[i] = mergCanData[i];
}
CANbus.write(txmsg);
#else
Can.sendMsgBuf(nodeId.getCanID(),0,3,mergCanData);
#endif
}
return;
}
/** \brief
* Handle all config messages
* Do the hard work of learning and managing the memory
*/
byte MergCBUS::handleConfigMessages(){
uint8_t ind,val,evidx,resp;
unsigned int ev,nn;
//config messages should be directed to node number or device id
if (message.getNodeNumber() != nodeId.getNodeNumber()) {
#ifdef DEBUGDEF
Serial.println(F("handleConfigMessages- NN different from message NN"));
#endif // DEBUGDEF
if (state_mode == NORMAL || state_mode == SELF_ENUMERATION || state_mode == BOOT){
#ifdef DEBUGDEF
Serial.println(F("handleConfigMessages- not in setup mode. leaving"));
#endif // DEBUGDEF
return OK;
}
}
#ifdef DEBUGDEF
Serial.println(F("handleConfigMessages- Processing config message"));
Serial.print(F("handleConfigMessages- state:"));
Serial.println(state_mode);
printReceivedMessage();
#endif // DEBUGDEF
nn = nodeId.getNodeNumber();
uint8_t opc = message.getOpc();
switch (opc){
case OPC_RSTAT:
//command station
return OK;
break;
case OPC_QNN:
//response with a OPC_PNN if we have a node ID
//[<MjPri><MinPri=3><CANID>]<B6><NN Hi><NN Lo><Manuf Id><Module Id><Flags>
if (nn > 0){
prepareMessage(OPC_PNN);
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_QNN sending OPC_PNN"));
printSentMessage();
#endif // DEBUGDEF
return sendCanMessage();
}
break;
case OPC_RQNP:
//Answer with OPC_PARAMS
//<0xEF><PARA 1><PARA 2><PARA 3> <PARA 4><PARA 5><PARA 6><PARA 7>
//The parameters are defined as:
//Para 1 The manufacturer ID as a HEX numeric (If the manufacturer has a NMRA
//number this can be used)
//Para 2 Minor code version as an alphabetic character (ASCII)
//Para 3 Manufacturer’s module identifier as a HEX numeric
//Para 4 Number of supported events as a HEX numeric
//Para 5 Number of Event Variables per event as a HEX numeric
//Para 6 Number of supported Node Variables as a HEX numeric
//Para 7 Major version as a HEX numeric. (can be 0 if no major version allocated)
//Para 8 Node Flags
if (state_mode == SETUP){
clearMsgToSend();
prepareMessage(OPC_PARAMS);
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_RQNP sending OPC_PARAMS"));
printSentMessage();
#endif // DEBUGDEF
return sendCanMessage();
}
break;
case OPC_RQMN:
//Answer with OPC_NAME
if (state_mode == SETUP){
prepareMessage(OPC_NAME);
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_RQNN sending OPC_NAME"));
printSentMessage();
#endif // DEBUGDEF
return sendCanMessage();
}else{
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_RQNN and not in setup mode."));
#endif // DEBUGDEF
sendERRMessage(CMDERR_NOT_SETUP);
}
break;
case OPC_SNN:
//set the node number
//answer with OPC_NNACK
if (state_mode == SETUP){
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_SNN sending OPC_NNACK"));
//printSentMessage();
#endif // DEBUGDEF
nodeId.setNodeNumber(message.getNodeNumber());
memory.setNodeNumber(nodeId.getNodeNumber());
prepareMessage(OPC_NNACK);
state_mode = NORMAL;
setFlimMode();
saveNodeFlags();
return sendCanMessage();
}else{
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_SNN and not in setup mode."));
//printSentMessage();
#endif // DEBUGDEF
sendERRMessage(CMDERR_NOT_SETUP);
}
break;
case OPC_NNLRN:
//put the node in the lear mode
state_mode = LEARN;
#ifdef DEBUGDEF
Serial.println(F("going to LEARN MODE."));
//printSentMessage();
#endif // DEBUGDEF
break;
case OPC_NNULN:
//leaving the learn mode
state_mode = NORMAL;
#ifdef DEBUGDEF
Serial.println(F("going to NORMAL MODE."));
//printSentMessage();
#endif // DEBUGDEF
break;
case OPC_NNCLR:
//clear all events from the node
if (state_mode == LEARN){
#ifdef DEBUGDEF
Serial.println(F("Clear all events."));
//printSentMessage();
#endif // DEBUGDEF
memory.eraseAllEvents();
return OK;
}
break;
case OPC_NNEVN:
//read the events available in memory
prepareMessage(OPC_EVNLF);
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_NNEVN sending OPC_EVNLF"));
printSentMessage();
#endif // DEBUGDEF
return sendCanMessage();
break;
case OPC_NERD:
//send back all stored events in message OPC_ENRSP
uint8_t i;
i = memory.getNumEvents();
#ifdef DEBUGDEF
Serial.print(F("RECEIVED OPC_NERD sending OPC_ENRSP "));
Serial.println(i);
//printSentMessage();
#endif // DEBUGDEF
if (i > 0){
//byte *events=memory.getEvents();
for (uint8_t j = 0;j < i;j++){
byte *event = memory.getEvent(j);
if (memory.getLastError() != 0){
#ifdef DEBUGDEF
Serial.println(F("Get event.Index invalid"));
#endif // DEBUGDEF
sendERRMessage(CMDERR_INV_NV_IDX);
break;
}
prepareMessageBuff(OPC_ENRSP,highByte(nn),lowByte(nn),
event[0],
event[1],
event[2],
event[3],
(j+1));
ind = sendCanMessage();
if (ind != OK){
Serial.println(F("FAILED to send CAN"));
}
#ifdef DEBUGDEF
Serial.println();
printSentMessage();
#endif // DEBUGDEF
}
}
break;
case OPC_RQEVN:
//request the number of stored events
prepareMessage(OPC_NUMEV);
#ifdef DEBUGDEF
Serial.print(F("RECEIVED OPC_RQEVN sending OPC_NUMEV "));
Serial.println(memory.getNumEvents());
printSentMessage();
#endif // DEBUGDEF
sendCanMessage();
break;
case OPC_BOOT:
//boot mode. not supported
return OK;
break;
case OPC_ENUM:
//has to be handled in the automatic procedure
if (message.getNodeNumber()==nodeId.getNodeNumber()){
#ifdef DEBUGDEF
Serial.println(F("Doing self ennumeration"));
#endif // DEBUGDEF
doSelfEnnumeration(true);
}
break;
case OPC_NVRD:
//answer with NVANS
ind=message.getNodeVariableIndex();
prepareMessageBuff(OPC_NVANS,highByte(nn),lowByte(nn),ind,memory.getVar(ind-1));//the CBUS index start with 1
#ifdef DEBUGDEF
Serial.println(F("RECEIVED OPC_NVRD sending OPC_NVANS"));
printSentMessage();
#endif // DEBUGDEF
sendCanMessage();
break;
case OPC_NENRD:
//Request read of stored events by event index
clearMsgToSend();
ind=message.getEventIndex();
byte *event;
event=memory.getEvent(ind-1);//the CBUS index start with 1
prepareMessageBuff(OPC_ENRSP,highByte(nn),lowByte(nn),event[0],event[1],event[2],event[3],ind);