+ if (!ao_btm_running)
+ return AO_READ_AGAIN;
+ c = ao_serial_pollchar();
+ if (c != AO_READ_AGAIN)
+ if (ao_btm_ptr < sizeof (ao_btm_buffer))
+ ao_btm_buffer[ao_btm_ptr++] = c;
+ return c;
+}
+
+/*
+ * Wait for the bluetooth device to return
+ * status from the previously executed command
+ */
+uint8_t
+ao_btm_wait_reply(void)
+{
+ for (;;) {
+ ao_btm_get_line();
+ if (!strcmp(ao_btm_reply, "OK"))
+ return 1;
+ if (!strcmp(ao_btm_reply, "ERROR"))
+ return -1;
+ if (ao_btm_reply[0] == '\0')
+ return 0;
+ }
+}
+
+void
+ao_btm_cmd(__code char *cmd)
+{
+ ao_cur_stdio = ao_btm_stdio;
+ printf(cmd);
+ ao_btm_wait_reply();
+}
+
+/*
+ * A thread to initialize the bluetooth device and
+ * hang around to blink the LED when connected
+ */
+void
+ao_btm(void)
+{
+ ao_serial_set_speed(AO_SERIAL_SPEED_19200);
+ ao_add_stdio(ao_btm_pollchar,
+ ao_serial_putchar,
+ NULL);
+ ao_btm_stdio = ao_num_stdios - 1;
+ ao_cur_stdio = ao_btm_stdio;
+ ao_btm_echo(0);
+ ao_btm_drain();
+ ao_delay(AO_SEC_TO_TICKS(1));
+ printf("+++");
+ ao_btm_drain();
+ ao_delay(AO_SEC_TO_TICKS(1));
+ printf("\r");
+ ao_btm_drain();
+ ao_btm_cmd("ATQ0\r");
+ ao_btm_cmd("ATE0\r");
+ ao_btm_cmd("ATH\r");
+ ao_delay(AO_SEC_TO_TICKS(1));
+ ao_btm_cmd("ATC0\r");
+ ao_btm_cmd("ATL4\r");
+ ao_serial_set_speed(AO_SERIAL_SPEED_57600);
+ ao_btm_drain();
+ printf("ATN=TeleBT-%d\r", ao_serial_number);
+ ao_btm_wait_reply();
+ ao_btm_running = 1;
+ for (;;) {
+ while (!ao_btm_connected && !ao_btm_chat)
+ ao_sleep(&ao_btm_connected);
+ if (ao_btm_chat) {
+ ao_btm_running = 0;
+ while (ao_btm_chat) {
+ char c;
+ c = ao_serial_pollchar();
+ if (c != AO_READ_AGAIN)
+ ao_usb_putchar(c);
+ else {
+ ao_usb_flush();
+ ao_sleep(&ao_usart1_rx_fifo);
+ }
+ }
+ ao_btm_running = 1;
+ }
+ while (ao_btm_connected) {
+ ao_led_for(AO_LED_GREEN, AO_MS_TO_TICKS(20));
+ ao_delay(AO_SEC_TO_TICKS(3));