You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

306 lines
10 KiB

  1. /* Copyright 2021 QMK
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "serial_usart.h"
  17. #if defined(SERIAL_USART_CONFIG)
  18. static SerialConfig serial_config = SERIAL_USART_CONFIG;
  19. #else
  20. static SerialConfig serial_config = {
  21. .speed = (SERIAL_USART_SPEED), /* speed - mandatory */
  22. .cr1 = (SERIAL_USART_CR1),
  23. .cr2 = (SERIAL_USART_CR2),
  24. # if !defined(SERIAL_USART_FULL_DUPLEX)
  25. .cr3 = ((SERIAL_USART_CR3) | USART_CR3_HDSEL) /* activate half-duplex mode */
  26. # else
  27. .cr3 = (SERIAL_USART_CR3)
  28. # endif
  29. };
  30. #endif
  31. static SerialDriver* serial_driver = &SERIAL_USART_DRIVER;
  32. static inline bool react_to_transactions(void);
  33. static inline bool __attribute__((nonnull)) receive(uint8_t* destination, const size_t size);
  34. static inline bool __attribute__((nonnull)) send(const uint8_t* source, const size_t size);
  35. static inline bool initiate_transaction(uint8_t sstd_index);
  36. static inline void usart_clear(void);
  37. /**
  38. * @brief Clear the receive input queue.
  39. */
  40. static inline void usart_clear(void) {
  41. osalSysLock();
  42. bool volatile queue_not_empty = !iqIsEmptyI(&serial_driver->iqueue);
  43. osalSysUnlock();
  44. while (queue_not_empty) {
  45. osalSysLock();
  46. /* Hard reset the input queue. */
  47. iqResetI(&serial_driver->iqueue);
  48. osalSysUnlock();
  49. /* Allow pending interrupts to preempt.
  50. * Do not merge the lock/unlock blocks into one
  51. * or the code will not work properly.
  52. * The empty read adds a tiny amount of delay. */
  53. (void)queue_not_empty;
  54. osalSysLock();
  55. queue_not_empty = !iqIsEmptyI(&serial_driver->iqueue);
  56. osalSysUnlock();
  57. }
  58. }
  59. /**
  60. * @brief Blocking send of buffer with timeout.
  61. *
  62. * @return true Send success.
  63. * @return false Send failed.
  64. */
  65. static inline bool send(const uint8_t* source, const size_t size) {
  66. bool success = (size_t)sdWriteTimeout(serial_driver, source, size, TIME_MS2I(SERIAL_USART_TIMEOUT)) == size;
  67. #if !defined(SERIAL_USART_FULL_DUPLEX)
  68. if (success) {
  69. /* Half duplex fills the input queue with the data we wrote - just throw it away.
  70. Under the right circumstances (e.g. bad cables paired with high baud rates)
  71. less bytes can be present in the input queue, therefore a timeout is needed. */
  72. uint8_t dump[size];
  73. return receive(dump, size);
  74. }
  75. #endif
  76. return success;
  77. }
  78. /**
  79. * @brief Blocking receive of size * bytes with timeout.
  80. *
  81. * @return true Receive success.
  82. * @return false Receive failed.
  83. */
  84. static inline bool receive(uint8_t* destination, const size_t size) {
  85. bool success = (size_t)sdReadTimeout(serial_driver, destination, size, TIME_MS2I(SERIAL_USART_TIMEOUT)) == size;
  86. return success;
  87. }
  88. #if !defined(SERIAL_USART_FULL_DUPLEX)
  89. /**
  90. * @brief Initiate pins for USART peripheral. Half-duplex configuration.
  91. */
  92. __attribute__((weak)) void usart_init(void) {
  93. # if defined(MCU_STM32)
  94. # if defined(USE_GPIOV1)
  95. palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE_OPENDRAIN);
  96. # else
  97. palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_OUTPUT_TYPE_OPENDRAIN);
  98. # endif
  99. # if defined(USART_REMAP)
  100. USART_REMAP;
  101. # endif
  102. # else
  103. # pragma message "usart_init: MCU Familiy not supported by default, please supply your own init code by implementing usart_init() in your keyboard files."
  104. # endif
  105. }
  106. #else
  107. /**
  108. * @brief Initiate pins for USART peripheral. Full-duplex configuration.
  109. */
  110. __attribute__((weak)) void usart_init(void) {
  111. # if defined(MCU_STM32)
  112. # if defined(USE_GPIOV1)
  113. palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE_PUSHPULL);
  114. palSetLineMode(SERIAL_USART_RX_PIN, PAL_MODE_INPUT);
  115. # else
  116. palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
  117. palSetLineMode(SERIAL_USART_RX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_RX_PAL_MODE) | PAL_OUTPUT_TYPE_PUSHPULL | PAL_OUTPUT_SPEED_HIGHEST);
  118. # endif
  119. # if defined(USART_REMAP)
  120. USART_REMAP;
  121. # endif
  122. # else
  123. # pragma message "usart_init: MCU Familiy not supported by default, please supply your own init code by implementing usart_init() in your keyboard files."
  124. # endif
  125. }
  126. #endif
  127. /**
  128. * @brief Overridable master specific initializations.
  129. */
  130. __attribute__((weak, nonnull)) void usart_master_init(SerialDriver** driver) {
  131. (void)driver;
  132. usart_init();
  133. }
  134. /**
  135. * @brief Overridable slave specific initializations.
  136. */
  137. __attribute__((weak, nonnull)) void usart_slave_init(SerialDriver** driver) {
  138. (void)driver;
  139. usart_init();
  140. }
  141. /**
  142. * @brief This thread runs on the slave and responds to transactions initiated
  143. * by the master.
  144. */
  145. static THD_WORKING_AREA(waSlaveThread, 1024);
  146. static THD_FUNCTION(SlaveThread, arg) {
  147. (void)arg;
  148. chRegSetThreadName("usart_tx_rx");
  149. while (true) {
  150. if (!react_to_transactions()) {
  151. /* Clear the receive queue, to start with a clean slate.
  152. * Parts of failed transactions or spurious bytes could still be in it. */
  153. usart_clear();
  154. }
  155. }
  156. }
  157. /**
  158. * @brief Slave specific initializations.
  159. */
  160. void soft_serial_target_init(void) {
  161. usart_slave_init(&serial_driver);
  162. sdStart(serial_driver, &serial_config);
  163. /* Start transport thread. */
  164. chThdCreateStatic(waSlaveThread, sizeof(waSlaveThread), HIGHPRIO, SlaveThread, NULL);
  165. }
  166. /**
  167. * @brief React to transactions started by the master.
  168. */
  169. static inline bool react_to_transactions(void) {
  170. /* Wait until there is a transaction for us. */
  171. uint8_t sstd_index = (uint8_t)sdGet(serial_driver);
  172. /* Sanity check that we are actually responding to a valid transaction. */
  173. if (sstd_index >= NUM_TOTAL_TRANSACTIONS) {
  174. return false;
  175. }
  176. split_transaction_desc_t* trans = &split_transaction_table[sstd_index];
  177. /* Send back the handshake which is XORed as a simple checksum,
  178. to signal that the slave is ready to receive possible transaction buffers */
  179. sstd_index ^= HANDSHAKE_MAGIC;
  180. if (!send(&sstd_index, sizeof(sstd_index))) {
  181. return false;
  182. }
  183. /* Receive transaction buffer from the master. If this transaction requires it.*/
  184. if (trans->initiator2target_buffer_size) {
  185. if (!receive(split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size)) {
  186. return false;
  187. }
  188. }
  189. /* Allow any slave processing to occur. */
  190. if (trans->slave_callback) {
  191. trans->slave_callback(trans->initiator2target_buffer_size, split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size, split_trans_target2initiator_buffer(trans));
  192. }
  193. /* Send transaction buffer to the master. If this transaction requires it. */
  194. if (trans->target2initiator_buffer_size) {
  195. if (!send(split_trans_target2initiator_buffer(trans), trans->target2initiator_buffer_size)) {
  196. return false;
  197. }
  198. }
  199. return true;
  200. }
  201. /**
  202. * @brief Master specific initializations.
  203. */
  204. void soft_serial_initiator_init(void) {
  205. usart_master_init(&serial_driver);
  206. #if defined(MCU_STM32) && defined(SERIAL_USART_PIN_SWAP)
  207. serial_config.cr2 |= USART_CR2_SWAP; // master has swapped TX/RX pins
  208. #endif
  209. sdStart(serial_driver, &serial_config);
  210. }
  211. /**
  212. * @brief Start transaction from the master half to the slave half.
  213. *
  214. * @param index Transaction Table index of the transaction to start.
  215. * @return bool Indicates success of transaction.
  216. */
  217. bool soft_serial_transaction(int index) {
  218. /* Clear the receive queue, to start with a clean slate.
  219. * Parts of failed transactions or spurious bytes could still be in it. */
  220. usart_clear();
  221. return initiate_transaction((uint8_t)index);
  222. }
  223. /**
  224. * @brief Initiate transaction to slave half.
  225. */
  226. static inline bool initiate_transaction(uint8_t sstd_index) {
  227. /* Sanity check that we are actually starting a valid transaction. */
  228. if (sstd_index >= NUM_TOTAL_TRANSACTIONS) {
  229. dprintln("USART: Illegal transaction Id.");
  230. return false;
  231. }
  232. split_transaction_desc_t* trans = &split_transaction_table[sstd_index];
  233. /* Send transaction table index to the slave, which doubles as basic handshake token. */
  234. if (!send(&sstd_index, sizeof(sstd_index))) {
  235. dprintln("USART: Send Handshake failed.");
  236. return false;
  237. }
  238. uint8_t sstd_index_shake = 0xFF;
  239. /* Which we always read back first so that we can error out correctly.
  240. * - due to the half duplex limitations on return codes, we always have to read *something*.
  241. * - without the read, write only transactions *always* succeed, even during the boot process where the slave is not ready.
  242. */
  243. if (!receive(&sstd_index_shake, sizeof(sstd_index_shake)) || (sstd_index_shake != (sstd_index ^ HANDSHAKE_MAGIC))) {
  244. dprintln("USART: Handshake failed.");
  245. return false;
  246. }
  247. /* Send transaction buffer to the slave. If this transaction requires it. */
  248. if (trans->initiator2target_buffer_size) {
  249. if (!send(split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size)) {
  250. dprintln("USART: Send failed.");
  251. return false;
  252. }
  253. }
  254. /* Receive transaction buffer from the slave. If this transaction requires it. */
  255. if (trans->target2initiator_buffer_size) {
  256. if (!receive(split_trans_target2initiator_buffer(trans), trans->target2initiator_buffer_size)) {
  257. dprintln("USART: Receive failed.");
  258. return false;
  259. }
  260. }
  261. return true;
  262. }