CANClock.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. * Modified for Ardupilot by Siddharth Bharat Purohit
  38. */
  39. #include "AP_HAL_ChibiOS.h"
  40. #if HAL_WITH_UAVCAN
  41. #include "CANClock.h"
  42. #include "CANThread.h"
  43. #include "CANInternal.h"
  44. #ifndef UAVCAN_STM32_TIMER_NUMBER
  45. #define UAVCAN_STM32_TIMER_NUMBER 0
  46. #endif
  47. #if UAVCAN_STM32_TIMER_NUMBER
  48. #include <cassert>
  49. #include <cmath>
  50. /*
  51. * Timer instance
  52. */
  53. # if (CH_KERNEL_MAJOR == 2)
  54. # define TIMX UAVCAN_STM32_GLUE2(TIM, UAVCAN_STM32_TIMER_NUMBER)
  55. # define TIMX_IRQn UAVCAN_STM32_GLUE3(TIM, UAVCAN_STM32_TIMER_NUMBER, _IRQn)
  56. # define TIMX_INPUT_CLOCK STM32_TIMCLK1
  57. # endif
  58. # if (CH_KERNEL_MAJOR == 3 || CH_KERNEL_MAJOR == 4)
  59. # define TIMX UAVCAN_STM32_GLUE2(STM32_TIM, UAVCAN_STM32_TIMER_NUMBER)
  60. # define TIMX_IRQn UAVCAN_STM32_GLUE3(STM32_TIM, UAVCAN_STM32_TIMER_NUMBER, _NUMBER)
  61. # define TIMX_IRQHandler UAVCAN_STM32_GLUE3(STM32_TIM, UAVCAN_STM32_TIMER_NUMBER, _HANDLER)
  62. # define TIMX_INPUT_CLOCK STM32_TIMCLK1
  63. # else
  64. # define TIMX_IRQHandler UAVCAN_STM32_GLUE3(TIM, UAVCAN_STM32_TIMER_NUMBER, _IRQHandler)
  65. # endif
  66. # if UAVCAN_STM32_TIMER_NUMBER >= 2 && UAVCAN_STM32_TIMER_NUMBER <= 7
  67. # define TIMX_RCC_ENR RCC->APB1ENR
  68. # define TIMX_RCC_RSTR RCC->APB1RSTR
  69. # define TIMX_RCC_ENR_MASK UAVCAN_STM32_GLUE3(RCC_APB1ENR_TIM, UAVCAN_STM32_TIMER_NUMBER, EN)
  70. # define TIMX_RCC_RSTR_MASK UAVCAN_STM32_GLUE3(RCC_APB1RSTR_TIM, UAVCAN_STM32_TIMER_NUMBER, RST)
  71. # else
  72. # error "This UAVCAN_STM32_TIMER_NUMBER is not supported yet"
  73. # endif
  74. # if (TIMX_INPUT_CLOCK % 1000000) != 0
  75. # error "No way, timer clock must be divisible to 1e6. FIXME!"
  76. # endif
  77. extern "C" UAVCAN_STM32_IRQ_HANDLER(TIMX_IRQHandler);
  78. namespace ChibiOS_CAN {
  79. namespace clock {
  80. namespace {
  81. const uavcan::uint32_t USecPerOverflow = 65536;
  82. Mutex mutex;
  83. bool initialized = false;
  84. bool utc_set = false;
  85. bool utc_locked = false;
  86. uavcan::uint32_t utc_jump_cnt = 0;
  87. UtcSyncParams utc_sync_params;
  88. float utc_prev_adj = 0;
  89. float utc_rel_rate_ppm = 0;
  90. float utc_rel_rate_error_integral = 0;
  91. uavcan::int32_t utc_accumulated_correction_nsec = 0;
  92. uavcan::int32_t utc_correction_nsec_per_overflow = 0;
  93. uavcan::MonotonicTime prev_utc_adj_at;
  94. uavcan::uint64_t time_mono = 0;
  95. uavcan::uint64_t time_utc = 0;
  96. }
  97. void init()
  98. {
  99. CriticalSectionLocker lock;
  100. if (initialized) {
  101. return;
  102. }
  103. initialized = true;
  104. // Power-on and reset
  105. TIMX_RCC_ENR |= TIMX_RCC_ENR_MASK;
  106. TIMX_RCC_RSTR |= TIMX_RCC_RSTR_MASK;
  107. TIMX_RCC_RSTR &= ~TIMX_RCC_RSTR_MASK;
  108. // Enable IRQ
  109. nvicEnableVector(TIMX_IRQn, UAVCAN_STM32_IRQ_PRIORITY_MASK);
  110. # if (TIMX_INPUT_CLOCK % 1000000) != 0
  111. # error "No way, timer clock must be divisible to 1e6. FIXME!"
  112. # endif
  113. // Start the timer
  114. TIMX->ARR = 0xFFFF;
  115. TIMX->PSC = (TIMX_INPUT_CLOCK / 1000000) - 1; // 1 tick == 1 microsecond
  116. TIMX->CR1 = TIM_CR1_URS;
  117. TIMX->SR = 0;
  118. TIMX->EGR = TIM_EGR_UG; // Reload immediately
  119. TIMX->DIER = TIM_DIER_UIE;
  120. TIMX->CR1 = TIM_CR1_CEN; // Start
  121. }
  122. void setUtc(uavcan::UtcTime time)
  123. {
  124. MutexLocker mlocker(mutex);
  125. UAVCAN_ASSERT(initialized);
  126. {
  127. CriticalSectionLocker locker;
  128. time_utc = time.toUSec();
  129. }
  130. utc_set = true;
  131. utc_locked = false;
  132. utc_jump_cnt++;
  133. utc_prev_adj = 0;
  134. utc_rel_rate_ppm = 0;
  135. }
  136. static uavcan::uint64_t sampleUtcFromCriticalSection()
  137. {
  138. UAVCAN_ASSERT(initialized);
  139. UAVCAN_ASSERT(TIMX->DIER & TIM_DIER_UIE);
  140. volatile uavcan::uint64_t time = time_utc;
  141. volatile uavcan::uint32_t cnt = TIMX->CNT;
  142. if (TIMX->SR & TIM_SR_UIF) {
  143. cnt = TIMX->CNT;
  144. const uavcan::int32_t add = uavcan::int32_t(USecPerOverflow) +
  145. (utc_accumulated_correction_nsec + utc_correction_nsec_per_overflow) / 1000;
  146. time = uavcan::uint64_t(uavcan::int64_t(time) + add);
  147. }
  148. return time + cnt;
  149. }
  150. uavcan::uint64_t getUtcUSecFromCanInterrupt()
  151. {
  152. return utc_set ? sampleUtcFromCriticalSection() : 0;
  153. }
  154. uavcan::MonotonicTime getMonotonic()
  155. {
  156. uavcan::uint64_t usec = 0;
  157. // Scope Critical section
  158. {
  159. CriticalSectionLocker locker;
  160. volatile uavcan::uint64_t time = time_mono;
  161. volatile uavcan::uint32_t cnt = TIMX->CNT;
  162. if (TIMX->SR & TIM_SR_UIF) {
  163. cnt = TIMX->CNT;
  164. time += USecPerOverflow;
  165. }
  166. usec = time + cnt;
  167. # ifndef NDEBUG
  168. static uavcan::uint64_t prev_usec = 0; // Self-test
  169. UAVCAN_ASSERT(prev_usec <= usec);
  170. (void)prev_usec;
  171. prev_usec = usec;
  172. # endif
  173. } // End Scope Critical section
  174. return uavcan::MonotonicTime::fromUSec(usec);
  175. }
  176. uavcan::UtcTime getUtc()
  177. {
  178. if (utc_set) {
  179. uavcan::uint64_t usec = 0;
  180. {
  181. CriticalSectionLocker locker;
  182. usec = sampleUtcFromCriticalSection();
  183. }
  184. return uavcan::UtcTime::fromUSec(usec);
  185. }
  186. return uavcan::UtcTime();
  187. }
  188. static float lowpass(float xold, float xnew, float corner, float dt)
  189. {
  190. const float tau = 1.F / corner;
  191. return (dt * xnew + tau * xold) / (dt + tau);
  192. }
  193. static void updateRatePID(uavcan::UtcDuration adjustment)
  194. {
  195. const uavcan::MonotonicTime ts = getMonotonic();
  196. const float dt = float((ts - prev_utc_adj_at).toUSec()) / 1e6F;
  197. prev_utc_adj_at = ts;
  198. const float adj_usec = float(adjustment.toUSec());
  199. /*
  200. * Target relative rate in PPM
  201. * Positive to go faster
  202. */
  203. const float target_rel_rate_ppm = adj_usec * utc_sync_params.offset_p;
  204. /*
  205. * Current relative rate in PPM
  206. * Positive if the local clock is faster
  207. */
  208. const float new_rel_rate_ppm = (utc_prev_adj - adj_usec) / dt; // rate error in [usec/sec], which is PPM
  209. utc_prev_adj = adj_usec;
  210. utc_rel_rate_ppm = lowpass(utc_rel_rate_ppm, new_rel_rate_ppm, utc_sync_params.rate_error_corner_freq, dt);
  211. const float rel_rate_error = target_rel_rate_ppm - utc_rel_rate_ppm;
  212. if (dt > 10) {
  213. utc_rel_rate_error_integral = 0;
  214. }
  215. else {
  216. utc_rel_rate_error_integral += rel_rate_error * dt * utc_sync_params.rate_i;
  217. utc_rel_rate_error_integral =
  218. uavcan::max(utc_rel_rate_error_integral, -utc_sync_params.max_rate_correction_ppm);
  219. utc_rel_rate_error_integral =
  220. uavcan::min(utc_rel_rate_error_integral, utc_sync_params.max_rate_correction_ppm);
  221. }
  222. /*
  223. * Rate controller
  224. */
  225. float total_rate_correction_ppm = rel_rate_error + utc_rel_rate_error_integral;
  226. total_rate_correction_ppm = uavcan::max(total_rate_correction_ppm, -utc_sync_params.max_rate_correction_ppm);
  227. total_rate_correction_ppm = uavcan::min(total_rate_correction_ppm, utc_sync_params.max_rate_correction_ppm);
  228. utc_correction_nsec_per_overflow = uavcan::int32_t((USecPerOverflow * 1000) * (total_rate_correction_ppm / 1e6F));
  229. // syslog("$ adj=%f rel_rate=%f rel_rate_eint=%f tgt_rel_rate=%f ppm=%f\n",
  230. // adj_usec, utc_rel_rate_ppm, utc_rel_rate_error_integral, target_rel_rate_ppm,
  231. // total_rate_correction_ppm);
  232. }
  233. void adjustUtc(uavcan::UtcDuration adjustment)
  234. {
  235. MutexLocker mlocker(mutex);
  236. UAVCAN_ASSERT(initialized);
  237. if (adjustment.getAbs() > utc_sync_params.min_jump || !utc_set) {
  238. const uavcan::int64_t adj_usec = adjustment.toUSec();
  239. {
  240. CriticalSectionLocker locker;
  241. if ((adj_usec < 0) && uavcan::uint64_t(-adj_usec) > time_utc) {
  242. time_utc = 1;
  243. }
  244. else {
  245. time_utc = uavcan::uint64_t(uavcan::int64_t(time_utc) + adj_usec);
  246. }
  247. }
  248. utc_set = true;
  249. utc_locked = false;
  250. utc_jump_cnt++;
  251. utc_prev_adj = 0;
  252. utc_rel_rate_ppm = 0;
  253. }
  254. else {
  255. updateRatePID(adjustment);
  256. if (!utc_locked) {
  257. utc_locked =
  258. (std::abs(utc_rel_rate_ppm) < utc_sync_params.lock_thres_rate_ppm) &&
  259. (std::abs(utc_prev_adj) < utc_sync_params.lock_thres_offset.toUSec());
  260. }
  261. }
  262. }
  263. float getUtcRateCorrectionPPM()
  264. {
  265. MutexLocker mlocker(mutex);
  266. const float rate_correction_mult = float(utc_correction_nsec_per_overflow) / float(USecPerOverflow * 1000);
  267. return 1e6F * rate_correction_mult;
  268. }
  269. uavcan::uint32_t getUtcJumpCount()
  270. {
  271. MutexLocker mlocker(mutex);
  272. return utc_jump_cnt;
  273. }
  274. bool isUtcLocked()
  275. {
  276. MutexLocker mlocker(mutex);
  277. return utc_locked;
  278. }
  279. UtcSyncParams getUtcSyncParams()
  280. {
  281. MutexLocker mlocker(mutex);
  282. return utc_sync_params;
  283. }
  284. void setUtcSyncParams(const UtcSyncParams& params)
  285. {
  286. MutexLocker mlocker(mutex);
  287. // Add some sanity check
  288. utc_sync_params = params;
  289. }
  290. } // namespace clock
  291. SystemClock& SystemClock::get_singleton()
  292. {
  293. static union SystemClockStorage {
  294. uavcan::uint8_t buffer[sizeof(SystemClock)];
  295. long long _aligner_1;
  296. long double _aligner_2;
  297. } storage;
  298. SystemClock* const ptr = reinterpret_cast<SystemClock*>(storage.buffer);
  299. if (!clock::initialized) {
  300. MutexLocker mlocker(clock::mutex);
  301. clock::init();
  302. new (ptr)SystemClock();
  303. }
  304. return *ptr;
  305. }
  306. } // namespace uavcan_stm32
  307. /**
  308. * Timer interrupt handler
  309. */
  310. extern "C"
  311. UAVCAN_STM32_IRQ_HANDLER(TIMX_IRQHandler)
  312. {
  313. UAVCAN_STM32_IRQ_PROLOGUE();
  314. TIMX->SR = 0;
  315. using namespace uavcan_stm32::clock;
  316. UAVCAN_ASSERT(initialized);
  317. time_mono += USecPerOverflow;
  318. if (utc_set) {
  319. time_utc += USecPerOverflow;
  320. utc_accumulated_correction_nsec += utc_correction_nsec_per_overflow;
  321. if (std::abs(utc_accumulated_correction_nsec) >= 1000) {
  322. time_utc = uavcan::uint64_t(uavcan::int64_t(time_utc) + utc_accumulated_correction_nsec / 1000);
  323. utc_accumulated_correction_nsec %= 1000;
  324. }
  325. // Correction decay - 1 nsec per 65536 usec
  326. if (utc_correction_nsec_per_overflow > 0) {
  327. utc_correction_nsec_per_overflow--;
  328. }
  329. else if (utc_correction_nsec_per_overflow < 0) {
  330. utc_correction_nsec_per_overflow++;
  331. }
  332. else {
  333. ; // Zero
  334. }
  335. }
  336. UAVCAN_STM32_IRQ_EPILOGUE();
  337. }
  338. #endif
  339. #endif //HAL_WITH_UAVCAN