CANFDIface.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /*
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2014 Pavel Kirienko
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  7. * this software and associated documentation files (the "Software"), to deal in
  8. * the Software without restriction, including without limitation the rights to
  9. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  10. * the Software, and to permit persons to whom the Software is furnished to do so,
  11. * subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in all
  14. * copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  18. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  19. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  20. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. /*
  24. * This file is free software: you can redistribute it and/or modify it
  25. * under the terms of the GNU General Public License as published by the
  26. * Free Software Foundation, either version 3 of the License, or
  27. * (at your option) any later version.
  28. *
  29. * This file is distributed in the hope that it will be useful, but
  30. * WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  32. * See the GNU General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU General Public License along
  35. * with this program. If not, see <http://www.gnu.org/licenses/>.
  36. *
  37. * Code by Siddharth Bharat Purohit
  38. */
  39. #pragma once
  40. #include "AP_HAL_ChibiOS.h"
  41. #if HAL_WITH_UAVCAN
  42. #include "CANThread.h"
  43. #include "fdcan.hpp"
  44. class SLCANRouter;
  45. namespace ChibiOS_CAN
  46. {
  47. /**
  48. * Driver error codes.
  49. * These values can be returned from driver functions negated.
  50. */
  51. //static const uavcan::int16_t ErrUnknown = 1000; ///< Reserved for future use
  52. static const uavcan::int16_t ErrNotImplemented = 1001; ///< Feature not implemented
  53. static const uavcan::int16_t ErrInvalidBitRate = 1002; ///< Bit rate not supported
  54. static const uavcan::int16_t ErrLogic = 1003; ///< Internal logic error
  55. static const uavcan::int16_t ErrUnsupportedFrame = 1004; ///< Frame not supported (e.g. RTR, CAN FD, etc)
  56. static const uavcan::int16_t ErrMsrInakNotSet = 1005; ///< INAK bit of the MSR register is not 1
  57. static const uavcan::int16_t ErrMsrInakNotCleared = 1006; ///< INAK bit of the MSR register is not 0
  58. static const uavcan::int16_t ErrBitRateNotDetected = 1007; ///< Auto bit rate detection could not be finished
  59. static const uavcan::int16_t ErrFilterNumConfigs = 1008; ///< Number of filters is more than supported
  60. /**
  61. * RX queue item.
  62. * The application shall not use this directly.
  63. */
  64. struct CanRxItem {
  65. uavcan::uint64_t utc_usec;
  66. uavcan::CanFrame frame;
  67. uavcan::CanIOFlags flags;
  68. CanRxItem()
  69. : utc_usec(0)
  70. , flags(0)
  71. { }
  72. };
  73. /**
  74. * Single CAN iface.
  75. * The application shall not use this directly.
  76. */
  77. class CanIface : public uavcan::ICanIface, uavcan::Noncopyable
  78. {
  79. #if AP_UAVCAN_SLCAN_ENABLED
  80. friend class ::SLCANRouter;
  81. static SLCANRouter _slcan_router;
  82. #endif
  83. class RxQueue
  84. {
  85. CanRxItem* const buf_;
  86. const uavcan::uint8_t capacity_;
  87. uavcan::uint8_t in_;
  88. uavcan::uint8_t out_;
  89. uavcan::uint8_t len_;
  90. uavcan::uint32_t overflow_cnt_;
  91. void registerOverflow();
  92. public:
  93. RxQueue(CanRxItem* buf, uavcan::uint8_t capacity)
  94. : buf_(buf)
  95. , capacity_(capacity)
  96. , in_(0)
  97. , out_(0)
  98. , len_(0)
  99. , overflow_cnt_(0)
  100. { }
  101. void push(const uavcan::CanFrame& frame, const uint64_t& utc_usec, uavcan::CanIOFlags flags);
  102. void pop(uavcan::CanFrame& out_frame, uavcan::uint64_t& out_utc_usec, uavcan::CanIOFlags& out_flags);
  103. void reset();
  104. unsigned getLength() const
  105. {
  106. return len_;
  107. }
  108. uavcan::uint32_t getOverflowCount() const
  109. {
  110. return overflow_cnt_;
  111. }
  112. };
  113. struct MessageRAM {
  114. uavcan::uint32_t StandardFilterSA;
  115. uavcan::uint32_t ExtendedFilterSA;
  116. uavcan::uint32_t RxFIFO0SA;
  117. uavcan::uint32_t RxFIFO1SA;
  118. uavcan::uint32_t TxFIFOQSA;
  119. uavcan::uint32_t EndAddress;
  120. } MessageRam_;
  121. struct Timings {
  122. uavcan::uint16_t prescaler;
  123. uavcan::uint8_t sjw;
  124. uavcan::uint8_t bs1;
  125. uavcan::uint8_t bs2;
  126. Timings()
  127. : prescaler(0)
  128. , sjw(0)
  129. , bs1(0)
  130. , bs2(0)
  131. { }
  132. };
  133. struct TxItem {
  134. uavcan::MonotonicTime deadline;
  135. uavcan::CanFrame frame;
  136. bool loopback;
  137. bool abort_on_error;
  138. uint8_t index;
  139. TxItem() :
  140. loopback(false),
  141. abort_on_error(false)
  142. { }
  143. };
  144. enum { NumTxMailboxes = 32 };
  145. static const uavcan::uint32_t TSR_ABRQx[NumTxMailboxes];
  146. static uint32_t FDCANMessageRAMOffset_;
  147. RxQueue rx_queue_;
  148. fdcan::CanType* const can_;
  149. uavcan::uint64_t error_cnt_;
  150. uavcan::uint32_t served_aborts_cnt_;
  151. BusEvent& update_event_;
  152. TxItem pending_tx_[NumTxMailboxes];
  153. uavcan::uint8_t peak_tx_mailbox_index_;
  154. const uavcan::uint8_t self_index_;
  155. bool had_activity_;
  156. int computeTimings(uavcan::uint32_t target_bitrate, Timings& out_timings);
  157. virtual uavcan::int16_t send(const uavcan::CanFrame& frame, uavcan::MonotonicTime tx_deadline,
  158. uavcan::CanIOFlags flags) override;
  159. virtual uavcan::int16_t receive(uavcan::CanFrame& out_frame, uavcan::MonotonicTime& out_ts_monotonic,
  160. uavcan::UtcTime& out_ts_utc, uavcan::CanIOFlags& out_flags) override;
  161. virtual uavcan::int16_t configureFilters(const uavcan::CanFilterConfig* filter_configs,
  162. uavcan::uint16_t num_configs) override;
  163. virtual uavcan::uint16_t getNumFilters() const override;
  164. void setupMessageRam(void);
  165. static uint32_t FDCAN2MessageRAMOffset_;
  166. public:
  167. enum { MaxRxQueueCapacity = 254 };
  168. enum OperatingMode {
  169. NormalMode,
  170. SilentMode
  171. };
  172. CanIface(fdcan::CanType* can, BusEvent& update_event, uavcan::uint8_t self_index,
  173. CanRxItem* rx_queue_buffer, uavcan::uint8_t rx_queue_capacity);
  174. /**
  175. * Initializes the hardware CAN controller.
  176. * Assumes:
  177. * - Iface clock is enabled
  178. * - Iface has been resetted via RCC
  179. * - Caller will configure NVIC by itself
  180. */
  181. int init(const uavcan::uint32_t bitrate, const OperatingMode mode);
  182. void handleTxCompleteInterrupt(uavcan::uint64_t utc_usec);
  183. void handleRxInterrupt(uavcan::uint8_t fifo_index);
  184. bool readRxFIFO(uavcan::uint8_t fifo_index);
  185. /**
  186. * This method is used to count errors and abort transmission on error if necessary.
  187. * This functionality used to be implemented in the SCE interrupt handler, but that approach was
  188. * generating too much processing overhead, especially on disconnected interfaces.
  189. *
  190. * Should be called from RX ISR, TX ISR, and select(); interrupts must be enabled.
  191. */
  192. void pollErrorFlagsFromISR();
  193. void discardTimedOutTxMailboxes(uavcan::MonotonicTime current_time);
  194. bool canAcceptNewTxFrame(const uavcan::CanFrame& frame) const;
  195. bool isRxBufferEmpty() const;
  196. /**
  197. * Number of RX frames lost due to queue overflow.
  198. * This is an atomic read, it doesn't require a critical section.
  199. */
  200. uavcan::uint32_t getRxQueueOverflowCount() const
  201. {
  202. return rx_queue_.getOverflowCount();
  203. }
  204. /**
  205. * Total number of hardware failures and other kinds of errors (e.g. queue overruns).
  206. * May increase continuously if the interface is not connected to the bus.
  207. */
  208. virtual uavcan::uint64_t getErrorCount() const override;
  209. /**
  210. * Number of times the driver exercised library's requirement to abort transmission on first error.
  211. * This is an atomic read, it doesn't require a critical section.
  212. * See @ref uavcan::CanIOFlagAbortOnError.
  213. */
  214. uavcan::uint32_t getVoluntaryTxAbortCount() const
  215. {
  216. return served_aborts_cnt_;
  217. }
  218. /**
  219. * Returns the number of frames pending in the RX queue.
  220. * This is intended for debug use only.
  221. */
  222. unsigned getRxQueueLength() const;
  223. /**
  224. * Whether this iface had at least one successful IO since the previous call of this method.
  225. * This is designed for use with iface activity LEDs.
  226. */
  227. bool hadActivity();
  228. /**
  229. * Peak number of TX mailboxes used concurrently since initialization.
  230. * Range is [1, 3].
  231. * Value of 3 suggests that priority inversion could be taking place.
  232. */
  233. uavcan::uint8_t getPeakNumTxMailboxesUsed() const
  234. {
  235. return uavcan::uint8_t(peak_tx_mailbox_index_ + 1);
  236. }
  237. fdcan::CanType* can_reg(void)
  238. {
  239. return can_;
  240. }
  241. #if AP_UAVCAN_SLCAN_ENABLED
  242. static SLCANRouter &slcan_router() { return _slcan_router; }
  243. #endif
  244. };
  245. /**
  246. * CAN driver, incorporates all available CAN ifaces.
  247. * Please avoid direct use, prefer @ref CanInitHelper instead.
  248. */
  249. class CanDriver : public uavcan::ICanDriver, uavcan::Noncopyable
  250. {
  251. BusEvent update_event_;
  252. static bool clock_init_;
  253. CanIface if0_;
  254. #if UAVCAN_STM32_NUM_IFACES > 1
  255. CanIface if1_;
  256. #endif
  257. bool initialized_by_me_[UAVCAN_STM32_NUM_IFACES];
  258. uavcan::uint8_t num_ifaces_;
  259. uavcan::uint8_t if_int_to_gl_index_[UAVCAN_STM32_NUM_IFACES];
  260. virtual uavcan::int16_t select(uavcan::CanSelectMasks& inout_masks,
  261. const uavcan::CanFrame* (& pending_tx)[uavcan::MaxCanIfaces],
  262. uavcan::MonotonicTime blocking_deadline) override;
  263. static void initOnce();
  264. static void initOnce(uavcan::uint8_t can_number, bool enable_irqs);
  265. public:
  266. template <unsigned RxQueueCapacity>
  267. CanDriver(CanRxItem(&rx_queue_storage)[UAVCAN_STM32_NUM_IFACES][RxQueueCapacity])
  268. : update_event_(*this)
  269. , if0_(fdcan::Can[0], update_event_, 0, rx_queue_storage[0], RxQueueCapacity)
  270. #if UAVCAN_STM32_NUM_IFACES > 1
  271. , if1_(fdcan::Can[1], update_event_, 1, rx_queue_storage[1], RxQueueCapacity)
  272. #endif
  273. {
  274. uavcan::StaticAssert<(RxQueueCapacity <= CanIface::MaxRxQueueCapacity)>::check();
  275. }
  276. /**
  277. * This function returns select masks indicating which interfaces are available for read/write.
  278. */
  279. uavcan::CanSelectMasks makeSelectMasks(const uavcan::CanFrame* (& pending_tx)[uavcan::MaxCanIfaces]) const;
  280. BusEvent* getUpdateEvent()
  281. {
  282. return &update_event_;
  283. }
  284. /**
  285. * Whether there's at least one interface where receive() would return a frame.
  286. */
  287. bool hasReadableInterfaces() const;
  288. /**
  289. * Returns zero if OK.
  290. * Returns negative value if failed (e.g. invalid bitrate).
  291. */
  292. int init(const uavcan::uint32_t bitrate, const CanIface::OperatingMode mode);
  293. int init(const uavcan::uint32_t bitrate, const CanIface::OperatingMode mode, uavcan::uint8_t can_number);
  294. virtual CanIface* getIface(uavcan::uint8_t iface_index) override;
  295. virtual uavcan::uint8_t getNumIfaces() const override
  296. {
  297. return num_ifaces_;
  298. }
  299. /**
  300. * Whether at least one iface had at least one successful IO since previous call of this method.
  301. * This is designed for use with iface activity LEDs.
  302. */
  303. bool hadActivity();
  304. };
  305. /**
  306. * Helper class.
  307. * Normally only this class should be used by the application.
  308. * 145 usec per Extended CAN frame @ 1 Mbps, e.g. 32 RX slots * 145 usec --> 4.6 msec before RX queue overruns.
  309. */
  310. template <unsigned RxQueueCapacity = 128>
  311. class CanInitHelper
  312. {
  313. CanRxItem queue_storage_[UAVCAN_STM32_NUM_IFACES][RxQueueCapacity];
  314. public:
  315. enum { BitRateAutoDetect = 0 };
  316. CanDriver driver;
  317. CanInitHelper() :
  318. driver(queue_storage_)
  319. { }
  320. /**
  321. * This overload simply configures the provided bitrate.
  322. * Auto bit rate detection will not be performed.
  323. * Bitrate value must be positive.
  324. * @return Negative value on error; non-negative on success. Refer to constants Err*.
  325. */
  326. int init(uavcan::uint32_t bitrate)
  327. {
  328. return driver.init(bitrate, CanIface::NormalMode);
  329. }
  330. int init(const uavcan::uint32_t bitrate, const CanIface::OperatingMode mode, uavcan::uint8_t can_number)
  331. {
  332. return driver.init(bitrate, mode, can_number);
  333. }
  334. /**
  335. * This function can either initialize the driver at a fixed bit rate, or it can perform
  336. * automatic bit rate detection. For theory please refer to the CiA application note #801.
  337. *
  338. * @param delay_callable A callable entity that suspends execution for strictly more than one second.
  339. * The callable entity will be invoked without arguments.
  340. * @ref getRecommendedListeningDelay().
  341. *
  342. * @param inout_bitrate Fixed bit rate or zero. Zero invokes the bit rate detection process.
  343. * If auto detection was used, the function will update the argument
  344. * with established bit rate. In case of an error the value will be undefined.
  345. *
  346. * @return Negative value on error; non-negative on success. Refer to constants Err*.
  347. */
  348. template <typename DelayCallable>
  349. int init(DelayCallable delay_callable, uavcan::uint32_t& inout_bitrate = BitRateAutoDetect)
  350. {
  351. if (inout_bitrate > 0) {
  352. return driver.init(inout_bitrate, CanIface::NormalMode);
  353. } else {
  354. static const uavcan::uint32_t StandardBitRates[] = {
  355. 1000000,
  356. 500000,
  357. 250000,
  358. 125000
  359. };
  360. for (uavcan::uint8_t br = 0; br < sizeof(StandardBitRates) / sizeof(StandardBitRates[0]); br++) {
  361. inout_bitrate = StandardBitRates[br];
  362. const int res = driver.init(inout_bitrate, CanIface::SilentMode);
  363. delay_callable();
  364. if (res >= 0) {
  365. for (uavcan::uint8_t iface = 0; iface < driver.getNumIfaces(); iface++) {
  366. if (!driver.getIface(iface)->isRxBufferEmpty()) {
  367. // Re-initializing in normal mode
  368. return driver.init(inout_bitrate, CanIface::NormalMode);
  369. }
  370. }
  371. }
  372. }
  373. return -ErrBitRateNotDetected;
  374. }
  375. }
  376. /**
  377. * Use this value for listening delay during automatic bit rate detection.
  378. */
  379. static uavcan::MonotonicDuration getRecommendedListeningDelay()
  380. {
  381. return uavcan::MonotonicDuration::fromMSec(1050);
  382. }
  383. };
  384. }
  385. #include "CANSerialRouter.h"
  386. #endif //HAL_WITH_UAVCAN