-
Notifications
You must be signed in to change notification settings - Fork 0
/
NMEA2000.cpp
2572 lines (2239 loc) · 110 KB
/
NMEA2000.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
/*
NMEA2000.cpp
Copyright (c) 2015-2020 Timo Lappalainen, Kave Oy, www.kave.fi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "NMEA2000.h"
#include "N2kDef.h"
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
#include "N2kGroupFunctionDefaultHandlers.h"
#endif
#include <string.h>
#include <stdlib.h>
#include <iostream>
#define DebugStream Serial
// #define NMEA2000_FRAME_ERROR_DEBUG
// #define NMEA2000_FRAME_IN_DEBUG
// #define NMEA2000_FRAME_OUT_DEBUG
// #define NMEA2000_MSG_DEBUG
// #define NMEA2000_BUF_DEBUG
// #define NMEA2000_DEBUG
#if defined(NMEA2000_FRAME_ERROR_DEBUG)
# define N2kFrameErrDbg(fmt, args...) DebugStream.print (fmt , ## args)
# define N2kFrameErrDbgln(fmt, args...) DebugStream.println (fmt , ## args)
#else
# define N2kFrameErrDbg(fmt, args...)
# define N2kFrameErrDbgln(fmt, args...)
#endif
#if defined(NMEA2000_FRAME_IN_DEBUG)
# define N2kFrameInDbg(fmt, args...) DebugStream.print (fmt , ## args)
# define N2kFrameInDbgln(fmt, args...) DebugStream.println (fmt , ## args)
#else
# define N2kFrameInDbg(fmt, args...)
# define N2kFrameInDbgln(fmt, args...)
#endif
#if defined(NMEA2000_FRAME_OUT_DEBUG)
# define N2kFrameOutDbg(fmt, args...) DebugStream.print (fmt , ## args)
# define N2kFrameOutDbgln(fmt, args...) DebugStream.println (fmt , ## args)
#else
# define N2kFrameOutDbg(fmt, args...)
# define N2kFrameOutDbgln(fmt, args...)
#endif
#if defined(NMEA2000_MSG_DEBUG)
# define N2kMsgDbg(fmt, args...) DebugStream.print (fmt , ## args)
# define N2kMsgDbgln(fmt, args...) DebugStream.println (fmt , ## args)
#else
# define N2kMsgDbg(fmt, args...)
# define N2kMsgDbgln(fmt, args...)
#endif
#if defined(NMEA2000_BUF_DEBUG)
# define DbgPrintBuf(len, buf, addln) PrintBuf(&DebugStream, len, buf, addln)
#else
# define DbgPrintBuf(len, buf, addln)
#endif
#if defined(NMEA2000_DEBUG)
# define N2kDbg(fmt, args...) DebugStream.print (fmt , ## args)
# define N2kDbgln(fmt, args...) DebugStream.println (fmt , ## args)
#else
# define N2kDbg(fmt, args...)
# define N2kDbgln(fmt, args...)
#endif
// #define NMEA2000_MEMORY_TEST 1
#if defined(NMEA2000_MEMORY_TEST)
#include <MemoryFree.h>
void N2kPrintFreeMemory(const char *Source) {
Serial.print(Source);
Serial.print(", free memory=");
Serial.println(freeMemory());
}
#else
#define N2kPrintFreeMemory(a)
#endif
#define N2kAddressClaimTimeout 250
#define MaxHeartbeatInterval 655320UL
#define TP_MAX_FRAMES 5 // Max frames, which can be received at time
#define TP_CM 60416L /* Multi packet connection management, TP.CM */
#define TP_DT 60160L /* Multi packet data transfer, TP.DT */
#define TP_CM_BAM 32
#define TP_CM_RTS 16
#define TP_CM_CTS 17
#define TP_CM_ACK 19
#define TP_CM_Abort 255
#define TP_CM_AbortBusy 1 // Already in one or more connection managed sessions and cannot support another.
#define TP_CM_AbortNoResources 2 // System resources were needed for another task so this connection managed session was terminated.
#define TP_CM_AbortTimeout 3 // A timeout occurred and this is the connection abort to close the session.
const unsigned long DefTransmitMessages[] PROGMEM = {
59392L, /* ISO Acknowledgement, pri=6, period=NA */
59904L, /* ISO Request, pri=6, period=NA */
#if !defined(N2K_NO_ISO_MULTI_PACKET_SUPPORT)
TP_DT, /* Multi packet data transfer, TP.DT, pri=6, period=NA */
TP_CM, /* Multi packet connection management, TP.CM, pri=6, period=NA */
#endif
60928L, /* ISO Address Claim, pri=6, period=NA */
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
126208L, /* NMEA Request/Command/Acknowledge group function, pri=3, period=NA */
#endif
126464L, /* PGN List (Transmit and Receive), pri=6, period=NA */
#if !defined(N2K_NO_HEARTBEAT_SUPPORT)
126993L, /* Heartbeat, pri=7, period=60000 */
#endif
126996L, /* Product information, pri=6, period=NA */
126998L, /* Configuration information, pri=6, period=NA */
0};
const unsigned long DefReceiveMessages[] PROGMEM = {
59392L, /* ISO Acknowledgement, pri=6, period=NA */
59904L, /* ISO Request, pri=6, period=NA */
#if !defined(N2K_NO_ISO_MULTI_PACKET_SUPPORT)
TP_DT, /* Multi packet data transfer, TP.DT */
TP_CM, /* Multi packet connection management, TP.CM */
#endif
60928L, /* ISO Address Claim */
65240L, /* Commanded Address */
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
126208L, /* NMEA Request/Command/Acknowledge group function */
#endif
0};
bool IsSingleFrameSystemMessage(unsigned long PGN) {
switch (PGN) {
case 59392L: /* ISO Acknowledgement */
case TP_DT: /* Multi packet data transfer, TP.DT */
case TP_CM: /* Multi packet connection management, TP.CM */
case 59904L: /* ISO Request */
case 60928L: /* ISO Address Claim */
return true;
}
return false;
}
bool IsFastPacketSystemMessage(unsigned long PGN) {
switch (PGN) {
case 65240L: /* Commanded Address*/
case 126208L: /* NMEA Request/Command/Acknowledge group function */
return true;
}
return false;
}
bool IsDefaultSingleFrameMessage(unsigned long PGN) {
switch (PGN) {
case 126992L: // System date/time, pri=3, period=1000
case 126993L: // Heartbeat, pri=7, period=60000
case 127245L: // Rudder, pri=2, period=100
case 127250L: // Vessel Heading, pri=2, period=100
case 127251L: // Rate of Turn, pri=2, period=100
case 127257L: // Attitude, pri=3, period=1000
case 127488L: // Engine parameters rapid, rapid Update, pri=2, period=100
case 127493L: // Transmission parameters: dynamic, pri=2, period=100
case 127501L: // Binary status report, pri=3, period=NA
case 127505L: // Fluid level, pri=6, period=2500
case 127508L: // Battery Status, pri=6, period=1500
case 128259L: // Boat speed, pri=2, period=1000
case 128267L: // Water depth, pri=3, period=1000
case 129025L: // Lat/lon rapid, pri=2, period=100
case 129026L: // COG SOG rapid, pri=2, period=250
case 129283L: // Cross Track Error, pri=3, period=1000
case 130306L: // Wind Speed, pri=2, period=100
case 130310L: // Outside Environmental parameters, pri=5, period=500
case 130311L: // Environmental parameters, pri=5, period=500
case 130312L: // Temperature, pri=5, period=2000
case 130313L: // Humidity, pri=5, period=2000
case 130314L: // Pressure, pri=5, period=2000
case 130316L: // Temperature extended range, pri=5, period=NA
case 130576L: // Small Craft Status (Trim Tab position), pri=2, period=200
return true;
}
return false;
}
bool IsMandatoryFastPacketMessage(unsigned long PGN) {
switch (PGN) {
case 126464L: // PGN List (Transmit and Receive), pri=6, period=NA
case 126996L: // Product information, pri=6, period=NA
case 126998L: // Configuration information, pri=6, period=NA
return true;
}
return false;
}
bool IsDefaultFastPacketMessage(unsigned long PGN) {
switch (PGN) {
case 126983L: // Alert, pri=2, period=1000
case 126984L: // Alert Response, pri=2, period=NA
case 126985L: // Alert Text, pri=2, period=10000
case 126986L: // Alert Configuration, pri=2, period=NA
case 126987L: // Alert Threshold, pri=2, period=NA
case 126988L: // Alert Value, pri=2, period=10000
case 127233L: // Alert Value, pri=3, period=NA
case 127237L: // Heading/Track control, pri=2, period=250
case 127489L: // Engine parameters dynamic, pri=2, period=500
case 127496L: // Trip fuel consumption, vessel, pri=5, period=1000
case 127497L: // Trip fuel consumption, engine, pri=5, period=1000
case 127498L: // Engine parameters static, pri=5, period=NA
case 127503L: // AC Input Status, pri=6, period=1500
case 127504L: // AC Output Status, pri=6, period=1500
case 127506L: // DC Detailed status, pri=6, period=1500
case 127507L: // Charger status, pri=6, period=1500
case 127509L: // Inverter status, pri=6, period=1500
case 127510L: // Charger configuration status, pri=6, period=NA
case 127511L: // Inverter Configuration Status, pri=6, period=NA
case 127512L: // AGS configuration status, pri=6, period=NA
case 127513L: // Battery configuration status, pri=6, period=NA
case 127514L: // AGS Status, pri=6, period=1500
case 128275L: // Distance log, pri=6, period=1000
case 128520L: // Tracked Target Data, pri=2, period=1000
case 129029L: // GNSS Position Data, pri=3, period=1000
case 129038L: // AIS Class A Position Report, pri=4, period=NA
case 129039L: // AIS Class B Position Report, pri=4, period=NA
case 129040L: // AIS Class B Extended Position Report, pri=4, period=NA
case 129041L: // AIS Aids to Navigation (AtoN) Report, pri=4, period=NA
case 129044L: // Datum, pri=6, period=10000
case 129045L: // User Datum Settings, pri=6, period=NA
case 129284L: // Navigation info, pri=3, period=1000
case 129285L: // Waypoint list, pri=3, period=NA
case 129301L: // Time to/from Mark, pri=3, period=1000
case 129302L: // Bearing and Distance between two Marks, pri=6, period=NA
case 129538L: // GNSS Control Status, pri=6, period=NA
case 129540L: // GNSS Sats in View, pri=6, period=1000
case 129541L: // GPS Almanac Data, pri=6, period=NA
case 129542L: // GNSS Pseudorange Noise Statistics, pri=6, period=1000
case 129545L: // GNSS RAIM Output, pri=6, period=NA
case 129547L: // GNSS Pseudorange Error Statistics, pri=6, period=NA
case 129549L: // DGNSS Corrections, pri=6, period=NA
case 129551L: // GNSS Differential Correction Receiver Signal, pri=6, period=NA
case 129556L: // GLONASS Almanac Data, pri=6, period=NA
case 129792L: // AIS DGNSS Broadcast Binary Message, pri=6, period=NA
case 129793L: // AIS UTC and Date Report, pri=7, period=NA
case 129794L: // AIS Class A Static data, pri=6, period=NA
case 129795L: // AIS Addressed Binary Message, pri=5, period=NA
case 129796L: // AIS Acknowledge, pri=7, period=NA
case 129797L: // AIS Binary Broadcast Message, pri=5, period=NA
case 129798L: // AIS SAR Aircraft Position Report, pri=4, period=NA
case 129799L: // Radio Frequency/Mode/Power, pri=3, period=NA
case 129800L: // AIS UTC/Date Inquiry, pri=7, period=NA
case 129801L: // AIS Addressed Safety Related Message, pri=5, period=NA
case 129802L: // AIS Safety Related Broadcast Message, pri=5, period=NA
case 129803L: // AIS Interrogation PGN, pri=7, period=NA
case 129804L: // AIS Assignment Mode Command, pri=7, period=NA
case 129805L: // AIS Data Link Management Message, pri=7, period=NA
case 129806L: // AIS Channel Management, pri=7, period=NA
case 129807L: // AIS Group Assignment, pri=7, period=NA
case 129808L: // DSC Call Information, pri=8, period=NA
case 129809L: // AIS Class B Static Data: Part A, pri=6, period=NA
case 129810L: // AIS Class B Static Data Part B, pri=6, period=NA
case 129811L: // AIS Single Slot Binary Message, pri=5, period=NA
case 129812L: // AIS Multi Slot Binary Message, pri=5, period=NA
case 129813L: // AIS Long-Range Broadcast Message, pri=5, period=NA
case 130052L: // Loran-C TD Data, pri=3, period=1000
case 130053L: // Loran-C Range Data, pri=3, period=1000
case 130054L: // Loran-C Signal Data, pri=3, period=1000
case 130060L: // Label, pri=7, period=NA
case 130061L: // Channel Source Configuration, pri=7, period=NA
case 130064L: // Route and WP Service - Database List, pri=7, period=NA
case 130065L: // Route and WP Service - Route List, pri=7, period=NA
case 130066L: // Route and WP Service - Route/WP-List Attributes, pri=7, period=NA
case 130067L: // Route and WP Service - Route - WP Name & Position, pri=7, period=NA
case 130068L: // Route and WP Service - Route - WP Name, pri=7, period=NA
case 130069L: // Route and WP Service - XTE Limit & Navigation Method, pri=7, period=NA
case 130070L: // Route and WP Service - WP Comment, pri=7, period=NA
case 130071L: // Route and WP Service - Route Comment, pri=7, period=NA
case 130072L: // Route and WP Service - Database Comment, pri=7, period=NA
case 130073L: // Route and WP Service - Radius of Turn, pri=7, period=NA
case 130074L: // Route and WP Service - WP List - WP Name & Position, pri=7, period=NA
case 130320L: // Tide Station Data, pri=6, period=1000
case 130321L: // Salinity Station Data, pri=6, period=1000
case 130322L: // Current Station Data, pri=6, period=1000
case 130323L: // Meteorological Station Data, pri=6, period=1000
case 130324L: // Moored Buoy Station Data, pri=6, period=1000
case 130567L: // Watermaker Input Setting and Status, pri=6, period=2500
case 130577L: // Direction Data PGN, pri=3, period=1000
case 130578L: // Vessel Speed Components, pri=2, period=250
return true;
}
return false;
}
bool IsProprietaryFastPacketMessage(unsigned long PGN) {
return ( PGN==126720L ) || ( 130816L<=PGN && PGN<=131071L );
}
bool tNMEA2000::IsProprietaryMessage(unsigned long PGN) {
return IsProprietaryFastPacketMessage(PGN) || ( PGN==61184L ) || ( 65280L<=PGN && PGN<=65535L );
}
const tNMEA2000::tProductInformation DefProductInformation PROGMEM = {
2101, // N2kVersion
666, // ProductCode
"Arduino N2k->PC", //N2kModelID
"1.0.0.0", //N2kSwCode
"1.0.0", // N2kModelVersion
"00000001", // N2kModelSerialCode
0, // CertificationLevel
1 // LoadEquivalency
};
const char DefManufacturerInformation [] PROGMEM = "NMEA2000 library, https://github.com/ttlappalainen/NMEA2000";
const char DefInstallationDescription1 [] PROGMEM = "";
const char DefInstallationDescription2 [] PROGMEM = "";
//*****************************************************************************
void tNMEA2000::tProductInformation::Clear() {
memset(this,0,sizeof(tProductInformation));
}
//*****************************************************************************
bool tNMEA2000::tProductInformation::IsSame(const tProductInformation &Other) {
return memcmp(this,&Other,sizeof(tProductInformation))==0;
}
//*****************************************************************************
void tNMEA2000::ClearCharBuf(size_t MaxLen, char *buf) {
if ( buf==0 ) return;
size_t i=0;
for (; i<MaxLen; i++) buf[i]=0;
}
//*****************************************************************************
void tNMEA2000::SetCharBuf(const char *str, size_t MaxLen, char *buf) {
if ( buf==0 || MaxLen==0 ) return; // nothing to do for 0 buffer
if ( str==0 ) { buf[0]=0; return; }
size_t i=0;
for (; i<MaxLen-1 && str[i]!=0; i++) buf[i]=str[i];
for (; i<MaxLen; i++) buf[i]=0;
buf[MaxLen-1]=0; // Force null termination
}
//*****************************************************************************
void tNMEA2000::ClearSetCharBuf(const char *str, size_t MaxLen, char *buf) {
ClearCharBuf(MaxLen,buf);
if (str) SetCharBuf(str,MaxLen,buf);
}
//*****************************************************************************
tNMEA2000::tNMEA2000() {
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
pGroupFunctionHandlers=0;
#endif
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
InstallationDescriptionChanged=false;
#endif
ForwardStream=0;
for (int i=0; i<N2kMessageGroups; i++) {SingleFrameMessages[i]=0; FastPacketMessages[i]=0;}
N2kCANMsgBuf=0;
MaxN2kCANMsgs=0;
MaxCANSendFrames=40;
MaxCANReceiveFrames=0; // Use driver default
CANSendFrameBuf=0;
MsgHandler=0;
MsgHandlers=0;
ISORqstHandler=0;
DeviceReady=false;
AddressChanged=false;
DeviceInformationChanged=false;
dbMode=dm_None;
N2kMode=N2km_ListenOnly;
ForwardType=fwdt_Actisense;
ForwardMode=0;
EnableForward();
SetForwardSystemMessages();
SetForwardOwnMessages();
LocalConfigurationInformationData=0;
SetProgmemConfigurationInformation(DefManufacturerInformation,
DefInstallationDescription1,
DefInstallationDescription2);
Devices=0;
DeviceCount=1;
}
//*****************************************************************************
void tNMEA2000::SetDeviceCount(const uint8_t _DeviceCount) {
// Note that we can set this only before any initialization. Limit count to 10.
if ( Devices==0 && _DeviceCount>=1 && _DeviceCount<10 ) DeviceCount=_DeviceCount;
}
//*****************************************************************************
void tNMEA2000::InitDevices() {
if ( Devices==0 ) {
N2kDbgln("Init devices");
Devices=new tInternalDevice[DeviceCount];
MaxCANSendFrames*=DeviceCount; // We need bigger buffer for sending all information
// for (int i=0; i<DeviceCount; i++) Devices[i].tDevice();
// We set default device information here.
Devices[0].LocalProductInformation=0;
Devices[0].ProductInformation=&DefProductInformation;
for ( int i=0; i<DeviceCount; i++) { // Initialize all devices with some value
SetDeviceInformation(1+i, // 21 bit resolution, max 2097151. Each device from same manufacturer should have unique number.
130, // PC Gateway. See codes on http://www.nmea.org/Assets/20120726%20nmea%202000%20class%20&%20function%20codes%20v%202.00.pdf
25, // Inter/Intranetwork Device. See codes on http://www.nmea.org/Assets/20120726%20nmea%202000%20class%20&%20function%20codes%20v%202.00.pdf
2046, // Maximum 2046. See the list of codes on http://www.nmea.org/Assets/20121020%20nmea%202000%20registration%20list.pdf
4, // Marine
i
);
if ( i>0 ) {
Devices[i].LocalProductInformation=0;
Devices[i].ProductInformation=0;
}
}
}
}
//*****************************************************************************
void tNMEA2000::SetProductInformation(const tProductInformation *_ProductInformation, int iDev) {
if ( !IsValidDevice(iDev) ) return;
InitDevices();
Devices[iDev].ProductInformation=_ProductInformation;
if (Devices[iDev].ProductInformation==0) Devices[iDev].ProductInformation=Devices[iDev].LocalProductInformation;
if (Devices[iDev].ProductInformation==0) Devices[iDev].ProductInformation=&DefProductInformation;
}
//*****************************************************************************
void tNMEA2000::SetProductInformation(const char *_ModelSerialCode,
unsigned short _ProductCode,
const char *_ModelID,
const char *_SwCode,
const char *_ModelVersion,
unsigned char _LoadEquivalency,
unsigned short _N2kVersion,
unsigned char _CertificationLevel,
int iDev) {
if ( !IsValidDevice(iDev) ) return;
InitDevices();
if (Devices[iDev].LocalProductInformation==0) {
Devices[iDev].LocalProductInformation=new tProductInformation();
}
Devices[iDev].ProductInformation=Devices[iDev].LocalProductInformation;
Devices[iDev].LocalProductInformation->Set(_ModelSerialCode,_ProductCode,_ModelID,_SwCode,_ModelVersion,_LoadEquivalency,_N2kVersion,_CertificationLevel);
}
//*****************************************************************************
void tNMEA2000::SetConfigurationInformation(const char *ManufacturerInformation,
const char *InstallationDescription1,
const char *InstallationDescription2) {
if ( LocalConfigurationInformationData!=0 ) free(LocalConfigurationInformationData); // This happens on second call, which is not good.
LocalConfigurationInformationData=0;
size_t ManInfoLen=(ManufacturerInformation?strlen(ManufacturerInformation)+1:0);
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
size_t InstDesc1Len=Max_N2kConfigurationInfoField_len;
size_t InstDesc2Len=Max_N2kConfigurationInfoField_len;
#else
size_t InstDesc1Len=(InstallationDescription1?strlen(InstallationDescription1)+1:0);
size_t InstDesc2Len=(InstallationDescription2?strlen(InstallationDescription2)+1:0);
#endif
if ( ManInfoLen>Max_N2kConfigurationInfoField_len ) ManInfoLen=Max_N2kConfigurationInfoField_len;
if ( InstDesc1Len>Max_N2kConfigurationInfoField_len ) InstDesc1Len=Max_N2kConfigurationInfoField_len;
if ( InstDesc2Len>Max_N2kConfigurationInfoField_len ) InstDesc2Len=Max_N2kConfigurationInfoField_len;
size_t TotalSize=ManInfoLen+InstDesc1Len+InstDesc2Len;
void *mem=(TotalSize>0?malloc(TotalSize):0);
LocalConfigurationInformationData=(char*)mem;
char *Info=LocalConfigurationInformationData;
SetCharBuf(InstallationDescription1,InstDesc1Len,Info);
ConfigurationInformation.InstallationDescription1=(InstallationDescription1?Info:0);
Info+=InstDesc1Len;
SetCharBuf(InstallationDescription2,InstDesc2Len,Info);
ConfigurationInformation.InstallationDescription2=(InstallationDescription2?Info:0);
Info+=InstDesc2Len;
SetCharBuf(ManufacturerInformation,ManInfoLen,Info);
ConfigurationInformation.ManufacturerInformation=(ManufacturerInformation?Info:0);
}
//*****************************************************************************
void tNMEA2000::SetProgmemConfigurationInformation(const char *ManufacturerInformation,
const char *InstallationDescription1,
const char *InstallationDescription2) {
if ( LocalConfigurationInformationData!=0 ) free(LocalConfigurationInformationData); // This happens on second call, which is not good.
LocalConfigurationInformationData=0;
ConfigurationInformation.ManufacturerInformation=ManufacturerInformation;
ConfigurationInformation.InstallationDescription1=InstallationDescription1;
ConfigurationInformation.InstallationDescription2=InstallationDescription2;
}
//*****************************************************************************
size_t tNMEA2000::GetFastPacketTxPGNCount(int iDev) {
if ( !IsValidDevice(iDev) ) return 0;
unsigned long ListPGN;
size_t FPTxPGNCount=0;
for (int i=0; (ListPGN=pgm_read_dword(&DefTransmitMessages[i]))!=0; i++) {
if ( IsFastPacketPGN(ListPGN) ) FPTxPGNCount++;
}
if (Devices[iDev].TransmitMessages!=0) {
for (int i=0; (ListPGN=pgm_read_dword(&Devices[iDev].TransmitMessages[i]))!=0; i++) {
if ( IsFastPacketPGN(ListPGN) ) FPTxPGNCount++;
}
}
return FPTxPGNCount;
}
//*****************************************************************************
int tNMEA2000::GetSequenceCounter(unsigned long PGN, int iDev) {
if ( !IsValidDevice(iDev) ) return 0;
if ( Devices[iDev].PGNSequenceCounters==0 ) { // Sequence counters has not yet been initialized
Devices[iDev].MaxPGNSequenceCounters=GetFastPacketTxPGNCount(iDev)+1; // Reserve 1 for undefined PGNs
Devices[iDev].PGNSequenceCounters=new unsigned long[Devices[iDev].MaxPGNSequenceCounters];
for ( size_t i=0; i<Devices[iDev].MaxPGNSequenceCounters; i++ ) Devices[iDev].PGNSequenceCounters[i]=0;
}
if ( Devices[iDev].PGNSequenceCounters==0 ) return 0; // Should not be. Only in case of memory allocation problem.
size_t last=Devices[iDev].MaxPGNSequenceCounters-1;
unsigned long sc;
for ( size_t i=0; i<last; i++ ) {
if ( Devices[iDev].PGNSequenceCounters[i]==0 ) { // Empty place, use this
Devices[iDev].PGNSequenceCounters[i]=PGN;
return 0; // Start from sequence 0
}
if ( (Devices[iDev].PGNSequenceCounters[i]&0x00ffffff) == PGN ) { // Found counter, use it
sc=Devices[iDev].PGNSequenceCounters[i]>>24;
sc++; if (sc>7) sc=0; // Get next counter
Devices[iDev].PGNSequenceCounters[i]=PGN | (sc << 24);
return sc;
}
}
// PGN counter not found, so use common
sc=Devices[iDev].PGNSequenceCounters[last];
sc++; if (sc>7) sc=0;
Devices[iDev].PGNSequenceCounters[last]=sc;
return sc;
}
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
//*****************************************************************************
void CopyProgmemString(const char *str, size_t MaxLen, char *buf) {
if ( buf==0 || MaxLen==0 ) return; // nothing to do for 0 buffer
if ( str==0 ) { buf[0]=0; return; }
size_t i=0;
char c;
for (; i<MaxLen-1 && (c=pgm_read_byte(&(str[i])))!=0; i++) buf[i]=c;
for (; i<MaxLen; i++) buf[i]=0;
buf[MaxLen-1]=0; // Force null termination
}
//*****************************************************************************
bool tNMEA2000::IsTxPGN(unsigned long PGN, int iDev) {
if ( !IsValidDevice(iDev) ) return false;
unsigned long ListPGN;
for (int i=0; (ListPGN=pgm_read_dword(&DefTransmitMessages[i]))!=0; i++) {
if ( ListPGN==PGN ) return true;
}
if (Devices[iDev].TransmitMessages!=0) {
for (int i=0; (ListPGN=pgm_read_dword(&Devices[iDev].TransmitMessages[i]))!=0; i++) {
if ( ListPGN==PGN ) return true;
}
}
return false;
}
//*****************************************************************************
const tNMEA2000::tProductInformation * tNMEA2000::GetProductInformation(int iDev, bool &IsProgMem) const {
if ( !IsValidDevice(iDev) ) return 0;
int iPIDev=iDev;
if ( Devices[iPIDev].ProductInformation==0 ) iPIDev=0; // Use first device product information
if ( Devices[iPIDev].ProductInformation==0 ) return 0; // Can not do anything.
IsProgMem = (Devices[iPIDev].ProductInformation!=Devices[iPIDev].LocalProductInformation );
return Devices[iPIDev].ProductInformation;
}
//*****************************************************************************
unsigned short tNMEA2000::GetN2kVersion(int iDev) const {
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return 0;
if ( !IsProgMem ) {
return ProductInformation->N2kVersion;
} else {
return pgm_read_word(&ProductInformation->N2kVersion);
}
}
//*****************************************************************************
unsigned short tNMEA2000::GetProductCode(int iDev) const {
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return 0;
if ( !IsProgMem ) {
return ProductInformation->ProductCode;
} else {
return pgm_read_word(&ProductInformation->ProductCode);
}
}
//*****************************************************************************
void tNMEA2000::GetModelID(char *buf, size_t max_len, int iDev) const {
if ( max_len==0 ) return;
buf[0]=0;
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return;
if ( !IsProgMem ) {
SetCharBuf(ProductInformation->N2kModelID,max_len,buf);
} else {
CopyProgmemString(ProductInformation->N2kModelID,max_len,buf);
}
}
//*****************************************************************************
void tNMEA2000::GetSwCode(char *buf, size_t max_len, int iDev) const {
if ( max_len==0 ) return;
buf[0]=0;
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return;
if ( !IsProgMem ) {
SetCharBuf(ProductInformation->N2kSwCode,max_len,buf);
} else {
CopyProgmemString(ProductInformation->N2kSwCode,max_len,buf);
}
}
//*****************************************************************************
void tNMEA2000::GetModelVersion(char *buf, size_t max_len, int iDev) const {
if ( max_len==0 ) return;
buf[0]=0;
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return;
if ( !IsProgMem ) {
SetCharBuf(ProductInformation->N2kModelVersion,max_len,buf);
} else {
CopyProgmemString(ProductInformation->N2kModelVersion,max_len,buf);
}
}
//*****************************************************************************
void tNMEA2000::GetModelSerialCode(char *buf, size_t max_len, int iDev) const {
if ( max_len==0 ) return;
buf[0]=0;
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return;
if ( !IsProgMem ) {
SetCharBuf(ProductInformation->N2kModelSerialCode,max_len,buf);
} else {
CopyProgmemString(ProductInformation->N2kModelSerialCode,max_len,buf);
}
}
//*****************************************************************************
unsigned char tNMEA2000::GetCertificationLevel(int iDev) const {
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return 0;
if ( !IsProgMem ) {
return ProductInformation->CertificationLevel;
} else {
return pgm_read_byte(&ProductInformation->CertificationLevel);
}
}
//*****************************************************************************
unsigned char tNMEA2000::GetLoadEquivalency(int iDev) const {
bool IsProgMem;
const tProductInformation *ProductInformation=GetProductInformation(iDev,IsProgMem);
if ( ProductInformation==0 ) return 0;
if ( !IsProgMem ) {
return ProductInformation->LoadEquivalency;
} else {
return pgm_read_byte(&ProductInformation->LoadEquivalency);
}
}
//*****************************************************************************
void tNMEA2000::CopyProgmemConfigurationInformationToLocal() {
if ( LocalConfigurationInformationData==0 ) {
char Buf[Max_N2kConfigurationInfoField_len];
const char *ID1=ConfigurationInformation.InstallationDescription1;
const char *ID2=ConfigurationInformation.InstallationDescription2;
CopyProgmemString(ConfigurationInformation.ManufacturerInformation,Max_N2kConfigurationInfoField_len,Buf);
SetConfigurationInformation(Buf);
CopyProgmemString(ID1,Max_N2kConfigurationInfoField_len,Buf);
SetInstallationDescription1(Buf);
CopyProgmemString(ID2,Max_N2kConfigurationInfoField_len,Buf);
SetInstallationDescription2(Buf);
}
}
//*****************************************************************************
void tNMEA2000::SetInstallationDescription1(const char *InstallationDescription1) {
CopyProgmemConfigurationInformationToLocal();
// Get pointer to local InstallationDescription1, which is after
char *Info=LocalConfigurationInformationData;
SetCharBuf(InstallationDescription1,Max_N2kConfigurationInfoField_len,Info);
ConfigurationInformation.InstallationDescription1=(InstallationDescription1?Info:0);
InstallationDescriptionChanged=true;
}
//*****************************************************************************
void tNMEA2000::SetInstallationDescription2(const char *InstallationDescription2) {
CopyProgmemConfigurationInformationToLocal();
char *Info=LocalConfigurationInformationData+Max_N2kConfigurationInfoField_len;
SetCharBuf(InstallationDescription2,Max_N2kConfigurationInfoField_len,Info);
ConfigurationInformation.InstallationDescription2=(InstallationDescription2?Info:0);
InstallationDescriptionChanged=true;
}
//*****************************************************************************
void tNMEA2000::GetInstallationDescription1(char *buf, size_t max_len) {
if ( LocalConfigurationInformationData!=0 ) {
SetCharBuf(ConfigurationInformation.InstallationDescription1,max_len,buf);
} else {
CopyProgmemString(ConfigurationInformation.InstallationDescription1,max_len,buf);
}
}
//*****************************************************************************
void tNMEA2000::GetInstallationDescription2(char *buf, size_t max_len) {
if ( LocalConfigurationInformationData!=0 ) {
SetCharBuf(ConfigurationInformation.InstallationDescription2,max_len,buf);
} else {
CopyProgmemString(ConfigurationInformation.InstallationDescription2,max_len,buf);
}
}
//*****************************************************************************
void tNMEA2000::GetManufacturerInformation(char *buf, size_t max_len) {
if ( LocalConfigurationInformationData!=0 ) {
SetCharBuf(ConfigurationInformation.ManufacturerInformation,max_len,buf);
} else {
CopyProgmemString(ConfigurationInformation.ManufacturerInformation,max_len,buf);
}
}
//*****************************************************************************
bool tNMEA2000::ReadResetInstallationDescriptionChanged() {
bool result=InstallationDescriptionChanged;
InstallationDescriptionChanged=false;
return result;
}
#endif
//*****************************************************************************
void tNMEA2000::SetDeviceInformation(unsigned long _UniqueNumber,
unsigned char _DeviceFunction,
unsigned char _DeviceClass,
uint16_t _ManufacturerCode,
unsigned char _IndustryGroup,
int iDev
) {
if ( !IsValidDevice(iDev) ) return;
InitDevices();
if (_ManufacturerCode!=0xffff) Devices[iDev].DeviceInformation.SetManufacturerCode(_ManufacturerCode);
if (_UniqueNumber!=0xffffffff) Devices[iDev].DeviceInformation.SetUniqueNumber(_UniqueNumber);
if (_DeviceFunction!=0xff) Devices[iDev].DeviceInformation.SetDeviceFunction(_DeviceFunction);
if (_DeviceClass!=0xff) Devices[iDev].DeviceInformation.SetDeviceClass(_DeviceClass);
if (_IndustryGroup!=0xff) Devices[iDev].DeviceInformation.SetIndustryGroup(_IndustryGroup);
}
//*****************************************************************************
void tNMEA2000::SetDeviceInformationInstances(
uint8_t _DeviceInstanceLower,
uint8_t _DeviceInstanceUpper,
uint8_t _SystemInstance,
int iDev
) {
if ( !IsValidDevice(iDev) ) return;
InitDevices();
uint8_t DeviceInstance=Devices[iDev].DeviceInformation.GetDeviceInstance();
if (_DeviceInstanceLower!=0xff ) {
DeviceInstance=( (DeviceInstance & ~0x07) | (_DeviceInstanceLower & 0x07) );
}
if (_DeviceInstanceUpper!=0xff ) {
DeviceInstance=( (DeviceInstance & ~0xF8) | ((_DeviceInstanceUpper&0x1f)<<3) );
}
if ( Devices[iDev].DeviceInformation.GetDeviceInstance()!=DeviceInstance) {
Devices[iDev].DeviceInformation.SetDeviceInstance(DeviceInstance);
DeviceInformationChanged=true;
}
if (_SystemInstance!=0xff && Devices[iDev].DeviceInformation.GetSystemInstance()!=_SystemInstance) {
Devices[iDev].DeviceInformation.SetSystemInstance(_SystemInstance);
DeviceInformationChanged=true;
}
// Send delayed. Had problems with some devices with too fast response.
if ( IsReadyToSend() ) SendIsoAddressClaim(0xff,iDev,2);
}
//*****************************************************************************
void tNMEA2000::SetSingleFrameMessages(const unsigned long *_SingleFrameMessages) {
SingleFrameMessages[0]=_SingleFrameMessages;
}
//*****************************************************************************
void tNMEA2000::SetFastPacketMessages(const unsigned long *_FastPacketMessages) {
FastPacketMessages[0]=_FastPacketMessages;
}
//*****************************************************************************
void tNMEA2000::ExtendSingleFrameMessages(const unsigned long *_SingleFrameMessages) {
SingleFrameMessages[1]=_SingleFrameMessages;
}
//*****************************************************************************
void tNMEA2000::ExtendFastPacketMessages(const unsigned long *_FastPacketMessages) {
FastPacketMessages[1]=_FastPacketMessages;
}
//*****************************************************************************
void tNMEA2000::ExtendTransmitMessages(const unsigned long *_Messages, int iDev) {
if ( !IsValidDevice(iDev) ) return;
InitDevices();
Devices[iDev].TransmitMessages=_Messages;
}
//*****************************************************************************
void tNMEA2000::ExtendReceiveMessages(const unsigned long *_Messages, int iDev) {
if ( !IsValidDevice(iDev) ) return;
InitDevices();
Devices[iDev].ReceiveMessages=_Messages;
}
//*****************************************************************************
void tNMEA2000::SetMode(tN2kMode _N2kMode, uint8_t _N2kSource) {
InitDevices();
N2kMode=_N2kMode;
for (int i=0; i<DeviceCount; i++) {
Devices[i].N2kSource=_N2kSource+i;
Devices[i].UpdateAddressClaimEndSource();
}
AddressChanged=false;
}
//*****************************************************************************
void tNMEA2000::InitCANFrameBuffers() {
if ( CANSendFrameBuf==0 && !IsInitialized() ) {
if ( MaxCANSendFrames>0 ) CANSendFrameBuf = new tCANSendFrame[MaxCANSendFrames];
N2kDbg("Initialize frame buffer. Size: "); N2kDbg(MaxCANSendFrames); N2kDbg(", address:"); N2kDbgln((uint32_t)CANSendFrameBuf);
CANSendFrameBufferWrite=0;
CANSendFrameBufferRead=0;
}
// Receive buffer has sense only with interrupt handling. So it must be handled on inherited class.
}
//*****************************************************************************
bool tNMEA2000::Open() {
if (!DeviceReady) {
std::cout << "in Open()";
InitCANFrameBuffers();
InitDevices();
if ( N2kCANMsgBuf==0 ) {
if ( MaxN2kCANMsgs==0 ) MaxN2kCANMsgs=5;
N2kCANMsgBuf = new tN2kCANMsg[MaxN2kCANMsgs];
for (int i=0; i<MaxN2kCANMsgs; i++) N2kCANMsgBuf[i].FreeMessage();
#if !defined(N2K_NO_GROUP_FUNCTION_SUPPORT)
// On first open try add also default group function handlers
AddGroupFunctionHandler(new tN2kGroupFunctionHandlerForPGN60928(this)); // NAME handler
AddGroupFunctionHandler(new tN2kGroupFunctionHandlerForPGN126464(this)); // Rx/Tx list handler
#if !defined(N2K_NO_HEARTBEAT_SUPPORT)
AddGroupFunctionHandler(new tN2kGroupFunctionHandlerForPGN126993(this)); // Heartbeat handler
#endif
AddGroupFunctionHandler(new tN2kGroupFunctionHandlerForPGN126996(this)); // Product information
AddGroupFunctionHandler(new tN2kGroupFunctionHandlerForPGN126998(this)); // Configuration information handler
AddGroupFunctionHandler(new tN2kGroupFunctionHandler(this,0)); // Default handler at last
#endif
}
DeviceReady = (dbMode!=dm_None) || CANOpen();
if ( (ForwardStream!=0) && (ForwardType==tNMEA2000::fwdt_Text) ) {
if ( DeviceReady ) {
ForwardStream->println(F("CAN device ready"));
} else {
ForwardStream->println(F("CAN device failed to open"));
}
}
delay(200);
for (int i=0; i<DeviceCount; i++) {
if ( Devices[i].N2kSource==N2kNullCanBusAddress ) GetNextAddress(i,true); // On restart try address claiming from the beginning
StartAddressClaim(i);
}
}
return DeviceReady;
}
//*****************************************************************************
void CanIdToN2k(unsigned long id, unsigned char &prio, unsigned long &pgn, unsigned char &src, unsigned char &dst) {
unsigned char CanIdPF = (unsigned char) (id >> 16);
unsigned char CanIdPS = (unsigned char) (id >> 8);
unsigned char CanIdDP = (unsigned char) (id >> 24) & 1;
src = (unsigned char) id >> 0;
prio = (unsigned char) ((id >> 26) & 0x7);
if (CanIdPF < 240) {
/* PDU1 format, the PS contains the destination address */
dst = CanIdPS;
pgn = (((unsigned long)CanIdDP) << 16) | (((unsigned long)CanIdPF) << 8);
} else {
/* PDU2 format, the destination is implied global and the PGN is extended */
dst = 0xff;
pgn = (((unsigned long)CanIdDP) << 16) | (((unsigned long)CanIdPF) << 8) | (unsigned long)CanIdPS;
}
}
//*****************************************************************************
unsigned long N2ktoCanID(unsigned char priority, unsigned long PGN, unsigned long Source, unsigned char Destination) {
unsigned char CanIdPF = (unsigned char) (PGN >> 8);
if (CanIdPF < 240) { // PDU1 format
if ( (PGN & 0xff) != 0 ) return 0; // for PDU1 format PGN lowest byte has to be 0 for the destination.
return ( ((unsigned long)(priority & 0x7))<<26 | PGN<<8 | ((unsigned long)Destination)<<8 | (unsigned long)Source);
} else { // PDU2 format
return ( ((unsigned long)(priority & 0x7))<<26 | PGN<<8 | (unsigned long)Source);
}
}
//*****************************************************************************
bool tNMEA2000::SendFrames()
{ uint16_t temp;
if ( CANSendFrameBuf==0 ) return true; // This can be in case, where inherited class defines own buffering.
while (CANSendFrameBufferRead!=CANSendFrameBufferWrite) {
temp = (CANSendFrameBufferRead + 1) % MaxCANSendFrames;
if ( CANSendFrame(CANSendFrameBuf[temp].id, CANSendFrameBuf[temp].len, CANSendFrameBuf[temp].buf, CANSendFrameBuf[temp].wait_sent) ) {
CANSendFrameBufferRead=temp;
N2kFrameOutDbg("Frame unbuffered "); N2kFrameOutDbgln(CANSendFrameBuf[temp].id);
} else return false;
}
return true;
}
//*****************************************************************************
bool tNMEA2000::SendFrame(unsigned long id, unsigned char len, const unsigned char *buf, bool wait_sent) {