Example #1
1
/*
Scans for nearby bluetooth devices. It looks for a maximum of max_devices to be nearby.
The timeout for the discovery is set to (1.28*inquiry_length) seconds. Finally,
a reference to a discovered_dev_t (see scanner.h) array is passed, used to store the 
results of the scanning.

@param max_devices The number (maximum) of devices that can be discovered.
@param inquiry_length Time to wait for nearby devices to respond.
@param nearby Datastructure to hold information about the nearby/discovered devices.
@return nr_nearby The actual number of devices found nearby.
*/
int scan_nearby(int max_devices, int inquiry_length, discovered_dev_t* nearby){

	int adapter_id = hci_get_route(NULL);
	if(adapter_id < 0){
		log_event("<scan_nearby>", "Cannot access bluetooth device (maybe off?)", WARN);
		return -1;
	}

	int socket = hci_open_dev(adapter_id);
	
	if(socket < 0){
		log_event("<scan_nearby>", "Error opening socket", ERRO);
		exit(EXIT_ERR_OPEN_SOCKET);
	}

	// Setting parameters for discovery.
	int status; 					// -1 if any error, else is set by HCI_INQUIRY to number of devices discovered
	long flags = IREQ_CACHE_FLUSH;
	inquiry_info* inq_inf = NULL; 	// will store data for discovered devices.
	
	inq_inf = (inquiry_info*)malloc(max_devices*sizeof(inquiry_info));
	if (inq_inf == NULL){
		log_event("<scan_nearby>", "Error allocating resources for inquiry_info", ERRO);
		exit(EXIT_ERR_ALLOC_MEM);
	}

	status = hci_inquiry(adapter_id, inquiry_length, max_devices, NULL, &inq_inf,flags );
	if(status < 0){
		log_event("<scan_nearby>", "Error hci_inquiry", ERRO);
		exit(EXIT_ERR_HQI_INQUIRY);
	}
	
	int nr_nearby = status;
	int i;
	char name[20];

	for(i = 0; i < nr_nearby; i++){
		discovered_dev_t nearby_dev;
		memset(name,0,sizeof(name));
		bdaddr_t mac_addr = inq_inf[i].bdaddr;
		ba2str(&mac_addr,nearby_dev.addr);
		
		// try to get a name for the device ...
		status = hci_read_remote_name(socket, &mac_addr, sizeof(name),name,0);
		if(status < 0){
			strcpy(nearby_dev.name,"Unknown");
		}else{
			strcpy(nearby_dev.name,name);
		}

		nearby[i] = nearby_dev;

	}

	close(socket);
	free(inq_inf);
	return nr_nearby;

}
Example #2
0
int main(int argc,char **argv)
{
/*
    start_le_adv(0,-1);
    printf("le_adv started successful\n");
    printf("now try to stop adv\n");
    stop_le_adv(0,-1);
*/
    int dev_id = hci_get_route(NULL);
    if(dev_id < 0)
    {
        printf("hci_get_route faild\n");
        return 1;
    }

    int dd = hci_open_dev(dev_id);
//    stop_le_adv(0,-1);

    uint8_t cmd_data[32]= {0x1F};
    MYDATA mydata;
    memset(&mydata,0,sizeof(MYDATA));
    mydata.device_id = htobe64(123456789);
    mydata.length = 0x1E;
    mydata.magic_number = MAGIC_NUMBER_PERIPHERAL_TO_CENTRAL;

    sha1_hmac(KEY,strlen(KEY),(unsigned char *)&mydata.device_id,8,(unsigned char *)&mydata.checksum);

    memcpy(cmd_data+1,&mydata,sizeof(MYDATA));
    set_adv_data(dev_id,cmd_data,sizeof(cmd_data));

    start_le_adv(0,-1);
    lescan(dev_id,PERIPHERAL);
    return 0;
}
Example #3
0
int devname(char *pAddress, char *pName, int sz ) 
{
  bdaddr_t bdaddr;
  //char name[248]
  int dd;

  str2ba( pAddress, &bdaddr );

  int dev_id;
  dev_id = hci_get_route( &bdaddr );

  if ( dev_id < 0 ) {
    printf("Device not available\n");
    return -1;
  }
  
  dd = hci_open_dev(dev_id);
  if (dd < 0) {
    printf("HCI device open failed\n");
    return -2;
  }

  if ( hci_read_remote_name( dd, 
			     &bdaddr, 
			     sz, 
			     pName,
			     25000) != 0) {
    close(dd);
    printf("Could not find device %s\n", pAddress);
    return -3;
  }

  close(dd);
  return 0;
}
Example #4
0
static void register_server(uint16_t id)
{
	char path[MAX_PATH_LENGTH];
	bdaddr_t src;
	int dev_id;

	if (!conf->server_enabled)
		return;

	snprintf(path, MAX_PATH_LENGTH, NETWORK_PATH "/%s", bnep_name(id));

	if (g_slist_find_custom(server_paths, path,
				(GCompareFunc) strcmp))
		return;

	bacpy(&src, BDADDR_ANY);
	dev_id = hci_get_route(&src);
	if (dev_id < 0 || hci_devba(dev_id, &src))
		return;

	if (server_register(path, &src, id) < 0)
		return;

	server_store(path);

	server_paths = g_slist_append(server_paths, g_strdup(path));
}
Example #5
0
static void manager_remove_adapter(struct btd_adapter *adapter)
{
	uint16_t dev_id = adapter_get_dev_id(adapter);
	const gchar *path = adapter_get_path(adapter);

	adapters = g_slist_remove(adapters, adapter);

	manager_update_adapters();

	if (default_adapter_id == dev_id || default_adapter_id < 0) {
		int new_default = hci_get_route(NULL);

		manager_set_default_adapter(new_default);
	}

	g_dbus_emit_signal(connection, "/",
			MANAGER_INTERFACE, "AdapterRemoved",
			DBUS_TYPE_OBJECT_PATH, &path,
			DBUS_TYPE_INVALID);

	adapter_remove(adapter);
	btd_adapter_unref(adapter);

	if (adapters == NULL)
		btd_start_exit_timer();
}
struct hci_state open_default_hci_device()
{
  struct hci_state current_hci_state = {0};

