softuart.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #include "ets_sys.h"
  2. #include "osapi.h"
  3. #include "gpio.h"
  4. #include "os_type.h"
  5. #include "user_interface.h"
  6. #include "module.h"
  7. #include "lauxlib.h"
  8. #include "task/task.h"
  9. #include "platform.h"
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #define SOFTUART_MAX_RX_BUFF 128
  13. #define SOFTUART_GPIO_COUNT 13
  14. //TODO: Overflow flag as callback function + docs
  15. typedef struct {
  16. char receive_buffer[SOFTUART_MAX_RX_BUFF];
  17. uint8_t buffer_first;
  18. uint8_t buffer_last;
  19. uint8_t bytes_count;
  20. uint8_t buffer_overflow;
  21. } softuart_buffer_t;
  22. typedef struct {
  23. volatile softuart_buffer_t buffer;
  24. uint16_t bit_time;
  25. uint16_t need_len; // Buffer length needed to run callback function
  26. char end_char; // Used to run callback if last char in buffer will be the same
  27. uint8_t armed;
  28. uint8_t pin_rx;
  29. uint8_t pin_tx;
  30. } softuart_t;
  31. // Array of pointers to SoftUART instances
  32. softuart_t * softuart_gpio_instances[SOFTUART_GPIO_COUNT] = {NULL};
  33. // Array of callback reference to be able to find which callback is used to which rx pin
  34. static int softuart_rx_cb_ref[SOFTUART_GPIO_COUNT];
  35. // Task for receiving data
  36. static task_handle_t uart_recieve_task = 0;
  37. // Receiving buffer for callback usage
  38. static char softuart_rx_buffer[SOFTUART_MAX_RX_BUFF];
  39. static inline int32_t asm_ccount(void) {
  40. int32_t r;
  41. asm volatile ("rsr %0, ccount" : "=r"(r));
  42. return r;
  43. }
  44. static inline uint8_t checkbit(uint8_t data, uint8_t bit)
  45. {
  46. if ((data & bit) != 0) {
  47. return 1;
  48. } else {
  49. return 0;
  50. }
  51. }
  52. static uint32_t ICACHE_RAM_ATTR softuart_intr_handler(uint32_t ret_gpio_status)
  53. {
  54. // Disable all interrupts
  55. ets_intr_lock();
  56. int32_t start_time = asm_ccount();
  57. uint32_t gpio_status = GPIO_REG_READ(GPIO_STATUS_ADDRESS);
  58. uint32_t gpio_bits = gpio_status;
  59. for (uint8_t gpio_bit = 0; gpio_bits != 0; gpio_bit++, gpio_bits >>= 1) {
  60. // Check all pins for interrupts
  61. if (! (gpio_bits & 0x01)) continue;
  62. // We got pin that was interrupted
  63. // Load instance which has rx pin on interrupt pin attached
  64. softuart_t *s = softuart_gpio_instances[pin_num_inv[gpio_bit]];
  65. if (s == NULL) continue;
  66. // Clear interrupt status on that pin
  67. GPIO_REG_WRITE(GPIO_STATUS_W1TC_ADDRESS, gpio_status & (1 << pin_num[s->pin_rx]));
  68. ret_gpio_status &= ~(1 << pin_num[s->pin_rx]);
  69. if (softuart_rx_cb_ref[pin_num_inv[gpio_bit]] == LUA_NOREF) continue;
  70. if (!s->armed) continue;
  71. // There is an armed SoftUART rx instance on that pin
  72. // Start listening to transmission
  73. // TODO: inverted
  74. if (! (GPIO_INPUT_GET(GPIO_ID_PIN(pin_num[s->pin_rx])))) {
  75. //pin is low - therefore we have a start bit
  76. unsigned byte = 0;
  77. // Casting and using signed types to always be able to compute elapsed time even if there is a overflow
  78. uint32_t elapsed_time = (uint32_t)(asm_ccount() - start_time);
  79. // Wait till start bit is half over so we can sample the next one in the center
  80. if (elapsed_time < s->bit_time / 2) {
  81. uint16_t wait_time = s->bit_time / 2 - elapsed_time;
  82. while ((uint32_t)(asm_ccount() - start_time) < wait_time);
  83. start_time += wait_time;
  84. }
  85. // Sample bits
  86. // TODO: How many bits? Add other configs to softuart
  87. for (uint8_t i = 0; i < 8; i ++ ) {
  88. while ((uint32_t)(asm_ccount() - start_time) < s->bit_time);
  89. //shift d to the right
  90. byte >>= 1;
  91. // Read bit
  92. if(GPIO_INPUT_GET(GPIO_ID_PIN(pin_num[s->pin_rx]))) {
  93. // If high, set MSB of byte to 1
  94. byte |= 0x80;
  95. }
  96. // Recalculate start time for next bit
  97. start_time += s->bit_time;
  98. }
  99. // Store byte in buffer
  100. // If buffer full, set the overflow flag and return
  101. if (s->buffer.bytes_count == SOFTUART_MAX_RX_BUFF) {
  102. s->buffer.buffer_overflow = 1;
  103. } else if (s->buffer.bytes_count < SOFTUART_MAX_RX_BUFF) {
  104. s->buffer.receive_buffer[s->buffer.buffer_last] = byte;
  105. s->buffer.buffer_last++;
  106. s->buffer.bytes_count++;
  107. // Check for callback conditions
  108. if (((s->need_len != 0) && (s->buffer.bytes_count >= s->need_len)) || \
  109. ((s->need_len == 0) && ((char)byte == s->end_char))) {
  110. // Send the pointer to task handler
  111. s->armed = 0;
  112. task_post_medium(uart_recieve_task, (task_param_t)s);
  113. }
  114. }
  115. // Check for overflow after appending new byte
  116. if (s->buffer.bytes_count == SOFTUART_MAX_RX_BUFF) {
  117. s->buffer.buffer_overflow = 1;
  118. }
  119. // Roll over buffer index if necessary
  120. if (s->buffer.buffer_last == SOFTUART_MAX_RX_BUFF) {
  121. s->buffer.buffer_last = 0;
  122. }
  123. // Wait for stop bit
  124. // TODO: Add config for stop bits and parity bits
  125. while ((uint32_t)(asm_ccount() - start_time) < s->bit_time);
  126. // Break the loop after reading of the frame
  127. break;
  128. }
  129. }
  130. // re-enable all interrupts
  131. ets_intr_unlock();
  132. return ret_gpio_status;
  133. }
  134. static void softuart_putchar(softuart_t *s, char data)
  135. {
  136. // Disable all interrupts
  137. ets_intr_lock();
  138. int32_t start_time = asm_ccount();
  139. // Set start bit
  140. GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[s->pin_tx]), 0);
  141. for (uint32_t i = 0; i < 8; i++) {
  142. // Wait to transmit another bit
  143. while ((uint32_t)(asm_ccount() - start_time) < s->bit_time);
  144. GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[s->pin_tx]), checkbit(data, 1 << i));
  145. // Recalculate start time for next bit
  146. start_time += s->bit_time;
  147. }
  148. // Stop bit
  149. while ((uint32_t)(asm_ccount() - start_time) < s->bit_time);
  150. GPIO_OUTPUT_SET(GPIO_ID_PIN(pin_num[s->pin_tx]), 1);
  151. // Delay after byte, for new sync
  152. os_delay_us(s->bit_time*6 / system_get_cpu_freq());
  153. // Re-enable all interrupts
  154. ets_intr_unlock();
  155. }
  156. static int softuart_init(softuart_t *s)
  157. {
  158. // Init tx pin
  159. if (s->pin_tx != 0xFF) {
  160. platform_gpio_mode(s->pin_tx, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_PULLUP);
  161. platform_gpio_write(s->pin_tx, PLATFORM_GPIO_HIGH);
  162. }
  163. // Init rx pin
  164. if (s->pin_rx != 0xFF) {
  165. platform_gpio_mode(s->pin_rx, PLATFORM_GPIO_INT, PLATFORM_GPIO_PULLUP);
  166. // Enable interrupt for pin on falling edge
  167. platform_gpio_intr_init(s->pin_rx, GPIO_PIN_INTR_NEGEDGE);
  168. softuart_gpio_instances[s->pin_rx] = s;
  169. // Preserve other rx gpio pins
  170. uint32_t mask = 0;
  171. for (uint8_t i = 0; i < SOFTUART_GPIO_COUNT; i++) {
  172. if (softuart_gpio_instances[i] != NULL) {
  173. mask = mask | (1 << pin_num[softuart_gpio_instances[i]->pin_rx]);
  174. }
  175. }
  176. return platform_gpio_register_intr_hook(mask, softuart_intr_handler);
  177. }
  178. }
  179. static int softuart_setup(lua_State *L)
  180. {
  181. uint32_t baudrate;
  182. uint8_t tx_gpio_id, rx_gpio_id;
  183. softuart_t *softuart = NULL;
  184. NODE_DBG("[SoftUART]: setup called\n");
  185. baudrate = (uint32_t)luaL_checkinteger(L, 1); // Get Baudrate from
  186. luaL_argcheck(L, (baudrate > 0 && baudrate < 230400), 1, "Invalid baud rate");
  187. lua_remove(L, 1); // Remove baudrate argument from stack
  188. if (lua_gettop(L) == 2) { // 2 arguments: 1st can be nil
  189. if (lua_isnil(L, 1)) {
  190. tx_gpio_id = 0xFF;
  191. } else {
  192. tx_gpio_id = (uint8_t)luaL_checkinteger(L, 1);
  193. luaL_argcheck(L, (platform_gpio_exists(tx_gpio_id) && tx_gpio_id != 0)
  194. , 2, "Invalid SoftUART tx GPIO");
  195. }
  196. rx_gpio_id = (uint8_t)luaL_checkinteger(L, 2);
  197. luaL_argcheck(L, (platform_gpio_exists(rx_gpio_id) && rx_gpio_id != 0)
  198. , 3, "Invalid SoftUART rx GPIO");
  199. luaL_argcheck(L, softuart_gpio_instances[rx_gpio_id] == NULL
  200. , 3, "SoftUART rx already configured on the pin");
  201. } else if (lua_gettop(L) == 1) { // 1 argument: transmit part only
  202. rx_gpio_id = 0xFF;
  203. tx_gpio_id = (uint8_t)luaL_checkinteger(L, 1);
  204. luaL_argcheck(L, (platform_gpio_exists(tx_gpio_id) && tx_gpio_id != 0)
  205. , 2, "Invalid SoftUART tx GPIO");
  206. } else {
  207. // SoftUART object without receive and transmit part would be useless
  208. return luaL_error(L, "Not enough arguments");
  209. }
  210. softuart = (softuart_t*)lua_newuserdata(L, sizeof(softuart_t));
  211. softuart->pin_rx = rx_gpio_id;
  212. softuart->pin_tx = tx_gpio_id;
  213. softuart->need_len = SOFTUART_MAX_RX_BUFF;
  214. softuart->armed = 0;
  215. // Set buffer
  216. softuart->buffer.buffer_first = 0;
  217. softuart->buffer.buffer_last = 0;
  218. softuart->buffer.bytes_count = 0;
  219. softuart->buffer.buffer_overflow = 0;
  220. // Set bit time
  221. softuart->bit_time = system_get_cpu_freq() * 1000000 / baudrate;
  222. // Set metatable
  223. luaL_getmetatable(L, "softuart.port");
  224. lua_setmetatable(L, -2);
  225. // Init SoftUART
  226. int result = softuart_init(softuart);
  227. if (result == 0) {
  228. luaL_error(L, "Couldn't register interrupt");
  229. }
  230. return 1;
  231. }
  232. static void softuart_rx_callback(task_param_t arg)
  233. {
  234. softuart_t *softuart = (softuart_t*)arg; //Receive pointer from ISR
  235. lua_State *L = lua_getstate();
  236. lua_rawgeti(L, LUA_REGISTRYINDEX, softuart_rx_cb_ref[softuart->pin_rx]);
  237. // Clear overflow flag if needed
  238. if(softuart->buffer.bytes_count == SOFTUART_MAX_RX_BUFF) {
  239. softuart->buffer.buffer_overflow = 0;
  240. }
  241. // Copy volatile data to static buffer
  242. uint8_t buffer_length = softuart->buffer.bytes_count;
  243. for (int i = 0; i < buffer_length; i++) {
  244. softuart_rx_buffer[i] = softuart->buffer.receive_buffer[softuart->buffer.buffer_first];
  245. softuart->buffer.buffer_first++;
  246. softuart->buffer.bytes_count--;
  247. if (softuart->buffer.buffer_first == SOFTUART_MAX_RX_BUFF) {
  248. softuart->buffer.buffer_first = 0;
  249. }
  250. }
  251. lua_pushlstring(L, softuart_rx_buffer, buffer_length);
  252. softuart->armed = 1;
  253. luaL_pcallx(L, 1, 0);
  254. }
  255. // Arguments: event name, minimum buffer filled to run callback, callback function
  256. static int softuart_on(lua_State *L)
  257. {
  258. NODE_DBG("[SoftUART] on: called\n");
  259. size_t name_len, arg_len;
  260. softuart_t *softuart = (softuart_t*)luaL_checkudata(L, 1, "softuart.port");
  261. const char *method = luaL_checklstring(L, 2, &name_len);
  262. luaL_argcheck(L, lua_isfunction(L, 4), -1, "No callback function specified");
  263. luaL_argcheck(L, (name_len == 4 && strcmp(method, "data") == 0), 2, "Method not supported");
  264. luaL_argcheck(L, softuart->pin_rx != 0xFF, 1, "Rx pin was not declared");
  265. if (lua_isnumber(L, 3)) {
  266. luaL_argcheck(L, luaL_checkinteger(L, 3) < SOFTUART_MAX_RX_BUFF,
  267. 2, "Argument bigger than SoftUART buffer");
  268. softuart->end_char = 0;
  269. softuart->need_len = (uint16_t) luaL_checkinteger(L, 3);
  270. } else if (lua_isstring(L, 3)) {
  271. const char *end = luaL_checklstring(L , 3, &arg_len);
  272. luaL_argcheck(L, arg_len == 1, 3, "Wrong end char length");
  273. softuart->end_char = end[0];
  274. softuart->need_len = 0;
  275. } else {
  276. return luaL_error(L, "Wrong argument type");
  277. }
  278. lua_settop(L, 4); // Move to the top of the stack
  279. // Register callback or reregister new one
  280. luaL_reref(L, LUA_REGISTRYINDEX, &softuart_rx_cb_ref[softuart->pin_rx]);
  281. // Arm the instance
  282. softuart->armed = 1;
  283. return 0;
  284. }
  285. static int softuart_write(lua_State *L)
  286. {
  287. softuart_t *softuart = NULL;
  288. size_t str_len;
  289. softuart = (softuart_t*) luaL_checkudata(L, 1, "softuart.port");
  290. luaL_argcheck(L, softuart->pin_tx != 0xFF, 1, "Tx pin was not declared");
  291. if (lua_isnumber(L, 2)) {
  292. // Send byte
  293. uint32_t byte = (uint32_t)luaL_checkinteger(L, 2);
  294. luaL_argcheck(L, byte < 256, 2, "Integer too large for a byte");
  295. softuart_putchar(softuart, (char)byte);
  296. } else if (lua_isstring(L, 2)) {
  297. // Send string
  298. const char *string = luaL_checklstring(L, 2, &str_len);
  299. for (size_t i = 0; i < str_len; i++) {
  300. softuart_putchar(softuart, string[i]);
  301. }
  302. } else {
  303. return luaL_error(L, "Wrong argument type");
  304. }
  305. return 0;
  306. }
  307. static int softuart_gcdelete(lua_State *L)
  308. {
  309. NODE_DBG("SoftUART GC called\n");
  310. softuart_t *softuart = NULL;
  311. softuart = (softuart_t*) luaL_checkudata(L, 1, "softuart.port");
  312. uint8_t last_instance = 1;
  313. for(uint8_t instance = 0; instance < SOFTUART_GPIO_COUNT; instance++)
  314. if (softuart_gpio_instances[instance] != NULL && instance != softuart->pin_rx)
  315. last_instance = 0;
  316. softuart_gpio_instances[softuart->pin_rx] = NULL;
  317. luaL_unref2(L, LUA_REGISTRYINDEX, softuart_rx_cb_ref[softuart->pin_rx]);
  318. // Try to unregister the interrupt hook if this was last or the only instance
  319. if (last_instance)
  320. platform_gpio_register_intr_hook(0, softuart_intr_handler);
  321. return 0;
  322. }
  323. // Port function map
  324. LROT_BEGIN(softuart_port, NULL, LROT_MASK_GC_INDEX)
  325. LROT_FUNCENTRY( __gc, softuart_gcdelete)
  326. LROT_TABENTRY( __index, softuart_port)
  327. LROT_FUNCENTRY( on, softuart_on)
  328. LROT_FUNCENTRY( write, softuart_write)
  329. LROT_END(softuart_port, NULL, LROT_MASK_GC_INDEX)
  330. // Module function map
  331. LROT_BEGIN(softuart, LROT_TABLEREF(softuart_port), 0)
  332. LROT_FUNCENTRY( setup, softuart_setup)
  333. LROT_END(softuart, LROT_TABLEREF(softuart_port), 0)
  334. static int luaopen_softuart(lua_State *L)
  335. {
  336. for(int i = 0; i < SOFTUART_GPIO_COUNT; i++) {
  337. softuart_rx_cb_ref[i] = LUA_NOREF;
  338. }
  339. uart_recieve_task = task_get_id((task_callback_t) softuart_rx_callback);
  340. luaL_rometatable(L, "softuart.port", LROT_TABLEREF(softuart_port));
  341. return 0;
  342. }
  343. NODEMCU_MODULE(SOFTUART, "softuart", softuart, luaopen_softuart);