CANIface.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. # if defined(STM32H7XX)
  43. #include "CANFDIface.h"
  44. #else
  45. #include "CANThread.h"
  46. #include "CANIface.h"
  47. #include "bxcan.hpp"
  48. class SLCANRouter;
  49. namespace ChibiOS_CAN {
  50. /**
  51. * Driver error codes.
  52. * These values can be returned from driver functions negated.
  53. */
  54. //static const uavcan::int16_t ErrUnknown = 1000; ///< Reserved for future use
  55. static const uavcan::int16_t ErrNotImplemented = 1001; ///< Feature not implemented
  56. static const uavcan::int16_t ErrInvalidBitRate = 1002; ///< Bit rate not supported
  57. static const uavcan::int16_t ErrLogic = 1003; ///< Internal logic error
  58. static const uavcan::int16_t ErrUnsupportedFrame = 1004; ///< Frame not supported (e.g. RTR, CAN FD, etc)
  59. static const uavcan::int16_t ErrMsrInakNotSet = 1005; ///< INAK bit of the MSR register is not 1
  60. static const uavcan::int16_t ErrMsrInakNotCleared = 1006; ///< INAK bit of the MSR register is not 0
  61. static const uavcan::int16_t ErrBitRateNotDetected = 1007; ///< Auto bit rate detection could not be finished
  62. static const uavcan::int16_t ErrFilterNumConfigs = 1008; ///< Number of filters is more than supported
  63. /**
  64. * RX queue item.
  65. * The application shall not use this directly.
  66. */
  67. struct CanRxItem {
  68. uavcan::uint64_t utc_usec;
  69. uavcan::CanFrame frame;
  70. uavcan::CanIOFlags flags;
  71. CanRxItem()
  72. : utc_usec(0)
  73. , flags(0)
  74. { }
  75. };
  76. /**
  77. * Single CAN iface.
  78. * The application shall not use this directly.
  79. */
  80. class CanIface : public uavcan::ICanIface, uavcan::Noncopyable {
  81. #if AP_UAVCAN_SLCAN_ENABLED
  82. friend class ::SLCANRouter;
  83. static SLCANRouter _slcan_router;
  84. #endif
  85. class RxQueue {
  86. CanRxItem* const buf_;
  87. const uavcan::uint8_t capacity_;
  88. uavcan::uint8_t in_;
  89. uavcan::uint8_t out_;
  90. uavcan::uint8_t len_;
  91. uavcan::uint32_t overflow_cnt_;
  92. void registerOverflow();
  93. public:
  94. RxQueue(CanRxItem* buf, uavcan::uint8_t capacity)
  95. : buf_(buf)
  96. , capacity_(capacity)
  97. , in_(0)
  98. , out_(0)
  99. , len_(0)
  100. , overflow_cnt_(0)
  101. { }
  102. void push(const uavcan::CanFrame& frame, const uint64_t& utc_usec, uavcan::CanIOFlags flags);
  103. void pop(uavcan::CanFrame& out_frame, uavcan::uint64_t& out_utc_usec, uavcan::CanIOFlags& out_flags);
  104. void reset();
  105. unsigned getLength() const
  106. {
  107. return len_;
  108. }
  109. uavcan::uint32_t getOverflowCount() const
  110. {
  111. return overflow_cnt_;
  112. }
  113. };
  114. struct Timings {
  115. uavcan::uint16_t prescaler;
  116. uavcan::uint8_t sjw;
  117. uavcan::uint8_t bs1;
  118. uavcan::uint8_t bs2;
  119. Timings()
  120. : prescaler(0)
  121. , sjw(0)
  122. , bs1(0)
  123. , bs2(0)
  124. { }
  125. };
  126. struct TxItem {
  127. uavcan::MonotonicTime deadline;
  128. uavcan::CanFrame frame;
  129. bool pending;
  130. bool loopback;
  131. bool abort_on_error;
  132. TxItem()
  133. : pending(false)
  134. , loopback(false)
  135. , abort_on_error(false)
  136. { }
  137. };
  138. enum { NumTxMailboxes = 3 };
  139. enum { NumFilters = 14 };
  140. static const uavcan::uint32_t TSR_ABRQx[NumTxMailboxes];
  141. RxQueue rx_queue_;
  142. bxcan::CanType* const can_;
  143. uavcan::uint64_t error_cnt_;
  144. uavcan::uint32_t served_aborts_cnt_;
  145. BusEvent& update_event_;
  146. TxItem pending_tx_[NumTxMailboxes];
  147. uavcan::uint8_t peak_tx_mailbox_index_;
  148. const uavcan::uint8_t self_index_;
  149. bool had_activity_;
  150. int computeTimings(uavcan::uint32_t target_bitrate, Timings& out_timings);
  151. virtual uavcan::int16_t send(const uavcan::CanFrame& frame, uavcan::MonotonicTime tx_deadline,
  152. uavcan::CanIOFlags flags) override;
  153. virtual uavcan::int16_t receive(uavcan::CanFrame& out_frame, uavcan::MonotonicTime& out_ts_monotonic,
  154. uavcan::UtcTime& out_ts_utc, uavcan::CanIOFlags& out_flags) override;
  155. virtual uavcan::int16_t configureFilters(const uavcan::CanFilterConfig* filter_configs,
  156. uavcan::uint16_t num_configs) override;
  157. virtual uavcan::uint16_t getNumFilters() const override
  158. {
  159. return NumFilters;
  160. }
  161. void handleTxMailboxInterrupt(uavcan::uint8_t mailbox_index, bool txok, uavcan::uint64_t utc_usec);
  162. bool waitMsrINakBitStateChange(bool target_state);
  163. public:
  164. enum { MaxRxQueueCapacity = 254 };
  165. enum OperatingMode {
  166. NormalMode,
  167. SilentMode
  168. };
  169. CanIface(bxcan::CanType* can, BusEvent& update_event, uavcan::uint8_t self_index,
  170. CanRxItem* rx_queue_buffer, uavcan::uint8_t rx_queue_capacity)
  171. : rx_queue_(rx_queue_buffer, rx_queue_capacity)
  172. , can_(can)
  173. , error_cnt_(0)
  174. , served_aborts_cnt_(0)
  175. , update_event_(update_event)
  176. , peak_tx_mailbox_index_(0)
  177. , self_index_(self_index)
  178. , had_activity_(false)
  179. {
  180. UAVCAN_ASSERT(self_index_ < UAVCAN_STM32_NUM_IFACES);
  181. }
  182. /**
  183. * Initializes the hardware CAN controller.
  184. * Assumes:
  185. * - Iface clock is enabled
  186. * - Iface has been resetted via RCC
  187. * - Caller will configure NVIC by itself
  188. */
  189. int init(const uavcan::uint32_t bitrate, const OperatingMode mode);
  190. void handleTxInterrupt(uavcan::uint64_t utc_usec);
  191. void handleRxInterrupt(uavcan::uint8_t fifo_index, uavcan::uint64_t utc_usec);
  192. /**
  193. * This method is used to count errors and abort transmission on error if necessary.
  194. * This functionality used to be implemented in the SCE interrupt handler, but that approach was
  195. * generating too much processing overhead, especially on disconnected interfaces.
  196. *
  197. * Should be called from RX ISR, TX ISR, and select(); interrupts must be enabled.
  198. */
  199. void pollErrorFlagsFromISR();
  200. void discardTimedOutTxMailboxes(uavcan::MonotonicTime current_time);
  201. bool canAcceptNewTxFrame(const uavcan::CanFrame& frame) const;
  202. bool isRxBufferEmpty() const;
  203. /**
  204. * Number of RX frames lost due to queue overflow.
  205. * This is an atomic read, it doesn't require a critical section.
  206. */
  207. uavcan::uint32_t getRxQueueOverflowCount() const
  208. {
  209. return rx_queue_.getOverflowCount();
  210. }
  211. /**
  212. * Total number of hardware failures and other kinds of errors (e.g. queue overruns).
  213. * May increase continuously if the interface is not connected to the bus.
  214. */
  215. virtual uavcan::uint64_t getErrorCount() const override;
  216. /**
  217. * Number of times the driver exercised library's requirement to abort transmission on first error.
  218. * This is an atomic read, it doesn't require a critical section.
  219. * See @ref uavcan::CanIOFlagAbortOnError.
  220. */
  221. uavcan::uint32_t getVoluntaryTxAbortCount() const
  222. {
  223. return served_aborts_cnt_;
  224. }
  225. /**
  226. * Returns the number of frames pending in the RX queue.
  227. * This is intended for debug use only.
  228. */
  229. unsigned getRxQueueLength() const;
  230. /**
  231. * Whether this iface had at least one successful IO since the previous call of this method.
  232. * This is designed for use with iface activity LEDs.
  233. */
  234. bool hadActivity();
  235. /**
  236. * Peak number of TX mailboxes used concurrently since initialization.
  237. * Range is [1, 3].
  238. * Value of 3 suggests that priority inversion could be taking place.
  239. */
  240. uavcan::uint8_t getPeakNumTxMailboxesUsed() const
  241. {
  242. return uavcan::uint8_t(peak_tx_mailbox_index_ + 1);
  243. }
  244. #if AP_UAVCAN_SLCAN_ENABLED
  245. static SLCANRouter &slcan_router() { return _slcan_router; }
  246. #endif
  247. };
  248. /**
  249. * CAN driver, incorporates all available CAN ifaces.
  250. * Please avoid direct use, prefer @ref CanInitHelper instead.
  251. */
  252. class CanDriver : public uavcan::ICanDriver, uavcan::Noncopyable {
  253. BusEvent update_event_;
  254. CanIface if0_;
  255. #if UAVCAN_STM32_NUM_IFACES > 1
  256. CanIface if1_;
  257. #endif
  258. bool initialized_by_me_[UAVCAN_STM32_NUM_IFACES];
  259. uavcan::uint8_t num_ifaces_;
  260. uavcan::uint8_t if_int_to_gl_index_[UAVCAN_STM32_NUM_IFACES];
  261. virtual uavcan::int16_t select(uavcan::CanSelectMasks& inout_masks,
  262. const uavcan::CanFrame* (& pending_tx)[uavcan::MaxCanIfaces],
  263. uavcan::MonotonicTime blocking_deadline) override;
  264. static void initOnce();
  265. static void initOnce(uavcan::uint8_t can_number, bool enable_irqs);
  266. public:
  267. template <unsigned RxQueueCapacity>
  268. CanDriver(CanRxItem(&rx_queue_storage)[UAVCAN_STM32_NUM_IFACES][RxQueueCapacity])
  269. : update_event_(*this)
  270. , if0_(bxcan::Can[0], update_event_, 0, rx_queue_storage[0], RxQueueCapacity)
  271. #if UAVCAN_STM32_NUM_IFACES > 1
  272. , if1_(bxcan::Can[1], update_event_, 1, rx_queue_storage[1], RxQueueCapacity)
  273. #endif
  274. {
  275. uavcan::StaticAssert<(RxQueueCapacity <= CanIface::MaxRxQueueCapacity)>::check();
  276. }
  277. /**
  278. * This function returns select masks indicating which interfaces are available for read/write.
  279. */
  280. uavcan::CanSelectMasks makeSelectMasks(const uavcan::CanFrame* (& pending_tx)[uavcan::MaxCanIfaces]) const;
  281. BusEvent* getUpdateEvent()
  282. {
  283. return &update_event_;
  284. }
  285. /**
  286. * Whether there's at least one interface where receive() would return a frame.
  287. */
  288. bool hasReadableInterfaces() const;
  289. /**
  290. * Returns zero if OK.
  291. * Returns negative value if failed (e.g. invalid bitrate).
  292. */
  293. int init(const uavcan::uint32_t bitrate, const CanIface::OperatingMode mode);
  294. int init(const uavcan::uint32_t bitrate, const CanIface::OperatingMode mode, uavcan::uint8_t can_number);
  295. virtual CanIface* getIface(uavcan::uint8_t iface_index) override;
  296. virtual uavcan::uint8_t getNumIfaces() const override
  297. {
  298. return num_ifaces_;
  299. }
  300. /**
  301. * Whether at least one iface had at least one successful IO since previous call of this method.
  302. * This is designed for use with iface activity LEDs.
  303. */
  304. bool hadActivity();
  305. };
  306. /**
  307. * Helper class.
  308. * Normally only this class should be used by the application.
  309. * 145 usec per Extended CAN frame @ 1 Mbps, e.g. 32 RX slots * 145 usec --> 4.6 msec before RX queue overruns.
  310. */
  311. template <unsigned RxQueueCapacity = 128>
  312. class CanInitHelper {
  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. }
  354. else {
  355. static const uavcan::uint32_t StandardBitRates[] = {
  356. 1000000,
  357. 500000,
  358. 250000,
  359. 125000
  360. };
  361. for (uavcan::uint8_t br = 0; br < sizeof(StandardBitRates) / sizeof(StandardBitRates[0]); br++) {
  362. inout_bitrate = StandardBitRates[br];
  363. const int res = driver.init(inout_bitrate, CanIface::SilentMode);
  364. delay_callable();
  365. if (res >= 0) {
  366. for (uavcan::uint8_t iface = 0; iface < driver.getNumIfaces(); iface++) {
  367. if (!driver.getIface(iface)->isRxBufferEmpty()) {
  368. // Re-initializing in normal mode
  369. return driver.init(inout_bitrate, CanIface::NormalMode);
  370. }
  371. }
  372. }
  373. }
  374. return -ErrBitRateNotDetected;
  375. }
  376. }
  377. /**
  378. * Use this value for listening delay during automatic bit rate detection.
  379. */
  380. static uavcan::MonotonicDuration getRecommendedListeningDelay()
  381. {
  382. return uavcan::MonotonicDuration::fromMSec(1050);
  383. }
  384. };
  385. }
  386. #include "CANSerialRouter.h"
  387. #endif // defined(STM32H7XX)
  388. #endif //HAL_WITH_UAVCAN