static void event_handler(uint8_t *packet, int size){ bd_addr_t addr; uint8_t link_type; hci_con_handle_t handle; hci_connection_t * conn; int i; // printf("HCI:EVENT:%02x\n", packet[0]); switch (packet[0]) { case HCI_EVENT_COMMAND_COMPLETE: // get num cmd packets // log_info("HCI_EVENT_COMMAND_COMPLETE cmds old %u - new %u\n", hci_stack.num_cmd_packets, packet[2]); hci_stack.num_cmd_packets = packet[2]; if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){ // from offset 5 // status // "The HC_ACL_Data_Packet_Length return parameter will be used to determine the size of the L2CAP segments contained in ACL Data Packets" hci_stack.acl_data_packet_length = READ_BT_16(packet, 6); // ignore: SCO data packet len (8) hci_stack.total_num_acl_packets = packet[9]; // ignore: total num SCO packets if (hci_stack.state == HCI_STATE_INITIALIZING){ // determine usable ACL payload size if (HCI_ACL_PAYLOAD_SIZE < hci_stack.acl_data_packet_length){ hci_stack.acl_data_packet_length = HCI_ACL_PAYLOAD_SIZE; } // determine usable ACL packet types hci_stack.packet_types = hci_acl_packet_types_for_buffer_size(hci_stack.acl_data_packet_length); log_error("hci_read_buffer_size: used size %u, count %u, packet types %04x\n", hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets, hci_stack.packet_types); } } // Dump local address if (COMMAND_COMPLETE_EVENT(packet, hci_read_bd_addr)) { bd_addr_t addr; bt_flip_addr(addr, &packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE + 1]); log_info("Local Address, Status: 0x%02x: Addr: %s\n", packet[OFFSET_OF_DATA_IN_COMMAND_COMPLETE], bd_addr_to_str(addr)); } if (COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ hci_emit_discoverable_enabled(hci_stack.discoverable); } break; case HCI_EVENT_COMMAND_STATUS: // get num cmd packets // log_info("HCI_EVENT_COMMAND_STATUS cmds - old %u - new %u\n", hci_stack.num_cmd_packets, packet[3]); hci_stack.num_cmd_packets = packet[3]; break; case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS: for (i=0; i<packet[2];i++){ handle = READ_BT_16(packet, 3 + 2*i); uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i); conn = connection_for_handle(handle); if (!conn){ log_error("hci_number_completed_packet lists unused con handle %u\n", handle); continue; } conn->num_acl_packets_sent -= num_packets; // log_info("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent); } break; case HCI_EVENT_CONNECTION_REQUEST: bt_flip_addr(addr, &packet[2]); // TODO: eval COD 8-10 link_type = packet[11]; log_info("Connection_incoming: %s, type %u\n", bd_addr_to_str(addr), link_type); if (link_type == 1) { // ACL conn = connection_for_address(addr); if (!conn) { conn = create_connection_for_addr(addr); } if (!conn) { // CONNECTION REJECTED DUE TO LIMITED RESOURCES (0X0D) hci_stack.decline_reason = 0x0d; BD_ADDR_COPY(hci_stack.decline_addr, addr); break; } conn->state = RECEIVED_CONNECTION_REQUEST; hci_run(); } else { // SYNCHRONOUS CONNECTION LIMIT TO A DEVICE EXCEEDED (0X0A) hci_stack.decline_reason = 0x0a; BD_ADDR_COPY(hci_stack.decline_addr, addr); } break; case HCI_EVENT_CONNECTION_COMPLETE: // Connection management bt_flip_addr(addr, &packet[5]); log_info("Connection_complete (status=%u) %s\n", packet[2], bd_addr_to_str(addr)); conn = connection_for_address(addr); if (conn) { if (!packet[2]){ conn->state = OPEN; conn->con_handle = READ_BT_16(packet, 3); // restart timer run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); run_loop_add_timer(&conn->timeout); log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); hci_emit_nr_connections_changed(); } else { // connection failed, remove entry linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); btstack_memory_hci_connection_free( conn ); // if authentication error, also delete link key if (packet[2] == 0x05) { hci_drop_link_key_for_bd_addr(&addr); } } } break; case HCI_EVENT_LINK_KEY_REQUEST: log_info("HCI_EVENT_LINK_KEY_REQUEST\n"); hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_REQUEST); if (!hci_stack.remote_device_db) break; hci_add_connection_flags_for_flipped_bd_addr(&packet[2], HANDLE_LINK_KEY_REQUEST); hci_run(); // request handled by hci_run() as HANDLE_LINK_KEY_REQUEST gets set return; case HCI_EVENT_LINK_KEY_NOTIFICATION: hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_LINK_KEY_NOTIFICATION); if (!hci_stack.remote_device_db) break; bt_flip_addr(addr, &packet[2]); hci_stack.remote_device_db->put_link_key(&addr, (link_key_t *) &packet[8]); // still forward event to allow dismiss of pairing dialog break; case HCI_EVENT_PIN_CODE_REQUEST: hci_add_connection_flags_for_flipped_bd_addr(&packet[2], RECV_PIN_CODE_REQUEST); // PIN CODE REQUEST means the link key request didn't succee -> delete stored link key if (!hci_stack.remote_device_db) break; bt_flip_addr(addr, &packet[2]); hci_stack.remote_device_db->delete_link_key(&addr); break; #ifndef EMBEDDED case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: if (!hci_stack.remote_device_db) break; if (packet[2]) break; // status not ok bt_flip_addr(addr, &packet[3]); // fix for invalid remote names - terminate on 0xff for (i=0; i<248;i++){ if (packet[9+i] == 0xff){ packet[9+i] = 0; break; } } memset(&device_name, 0, sizeof(device_name_t)); strncpy((char*) device_name, (char*) &packet[9], 248); hci_stack.remote_device_db->put_name(&addr, &device_name); break; case HCI_EVENT_INQUIRY_RESULT: case HCI_EVENT_INQUIRY_RESULT_WITH_RSSI: if (!hci_stack.remote_device_db) break; // first send inq result packet hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); // then send cached remote names for (i=0; i<packet[2];i++){ bt_flip_addr(addr, &packet[3+i*6]); if (hci_stack.remote_device_db->get_name(&addr, &device_name)){ hci_emit_remote_name_cached(&addr, &device_name); } } return; #endif case HCI_EVENT_DISCONNECTION_COMPLETE: if (!packet[2]){ handle = READ_BT_16(packet, 3); hci_connection_t * conn = connection_for_handle(handle); if (conn) { hci_shutdown_connection(conn); } } break; case HCI_EVENT_HARDWARE_ERROR: if(hci_stack.control->hw_error){ (*hci_stack.control->hw_error)(); } break; #ifdef HAVE_BLE case HCI_EVENT_LE_META: switch (packet[2]) { case HCI_SUBEVENT_LE_CONNECTION_COMPLETE: // Connection management bt_flip_addr(addr, &packet[8]); log_info("LE Connection_complete (status=%u) %s\n", packet[3], bd_addr_to_str(addr)); // LE connections are auto-accepted, so just create a connection if there isn't one already conn = connection_for_address(addr); if (packet[3]){ if (conn){ // outgoing connection failed, remove entry linked_list_remove(&hci_stack.connections, (linked_item_t *) conn); btstack_memory_hci_connection_free( conn ); } // if authentication error, also delete link key if (packet[3] == 0x05) { hci_drop_link_key_for_bd_addr(&addr); } break; } if (!conn){ conn = create_connection_for_addr(addr); } if (!conn){ // no memory break; } conn->state = OPEN; conn->con_handle = READ_BT_16(packet, 4); // TODO: store - role, peer address type, conn_interval, conn_latency, supervision timeout, master clock // restart timer // run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS); // run_loop_add_timer(&conn->timeout); log_info("New connection: handle %u, %s\n", conn->con_handle, bd_addr_to_str(conn->address)); hci_emit_nr_connections_changed(); break; default: break; } break; #endif default: break; } // handle BT initialization if (hci_stack.state == HCI_STATE_INITIALIZING){ // handle H4 synchronization loss on restart // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){ // hci_stack.substate = 0; // } // handle normal init sequence if (hci_stack.substate % 2){ // odd: waiting for event if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){ hci_stack.substate++; } } } // help with BT sleep if (hci_stack.state == HCI_STATE_FALLING_ASLEEP && hci_stack.substate == 1 && COMMAND_COMPLETE_EVENT(packet, hci_write_scan_enable)){ hci_stack.substate++; } hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size); // execute main loop hci_run(); }
static void one_shot_timer_setup(){ // set one-shot timer heartbeat.process = &heartbeat_handler; run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS); run_loop_add_timer(&heartbeat); }
// main int main(void) { // stop watchdog timer WDTCTL = WDTPW + WDTHOLD; //Initialize clock and peripherals halBoardInit(); halBoardStartXT1(); halBoardSetSystemClock(SYSCLK_16MHZ); // init debug UART halUsbInit(); // init LEDs LED_PORT_OUT |= LED_1 | LED_2; LED_PORT_DIR |= LED_1 | LED_2; /// GET STARTED with BTstack /// btstack_memory_init(); run_loop_init(RUN_LOOP_EMBEDDED); // init HCI hci_transport_t * transport = hci_transport_h4_dma_instance(); bt_control_t * control = bt_control_cc256x_instance(); hci_uart_config_t * config = hci_uart_config_cc256x_instance(); remote_device_db_t * remote_db = (remote_device_db_t *) &remote_device_db_memory; hci_init(transport, config, control, remote_db); // use eHCILL bt_control_cc256x_enable_ehcill(1); // init L2CAP l2cap_init(); l2cap_register_packet_handler(packet_handler); // init RFCOMM rfcomm_init(); rfcomm_register_packet_handler(packet_handler); rfcomm_register_service_with_initial_credits_internal(NULL, rfcomm_channel_nr, 100, 1); // reserved channel, mtu=100, 1 credit // init SDP, create record for SPP and register with SDP sdp_init(); memset(spp_service_buffer, 0, sizeof(spp_service_buffer)); service_record_item_t * service_record_item = (service_record_item_t *) spp_service_buffer; sdp_create_spp_service( (uint8_t*) &service_record_item->service_record, 1, "SPP Counter"); printf("SDP service buffer size: %u\n\r", (uint16_t) (sizeof(service_record_item_t) + de_get_len((uint8_t*) &service_record_item->service_record))); sdp_register_service_internal(NULL, service_record_item); // set one-shot timer timer_source_t heartbeat; heartbeat.process = &heartbeat_handler; run_loop_set_timer(&heartbeat, HEARTBEAT_PERIOD_MS); run_loop_add_timer(&heartbeat); puts("SPP FlowControl Demo: simulates processing on received data...\n\r"); // ready - enable irq used in h4 task __enable_interrupt(); // turn on! hci_power_control(HCI_POWER_ON); // go! run_loop_execute(); // happy compiler! return 0; }
static void run_loop_register_timer(timer_source_t *timer, uint16_t period){ run_loop_set_timer(timer, period); run_loop_add_timer(timer); }
static int usb_open(void *transport_config){ int r; sco_state_machine_init(); sco_ring_init(); handle_packet = NULL; // default endpoint addresses event_in_addr = 0x81; // EP1, IN interrupt acl_in_addr = 0x82; // EP2, IN bulk acl_out_addr = 0x02; // EP2, OUT bulk sco_in_addr = 0x83; // EP3, IN isochronous sco_out_addr = 0x03; // EP3, OUT isochronous // USB init r = libusb_init(NULL); if (r < 0) return -1; libusb_state = LIB_USB_OPENED; // configure debug level libusb_set_debug(NULL, LIBUSB_LOG_LEVEL_WARNING); #ifdef HAVE_USB_VENDOR_ID_AND_PRODUCT_ID // Use a specified device log_info("Want vend: %04x, prod: %04x", USB_VENDOR_ID, USB_PRODUCT_ID); handle = libusb_open_device_with_vid_pid(NULL, USB_VENDOR_ID, USB_PRODUCT_ID); if (!handle){ log_error("libusb_open_device_with_vid_pid failed!"); usb_close(handle); return -1; } log_info("libusb open %d, handle %p", r, handle); r = prepare_device(handle); if (r < 0){ usb_close(handle); return -1; } #else // Scan system for an appropriate devices libusb_device **devs; ssize_t cnt; log_info("Scanning for USB Bluetooth device"); cnt = libusb_get_device_list(NULL, &devs); if (cnt < 0) { usb_close(handle); return -1; } int startIndex = 0; dev = NULL; while (1){ int deviceIndex = scan_for_bt_device(devs, startIndex); if (deviceIndex < 0){ break; } startIndex = deviceIndex+1; log_info("USB Bluetooth device found, index %u", deviceIndex); handle = NULL; r = libusb_open(devs[deviceIndex], &handle); if (r < 0) { log_error("libusb_open failed!"); handle = NULL; continue; } log_info("libusb open %d, handle %p", r, handle); // reset device libusb_reset_device(handle); if (r < 0) { log_error("libusb_reset_device failed!"); libusb_close(handle); handle = NULL; continue; } // device found r = prepare_device(handle); if (r < 0){ continue; } libusb_state = LIB_USB_INTERFACE_CLAIMED; break; } libusb_free_device_list(devs, 1); if (handle == 0){ log_error("No USB Bluetooth device found"); return -1; } scan_for_bt_endpoints(); #endif // allocate transfer handlers int c; for (c = 0 ; c < ASYNC_BUFFERS ; c++) { event_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers Events acl_in_transfer[c] = libusb_alloc_transfer(0); // 0 isochronous transfers ACL in if ( !event_in_transfer[c] || !acl_in_transfer[c]) { usb_close(handle); return LIBUSB_ERROR_NO_MEM; } } command_out_transfer = libusb_alloc_transfer(0); acl_out_transfer = libusb_alloc_transfer(0); // TODO check for error libusb_state = LIB_USB_TRANSFERS_ALLOCATED; #ifdef HAVE_SCO // incoming for (c = 0 ; c < ASYNC_BUFFERS ; c++) { sco_in_transfer[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // isochronous transfers SCO in log_info("Alloc iso transfer"); if (!sco_in_transfer[c]) { usb_close(handle); return LIBUSB_ERROR_NO_MEM; } // configure sco_in handlers libusb_fill_iso_transfer(sco_in_transfer[c], handle, sco_in_addr, hci_sco_in_buffer[c], SCO_PACKET_SIZE, NUM_ISO_PACKETS, async_callback, NULL, 0); libusb_set_iso_packet_lengths(sco_in_transfer[c], ISO_PACKET_SIZE); r = libusb_submit_transfer(sco_in_transfer[c]); log_info("Submit iso transfer res = %d", r); if (r) { log_error("Error submitting isochronous in transfer %d", r); usb_close(handle); return r; } } // outgoing for (c=0; c < SCO_RING_BUFFER_COUNT ; c++){ sco_ring_transfers[c] = libusb_alloc_transfer(NUM_ISO_PACKETS); // 1 isochronous transfers SCO out - up to 3 parts } #endif for (c = 0 ; c < ASYNC_BUFFERS ; c++) { // configure event_in handlers libusb_fill_interrupt_transfer(event_in_transfer[c], handle, event_in_addr, hci_event_in_buffer[c], HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ; r = libusb_submit_transfer(event_in_transfer[c]); if (r) { log_error("Error submitting interrupt transfer %d", r); usb_close(handle); return r; } // configure acl_in handlers libusb_fill_bulk_transfer(acl_in_transfer[c], handle, acl_in_addr, hci_acl_in_buffer[c] + HCI_INCOMING_PRE_BUFFER_SIZE, HCI_ACL_BUFFER_SIZE, async_callback, NULL, 0) ; r = libusb_submit_transfer(acl_in_transfer[c]); if (r) { log_error("Error submitting bulk in transfer %d", r); usb_close(handle); return r; } } // Check for pollfds functionality doing_pollfds = libusb_pollfds_handle_timeouts(NULL); // NOTE: using pollfds doesn't work on Linux, so it is disable until further investigation here doing_pollfds = 0; if (doing_pollfds) { log_info("Async using pollfds:"); const struct libusb_pollfd ** pollfd = libusb_get_pollfds(NULL); for (num_pollfds = 0 ; pollfd[num_pollfds] ; num_pollfds++); pollfd_data_sources = malloc(sizeof(data_source_t) * num_pollfds); if (!pollfd_data_sources){ log_error("Cannot allocate data sources for pollfds"); usb_close(handle); return 1; } for (r = 0 ; r < num_pollfds ; r++) { data_source_t *ds = &pollfd_data_sources[r]; ds->fd = pollfd[r]->fd; ds->process = usb_process_ds; run_loop_add_data_source(ds); log_info("%u: %p fd: %u, events %x", r, pollfd[r], pollfd[r]->fd, pollfd[r]->events); } free(pollfd); } else { log_info("Async using timers:"); usb_timer.process = usb_process_ts; run_loop_set_timer(&usb_timer, AYSNC_POLLING_INTERVAL_MS); run_loop_add_timer(&usb_timer); usb_timer_active = 1; } return 0; }
void timer_handler(struct timer *ts){ bt_send_cmd(&hci_read_bd_addr); run_loop_set_timer(&timer, 3000); run_loop_add_timer(&timer); };
static void hsp_ringing_timer_start(void){ run_loop_remove_timer(&hs_timeout); run_loop_set_timer_handler(&hs_timeout, hsp_ringing_timeout_handler); run_loop_set_timer(&hs_timeout, 2000); // 2 seconds timeout run_loop_add_timer(&hs_timeout); }
static void hsp_ringing_timeout_handler(timer_source_t * timer){ ag_ring = 1; run_loop_set_timer(&hs_timeout, 2000); // 2 seconds timeout run_loop_add_timer(&hs_timeout); }