  current_hci_state.device_id = hci_get_route(NULL);

  if((current_hci_state.device_handle = hci_open_dev(current_hci_state.device_id)) < 0) 
  {
    current_hci_state.has_error = TRUE;
    snprintf(current_hci_state.error_message, sizeof(current_hci_state.error_message), "Could not open device: %s", strerror(errno));
    return current_hci_state;
  }

  // Set fd non-blocking
  int on = 1;
  if(ioctl(current_hci_state.device_handle, FIONBIO, (char *)&on) < 0)
  {
    current_hci_state.has_error = TRUE;
    snprintf(current_hci_state.error_message, sizeof(current_hci_state.error_message), "Could set device to non-blocking: %s", strerror(errno));
    return current_hci_state;
  }

  current_hci_state.state = HCI_STATE_OPEN;

  return current_hci_state;
}
Example #7
0
/**
* @brief 
*
* @return 
*/
int cbeacon_init()
{
  	int device_id = hci_get_route(NULL); // Get device
  	device_handle = start_lescan(device_id);
	g_sd = open_socket(0);
	return  device_handle;
}
Example #8
0
int bt_disconnect(char bdaddr[18])
{
  int err = 0, dd;
  struct hci_conn_info_req *cr = 0;

  // find the connection handle to the specified bluetooth device
  cr = (struct hci_conn_info_req*) malloc(
      sizeof(struct hci_conn_info_req) + sizeof(struct hci_conn_info));
  str2ba(bdaddr, &cr->bdaddr);
  cr->type = ACL_LINK;
  dd = hci_open_dev(hci_get_route(&cr->bdaddr));
  if (dd < 0)
  {
    err = dd;
    goto cleanup;
  }
  err = ioctl(dd, HCIGETCONNINFO, (unsigned long) cr);
  if (err)
    goto cleanup;

  hci_disconnect(dd, cr->conn_info->handle, HCI_OE_USER_ENDED_CONNECTION, HCI_REQ_TIMEOUT);

  cleanup: free(cr);
  if (dd >= 0)
    close(dd);

  return err;
}
Example #9
0
/*
 * Class:     com_example_pmxota_OtaLoadJNI
 * Method:    btDeviceGetName
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_pmxota_OtaLoadJNI_btDeviceGetName(JNIEnv *env, jobject obj, jstring btAddressString) {
	const char *buffer = (*env)->GetStringUTFChars(env, btAddressString, 0);
	bdaddr_t   btAddress;
	char name[248] = {0};
	int dev_id, sock;

	str2ba(buffer, &btAddress);

	dev_id = hci_get_route(NULL);
	sock = hci_open_dev(dev_id);

	// if sock or dev_id returned with error
	if (dev_id<0 || sock<0) {
		close(sock);
		return (*env)->NewStringUTF(env, "[unknown]");
	}

	// Get the name of the remote bt Device
	memset(name, 0, sizeof(name));
	if (hci_read_remote_name(sock, &btAddress, sizeof(name), name, 0) < 0)
		strcpy(name, "[unknown]");

	close(sock);
	return (*env)->NewStringUTF(env, name);
}
Example #10
0
/*
 * Class:     com_example_pmxota_OtaLoadJNI
 * Method:    btDeviceScan
 * Signature: ()[Ljava/lang/String;
 */
