-
Notifications
You must be signed in to change notification settings - Fork 583
Expand file tree
/
Copy pathCanInterface.cpp
More file actions
1828 lines (1605 loc) · 60.4 KB
/
CanInterface.cpp
File metadata and controls
1828 lines (1605 loc) · 60.4 KB
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
/*
* CanInterface.cpp
*
* Created on: 19 Sep 2018
* Author: David
*/
#include "CanInterface.h"
#if SUPPORT_CAN_EXPANSION
#include "CanMotion.h"
#include "CommandProcessor.h"
#include "CanMessageGenericConstructor.h"
#include <CanMessageBuffer.h>
#include <CanMessageGenericTables.h>
#include <Movement/DDA.h>
#include <Movement/DriveMovement.h>
#include <Movement/Kinematics/HangprinterKinematics.h>
#include <Movement/StepTimer.h>
#include <Movement/Move.h>
#include <RTOSIface/RTOSIface.h>
#include <Platform/RepRap.h>
#include <Platform/Platform.h>
#include <Platform/TaskPriorities.h>
#include <GCodes/GCodes.h>
#include <GCodes/GCodeException.h>
#include <GCodes/GCodeBuffer/GCodeBuffer.h>
#include <ClosedLoop/ClosedLoop.h>
#include <AppNotifyIndices.h>
#if HAS_SBC_INTERFACE
# include "SBC/SbcInterface.h"
#endif
#if SUPPORT_REMOTE_COMMANDS
# include <Version.h>
# include <InputMonitors/InputMonitor.h>
# if HAS_STALL_DETECT
# include <Movement/StepperDrivers/SmartDrivers.h> // for extern declaration of driverStallsToNotify
# endif
#endif
#include <memory>
#define SUPPORT_CAN 1 // needed by CanDevice.h
#include <CanDevice.h>
#if SAME70
# include <pmc/pmc.h>
#endif
const unsigned int NumCanBuffers = 2 * MaxCanBoards + 10;
constexpr uint32_t MaxMotionSendWait = 20; // milliseconds
constexpr uint32_t MaxUrgentSendWait = 20; // milliseconds
constexpr uint32_t MaxTimeSyncSendWait = 2; // milliseconds
constexpr uint32_t MaxResponseSendWait = CanInterface::UsualSendTimeout; // milliseconds
constexpr uint32_t MaxRequestSendWait = CanInterface::UsualSendTimeout; // milliseconds
// Define how often we send time sync messages. This value and the time interval between sending broadcast status messages (currently 250ms) should be relatively prime.
// The reason is that if we try to send a time sync message just after a board has started broadcasting a status message, the time sync message will get delayed
// until the broadcast message finishes, which could be up to 600us at 1Mbps (the time taken to send a message with a 64-byte payload when not using BRS).
// When we used a 200us interval here, this meant that the same clash would occur 1 second later, and again 1 second after that.
// Using a value here that is relatively prime to 250ms avoids that happening. Alternatively we could add a random element to the interval.
constexpr uint32_t CanClockIntervalMillis = 211;
// Define the maximum time sync delay that we tolerate. Occasionally on the SAME70 we get spurious very long delays, so we must ignore those.
// CAN-FD packets have 42 header bits, up to 64*8 data bits and 45 trailer bits. The header and data parts may have added stuff bits.
// That's a maximum of 554 header+data bits plus up to 20% additional stuff bits, and 45 trailer bits including fixed stuff bits.
// So the maximum number of bits is less than 710, which takes 710us to transmit at 1Mbps. Allow an extra 5us for scheduling delays.
constexpr uint16_t MaxTimeSyncDelay = (uint16_t)MicrosecondsToStepClocks((42 + 64 * 8) * 1.2 + 45 + 5); // the maximum normal delay before a CAN time sync message is sent, in step clocks
static_assert(MaxTimeSyncDelay >= 400 && MaxTimeSyncDelay <= 1000); // check it's in the right ball park
#define USE_BIT_RATE_SWITCH 0
constexpr uint32_t MinBitRate = 15; // MCP2542 has a minimum bite rate of 14.4kbps
constexpr uint32_t MaxBitRate = 5000;
constexpr float MinSamplePoint = 0.5;
constexpr float MaxSamplePoint = 0.95;
constexpr float MinJumpWidth = 0.05;
constexpr float MaxJumpWidth = 0.5;
static Mutex transactionMutex;
static uint32_t longestWaitTime = 0;
static uint16_t longestWaitMessageType = 0;
static uint32_t peakTimeSyncTxDelay = 0;
// Debug
static unsigned int goodTimeStamps = 0;
static unsigned int badTimeStamps = 0;
static unsigned int timeSyncMessagesSent = 0;
// End debug
static volatile uint16_t timeSyncTxTimeStamp;
static volatile bool gotTimeSyncTxTimeStamp = false;
static CanAddress myAddress =
#ifdef DUET3_ATE
CanId::ATEMasterAddress;
#else
CanId::MasterAddress;
#endif
static uint8_t currentTimeSyncMarker = 0xFF;
#if SUPPORT_REMOTE_COMMANDS
static unsigned int messagesIgnored = 0;
static bool inExpansionMode = false;
static bool inTestMode = false;
static bool mainBoardAcknowledgedAnnounce = false;
#endif
//#define CAN_DEBUG
// Define the memory configuration we want to use
constexpr CanDevice::Config Can0Config =
{
.dataSize = 64,
.numTxBuffers = 5,
.txFifoSize = 16,
.numRxBuffers = 0,
.rxFifo0Size = 32, // increased from 16 to help with accelerometer and closed loop data collection
.rxFifo1Size = 16,
.numShortFilterElements = 0,
#ifdef DUET3_ATE
.numExtendedFilterElements = 4,
#else
.numExtendedFilterElements = 3,
#endif
.txEventFifoSize = 16
};
static_assert(Can0Config.IsValid());
// CAN buffer memory must be in the first 64Kb of RAM (SAME5x) or in non-cached RAM (SAME70), so put it in its own memory section
static uint32_t can0Memory[Can0Config.GetMemorySize()] __attribute__ ((section (".CanMessage")));
static CanDevice *can0dev = nullptr;
static unsigned int txTimeouts[Can0Config.numTxBuffers + 1] = { 0 };
static uint32_t lastCancelledId = 0;
#if DUAL_CAN
constexpr CanDevice::Config Can1Config =
{
.dataSize = 8,
.numTxBuffers = 2,
.txFifoSize = 4,
.numRxBuffers = 0,
.rxFifo0Size = 16,
.rxFifo1Size = 16,
.numShortFilterElements = 1,
.numExtendedFilterElements = 1,
.txEventFifoSize = 16
};
static_assert(Can1Config.IsValid());
// CAN buffer memory must be in the first 64Kb of RAM (SAME5x) or in non-cached RAM (SAME70), so put it in its own segment
static uint32_t can1Memory[Can1Config.GetMemorySize()] __attribute__ ((section (".CanMessage")));
static CanDevice *can1dev = nullptr;
#endif
// Transmit buffer usage. All dedicated buffer numbers must be < Can0Config.numTxBuffers.
constexpr auto TxBufferIndexUrgent = CanDevice::TxBufferNumber::buffer0;
constexpr auto TxBufferIndexTimeSync = CanDevice::TxBufferNumber::buffer1;
constexpr auto TxBufferIndexRequest = CanDevice::TxBufferNumber::buffer2;
constexpr auto TxBufferIndexResponse = CanDevice::TxBufferNumber::buffer3;
constexpr auto TxBufferIndexBroadcast = CanDevice::TxBufferNumber::buffer4;
constexpr auto TxBufferIndexMotion = CanDevice::TxBufferNumber::fifo; // we send lots of movement messages so use the FIFO for them
// Receive buffer/FIFO usage. All dedicated buffer numbers must be < Can0Config.numRxBuffers.
constexpr auto RxBufferIndexBroadcast = CanDevice::RxBufferNumber::fifo0;
constexpr auto RxBufferIndexRequest = CanDevice::RxBufferNumber::fifo0;
constexpr auto RxBufferIndexResponse = CanDevice::RxBufferNumber::fifo1;
// CanSender management task
constexpr size_t CanSenderTaskStackWords = 400;
static Task<CanSenderTaskStackWords> canSenderTask;
constexpr size_t CanReceiverTaskStackWords = 1000;
static Task<CanReceiverTaskStackWords> canReceiverTask;
constexpr size_t CanClockTaskStackWords = 400; // used to be 300 but RD had a stack overflow
static Task<CanSenderTaskStackWords> canClockTask;
static CanMessageBuffer * volatile pendingMotionBuffers = nullptr;
static CanMessageBuffer * volatile lastMotionBuffer; // only valid when pendingBuffers != nullptr
#if 0 //unused
static unsigned int numPendingMotionBuffers = 0;
#endif
extern "C" [[noreturn]] void CanSenderLoop(void *) noexcept;
extern "C" [[noreturn]] void CanClockLoop(void *) noexcept;
extern "C" [[noreturn]] void CanReceiverLoop(void *) noexcept;
// Status LED handling
#if SUPPORT_MULTICAST_DISCOVERY
// The STATUS LED is also used to identify one board among several visible to the user
static volatile uint32_t identInitialClocks = 0; // when we started identifying
static volatile uint32_t identTotalClocks = 0; // how many step clocks to identify for, zero means until cancelled
static volatile bool identifying = false;
void CanInterface::SetStatusLedIdentify(uint32_t seconds) noexcept
{
identTotalClocks = seconds * StepClockRate;
identInitialClocks = StepTimer::GetTimerTicks();
identifying = true;
}
void CanInterface::SetStatusLedNormal() noexcept
{
identifying = false;
}
#endif
// This is called only from the CAN clock loop, so inline
static inline void UpdateLed(uint32_t stepClocks) noexcept
{
#if SUPPORT_MULTICAST_DISCOVERY
if (identifying)
{
if (identTotalClocks != 0 && stepClocks - identInitialClocks >= identTotalClocks)
{
identifying = 0; // stop identifying
}
else
{
// Blink the LED fast. This function gets called every 200ms, so that's the fastest we can blink it without having another task do it.
reprap.GetPlatform().InvertDiagLed();
return;
}
}
#endif
// Blink the LED at about 1Hz. Duet 3 expansion boards will blink in sync when they have established clock sync with us.
reprap.GetPlatform().SetDiagLed((stepClocks & (1u << 19)) != 0);
}
static void InitReceiveFilters() noexcept
{
// Set up a filter to receive all request messages addressed to us in FIFO 0
can0dev->SetExtendedFilterElement(0, CanDevice::RxBufferNumber::fifo0,
CanInterface::GetCanAddress() << CanId::DstAddressShift,
(CanId::BoardAddressMask << CanId::DstAddressShift) | CanId::ResponseBit);
// Set up a filter to receive all broadcast messages also in FIFO 0
can0dev->SetExtendedFilterElement(1, CanDevice::RxBufferNumber::fifo0,
CanId::BroadcastAddress << CanId::DstAddressShift,
CanId::BoardAddressMask << CanId::DstAddressShift);
// Set up a filter to receive response messages in FIFO 1
can0dev->SetExtendedFilterElement(2, RxBufferIndexResponse,
(CanInterface::GetCanAddress() << CanId::DstAddressShift) | CanId::ResponseBit,
(CanId::BoardAddressMask << CanId::DstAddressShift) | CanId::ResponseBit);
# ifdef DUET3_ATE
// Also respond to requests addressed to board 0 so we can update firmware on ATE boards
can0dev->SetExtendedFilterElement(3, CanDevice::RxBufferNumber::fifo0,
CanId::MasterAddress << CanId::DstAddressShift,
(CanId::BoardAddressMask << CanId::DstAddressShift) | CanId::ResponseBit);
# endif
}
// This is the function called by the transmit event handler when the message marker is nonzero
void TxCallback(uint8_t marker, CanId id, uint16_t timeStamp) noexcept
{
if (marker == currentTimeSyncMarker)
{
timeSyncTxTimeStamp = timeStamp;
gotTimeSyncTxTimeStamp = true;
++goodTimeStamps;
}
else
{
++badTimeStamps;
}
}
void CanInterface::Init() noexcept
{
CanMessageBuffer::Init(NumCanBuffers);
pendingMotionBuffers = nullptr;
transactionMutex.Create("CanTrans");
#if SAME70
SetPinFunction(APIN_CAN1_TX, CAN1TXPinPeriphMode);
SetPinFunction(APIN_CAN1_RX, CAN1RXPinPeriphMode);
# if DUAL_CAN
SetPinFunction(APIN_CAN0_TX, CAN0PinPeriphMode);
SetPinFunction(APIN_CAN0_RX, CAN0PinPeriphMode);
# endif
pmc_enable_upll_clock(); // configure_mcan sets up PCLK5 to be the UPLL divided by something, so make sure the UPLL is running
#elif SAME5x
SetPinFunction(CanRxPin, CanPinsMode);
SetPinFunction(CanTxPin, CanPinsMode);
#else
# error Unsupported MCU
#endif
// Initialise the CAN hardware
CanTiming timing;
timing.SetDefaults(CanTiming::DefaultCanBitRate);
can0dev = CanDevice::Init(0, CanDeviceNumber, Can0Config, can0Memory, timing, nullptr);
InitReceiveFilters();
can0dev->Enable();
CanMotion::Init();
// Create the task that sends CAN messages
canClockTask.Create(CanClockLoop, "CanClock", nullptr, TaskPriority::CanClockPriority);
canSenderTask.Create(CanSenderLoop, "CanSender", nullptr, TaskPriority::CanSenderPriority);
canReceiverTask.Create(CanReceiverLoop, "CanReceiver", nullptr, TaskPriority::CanReceiverPriority);
#if DUAL_CAN
timing.SetDefaults(250'000);
can1dev = CanDevice::Init(1, SecondaryCanDeviceNumber, Can1Config, can1Memory, timing, nullptr);
can1dev->SetShortFilterElement(0, CanDevice::RxBufferNumber::fifo0, 0, 0); // set up a filter to receive all messages in FIFO 0
can1dev->SetExtendedFilterElement(0, CanDevice::RxBufferNumber::fifo0, 0, 0);
can1dev->Enable();
#endif
}
void CanInterface::Shutdown() noexcept
{
canClockTask.TerminateAndUnlink();
canSenderTask.TerminateAndUnlink();
canReceiverTask.TerminateAndUnlink();
if (can0dev != nullptr)
{
can0dev->DeInit();
can0dev = nullptr;
}
}
CanAddress CanInterface::GetCanAddress() noexcept
{
return myAddress;
}
#if SUPPORT_REMOTE_COMMANDS
bool CanInterface::InExpansionMode() noexcept
{
return inExpansionMode;
}
bool CanInterface::InTestMode() noexcept
{
return inTestMode;
}
void CanInterface::LogIgnoredMovementMessage() noexcept
{
++messagesIgnored;
}
static void ReInit() noexcept
{
can0dev->Disable();
InitReceiveFilters();
can0dev->Enable();
}
void CanInterface::SwitchToExpansionMode(CanAddress addr, bool useTestMode) noexcept
{
TaskCriticalSectionLocker lock;
myAddress = addr;
inExpansionMode = true;
inTestMode = useTestMode;
reprap.GetGCodes().SwitchToExpansionMode();
reprap.GetMove().SwitchToExpansionMode();
ReInit(); // reset the CAN filters to account for our new CAN address
}
// Send an announcement message if we haven't had an announce acknowledgement from a main board. On return the buffer is available to use again.
void CanInterface::SendAnnounce(CanMessageBuffer *buf) noexcept
{
if (inExpansionMode && !mainBoardAcknowledgedAnnounce)
{
auto msg = buf->SetupBroadcastMessage<CanMessageAnnounceNew>(myAddress);
msg->timeSinceStarted = millis();
msg->numDrivers = NumDirectDrivers;
msg->usesUf2Binary = BOARD_USES_UF2_BINARY;
msg->supportsMovementPaSnapshot = 1;
msg->zero = 0;
memcpy(msg->uniqueId, reprap.GetPlatform().GetUniqueId().GetRaw(), sizeof(msg->uniqueId));
// Note, board type name, firmware version, firmware date and firmware time are limited to 43 characters in the new
// We use vertical-bar to separate the three fields: board type, firmware version, date/time
SafeSnprintf(msg->boardTypeAndFirmwareVersion, ARRAY_SIZE(msg->boardTypeAndFirmwareVersion), "%s|%s|%s%.6s", BOARD_SHORT_NAME, VERSION, DateText, TimeSuffix);
buf->dataLength = msg->GetActualDataLength();
SendMessageNoReplyNoFree(buf);
}
}
// Send an event. The text will be truncated if it is longer than 55 characters.
void CanInterface::RaiseEvent(EventType type, uint16_t param, uint8_t device, const char *format, va_list vargs) noexcept
{
CanMessageBuffer buf;
auto msg = buf.SetupRequestMessageNoRid<CanMessageEvent>(GetCanAddress(), GetCurrentMasterAddress());
msg->eventType = type.ToBaseType();;
msg->deviceNumber = device;
msg->eventParam = param;
SafeVsnprintf(msg->text, ARRAY_SIZE(msg->text), format, vargs);
buf.dataLength = msg->GetActualDataLength();
CanInterface::SendMessageNoReplyNoFree(&buf);
}
void CanInterface::MainBoardAcknowledgedAnnounce() noexcept
{
mainBoardAcknowledgedAnnounce = true;
}
#endif
// Allocate a CAN request ID
// Currently we reserve the top bit of the 12-bit request ID so that CanRequestIdAcceptAlways is distinct from any genuine request ID.
// Currently we use a single RID sequence for all destination addresses. In future we may use a separate sequence for each address.
// The message buffer is provided so that if the board is not known, we can use the buffer to send a message to it to announce ourselves, but this is not yet implemented
CanRequestId CanInterface::AllocateRequestId(CanAddress destination, CanMessageBuffer *buf) noexcept
{
static uint16_t rid = 0;
CanRequestId rslt = rid & CanRequestIdMask;
++rid;
return rslt;
}
// Allocate a CAN message buffer, throw if failed
CanMessageBuffer *CanInterface::AllocateBuffer(const GCodeBuffer* gb) THROWS(GCodeException)
{
CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
if (buf == nullptr)
{
throw GCodeException((gb == nullptr) ? -1 : gb->GetLineNumber(), -1, NoCanBufferMessage);
}
return buf;
}
void CanInterface::CheckCanAddress(uint32_t address, const GCodeBuffer& gb) THROWS(GCodeException)
{
if (address == 0 || address > CanId::MaxCanAddress)
{
throw GCodeException(&gb, -1, "CAN address out of range");
}
}
uint16_t CanInterface::GetTimeStampCounter() noexcept
{
return can0dev->ReadTimeStampCounter();
}
#if !SAME70
uint16_t CanInterface::GetTimeStampPeriod() noexcept
{
return can0dev->GetTimeStampPeriod();
}
#endif
// Send a message on the CAN FD channel and record any errors
static void SendCanMessage(CanDevice::TxBufferNumber whichBuffer, uint32_t timeout, CanMessageBuffer *buffer) noexcept
{
const uint32_t cancelledId = can0dev->SendMessage(whichBuffer, timeout, buffer);
if (cancelledId != 0)
{
++txTimeouts[(unsigned int)whichBuffer];
lastCancelledId = cancelledId;
}
}
// This task picks up motion messages and sends them
extern "C" [[noreturn]] void CanSenderLoop(void *) noexcept
{
for (;;)
{
#if SUPPORT_REMOTE_COMMANDS
if (inExpansionMode)
{
// In expansion mode this task just send notifications when the states of input handles change
CanMessageBuffer buf;
auto msg = buf.SetupRequestMessageNoRid<CanMessageInputChangedNew>(CanInterface::GetCanAddress(), CanInterface::GetCurrentMasterAddress());
msg->states = 0;
msg->numHandles = 0;
#if HAS_STALL_DETECT
// Start by adding any stall detect endstops pending. Do this first so that it must succeed.
const uint16_t stallNotifications = SmartDrivers::driverStallsToNotify.exchange(0);
if (stallNotifications != 0)
{
constexpr RemoteInputHandle h(RemoteInputHandle::typeStallEndstop, 0, 0);
(void)msg->AddEntry(h.asU16(), (uint32_t)stallNotifications, true);
}
#endif
const uint32_t timeToWait = InputMonitor::AddStateChanges(msg);
if (msg->numHandles != 0)
{
buf.dataLength = msg->GetActualDataLength();
SendCanMessage(TxBufferIndexUrgent, MaxUrgentSendWait, &buf);
reprap.GetPlatform().OnProcessingCanMessage();
}
TaskBase::TakeIndexed(NotifyIndices::CanSender, timeToWait); // wait until we are woken up because a message is available, or we time out
}
else
#endif
{
// In main board mode this task sends urgent messages concerning motion
for (;;)
{
CanMessageBuffer * const urgentMessage = CanMotion::GetUrgentMessage();
if (urgentMessage != nullptr)
{
SendCanMessage(TxBufferIndexUrgent, MaxUrgentSendWait, urgentMessage);
}
else if (pendingMotionBuffers != nullptr)
{
CanMessageBuffer *buf;
{
TaskCriticalSectionLocker lock;
buf = pendingMotionBuffers;
pendingMotionBuffers = buf->next;
#if 0 //unused
--numPendingMotionBuffers;
#endif
}
// Send the message
SendCanMessage(TxBufferIndexMotion, MaxMotionSendWait, buf);
reprap.GetPlatform().OnProcessingCanMessage();
#ifdef CAN_DEBUG
// Display a debug message too
debugPrintf("CCCR %08" PRIx32 ", PSR %08" PRIx32 ", ECR %08" PRIx32 ", TXBRP %08" PRIx32 ", TXBTO %08" PRIx32 ", st %08" PRIx32 "\n",
MCAN1->MCAN_CCCR, MCAN1->MCAN_PSR, MCAN1->MCAN_ECR, MCAN1->MCAN_TXBRP, MCAN1->MCAN_TXBTO, GetAndClearStatusBits());
buf->msg.DebugPrint();
delay(50);
debugPrintf("CCCR %08" PRIx32 ", PSR %08" PRIx32 ", ECR %08" PRIx32 ", TXBRP %08" PRIx32 ", TXBTO %08" PRIx32 ", st %08" PRIx32 "\n",
MCAN1->MCAN_CCCR, MCAN1->MCAN_PSR, MCAN1->MCAN_ECR, MCAN1->MCAN_TXBRP, MCAN1->MCAN_TXBTO, GetAndClearStatusBits());
#endif
// Free the message buffer.
CanMessageBuffer::Free(buf);
}
else
{
break;
}
}
TaskBase::TakeIndexed(NotifyIndices::CanSender, Mutex::TimeoutUnlimited);
}
}
}
extern "C" [[noreturn]] void CanClockLoop(void *) noexcept
{
CanMessageBuffer buf;
uint32_t lastWakeTime = xTaskGetTickCount();
uint32_t lastTimeSent = 0;
uint32_t lastRealTimeSent = 0;
#if !SAME70
uint16_t lastTimeSyncTxPreparedStamp = 0;
#endif
for (;;)
{
CanMessageTimeSync * const msg = buf.SetupBroadcastMessage<CanMessageTimeSync>(CanInterface::GetCanAddress());
msg->lastTimeSent = lastTimeSent;
msg->lastTimeAcknowledgeDelay = 0; // assume we don't have the transmit delay available
currentTimeSyncMarker = ((currentTimeSyncMarker + 1) & 0x0F) | 0xA0;
buf.marker = currentTimeSyncMarker;
buf.reportInFifo = 1;
if (gotTimeSyncTxTimeStamp)
{
// Calculate the delay in sending the last time sync message, in step clocks
# if SAME70
// On the SAME70 the step clock is also the external time stamp counter
const uint32_t timeSyncTxDelay = (timeSyncTxTimeStamp - (uint16_t)lastTimeSent) & 0xFFFF;
# else
// On the SAME5x the time stamp counter counts CAN bit times. The step clock is the CAN clock divided by 64.
const uint32_t timeSyncTxDelay = ((uint32_t)((timeSyncTxTimeStamp - lastTimeSyncTxPreparedStamp) & 0xFFFF) * CanInterface::GetTimeStampPeriod()) >> 6;
# endif
if (timeSyncTxDelay > peakTimeSyncTxDelay)
{
peakTimeSyncTxDelay = timeSyncTxDelay;
}
// Occasionally on the SAME70 we get very large delays reported. These delays are not genuine.
if (timeSyncTxDelay < MaxTimeSyncDelay)
{
msg->lastTimeAcknowledgeDelay = timeSyncTxDelay;
}
gotTimeSyncTxTimeStamp = false;
}
msg->isPrinting = reprap.GetGCodes().IsReallyPrinting();
// Send the real time just once a second unless we also need to send the movement delay
const uint32_t realTime = (uint32_t)reprap.GetPlatform().GetDateTime();
const StepTimer::Ticks newMovementDelay = StepTimer::CheckMovementDelayIncreased();
if (newMovementDelay != 0)
{
msg->realTime = realTime;
lastRealTimeSent = realTime;
msg->movementDelay = newMovementDelay;
}
else if (realTime != lastRealTimeSent)
{
msg->realTime = realTime;
lastRealTimeSent = realTime;
buf.dataLength = CanMessageTimeSync::SizeWithRealTime;
}
else
{
buf.dataLength = CanMessageTimeSync::SizeWithoutRealTime; // send a short message to save CAN bandwidth
}
#if SAME70
lastTimeSent = StepTimer::GetTimerTicks();
#else
{
AtomicCriticalSectionLocker lock;
lastTimeSent = StepTimer::GetTimerTicksWhenInterruptsDisabled();
lastTimeSyncTxPreparedStamp = CanInterface::GetTimeStampCounter();
}
#endif
msg->timeSent = lastTimeSent;
SendCanMessage(TxBufferIndexTimeSync, 0, &buf);
++timeSyncMessagesSent;
UpdateLed(lastTimeSent);
// Delay until it is time again
vTaskDelayUntil(&lastWakeTime, CanClockIntervalMillis);
#if SUPPORT_REMOTE_COMMANDS
if (inExpansionMode)
{
TaskBase::GetCallerTaskHandle()->TerminateAndUnlink(); // once in expansion mode we can't revert to main board mode, so we don't need this task any more
}
#endif
// Check that the message was sent and get the time stamp
if (can0dev->IsSpaceAvailable(TxBufferIndexTimeSync, 0)) // if the buffer is free already then the message was sent
{
can0dev->PollTxEventFifo(TxCallback);
}
else
{
(void)can0dev->IsSpaceAvailable(TxBufferIndexTimeSync, MaxTimeSyncSendWait); // free the buffer
can0dev->PollTxEventFifo(TxCallback); // empty the fifo
gotTimeSyncTxTimeStamp = false; // ignore any values read from it
}
}
}
// Members of namespace CanInterface, and associated local functions
template<class T> static GCodeResult SetRemoteDriverValues(const CanDriversData<T>& data, const StringRef& reply, CanMessageType mt) noexcept
{
GCodeResult rslt = GCodeResult::ok;
size_t start = 0;
for (;;)
{
CanDriversBitmap driverBits;
const size_t savedStart = start;
const CanAddress boardAddress = data.GetNextBoardDriverBitmap(start, driverBits);
if (boardAddress == CanId::NoAddress)
{
break;
}
CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
if (buf == nullptr)
{
return GCodeResult::noCanBuffer;
}
const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress, buf);
CanMessageMultipleDrivesRequest<T> * const msg = buf->SetupRequestMessage<CanMessageMultipleDrivesRequest<T>>(rid, CanInterface::GetCanAddress(), boardAddress, mt);
msg->driversToUpdate = driverBits.GetRaw();
const size_t numDrivers = driverBits.CountSetBits();
for (size_t i = 0; i < numDrivers; ++i)
{
msg->values[i] = data.GetElement(savedStart + i);
}
buf->dataLength = msg->GetActualDataLength(numDrivers);
rslt = max(rslt, CanInterface::SendRequestAndGetStandardReply(buf, rid, reply));
}
return rslt;
}
// Set remote drivers to enabled, disabled, or idle
// This function is called by both the main task and the Move task.
// As there is no mutual exclusion on putting messages in buffers or receiving replies, when this is called by the Move task
// we send the commands through the FIFO and we use a special RequestId to say that we do not expect a response
static GCodeResult SetRemoteDriverStates(const CanDriversList& drivers, const StringRef& reply, DriverStateControl state) noexcept
{
GCodeResult rslt = GCodeResult::ok;
const bool fromMoveTask = TaskBase::GetCallerTaskHandle() == Move::GetMoveTaskHandle();
size_t start = 0;
for (;;)
{
CanDriversBitmap driverBits;
const CanAddress boardAddress = drivers.GetNextBoardDriverBitmap(start, driverBits);
if (boardAddress == CanId::NoAddress)
{
break;
}
CanMessageBuffer * const buf = CanMessageBuffer::Allocate();
if (buf == nullptr)
{
return GCodeResult::noCanBuffer;
}
const CanRequestId rid = (fromMoveTask) ? CanRequestIdNoReplyNeeded : CanInterface::AllocateRequestId(boardAddress, buf);
const auto msg = buf->SetupRequestMessage<CanMessageMultipleDrivesRequest<DriverStateControl>>(rid, CanInterface::GetCanAddress(), boardAddress, CanMessageType::setDriverStates);
msg->driversToUpdate = driverBits.GetRaw();
const size_t numDrivers = driverBits.CountSetBits();
for (size_t i = 0; i < numDrivers; ++i)
{
msg->values[i] = state;
}
buf->dataLength = msg->GetActualDataLength(numDrivers);
if (fromMoveTask)
{
CanInterface::SendMotion(buf); // if it's coming from the Move task then we must send the command via the fifo
}
else
{
rslt = max(rslt, CanInterface::SendRequestAndGetStandardReply(buf, rid, reply)); // send the command via the usual mechanism
}
}
return rslt;
}
// Add a buffer to the end of the send queue
void CanInterface::SendMotion(CanMessageBuffer *buf) noexcept
{
buf->next = nullptr;
#if 0
buf->msg.moveLinear.DebugPrint();
#endif
{
TaskCriticalSectionLocker lock;
if (pendingMotionBuffers == nullptr)
{
pendingMotionBuffers = buf;
}
else
{
lastMotionBuffer->next = buf;
}
lastMotionBuffer = buf;
#if 0 //unused
++numPendingMotionBuffers;
#endif
}
canSenderTask.Give(NotifyIndices::CanSender);
}
#if 0 // not currently used
// Get the number of motion messages waiting to be sent through the Tx fifo
unsigned int CanInterface::GetNumPendingMotionMessages() noexcept
{
return can0dev->NumTxMessagesPending(TxBufferIndexMotion) + numPendingMotionBuffers;
}
#endif
// Send a request to an expansion board and append the response to 'reply'
GCodeResult CanInterface::SendRequestAndGetStandardReply(CanMessageBuffer *buf, CanRequestId rid, const StringRef& reply, uint8_t *extra) noexcept
{
return SendRequestAndGetCustomReply(buf, rid, reply, extra, CanMessageType::unusedMessageType, [](const CanMessageBuffer*) { });
}
// Send a request to an expansion board and append the response to 'reply'. The response may either be a standard reply or 'replyType'.
GCodeResult CanInterface::SendRequestAndGetCustomReply(CanMessageBuffer *buf, CanRequestId rid, const StringRef& reply, uint8_t *extra, CanMessageType replyType, function_ref_noexcept<void(const CanMessageBuffer*) noexcept> callback) noexcept
{
if (can0dev == nullptr)
{
// Transactions sometimes get requested after we have shut down CAN, e.g. when we destroy filament monitors
CanMessageBuffer::Free(buf);
return GCodeResult::error;
}
const CanAddress dest = buf->id.Dst();
const CanMessageType msgType = buf->id.MsgType(); // save for possible error message
{
// This code isn't re-entrant and it can get called from a task other than Main to shut the system down, so we need to use a mutex
MutexLocker lock(transactionMutex);
SendCanMessage(TxBufferIndexRequest, MaxRequestSendWait, buf);
reprap.GetPlatform().OnProcessingCanMessage();
const uint32_t whenStartedWaiting = millis();
uint32_t timeWaiting = 0;
unsigned int fragmentsReceived = 0;
for (;;)
{
const uint32_t timeout = (timeWaiting < UsualResponseTimeout) ? UsualResponseTimeout - timeWaiting : 1;
if (!can0dev->ReceiveMessage(RxBufferIndexResponse, timeout, buf))
{
break;
}
if (reprap.Debug(Module::CAN))
{
buf->DebugPrint("Rx1:");
}
// The following code allows for the possibility of receiving a StandardReply (e.g. because an error occurred) when we were expecting a different reply.
// It assumes that any custom reply we may want has the requestId in the same place as a StandardReply.
const bool matchesRequest = buf->id.Src() == dest
&& (buf->msg.standardReply.requestId == rid || buf->msg.standardReply.requestId == CanRequestIdAcceptAlways);
if (matchesRequest && buf->id.MsgType() == CanMessageType::standardReply && buf->msg.standardReply.fragmentNumber == fragmentsReceived)
{
if (fragmentsReceived == 0)
{
const size_t textLength = buf->msg.standardReply.GetTextLength(buf->dataLength);
if (textLength != 0) // avoid concatenating blank lines to existing output
{
reply.lcatn(buf->msg.standardReply.text, textLength);
}
if (extra != nullptr)
{
*extra = buf->msg.standardReply.extra;
}
uint32_t waitedFor = millis() - whenStartedWaiting;
if (waitedFor > longestWaitTime)
{
longestWaitTime = waitedFor;
longestWaitMessageType = (uint16_t)msgType;
}
}
else
{
reply.catn(buf->msg.standardReply.text, buf->msg.standardReply.GetTextLength(buf->dataLength));
}
if (!buf->msg.standardReply.moreFollows)
{
const GCodeResult rslt = (GCodeResult)buf->msg.standardReply.resultCode;
CanMessageBuffer::Free(buf);
return rslt;
}
++fragmentsReceived;
}
else if (matchesRequest && buf->id.MsgType() == replyType && fragmentsReceived == 0)
{
callback(buf);
CanMessageBuffer::Free(buf);
return GCodeResult::ok;
}
else
{
// We received an unexpected message. Don't tack it on to 'reply' because some replies contain important data, e.g. request for board short name.
if (buf->id.MsgType() == CanMessageType::standardReply)
{
reprap.GetPlatform().MessageF(WarningMessage, "Discarded std reply src=%u RID=%u exp=%u \"%.*s\"\n",
buf->id.Src(), (unsigned int)buf->msg.standardReply.requestId, rid, buf->msg.standardReply.GetTextLength(buf->dataLength), buf->msg.standardReply.text);
}
else
{
reprap.GetPlatform().MessageF(WarningMessage, "Discarded msg src=%u typ=%u RID=%u exp=%u\n",
buf->id.Src(), (unsigned int)buf->id.MsgType(), (unsigned int)buf->msg.standardReply.requestId, rid);
}
}
timeWaiting = millis() - whenStartedWaiting;
}
}
CanMessageBuffer::Free(buf);
reply.lcatf("CAN response timeout: board %u, req type %u, RID %u", dest, (unsigned int)msgType, (unsigned int)rid);
return GCodeResult::canResponseTimeout;
}
// Send a response to an expansion board and free the buffer
void CanInterface::SendResponseNoFree(CanMessageBuffer *buf) noexcept
{
SendCanMessage(TxBufferIndexResponse, MaxResponseSendWait, buf);
}
// Send a broadcast message and free the buffer
void CanInterface::SendBroadcastNoFree(CanMessageBuffer *buf) noexcept
{
if (can0dev != nullptr)
{
SendCanMessage(TxBufferIndexBroadcast, MaxResponseSendWait, buf);
}
}
// Send a request message with no reply expected, and don't free the buffer. Used to send emergency stop messages.
void CanInterface::SendMessageNoReplyNoFree(CanMessageBuffer *buf) noexcept
{
if (can0dev != nullptr)
{
SendCanMessage(TxBufferIndexBroadcast, MaxResponseSendWait, buf);
}
}
#if DUAL_CAN
uint32_t CanInterface::SendPlainMessageNoFree(CanMessageBuffer *buf, uint32_t const timeout) noexcept
{
return (can1dev != nullptr) ? can1dev->SendMessage(CanDevice::TxBufferNumber::fifo, timeout, buf) : 0;
}
bool CanInterface::ReceivePlainMessage(CanMessageBuffer *null buf, uint32_t const timeout) noexcept
{
return can1dev != nullptr && can1dev->ReceiveMessage(CanDevice::RxBufferNumber::fifo0, timeout, buf);
}
#endif
// The CanReceiver task
extern "C" [[noreturn]] void CanReceiverLoop(void *) noexcept
{
CanMessageBuffer buf;
for (;;)
{
if (can0dev->ReceiveMessage(RxBufferIndexRequest, TaskBase::TimeoutUnlimited, &buf))
{
if (reprap.Debug(Module::CAN))
{
buf.DebugPrint("Rx0:");
}
CommandProcessor::ProcessReceivedMessage(&buf);
}
}
}
// This one is used by ATE
GCodeResult CanInterface::EnableRemoteDrivers(const CanDriversList& drivers, const StringRef& reply) noexcept
{
return SetRemoteDriverStates(drivers, reply, DriverStateControl(DriverStateControl::driverActive));
}
// This one is used by Prepare and by M17
void CanInterface::EnableRemoteDrivers(const CanDriversList& drivers) noexcept
{
String<1> dummy;
(void)EnableRemoteDrivers(drivers, dummy.GetRef());
}
// This one is used by ATE
GCodeResult CanInterface::DisableRemoteDrivers(const CanDriversList& drivers, const StringRef& reply) noexcept
{
return SetRemoteDriverStates(drivers, reply, DriverStateControl(DriverStateControl::driverDisabled));
}
// This one is used by Prepare
void CanInterface::DisableRemoteDrivers(const CanDriversList& drivers) noexcept
{
String<1> dummy;
(void)DisableRemoteDrivers(drivers, dummy.GetRef());
}
void CanInterface::SetRemoteDriversIdle(const CanDriversList& drivers, float idleCurrentFactor) noexcept
{
String<1> dummy;
(void)SetRemoteDriverStates(drivers, dummy.GetRef(), DriverStateControl(DriverStateControl::driverIdle, (uint16_t)lrintf(idleCurrentFactor * 100)));
}
GCodeResult CanInterface::SetRemoteStandstillCurrentPercent(const CanDriversData<float>& data, const StringRef& reply) noexcept
{
return SetRemoteDriverValues(data, reply, CanMessageType::setStandstillCurrentFactor);
}
GCodeResult CanInterface::SetRemoteDriverCurrents(const CanDriversData<float>& data, const StringRef& reply) noexcept
{
return SetRemoteDriverValues(data, reply, CanMessageType::setMotorCurrents);
}
GCodeResult CanInterface::SetRemoteDriverStepsPerMmAndMicrostepping(const CanDriversData<StepsPerUnitAndMicrostepping>& data, const StringRef& reply) noexcept
{
return SetRemoteDriverValues(data, reply, CanMessageType::setStepsPerMmAndMicrostepping);
}
// Set the pressure advance on remote drivers, returning true if successful
GCodeResult CanInterface::SetRemotePressureAdvance(const CanDriversData<float>& data, const StringRef& reply) noexcept
{
return SetRemoteDriverValues(data, reply, CanMessageType::setPressureAdvance);