softuart.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. return 1;
  179. }
  180. static int softuart_setup(lua_State *L)
  181. {
  182. uint32_t baudrate;
  183. uint8_t tx_gpio_id, rx_gpio_id;
  184. softuart_t *softuart = NULL;
  185. NODE_DBG("[SoftUART]: setup called\n");
  186. baudrate = (uint32_t)luaL_checkinteger(L, 1); // Get Baudrate from
  187. luaL_argcheck(L, (baudrate > 0 && baudrate < 230400), 1, "Invalid baud rate");
  188. if (lua_isnoneornil(L, 2)) {
  189. tx_gpio_id = 0xFF;
  190. } else {
  191. tx_gpio_id = (uint8_t)luaL_checkinteger(L, 2);
  192. luaL_argcheck(L, (platform_gpio_exists(tx_gpio_id) && tx_gpio_id != 0)
  193. , 2, "Invalid SoftUART tx GPIO");
  194. }
  195. if (lua_isnoneornil(L, 3)) {
  196. rx_gpio_id = 0xFF;
  197. } else {
  198. rx_gpio_id = (uint8_t)luaL_checkinteger(L, 3);
  199. luaL_argcheck(L, (platform_gpio_exists(rx_gpio_id) && rx_gpio_id != 0)
  200. , 3, "Invalid SoftUART rx GPIO");
  201. luaL_argcheck(L, softuart_gpio_instances[rx_gpio_id] == NULL
  202. , 3, "SoftUART rx already configured on the pin");
  203. }
  204. // SoftUART object without receive and transmit part would be useless
  205. if ((rx_gpio_id == 0xFF) && (tx_gpio_id == 0xFF)) {return luaL_error(L, "Not enough arguments");}
  206. softuart = (softuart_t*)lua_newuserdata(L, sizeof(softuart_t));
  207. softuart->pin_rx = rx_gpio_id;
  208. softuart->pin_tx = tx_gpio_id;
  209. softuart->need_len = SOFTUART_MAX_RX_BUFF;
  210. softuart->armed = 0;
  211. // Set buffer
  212. softuart->buffer.buffer_first = 0;
  213. softuart->buffer.buffer_last = 0;
  214. softuart->buffer.bytes_count = 0;
  215. softuart->buffer.buffer_overflow = 0;
  216. // Set bit time
  217. softuart->bit_time = system_get_cpu_freq() * 1000000 / baudrate;
  218. // Set metatable
  219. luaL_getmetatable(L, "softuart.port");
  220. lua_setmetatable(L, -2);
  221. // Init SoftUART
  222. int result = softuart_init(softuart);
  223. if (result == 0) {
  224. luaL_error(L, "Couldn't register interrupt");
  225. }
  226. return 1;
  227. }
  228. static void softuart_rx_callback(task_param_t arg)
  229. {
  230. softuart_t *softuart = (softuart_t*)arg; //Receive pointer from ISR
  231. lua_State *L = lua_getstate();
  232. lua_rawgeti(L, LUA_REGISTRYINDEX, softuart_rx_cb_ref[softuart->pin_rx]);
  233. // Clear overflow flag if needed
  234. if(softuart->buffer.bytes_count == SOFTUART_MAX_RX_BUFF) {
  235. softuart->buffer.buffer_overflow = 0;
  236. }
  237. // Copy volatile data to static buffer
  238. uint8_t buffer_length = softuart->buffer.bytes_count;
  239. for (int i = 0; i < buffer_length; i++) {
  240. softuart_rx_buffer[i] = softuart->buffer.receive_buffer[softuart->buffer.buffer_first];
  241. softuart->buffer.buffer_first++;
  242. softuart->buffer.bytes_count--;
  243. if (softuart->buffer.buffer_first == SOFTUART_MAX_RX_BUFF) {
  244. softuart->buffer.buffer_first = 0;
  245. }
  246. }
  247. lua_pushlstring(L, softuart_rx_buffer, buffer_length);
  248. softuart->armed = 1;
  249. luaL_pcallx(L, 1, 0);
  250. }
  251. // Arguments: event name, minimum buffer filled to run callback, callback function
  252. static int softuart_on(lua_State *L)
  253. {
  254. NODE_DBG("[SoftUART] on: called\n");
  255. size_t name_len, arg_len;
  256. softuart_t *softuart = (softuart_t*)luaL_checkudata(L, 1, "softuart.port");
  257. const char *method = luaL_checklstring(L, 2, &name_len);
  258. luaL_argcheck(L, lua_isfunction(L, 4), -1, "No callback function specified");
  259. luaL_argcheck(L, (name_len == 4 && strcmp(method, "data") == 0), 2, "Method not supported");
  260. luaL_argcheck(L, softuart->pin_rx != 0xFF, 1, "Rx pin was not declared");
  261. if (lua_isnumber(L, 3)) {
  262. luaL_argcheck(L, luaL_checkinteger(L, 3) < SOFTUART_MAX_RX_BUFF,
  263. 2, "Argument bigger than SoftUART buffer");
  264. softuart->end_char = 0;
  265. softuart->need_len = (uint16_t) luaL_checkinteger(L, 3);
  266. } else if (lua_isstring(L, 3)) {
  267. const char *end = luaL_checklstring(L , 3, &arg_len);
  268. luaL_argcheck(L, arg_len == 1, 3, "Wrong end char length");
  269. softuart->end_char = end[0];
  270. softuart->need_len = 0;
  271. } else {
  272. return luaL_error(L, "Wrong argument type");
  273. }
  274. lua_settop(L, 4); // Move to the top of the stack
  275. // Register callback or reregister new one
  276. luaL_reref(L, LUA_REGISTRYINDEX, &softuart_rx_cb_ref[softuart->pin_rx]);
  277. // Arm the instance
  278. softuart->armed = 1;
  279. return 0;
  280. }
  281. static int softuart_write(lua_State *L)
  282. {
  283. softuart_t *softuart = NULL;
  284. size_t str_len;
  285. softuart = (softuart_t*) luaL_checkudata(L, 1, "softuart.port");
  286. luaL_argcheck(L, softuart->pin_tx != 0xFF, 1, "Tx pin was not declared");
  287. if (lua_isnumber(L, 2)) {
  288. // Send byte
  289. uint32_t byte = (uint32_t)luaL_checkinteger(L, 2);
  290. luaL_argcheck(L, byte < 256, 2, "Integer too large for a byte");
  291. softuart_putchar(softuart, (char)byte);
  292. } else if (lua_isstring(L, 2)) {
  293. // Send string
  294. const char *string = luaL_checklstring(L, 2, &str_len);
  295. for (size_t i = 0; i < str_len; i++) {
  296. softuart_putchar(softuart, string[i]);
  297. }
  298. } else {
  299. return luaL_error(L, "Wrong argument type");
  300. }
  301. return 0;
  302. }
  303. static int softuart_gcdelete(lua_State *L)
  304. {
  305. NODE_DBG("SoftUART GC called\n");
  306. softuart_t *softuart = NULL;
  307. softuart = (softuart_t*) luaL_checkudata(L, 1, "softuart.port");
  308. uint8_t last_instance = 1;
  309. for(uint8_t instance = 0; instance < SOFTUART_GPIO_COUNT; instance++)
  310. if (softuart_gpio_instances[instance] != NULL && instance != softuart->pin_rx)
  311. last_instance = 0;
  312. softuart_gpio_instances[softuart->pin_rx] = NULL;
  313. luaL_unref2(L, LUA_REGISTRYINDEX, softuart_rx_cb_ref[softuart->pin_rx]);
  314. // Try to unregister the interrupt hook if this was last or the only instance
  315. if (last_instance)
  316. platform_gpio_register_intr_hook(0, softuart_intr_handler);
  317. return 0;
  318. }
  319. // Port function map
  320. LROT_BEGIN(softuart_port, NULL, LROT_MASK_GC_INDEX)
  321. LROT_FUNCENTRY( __gc, softuart_gcdelete)
  322. LROT_TABENTRY( __index, softuart_port)
  323. LROT_FUNCENTRY( on, softuart_on)
  324. LROT_FUNCENTRY( write, softuart_write)
  325. LROT_END(softuart_port, NULL, LROT_MASK_GC_INDEX)
  326. // Module function map
  327. LROT_BEGIN(softuart, LROT_TABLEREF(softuart_port), 0)
  328. LROT_FUNCENTRY( setup, softuart_setup)
  329. LROT_END(softuart, LROT_TABLEREF(softuart_port), 0)
  330. static int luaopen_softuart(lua_State *L)
  331. {
  332. for(int i = 0; i < SOFTUART_GPIO_COUNT; i++) {
  333. softuart_rx_cb_ref[i] = LUA_NOREF;
  334. }
  335. uart_recieve_task = task_get_id((task_callback_t) softuart_rx_callback);
  336. luaL_rometatable(L, "softuart.port", LROT_TABLEREF(softuart_port));
  337. return 0;
  338. }
  339. NODEMCU_MODULE(SOFTUART, "softuart", softuart, luaopen_softuart);