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.

318 lines
11 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 int 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_STM32_ALTERNATE_OPENDRAIN);
  96. # else
  97. palSetLineMode(SERIAL_USART_TX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_TX_PAL_MODE) | PAL_STM32_OTYPE_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_STM32_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_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_HIGHEST);
  117. palSetLineMode(SERIAL_USART_RX_PIN, PAL_MODE_ALTERNATE(SERIAL_USART_RX_PAL_MODE) | PAL_STM32_OTYPE_PUSHPULL | PAL_STM32_OSPEED_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. *trans->status = TRANSACTION_DATA_ERROR;
  182. return false;
  183. }
  184. /* Receive transaction buffer from the master. If this transaction requires it.*/
  185. if (trans->initiator2target_buffer_size) {
  186. if (!receive(split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size)) {
  187. *trans->status = TRANSACTION_DATA_ERROR;
  188. return false;
  189. }
  190. }
  191. /* Allow any slave processing to occur. */
  192. if (trans->slave_callback) {
  193. trans->slave_callback(trans->initiator2target_buffer_size, split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size, split_trans_target2initiator_buffer(trans));
  194. }
  195. /* Send transaction buffer to the master. If this transaction requires it. */
  196. if (trans->target2initiator_buffer_size) {
  197. if (!send(split_trans_target2initiator_buffer(trans), trans->target2initiator_buffer_size)) {
  198. *trans->status = TRANSACTION_DATA_ERROR;
  199. return false;
  200. }
  201. }
  202. *trans->status = TRANSACTION_ACCEPTED;
  203. return true;
  204. }
  205. /**
  206. * @brief Master specific initializations.
  207. */
  208. void soft_serial_initiator_init(void) {
  209. usart_master_init(&serial_driver);
  210. #if defined(MCU_STM32) && defined(SERIAL_USART_PIN_SWAP)
  211. serial_config.cr2 |= USART_CR2_SWAP; // master has swapped TX/RX pins
  212. #endif
  213. sdStart(serial_driver, &serial_config);
  214. }
  215. /**
  216. * @brief Start transaction from the master half to the slave half.
  217. *
  218. * @param index Transaction Table index of the transaction to start.
  219. * @return int TRANSACTION_NO_RESPONSE in case of Timeout.
  220. * TRANSACTION_TYPE_ERROR in case of invalid transaction index.
  221. * TRANSACTION_END in case of success.
  222. */
  223. int soft_serial_transaction(int index) {
  224. /* Clear the receive queue, to start with a clean slate.
  225. * Parts of failed transactions or spurious bytes could still be in it. */
  226. usart_clear();
  227. return initiate_transaction((uint8_t)index);
  228. }
  229. /**
  230. * @brief Initiate transaction to slave half.
  231. */
  232. static inline int initiate_transaction(uint8_t sstd_index) {
  233. /* Sanity check that we are actually starting a valid transaction. */
  234. if (sstd_index >= NUM_TOTAL_TRANSACTIONS) {
  235. dprintln("USART: Illegal transaction Id.");
  236. return TRANSACTION_TYPE_ERROR;
  237. }
  238. split_transaction_desc_t* trans = &split_transaction_table[sstd_index];
  239. /* Transaction is not registered. Abort. */
  240. if (!trans->status) {
  241. dprintln("USART: Transaction not registered.");
  242. return TRANSACTION_TYPE_ERROR;
  243. }
  244. /* Send transaction table index to the slave, which doubles as basic handshake token. */
  245. if (!send(&sstd_index, sizeof(sstd_index))) {
  246. dprintln("USART: Send Handshake failed.");
  247. return TRANSACTION_TYPE_ERROR;
  248. }
  249. uint8_t sstd_index_shake = 0xFF;
  250. /* Which we always read back first so that we can error out correctly.
  251. * - due to the half duplex limitations on return codes, we always have to read *something*.
  252. * - without the read, write only transactions *always* succeed, even during the boot process where the slave is not ready.
  253. */
  254. if (!receive(&sstd_index_shake, sizeof(sstd_index_shake)) || (sstd_index_shake != (sstd_index ^ HANDSHAKE_MAGIC))) {
  255. dprintln("USART: Handshake failed.");
  256. return TRANSACTION_NO_RESPONSE;
  257. }
  258. /* Send transaction buffer to the slave. If this transaction requires it. */
  259. if (trans->initiator2target_buffer_size) {
  260. if (!send(split_trans_initiator2target_buffer(trans), trans->initiator2target_buffer_size)) {
  261. dprintln("USART: Send failed.");
  262. return TRANSACTION_NO_RESPONSE;
  263. }
  264. }
  265. /* Receive transaction buffer from the slave. If this transaction requires it. */
  266. if (trans->target2initiator_buffer_size) {
  267. if (!receive(split_trans_target2initiator_buffer(trans), trans->target2initiator_buffer_size)) {
  268. dprintln("USART: Receive failed.");
  269. return TRANSACTION_NO_RESPONSE;
  270. }
  271. }
  272. return TRANSACTION_END;
  273. }