JNIEXPORT jobjectArray JNICALL Java_com_example_pmxota_OtaLoadJNI_btDeviceScan(JNIEnv *env, jobject obj) {
	inquiry_info *ii = NULL;
	int max_rsp = 255;
	// length of device scan * 1.25 sec
	int len = 8;
	int num_rsp;
	int dev_id, flags, i;
	char addr[19] = {0};
	char name[248] = {0};
	int bHasError = 0;
	jstring errMsg;    

	jobjectArray btDevices; 

	dev_id = hci_get_route(NULL);
	if (dev_id < 0) {
		bHasError = 1;
		errMsg = (*env)->NewStringUTF(env, "Error obtaining device ID");
	}

	flags = IREQ_CACHE_FLUSH;
	num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
	if (num_rsp < 0)
		perror("hci_inquiry failed");

	btDevices = (*env)->NewObjectArray(env, num_rsp, (*env)->FindClass(env, "java/lang/String"), (*env)->NewStringUTF(env, ""));

	for (i=0; i<num_rsp; i++) {
		ba2str(&(ii+i)->bdaddr, addr);

		(*env)->SetObjectArrayElement(env, btDevices, i, (*env)->NewStringUTF(env, addr));
	}
	return btDevices;
}
Example #11
0
/**
 *	@brief Find a wiimote or wiimotes.
 *
 *	@param wm			An array of wiimote_t structures.
 *	@param max_wiimotes	The number of wiimote structures in \a wm.
 *	@param timeout		The number of seconds before the search times out.
 *
 *	@return The number of wiimotes found.
 *
 *	@see wiimote_connect()
 *
 *	This function will only look for wiimote devices.						\n
 *	When a device is found the address in the structures will be set.		\n
 *	You can then call wiimote_connect() to connect to the found				\n
 *	devices.
 */
