altos/ao_rn4678: Send '$$$' for new devices. Fix name setting code.
[fw/altos] / src / drivers / ao_rn4678.c
1 /*
2  * Copyright © 2017 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  */
14
15 #include <ao.h>
16 #include <ao_rn4678.h>
17 #include <ao_exti.h>
18 #include <stdarg.h>
19
20 static uint8_t  ao_rn_connected;
21
22 #define AO_RN_DEBUG 0
23
24 #if AO_RN_DEBUG
25 static void ao_rn_dbg(char *format, ...) {
26         va_list a;
27         uint32_t        irq = ao_arch_irqsave();
28         ao_arch_release_interrupts();
29         va_start(a, format);
30         vprintf(format, a);
31         va_end(a);
32         flush();
33         ao_arch_irqrestore(irq);
34 }
35
36 static char     ao_rn_dir;
37
38 static void
39 ao_rn_log_char(char c, char dir)
40 {
41         if (dir != ao_rn_dir) {
42                 putchar(dir);
43                 ao_rn_dir = dir;
44         }
45         switch (c) {
46         case '\r':
47                 putchar('\\'); putchar('r');
48                 break;
49         case '\n':
50                 putchar('\\'); putchar('n');
51                 break;
52         default:
53                 putchar(c);
54         }
55         flush();
56 }
57
58 static void
59 ao_rn_log_out_char(char c)
60 {
61         ao_rn_log_char(c, '}');
62 }
63
64 static void
65 ao_rn_log_in_char(char c)
66 {
67         ao_rn_log_char(c, '{');
68 }
69
70 static inline void
71 ao_rn_putchar(char c)
72 {
73         ao_rn_log_out_char(c);
74         ao_serial_rn_putchar(c);
75 }
76
77 static inline int
78 _ao_rn_pollchar(void)
79 {
80         int     c = _ao_serial_rn_pollchar();
81
82         if (c != AO_READ_AGAIN) {
83                 ao_arch_release_interrupts();
84                 ao_rn_log_in_char((char) c);
85                 ao_arch_block_interrupts();
86         }
87         return c;
88 }
89 #else
90 #define ao_rn_dbg(fmt, ...)
91 #define ao_rn_putchar(c)        ao_serial_rn_putchar(c)
92 #define _ao_rn_pollchar()       _ao_serial_rn_pollchar()
93 #endif
94
95 /* For stdio, this skips all status messages *sigh* */
96
97 #define STATUS_CHAR     '%'
98
99 static const char *status_strings[] = {
100         "RFCOMM_CLOSE",
101         "RFCOMM_OPEN",
102         "CONNECT",
103         "DISCONN",
104         "BONDED",
105 };
106
107 #define NUM_STATUS_STRING       (sizeof status_strings/sizeof status_strings[0])
108
109 int
110 _ao_wrap_rn_pollchar(void)
111 {
112         static char     buffer[64];
113         static int      buf_cnt, buf_ptr;
114         static int      draining;
115         int             c = AO_READ_AGAIN;
116         unsigned        i;
117         int             done = 0;
118
119         while (!done && !draining) {
120                 c = _ao_serial_rn_pollchar();
121
122                 if (c == AO_READ_AGAIN)
123                         return AO_READ_AGAIN;
124
125                 if (buf_cnt) {
126                         /* buffering chars */
127
128                         if (c == STATUS_CHAR) {
129                                 /* End of status string, drop it and carry on */
130                                 buffer[buf_cnt] = '\0';
131                                 ao_rn_dbg("discard %s\n", buffer);
132                                 buf_cnt = 0;
133                         } else if (buf_cnt == sizeof(buffer)) {
134                                 /* If we filled the buffer, just give up */
135                                 draining = 1;
136                         } else {
137                                 buffer[buf_cnt++] = c;
138                                 for (i = 0; i < NUM_STATUS_STRING; i++) {
139                                         int cmp = strlen(status_strings[i]);
140                                         if (cmp >= buf_cnt)
141                                                 cmp = buf_cnt-1;
142                                         if (memcmp(buffer+1, status_strings[i], cmp) == 0)
143                                                 break;
144                                 }
145                                 if (i == NUM_STATUS_STRING)
146                                         draining = 1;
147                         }
148                 } else if (c == STATUS_CHAR) {
149                         buffer[0] = c;
150                         buf_cnt = 1;
151                         buf_ptr = 0;
152                 } else
153                         done = 1;
154         }
155         if (draining) {
156                 c = buffer[buf_ptr++] & 0xff;
157                 if (buf_ptr == buf_cnt) {
158                         buf_ptr = buf_cnt = 0;
159                         draining = 0;
160                 }
161         }
162 #if AO_RN_DEBUG
163         ao_arch_release_interrupts();
164         ao_usb_putchar(c); ao_usb_flush();
165         ao_arch_block_interrupts();
166 #endif
167         return c;
168 }
169
170 #if AO_RN_DEBUG
171 static void
172 ao_wrap_rn_putchar(char c)
173 {
174         ao_usb_putchar(c); ao_usb_flush();
175         ao_serial_rn_putchar(c);
176 }
177 #else
178 #define ao_wrap_rn_putchar ao_serial_rn_putchar
179 #endif
180
181 static void
182 ao_rn_puts(char *s)
183 {
184         char c;
185
186         while ((c = *s++))
187                 ao_rn_putchar(c);
188 }
189
190 static void
191 ao_rn_drain(void)
192 {
193         int     timeout = 0;
194
195         ao_rn_dbg("drain...\n");
196         ao_serial_rn_drain();
197         while (!timeout) {
198                 ao_arch_block_interrupts();
199                 while (_ao_rn_pollchar() == AO_READ_AGAIN) {
200                         if (_ao_serial_rn_sleep_for(AO_MS_TO_TICKS(10))) {
201                                 timeout = 1;
202                                 break;
203                         }
204                 }
205                 ao_arch_release_interrupts();
206         }
207         ao_rn_dbg("drain done\n");
208 }
209
210 static void
211 ao_rn_send_cmd(char *cmd, char *param)
212 {
213         ao_rn_dbg("send_cmd %s%s\n", cmd, param ? param : "");
214         ao_rn_drain();
215         ao_rn_puts(cmd);
216         if (param)
217                 ao_rn_puts(param);
218         ao_rn_putchar('\r');
219 }
220
221 static int
222 ao_rn_wait_char(AO_TICK_TYPE giveup_time)
223 {
224         int c;
225
226         ao_arch_block_interrupts();
227         while ((c = _ao_rn_pollchar()) == AO_READ_AGAIN) {
228                 AO_TICK_SIGNED  delay = (AO_TICK_SIGNED) (giveup_time - ao_time());
229                 if (delay < 0) {
230                         ao_arch_release_interrupts();
231                         return AO_READ_AGAIN;
232                 }
233                 _ao_serial_rn_sleep_for(delay);
234         }
235         ao_arch_release_interrupts();
236         return c;
237 }
238
239 static int
240 ao_rn_wait_for(int timeout, char *match)
241 {
242         char            reply[AO_RN_MAX_REPLY_LEN + 1];
243         int             match_len = strlen(match);
244         AO_TICK_TYPE    giveup_time = ao_time() + timeout;
245         int             c;
246
247         ao_rn_dbg("wait for %d, \"%s\"\n", timeout, match);
248         memset(reply, ' ', sizeof(reply));
249         while (memcmp(reply, match, match_len) != 0) {
250                 c = ao_rn_wait_char(giveup_time);
251                 if (c == AO_READ_AGAIN) {
252                         ao_rn_dbg("\twait for timeout\n");
253                         return AO_RN_TIMEOUT;
254                 }
255                 reply[match_len] = (char) c;
256                 memmove(reply, reply+1, match_len);
257                 reply[match_len] = '\0';
258                 ao_rn_dbg("\tmatch now \"%s\"\n", reply);
259         }
260         ao_rn_dbg("\twait for ok\n");
261         return AO_RN_OK;
262 }
263
264 static int
265 ao_rn_wait_line(AO_TICK_TYPE giveup_time, char *line, int len)
266 {
267         char *l = line;
268
269         ao_rn_dbg("wait line\n");
270         for (;;) {
271                 int c = ao_rn_wait_char(giveup_time);
272
273                 /* timeout */
274                 if (c == AO_READ_AGAIN) {
275                         ao_rn_dbg("\twait line timeout\n");
276                         return AO_RN_TIMEOUT;
277                 }
278
279                 /* done */
280                 if (c == '\r') {
281                         *l = '\0';
282                         ao_rn_dbg("\twait line \"%s\"\n", line);
283                         return AO_RN_OK;
284                 }
285
286                 if (c == '\n')
287                         continue;
288
289                 /* buffer overrun */
290                 if (len <= 1)
291                         return AO_RN_ERROR;
292
293                 *l++ = (char) c;
294                 len--;
295         }
296 }
297
298 static int
299 ao_rn_wait_status(void)
300 {
301         char            message[AO_RN_MAX_REPLY_LEN];
302         AO_TICK_TYPE    giveup_time = ao_time() + AO_RN_CMD_TIMEOUT;
303         int             status;
304
305         ao_rn_dbg("wait status\n");
306         status = ao_rn_wait_line(giveup_time, message, sizeof (message));
307         if (status == AO_RN_OK)
308                 if (strncmp(message, "AOK", 3) != 0)
309                         status = AO_RN_ERROR;
310         return status;
311 }
312
313 static int
314 ao_rn_set_name(void)
315 {
316         char    sn[8];
317         char    *s = sn + 8;
318         int     n;
319
320         ao_rn_dbg("set name...\n");
321         *--s = '\0';
322         n = ao_serial_number;
323         do {
324                 *--s = '0' + n % 10;
325         } while (n /= 10);
326         ao_rn_send_cmd(AO_RN_SET_NAME_CMD "TeleBT-", s);
327         return ao_rn_wait_status();
328 }
329
330 static int
331 ao_rn_get_name(char *name, int len)
332 {
333         ao_rn_dbg("get name...\n");
334         ao_rn_send_cmd(AO_RN_GET_NAME_CMD, NULL);
335         return ao_rn_wait_line(ao_time() + AO_RN_CMD_TIMEOUT, name, len);
336 }
337
338 static void
339 ao_rn_check_link(void)
340 {
341         ao_rn_connected = 1 - ao_gpio_get(AO_RN_CONNECTED_PORT, AO_RN_CONNECTED_PIN, foo);
342 }
343
344 static void
345 ao_rn_isr(void)
346 {
347         ao_rn_check_link();
348         ao_wakeup(&ao_rn_connected);
349 }
350
351 static void
352 ao_bt_panic(int where)
353 {
354         int i;
355         for (;;) {
356                 for (i = 0; i < 50; i++) {
357                         ao_led_toggle(AO_BT_LED);
358                         ao_delay(AO_MS_TO_TICKS(10));
359                 }
360                 ao_led_off(AO_BT_LED);
361                 ao_delay(AO_MS_TO_TICKS(500));
362                 for (i = 0; i < where; i++) {
363                         ao_led_for(AO_BT_LED, AO_MS_TO_TICKS(200));
364                         ao_delay(AO_MS_TO_TICKS(200));
365                 }
366         }
367 }
368
369 static uint8_t  ao_rn_stdio;
370
371 /*
372  * Set the stdio echo for the bluetooth link
373  */
374 void
375 ao_rn_echo(uint8_t echo)
376 {
377         ao_stdios[ao_rn_stdio].echo = echo;
378 }
379
380 static void
381 ao_rn(void)
382 {
383         int     status = AO_RN_ERROR;
384         char    name[17];
385         int     i;
386
387         ao_rn_dbg("ao_rn top\n");
388
389         /* Select CMD mode after the device gets out of reset */
390         ao_gpio_set(AO_RN_CMD_PORT, AO_RN_CMD_PIN, foo, AO_RN_CMD_CMD);
391
392         for (i = 0; i < 3; i++) {
393                 ao_rn_dbg("reset device\n");
394
395                 ao_gpio_set(AO_RN_RST_N_PORT, AO_RN_RST_N_PIN, foo, 0);
396                 ao_delay(AO_MS_TO_TICKS(100));
397
398                 /* Reboot the RN4678 and wait for it to start talking */
399                 ao_rn_drain();
400                 ao_gpio_set(AO_RN_RST_N_PORT, AO_RN_RST_N_PIN, foo, 1);
401                 status = ao_rn_wait_for(AO_RN_REBOOT_TIMEOUT, AO_RN_REBOOT_MSG);
402                 if (status != AO_RN_OK) {
403                         ao_rn_dbg("reboot failed\n");
404                         continue;
405                 }
406
407                 ao_rn_puts("$$$");
408
409                 /* After it reboots, it can take a moment before it responds
410                  * to commands
411                  */
412                 (void) ao_rn_wait_for(AO_RN_REBOOT_TIMEOUT, "CMD> ");
413
414                 /* Check to see if the name is already set and assume
415                  * that the device is ready to go
416                  */
417                 status = ao_rn_get_name(name, sizeof (name));
418                 if (status != AO_RN_OK) {
419                         ao_rn_dbg("get name failed\n");
420                         continue;
421                 }
422
423                 if (strncmp(name, "TeleBT-", 7) == 0) {
424                         ao_rn_dbg("name is set\n");
425                         status = AO_RN_OK;
426                         break;
427                 }
428
429                 /* Make the command pin control command/data mode */
430                 ao_rn_send_cmd(AO_RN_SET_COMMAND_PIN, NULL);
431                 if (ao_rn_wait_status() != AO_RN_OK) {
432                         ao_rn_dbg("set command pin failed\n");
433                         continue;
434                 }
435
436                 /* Select 'fast' mode to ignore command sequence (more or less) */
437                 ao_rn_send_cmd(AO_RN_SET_FAST_MODE, NULL);
438                 if (ao_rn_wait_status() != AO_RN_OK) {
439                         ao_rn_dbg("set fast mode failed\n");
440                         continue;
441                 }
442
443                 /* Finally, set the name. Doing this last makes it possible to check
444                  * if the whole sequence has been done
445                  */
446                 if (ao_rn_set_name() != AO_RN_OK) {
447                         ao_rn_dbg("set name failed\n");
448                         continue;
449                 }
450
451                 /* After we've configured the device, go back around and reboot it
452                  * as that's how we get the new configuration to take effect
453                  */
454         }
455         ao_rn_dbg("ao_rn status %d\n", status);
456
457         if (status != AO_RN_OK)
458                 ao_bt_panic(4);
459
460         ao_gpio_set(AO_RN_CMD_PORT, AO_RN_CMD_PIN, foo, AO_RN_CMD_DATA);
461
462         /* Wait for the hardware to finish sending messages, then clear the queue */
463         ao_delay(AO_MS_TO_TICKS(200));
464         ao_rn_drain();
465
466         ao_exti_enable(AO_RN_CONNECTED_PORT, AO_RN_CONNECTED_PIN);
467
468 #if 1
469         ao_rn_stdio = ao_add_stdio(_ao_wrap_rn_pollchar,
470                                    ao_wrap_rn_putchar,
471                                    NULL);
472
473         ao_rn_echo(0);
474
475         ao_rn_check_link();
476
477         ao_rn_dbg("RN running\n");
478
479         /*
480          * Now just hang around and flash the blue LED when we've got
481          * a connection
482          */
483         for (;;) {
484                 ao_arch_block_interrupts();
485                 while (!ao_rn_connected)
486                         ao_sleep(&ao_rn_connected);
487                 ao_arch_release_interrupts();
488                 while (ao_rn_connected) {
489                         ao_led_for(AO_BT_LED, AO_MS_TO_TICKS(20));
490                         ao_delay(AO_SEC_TO_TICKS(3));
491                 }
492         }
493 #else
494
495         /*
496          * Separate debug code when things aren't working. Just dump
497          * inbound bluetooth characters to stdout
498          */
499         for (;;) {
500                 int     c;
501
502                 while (rn_cmd_running)
503                         ao_delay(AO_MS_TO_TICKS(1000));
504
505                 ao_arch_block_interrupts();
506                 while ((c = _ao_wrap_rn_pollchar()) == AO_READ_AGAIN)
507                         ao_sleep(&ao_serial_rn_rx_fifo);
508                 ao_arch_release_interrupts();
509                 putchar(c); flush();
510         }
511 #endif
512 }
513
514 static struct ao_task ao_rn_task;
515
516 static void
517 ao_rn_factory(void)
518 {
519         int     i;
520         int     v = 0;
521
522         /*
523          * Factory reset. Flip pin P3_1 5 times within the first five
524          * seconds of power-on
525          */
526
527         /* Select our target output pin */
528         ao_enable_output(AO_RN_P3_1_PORT, AO_RN_P3_1_PIN, foo, v);
529
530         /* Turn off the BT device using the SW_BTN pin */
531         printf("Power down BT\n"); flush();
532         ao_gpio_set(AO_RN_SW_BTN_PORT, AO_RN_SW_BTN_PIN, foo, 0);
533         ao_delay(AO_MS_TO_TICKS(1000));
534
535         /* And turn it back on */
536         printf("Power up BT\n"); flush();
537         ao_gpio_set(AO_RN_SW_BTN_PORT, AO_RN_SW_BTN_PIN, foo, 1);
538
539         /* Right after power on, poke P3_1 five times to force a
540          * factory reset
541          */
542         for (i = 0; i < 10; i++) {
543                 v = 1-v;
544                 ao_delay(AO_MS_TO_TICKS(100));
545                 ao_gpio_set(AO_RN_P3_1_PORT, AO_RN_P3_1_PIN, foo, v);
546                 ao_led_toggle(AO_BT_LED);
547         }
548
549         /* And let P3_1 float again */
550         ao_enable_input(AO_RN_P3_1_PORT, AO_RN_P3_1_PIN, AO_EXTI_MODE_PULL_NONE);
551 }
552
553 static const struct ao_cmds rn_cmds[] = {
554         { ao_rn_factory, "F\0Factory reset rn4678" },
555         { 0 },
556 };
557
558 void
559 ao_rn4678_init(void)
560 {
561         (void) ao_rn_set_name;
562
563         ao_serial_rn_set_speed(AO_SERIAL_SPEED_115200);
564
565         /* Reset line */
566         ao_enable_output(AO_RN_RST_N_PORT, AO_RN_RST_N_PIN, foo, 0);
567
568         /* SW_BTN */
569         ao_enable_output(AO_RN_SW_BTN_PORT, AO_RN_SW_BTN_PIN, foo, 1);
570
571         /* P3_7 command/data selector */
572         ao_enable_output(AO_RN_CMD_PORT, AO_RN_CMD_PIN, foo, AO_RN_CMD_CMD);
573
574         ao_enable_input(AO_RN_CONNECTED_PORT, AO_RN_CONNECTED_PIN, AO_EXTI_MODE_PULL_NONE);
575         ao_exti_setup(AO_RN_CONNECTED_PORT, AO_RN_CONNECTED_PIN,
576                       AO_EXTI_MODE_FALLING|AO_EXTI_MODE_RISING|AO_EXTI_PRIORITY_LOW,
577                       ao_rn_isr);
578
579         ao_cmd_register(rn_cmds);
580         ao_add_task(&ao_rn_task, ao_rn, "bluetooth");
581 }