int wiic_find(struct wiimote_t** wm, int max_wiimotes, int timeout) {
    int device_id;
    int device_sock;
    int found_devices;
    int found_wiimotes;

    /* reset all wiimote bluetooth device addresses */
    for (found_wiimotes = 0; found_wiimotes < max_wiimotes; ++found_wiimotes)
        wm[found_wiimotes]->bdaddr = *BDADDR_ANY;
    found_wiimotes = 0;

    /* get the id of the first bluetooth device. */
    device_id = hci_get_route(NULL);
    if (device_id < 0) {
        perror("hci_get_route");
        return 0;
    }

    /* create a socket to the device */
    device_sock = hci_open_dev(device_id);
    if (device_sock < 0) {
        perror("hci_open_dev");
        return 0;
    }

    inquiry_info scan_info_arr[128];
    inquiry_info* scan_info = scan_info_arr;
    memset(&scan_info_arr, 0, sizeof(scan_info_arr));

    /* scan for bluetooth devices for 'timeout' seconds */
    found_devices = hci_inquiry(device_id, timeout, 128, NULL, &scan_info, IREQ_CACHE_FLUSH);
    if (found_devices < 0) {
        perror("hci_inquiry");
        return 0;
    }

    WIIC_INFO("Found %i bluetooth device(s).", found_devices);

    int i = 0;

    /* display discovered devices */
    for (; (i < found_devices) && (found_wiimotes < max_wiimotes); ++i) {
        if ((scan_info[i].dev_class[0] == WM_DEV_CLASS_0) &&
                (scan_info[i].dev_class[1] == WM_DEV_CLASS_1) &&
                (scan_info[i].dev_class[2] == WM_DEV_CLASS_2))
        {
            /* found a device */
            ba2str(&scan_info[i].bdaddr, wm[found_wiimotes]->bdaddr_str);

            WIIC_INFO("Found wiimote (%s) [id %i].", wm[found_wiimotes]->bdaddr_str, wm[found_wiimotes]->unid);

            wm[found_wiimotes]->bdaddr = scan_info[i].bdaddr;
            WIIMOTE_ENABLE_STATE(wm[found_wiimotes], WIIMOTE_STATE_DEV_FOUND);
            ++found_wiimotes;
        }
    }

    close(device_sock);
    return found_wiimotes;
}
Example #12
0
// If controler == NULL, we take the first present available BT adaptator.
hci_socket_t open_hci_socket(bdaddr_t *controller) {
    hci_socket_t result;
    memset(&result, 0, sizeof(result));

    if (controller) {
        char add[18];
        ba2str(controller, add);
        result.dev_id = hci_devid(add);
    } else {
        result.dev_id = hci_get_route(NULL);
    }

    if (result.dev_id < 0) {
        perror("open_hci_socket");
        result.sock = -1;
        return result;
    }

    result.sock = hci_open_dev(result.dev_id);
    if (result.sock < 0) {
        perror("open_hci_socket");
        result.sock = -1;
        return result;
    }

    return result;
}
Example #13
0
HCI::HCI(const char *bdaddr) : device(bdaddr, 0) {
  _dev_id = hci_get_route(&this->bdaddr);

  _hci_sock = hci_open_dev(_dev_id);
  if (_dev_id < 0 || _hci_sock < 0) {
    err::code = err::LIB_SYS;
  }
}
Example #14
0
static int l2cap_bluez_get_devid(bdaddr_t * ba_dst, int * devid)
{
    *devid = hci_get_route(ba_dst);
    if(*devid < 0)
    {
        fprintf(stderr, "can't get device id for destination\n");
        return -1;
    }
    return 0;
}
Example #15
0
HCI::HCI() : device() {
  _dev_id = hci_get_route(nullptr);

  _hci_sock = hci_open_dev(_dev_id);
  if (_dev_id < 0 || _hci_sock < 0) {
    err::code = err::LIB_SYS;
  }

  hci_devba(_dev_id, &this->bdaddr);
}
Example #16
0
static int l2cap_do_connect(struct sock *sk)
{
	bdaddr_t *src = &bluez_pi(sk)->src;
	bdaddr_t *dst = &bluez_pi(sk)->dst;
	struct l2cap_conn *conn;
	struct hci_conn   *hcon;
	struct hci_dev    *hdev;
	int err = 0;

	BT_DBG("%s -> %s psm 0x%2.2x", batostr(src), batostr(dst), l2cap_pi(sk)->psm);

	if (!(hdev = hci_get_route(dst, src)))
		return -EHOSTUNREACH;

	hci_dev_lock_bh(hdev);

	err = -ENOMEM;

	hcon = hci_connect(hdev, ACL_LINK, dst);
	if (!hcon)
		goto done;

	conn = l2cap_conn_add(hcon, 0);
	if (!conn) {
		hci_conn_put(hcon);
		goto done;
	}

	err = 0;

	/* Update source addr of the socket */
	bacpy(src, conn->src);

	l2cap_chan_add(conn, sk, NULL);

	sk->state = BT_CONNECT;
	l2cap_sock_set_timer(sk, sk->sndtimeo);

	if (hcon->state == BT_CONNECTED) {
		if (sk->type == SOCK_SEQPACKET) {
			l2cap_conn_req req;
			req.scid = __cpu_to_le16(l2cap_pi(sk)->scid);
			req.psm  = l2cap_pi(sk)->psm;
			l2cap_send_req(conn, L2CAP_CONN_REQ, L2CAP_CONN_REQ_SIZE, &req);
		} else {
			l2cap_sock_clear_timer(sk);
			sk->state = BT_CONNECTED;
		}
	}

done:
	hci_dev_unlock_bh(hdev);
	hci_dev_put(hdev);
	return err;
}
int main(int argc, char **argv)
{
    int dev_id;
    int err, opt, dd;
    uint8_t own_type = 0x00;
    uint8_t scan_type = 0x01;
    uint8_t filter_type = 0;
    uint8_t filter_policy = 0x00;
    uint16_t interval = htobs(0x0010);
    uint16_t window = htobs(0x0010);
    // uint8_t filter_dup = 1;
    uint8_t filter_dup = 0; // don't filter duplicate

    dev_id = hci_get_route(NULL);
    dd = hci_open_dev( dev_id );
    if (dev_id < 0 || dd < 0) {
        perror("opening socket");
        exit(1);
    }



    err = hci_le_set_scan_parameters(dd, scan_type, interval, window,
            own_type, filter_policy, 1000);

    if (err < 0) {
        perror("Set scan parameters failed");
    }

    err = hci_le_set_scan_enable(dd, 0x01, filter_dup, 1000);

    if (err < 0) {
        perror("Enable scan failed");
        exit(1);
    }

    printf("LE Scan ... \n");

    err = print_advertising_devices(dd, filter_type);

    if (err < 0) {
        perror("Could not receive advertising events");
        exit(1);
    }

    err = hci_le_set_scan_enable(dd, 0x00, filter_dup, 1000);
    if (err < 0) {
        perror("Disable scan failed");
        exit(1);
    }

    hci_close_dev(dd);
   
    return 0;
}
Example #18
0
int main(int argc, char *argv[]) {
	int dev_id;
	int ret;

	if (argc == 1) {
		dev_id = hci_get_route(NULL);
	} else if (argc == 2) {
		dev_id = hci_devid(argv[1]);
	} else {
		fprintf(stderr, "%s [<bluetooth-adapter>]\n", argv[0]);
		return 1;
	}
	if (dev_id < 0) {
		fprintf(stderr, "ERROR: Invalid device.\n");
		return 1;
	}

	LIST_INIT(&g_ble_connections);

	device_desc = hci_open_dev(dev_id);
	if (device_desc < 0) {
		fprintf(stderr, "ERROR: Could not open device.\n");
		return 1;
	}

	ret = ble_scan_enable(device_desc);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Scanning fail.\n");
		return 1;
	}

	pthread_mutex_lock(&g_mutex);
	ret = ble_scan(device_desc, ble_discovered_device, BLE_SCAN_TIMEOUT);
	if (ret != 0) {
		fprintf(stderr, "ERROR: Advertisement fail.\n");
		return 1;
	}

	ble_scan_disable(device_desc);

	puts("Scan completed");
	pthread_mutex_unlock(&g_mutex);

	// Wait for the thread to complete
	while (g_ble_connections.lh_first != NULL) {
		struct connection_t* connection = g_ble_connections.lh_first;
		pthread_join(connection->thread, NULL);
		LIST_REMOVE(g_ble_connections.lh_first, entries);
		free(connection->addr);
		free(connection);
	}

	return 0;
}
Example #19
0
/** send_hciCmd Function
 *  This function takes the hci commands for the BT chip configurations, creates 
 *  a hci channel to send the commadns through UART to configure BT chip
 *
 *  Parameters :
 *  @ dev_id            : HCI device ID
 *  @ command_length    : Number of arguments of the command
 *  @ command           : Pointer to command list
 *  Returns 0 upon success
 *        , different error messages depending upon the error.
 */
static void send_hciCmd(int dev_id, int command_length, char **command)
{
        unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr = buf;
        struct hci_filter flt;
        hci_event_hdr *hdr;
        int i, opt, len, dd;
        uint16_t ocf;
        uint8_t ogf;
        
        if (dev_id < 0)
                dev_id = hci_get_route(NULL);

        errno = 0;
        ogf = strtol(command[0], NULL, 16);
        ocf = strtol(command[1], NULL, 16);

        for (i = 2, len = 0; i < command_length && len < sizeof(buf); i++, len++)
                *ptr++ = (uint8_t) strtol(command[i], NULL, 16);

        dd = hci_open_dev(dev_id);
        if (dd < 0) {
                perror("Device open failed");
                return;
        }

        /* Setup filter */
        hci_filter_clear(&flt);
        hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
        hci_filter_all_events(&flt);
        if (setsockopt(dd, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
                perror("HCI filter setup failed");
                return;
        }

	    /* Send the BT chip configuration commands */
        if (hci_send_cmd(dd, ogf, ocf, len, buf) < 0) {
                perror("Send failed");
                return;
        }

	    /* Wait for the command completion event */
        len = read(dd, buf, sizeof(buf));
        if (len < 0) {
                perror("Read failed");
                return;
        }

        hdr = (void *)(buf + 1);
        ptr = buf + (1 + HCI_EVENT_HDR_SIZE);
        len -= (1 + HCI_EVENT_HDR_SIZE);

        hci_close_dev(dd);
}
Example #20
0
size_t bro_bt_scan_devices (bro_bt_device_t *devices[MAX_BT_DEVICES])
{
    inquiry_info *scan_res = NULL;
    size_t num_rsp;
    int dev_id, sock, flags;
    int i;
    char addr[19] = { 0 };
    char name[248] = { 0 };
    
    flags = IREQ_CACHE_FLUSH;
    
    // Initializing BT Device for scan
    dev_id = hci_get_route(NULL);
    sock = hci_open_dev( dev_id );
    
    if (dev_id < 0 || sock < 0) {
      perror("opening socket");
      return -1;
    }

    memset(devices, 0, MAX_BT_DEVICES * sizeof(bro_bt_device_t *));
    
    // Allocate memory for all the devices found
    scan_res = (inquiry_info*)malloc(MAX_BT_DEVICES * sizeof(inquiry_info));
    
    // Scan to find all the devices in range
    num_rsp = hci_inquiry(dev_id, BT_INQUIRY_LEN, MAX_BT_DEVICES, NULL,
                          &scan_res, flags);
    if( num_rsp < 0 ) {
        perror("hci_inquiry");
        return -1;
    }

    // For each of the found devices we retrieve its name
    for (i = 0; i < num_rsp; i++) {
      ba2str(&scan_res[i].bdaddr, addr);
      memset(name, 0, sizeof(name));
      if (hci_read_remote_name(sock, &scan_res[i].bdaddr, sizeof(name), 
          name, 0) < 0) {
        strcpy(name, "[unknown]");
      };
      //devices[i]->name = strdup(name);      // todo FREE on devices elements
      devices[i] = malloc(sizeof(bro_bt_device_t));
      strcpy(devices[i]->name, name);
      memcpy (&devices[i]->mac, &scan_res[i].bdaddr, sizeof(bdaddr_t));
    }

    free( scan_res );
    close( sock );
    return num_rsp;
}
Example #21
0
VALUE method_scan(int argc, VALUE *argv, VALUE klass)
{
  VALUE rb_device_id;
  int device_id;
  int device_handle;
  uint8_t scan_type = 0x01; //passive
  uint8_t own_type = 0x00; // I think this specifies not to use a random MAC
  uint8_t filter_dups = 0x00;
  uint8_t filter_policy = 0x00; // ?
  uint16_t interval = htobs(0x0005);
  uint16_t window = htobs(0x0005);

  struct hci_filter new_filter;
  socklen_t filter_size;

  // which device was specified?
  rb_scan_args(argc, argv, "01", &rb_device_id);
  if (rb_device_id == Qnil) {
    device_id = hci_get_route(NULL);
  } else {
    device_id = NUM2INT(rb_device_id);
  }
  // open the device
  if ( (device_handle = hci_open_dev(device_id)) < 0) {
    rb_raise(rb_eException, "Could not open device");
  }
  device_handles[device_id] = device_handle;
 
  // save the old filter so we can restore it later
  filter_size = sizeof(stored_filters[0]);
  if (getsockopt(device_handle, SOL_HCI, HCI_FILTER, &stored_filters[device_id], &filter_size) < 0) {
    rb_raise(rb_eException, "Could not get socket options");
  }

  // new filter to only look for event packets
  hci_filter_clear(&new_filter);
  hci_filter_set_ptype(HCI_EVENT_PKT, &new_filter);
  hci_filter_set_event(EVT_LE_META_EVENT, &new_filter);
  if (setsockopt(device_handle, SOL_HCI, HCI_FILTER, &new_filter, sizeof(new_filter)) < 0) {
    rb_raise(rb_eException, "Could not set socket options");
  }

  // set the params
  hci_le_set_scan_parameters(device_handle, scan_type, interval, window, own_type, filter_policy, 1000);
  hci_le_set_scan_enable(device_handle, 0x01, filter_dups, 1000);

  // perform the scan and make sure device gets put back into a proper state
  // even in the case of being interrupted by a ruby exception
  rb_ensure(perform_scan, INT2FIX(device_id), stop_scan, INT2FIX(device_id));
  return Qnil;
}
Example #22
0
int main(int argc, char* argv[])
{
	// An arr. of struct, later, contains devices data
	inquiry_info* devices = NULL;
	int max_rsp, num_rsp;
	int adapter_id, sock, len, flags;
	int i;
	// Temp variable to hold each addr and name of device
	char addr[19] = {0};
	char name[248] = {0};

	// Open bluetooth gate (to external env), and connect the socket
	adapter_id = hci_get_route(NULL);
	sock = hci_open_dev(adapter_id);
	if(adapter_id < 0 || sock < 0) {
		perror("opening socket");
		exit(1);
	}
	
	len = 8;
	max_rsp = 255;
	flags = IREQ_CACHE_FLUSH;
	devices = (inquiry_info*) malloc(max_rsp * sizeof(inquiry_info));
	
	// num_rsp: the number of remote device detected
	num_rsp = hci_inquiry(adapter_id, len, max_rsp, NULL, &devices, flags);
	if(num_rsp < 0) {
		perror("hci_inquiry");
	}
	
	for(i = 0; i < num_rsp; i++) {
		/*
		 * Convert struct bdaddr_t (contains only uchar[6]) into hexadec string.
		 * Other func, str2ba() do otherwise.
		 */
		ba2str(&(devices+i)->bdaddr, addr);
		memset(name, 0, sizeof(name));
		// See "not equal" (!=) comparison
		if(hci_read_remote_name(sock, &(devices+i)->bdaddr, sizeof(name), 
		                        name, 0) != 0) {
			strcpy(name, "[unknown]");
		}
		// Print device found
		printf("%s %s\n", addr, name);
	}
	
	free(devices);
	close(sock);
	
	return 0;
}
Example #23
0
int bt_start_server(int *s_sock)
{
    int dev_id;

    dev_id  = hci_get_route(NULL);
    *s_sock = hci_open_dev(dev_id);

    if( dev_id < 0 || *s_sock < 0)
    {
        perror("server: error opening bt socket\n");
        return -1;
    }
    return dev_id;
}
Example #24
0
int main(int argc, char *argv[])
{
	bdaddr_t src, dst;
	int opt, sk, dev_id;

	if (argc < 2) {
		usage();
		exit(0);
	}

	bacpy(&src, BDADDR_ANY);
	dev_id = hci_get_route(&src);
	if ((dev_id < 0) || (hci_devba(dev_id, &src) < 0)) {
		printf("Cannot find any local adapter\n");
		exit(-1);
	}

	while ((opt = getopt_long(argc, argv, "+i:h", main_options, NULL)) != -1) {
		switch (opt) {
		case 'i':
			if (!strncmp(optarg, "hci", 3))
				hci_devba(atoi(optarg + 3), &src);
			else
				str2ba(optarg, &src);
			break;

		case 'h':
		default:
			usage();
			exit(0);
		}
	}

	printf("Connecting ... \n");

	if (bachk(argv[optind]) < 0) {
		printf("Invalid argument\n");
		exit(1);
	}

	str2ba(argv[optind], &dst);
	sk = l2cap_connect(&src, &dst);
	if (sk < 0)
		exit(1);

	if (avdtp_discover(sk) < 0)
		exit(1);

	return 0;
}
Example #25
0
File: ble.c Project: dhn/ble
void
disconnect_from_device(int dev_id, uint16_t handle)
{
    if (dev_id < 0)
        dev_id = hci_get_route(NULL);

    if ((typ.dd = hci_open_dev(dev_id)) < 0)
        die("Could not open device\n");

    typ.err = hci_disconnect(typ.dd, handle, HCI_OE_USER_ENDED_CONNECTION, 10000);
    if (typ.err < 0)
        die("Could not disconnect\n");

    hci_close_dev(typ.dd);
}
Example #26
0
/*
 * Class:     com_example_pmxota_OtaLoadJNI
 * Method:    setupClient
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_com_example_pmxota_OtaLoadJNI_setupClientSocket(JNIEnv *env, jobject obj) {
	if (hci_get_route(NULL) < 0) {
		return -1;
	}
	// Open connection to Service Descovery Protokoll Server
	//if (sdp_open() < 0)
	//	return -2;
	// Add the HID Service
	//sdp_add_keyboard();
	//return init_sdp_server(0,0);
	
	// Initialize the bluetooth L2CAP connection
	init_server();
	return 0;
}
Example #27
0
int get_device_id(char* bdaddr)
{
  int id = 0;

  if(bdaddr)
  {
    id = hci_devid(bdaddr);
  }
  else
  {
    id = hci_get_route(NULL);
  }

  return id;
}
Example #28
0
int sco_connect(struct sock *sk)
{
	bdaddr_t *src = &bluez_pi(sk)->src;
	bdaddr_t *dst = &bluez_pi(sk)->dst;
	struct sco_conn *conn;
	struct hci_conn *hcon;
	struct hci_dev  *hdev;
	int err = 0;

	BT_DBG("%s -> %s", batostr(src), batostr(dst));

	if (!(hdev = hci_get_route(dst, src)))
		return -EHOSTUNREACH;

	hci_dev_lock_bh(hdev);

	err = -ENOMEM;

	hcon = hci_connect(hdev, SCO_LINK, dst);
	if (!hcon)
		goto done;

	conn = sco_conn_add(hcon, 0);
	if (!conn) {
		hci_conn_put(hcon);
		goto done;
	}

	/* Update source addr of the socket */
	bacpy(src, conn->src);

	err = sco_chan_add(conn, sk, NULL);
	if (err)
		goto done;

	if (hcon->state == BT_CONNECTED) {
		sco_sock_clear_timer(sk);
		sk->state = BT_CONNECTED;
	} else {
		sk->state = BT_CONNECT;
		sco_sock_set_timer(sk, sk->sndtimeo);
	}
done:
	hci_dev_unlock_bh(hdev);
	hci_dev_put(hdev);
	return err;
}
Example #29
0
int main(int argc, char** argv)
{
  if (argc != 2)
  {
    std::cout << "argument required" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    int dev_id;

    dev_id = hci_get_route(NULL);
    if (dev_id < 0) 
    {
      perror("Device is not available");
      exit(1);
    }

    std::cout << "connecting to: " << argv[1] << std::endl;
    bdaddr_t bdaddr;
    str2ba(argv[1], &bdaddr);

    int dd;
    dd = hci_open_dev(dev_id);
    if (dd < 0)
    {
      perror("hci_open_dev() failed");
      exit(1);
    }

    if (hci_authenticate_link(dd, htobs(cr->conn_info->handle), 25000) < 0) 
    {
      perror("HCI authentication request failed");
      exit(1);
    }

    if (hci_close_dev(dd) < 0)
    {
      perror("hci_close_dev()");
      exit(1);
    }

    return 0;
  }
}
Example #30
0
WiimoteScannerLinux::WiimoteScannerLinux() : m_device_id(-1), m_device_sock(-1)
{
  // Get the id of the first Bluetooth device.
  m_device_id = hci_get_route(nullptr);
  if (m_device_id < 0)
  {
    NOTICE_LOG(WIIMOTE, "Bluetooth not found.");
    return;
  }

  // Create a socket to the device
  m_device_sock = hci_open_dev(m_device_id);
  if (m_device_sock < 0)
  {
    ERROR_LOG(WIIMOTE, "Unable to open Bluetooth.");
    return;
  }
}