コード例 #1
0
def readTilt(cache):
    dev_id = 0
    while True:
        try:
            logTilt("Starting Bluetooth connection")

            sock = bluez.hci_open_dev(dev_id)
            blescan.hci_le_set_scan_parameters(sock)
            blescan.hci_enable_le_scan(sock)

            while True:
                beacons = distinct(blescan.parse_events(sock, 10))
                for beacon in beacons:
                    if beacon['uuid'] in list(TILTS.keys()):
                        cache[TILTS[beacon['uuid']]] = {
                            'Temp': beacon['major'],
                            'Gravity': beacon['minor']
                        }
                        #logTilt("Tilt data received: Temp %s Gravity %s" % (beacon['major'], beacon['minor']))
                time.sleep(4)
        except Exception as e:
            logTilt("Error starting Bluetooth device, exception: %s" % str(e))

        logTilt("Restarting Bluetooth process in 10 seconds")
        time.sleep(10)
コード例 #2
0
ファイル: spp.py プロジェクト: fhorinek/MotionLog
def perform_scan(dev_id = SCAN_DEVICE):
    sock = bluez.hci_open_dev(dev_id)
    mode = read_inquiry_mode(sock)

    if mode != 1:
        write_inquiry_mode(sock, 1)

    names = {}
    for line in bluetooth.discover_devices(duration=5, lookup_names=True, device_id = dev_id):
        names[line[0].lower()] = line[1]
    
    devices = {}
    for line in device_inquiry_with_with_rssi(sock):
        addr = line[0].lower()
        rssi = line[1]
        if addr in devices:
            devices[addr].append(rssi)
        else:
            devices[addr] = [rssi]
    
    result = {}
    for addr in names:
        name = names[addr]
        if addr not in devices:
            continue
        rssis = devices[addr];
        result[addr] =  [name, sum(rssis) / len(rssis)]
        
    return result
コード例 #3
0
ファイル: brewmonitor.py プロジェクト: tmclane/brewmonitor
def monitor(opts, dev_id=0):
    mqtt_config = {
        'server': opts.mqttserver,
        'port': opts.mqttport if opts.mqttport else PORT,
        'topic_prefix': opts.mqtttopic if opts.mqtttopic else TOPIC_PREFIX
    }
    try:
        sock = bluez.hci_open_dev(dev_id)

    except:
        print("FATAL: Can't access bluetooth device...")
        sys.exit(1)

    hci_le_set_scan_parameters(sock)
    hci_enable_le_scan(sock)

    while True:
        alive = {}
        dead = []
        reports = process_brewometers(sock)
        for addr, report in reports.iteritems():
            now = time.time()
            if now - report['timestamp'] > TIMEOUT:
                dead.append(addr)
            else:
                alive[addr] = report


        if opts.mqttserver:
            publish_mqtt(mqtt_config, alive)

        if dead:
            print("Brewometers: %s are no longer reporting.." % dead)
            for addr in dead:
                del brewometers[addr]
コード例 #4
0
ファイル: btscan.py プロジェクト: circumstance/wimpy
def _gethcisock (device_id = -1):
    try:
        sock = _bt.hci_open_dev (device_id)
	return sock
    except:
	debug("error accessing bluetooth device")
	exit(0)
コード例 #5
0
def set_bt_name(name, src_hci, src, dst):
    """
    Sets the name of the local bluetooth device to 'name'.

    Params:
        - 'name' - The new name of the device
        - 'src_hci' - Name of the bluetooth device to change the name of
        - 'src' - The bluetooth address of the local device
        - 'dst' - Bluetooth address of a remote device to temporarily connect with
                  (sets the REMOTE_NAME in 'dst')
    """
    # Create raw HCI sock to set our BT name
    raw_sock = bt.hci_open_dev(bt.hci_devid(src_hci))
    flt = bt.hci_filter_new()
    bt.hci_filter_all_ptypes(flt)
    bt.hci_filter_all_events(flt)
    raw_sock.setsockopt(bt.SOL_HCI, bt.HCI_FILTER, flt)

    # Send raw HCI command to controller (first 3 bytes are padding for alignment)
    raw_sock.sendall(
        binascii.unhexlify('01130cf8cccccc') +
        name.ljust(MAX_BT_NAME, b'\x00'))
    raw_sock.close()
    time.sleep(0.1)

    # Connect to BNEP to "refresh" the name
    bnep = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bnep.bind((src, 0))
    bnep.connect((dst, BNEP_PSM))
    bnep.close()

    # Close ACL connection again
    util.exec_command_block(["hcitool", "dc", dst])
コード例 #6
0
ファイル: adv_airpods.py プロジェクト: lucferbux/apple_bleee
    def advertisment(self):
        """Get values for the accesories of the airpod and genrates an le advertising with them
        """
        if self.args.random:
            left_speaker, right_speaker, case = self.random_values()
        else:
            left_speaker = (100,)
            right_speaker = (100,)
            case = (100,)

        interval = self.args.interval
        toggle_device(self.args.ble_iface, True)

        data1 = (0x1e, 0xff, 0x4c, 0x00, 0x07, 0x19, 0x01, 0x02, 0x20, 0x75, 0xaa, 0x30, 0x01, 0x00, 0x00, 0x45)
        data2 = (0xda, 0x29, 0x58, 0xab, 0x8d, 0x29, 0x40, 0x3d, 0x5c, 0x1b, 0x93, 0x3a)
        try:
            sock = bluez.hci_open_dev(args.ble_iface)
        except:
            print(f"Cannot open bluetooth device {self.args.ble_iface}")
            return
        try:
            print("Start advertising press ctrl + c to quit...")
            start_le_advertising(sock, adv_type=0x03, min_interval=interval, max_interval=interval,
                                data=(data1 + left_speaker + right_speaker + case + data2))
            while True:
                sleep(2)
        except:
            stop_le_advertising(sock)
            print()
            print("Bye")
コード例 #7
0
def get_RSSI(addr):
    # Open an hci socket
    hci_sock = bluez.hci_open_dev()
    hci_fd = hci_sock.fileno ()

    # Try to open a connection to remote BT device
    try:
        bt_sock = bluez.SDPSession ()
        bt_sock.connect(addr)
    except:
        bt_sock.close()
        hci_sock.close()
        return None
    # Get handle to ACL connection to remote BT device
    reqstr = struct.pack ("6sB17s", bluez.str2ba (addr),
            bluez.ACL_LINK, "\0" * 17)
    request = array.array ("c", reqstr)
    fcntl.ioctl (hci_fd, bluez.HCIGETCONNINFO, request, 1)
    handle = struct.unpack ("8xH14x", request.tostring ())[0]

    # Get RSSI
    cmd_pkt=struct.pack('H', handle)
    RSSI = bluez.hci_send_req(hci_sock, bluez.OGF_STATUS_PARAM,
                           bluez.OCF_READ_RSSI,
                           bluez.EVT_CMD_COMPLETE, 4, cmd_pkt)
    RSSI = struct.unpack('b', RSSI[3])[0]

    bt_sock.close()
    hci_sock.close()
    return RSSI
コード例 #8
0
ファイル: ble_utils.py プロジェクト: jazofra/Airdrop-Crazy
    def adv_airdrop(self):

        while True:
            dev_id = self.dev_id
            toggle_device(dev_id, True)
            header = (0x02, 0x01, 0x1a, 0x1b, 0xff, 0x4c, 0x00)
            data1 = (0x05, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                     0x00, 0x01)
            apple_id = (0x00, 0x00)
            phone = (0x00, 0x00)
            email = (0xb7, 0x9b)
            data2 = (0x00, 0x00, 0x00, 0x10, 0x02, 0x0b, 0x00)
            try:
                sock = bluez.hci_open_dev(dev_id)
            except:
                print("Cannot open bluetooth device %i" % dev_id)
                raise
            start_le_advertising(sock,
                                 adv_type=0x02,
                                 min_interval=500,
                                 max_interval=500,
                                 data=(header + data1 + apple_id + phone +
                                       email + data2))
            time.sleep(10)
            stop_le_advertising(sock)
コード例 #9
0
ファイル: app.py プロジェクト: bluewish/we_iot_demo
 def _open_bluetooth(self):
     try:
         self._dev_sock = bluez.hci_open_dev(0)
     except:
         logging.error("Fail to open bluetooth device.")
         return False
     return True
コード例 #10
0
    def find_local_bdaddr(self):
        dev_id = 0
        hci_sock = _bt.hci_open_dev(dev_id)

        old_filter = hci_sock.getsockopt( _bt.SOL_HCI, _bt.HCI_FILTER, 14)
        flt = _bt.hci_filter_new()
        opcode = _bt.cmd_opcode_pack(_bt.OGF_INFO_PARAM, _bt.OCF_READ_BD_ADDR)
        _bt.hci_filter_set_ptype(flt, _bt.HCI_EVENT_PKT)
        _bt.hci_filter_set_event(flt, _bt.EVT_CMD_COMPLETE);
        _bt.hci_filter_set_opcode(flt, opcode)
        hci_sock.setsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, flt)

        _bt.hci_send_cmd(hci_sock, _bt.OGF_INFO_PARAM, _bt.OCF_READ_BD_ADDR)

        pkt = hci_sock.recv(255)

        status,raw_bdaddr = struct.unpack("xxxxxxB6s", pkt)
        assert status == 0

        t = [ "%X" % ord(b) for b in raw_bdaddr ]
        t.reverse()
        bdaddr = ":".join(t)

        # restore old filter
        hci_sock.setsockopt( _bt.SOL_HCI, _bt.HCI_FILTER, old_filter )
        return bdaddr
コード例 #11
0
def rssi_main():
    dev_id = 0
    try:
        sock = bluez.hci_open_dev(dev_id)
    except:
        print("error accessing bluetooth device...")
        sys.exit(1)

    try:
        mode = read_inquiry_mode(sock)
    except Exception as e:
        print("error reading inquiry mode.  ")
        print("Are you sure this a bluetooth 1.2 device?")
        print(e)
        sys.exit(1)
    print("current inquiry mode is %d" % mode)

    if mode != 1:
        print("writing inquiry mode...")
        try:
            result = write_inquiry_mode(sock, 1)
        except Exception as e:
            print("error writing inquiry mode.  Are you sure you're root?")
            print(e)
            sys.exit(1)
        if result != 0:
            print("error while setting inquiry mode")
        #print("result: %d" % result)

    devs = device_inquiry_with_with_rssi(sock)
    return devs
コード例 #12
0
def setup_bluetooth():

    #Open bluetooth device
    try:
        bt_device = bluez.hci_open_dev(dev_id)
    except Exception as e:
        errorMsg("Error accessing bluetooth device:", e)

    #Read the inquiry mode
    try:
        mode = read_inquiry_mode(bt_device)
    except Exception as e:
        errorMsg("Error reading inquiry mode:", e)

    #Write inquiry mode
    if mode != 1:
        try:
            result = write_inquiry_mode(bt_device, 1)
            if result != 0:
                errorMsg("Error while setting inquiry mode:", None)
        except Exception as e:
            errorMsg("Error writing inquiry mode:", e)

    #Return bluetooth device if setup sucessful
    return bt_device
コード例 #13
0
    def le_set_scan_response_data(
        self,
        cmd_params={
            'Scan_Response_Data_Length': 0x1f,
            'Scan_Response_Data': bytes(0x1f)
        }
    ) -> dict:
        dd = hci_open_dev(self.devid)

        bin_cmd_params = cmd_params['Scan_Response_Data_Length'].to_bytes(1, 'little') + \
            cmd_params['Scan_Response_Data']

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_CMD_COMPLETE)
        hci_filter_set_opcode(
            flt, cmd_opcode_pack(OGF_LE_CTL, OCF_LE_SET_SCAN_RESPONSE_DATA))
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_LE_CTL, OCF_LE_SET_SCAN_RESPONSE_DATA,
                     bin_cmd_params)
        event_params = dd.recv(3 + EVT_CMD_COMPLETE_SIZE + 1)[3:]
        num_hci_cmd_pkts, cmd_opcode, status = struct.unpack(
            '<BHB', event_params)
        event_params = {
            'Num_HCI_Command_Packets': num_hci_cmd_pkts,
            'Command_Opcode': cmd_opcode,
            'Status': status
        }

        hci_close_dev(dd.fileno())
        return event_params
コード例 #14
0
    def getRSSI(self):
        """Detects whether the device is near by or not"""
        addr = self.address
		
        # Open hci socket
        hci_sock = bt.hci_open_dev()
        hci_fd = hci_sock.fileno()

        # Connect to device (to whatever you like)
        bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
        bt_sock.settimeout(10)
        result = bt_sock.connect_ex((addr, 1))	# PSM 1 - Service Discovery

        try:
            # Get ConnInfo
            reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
            request = array.array("c", reqstr )
            handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
            handle = struct.unpack("8xH14x", request.tostring())[0]

            # Get RSSI
            cmd_pkt=struct.pack('H', handle)
            rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                         bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
            rssi = struct.unpack('b', rssi[3])[0]

            # Close sockets
            bt_sock.close()
            hci_sock.close()

            return rssi

        except Exception, e:
            return None
コード例 #15
0
 def _init_bluetooth():
     os.system("sudo hciconfig hci0 down")
     os.system("sudo hciconfig hci0 up")
     try:
         return bluez.hci_open_dev(0)
     except:
         sys.exit(1)
コード例 #16
0
def main():
    dev_id = 0
    try:
        sock = bluez.hci_open_dev(dev_id)
    except:
        print("error accessing bluetooth device...")
        sys.exit(1)

    try:
        mode = read_inquiry_mode(sock)
    except Exception as e:
        print("error reading inquiry mode.  ")
        print("Are you sure this a bluetooth 1.2 device?")
        print(e)
        sys.exit(1)
    #print("current inquiry mode is %d" % mode)

    if mode != 1:
        print("writing inquiry mode...")
        try:
            result = write_inquiry_mode(sock, 1)
        except Exception as e:
            print("error writing inquiry mode.  Are you sure you're root?")
            print(e)
            sys.exit(1)
        if result != 0:
            print("error while setting inquiry mode")
        print("result: %d" % result)

    device_inquiry_with_with_rssi(sock)
コード例 #17
0
ファイル: WeBrew.py プロジェクト: jayjay300/pdp2017
def read_Sg():
    try:
        sock = bluez.hci_open_dev(dev_id)

    except:
        print("error accessing bluetooth device...")
        sys.exit(1)

    blescan.hci_le_set_scan_parameters(sock)
    blescan.hci_enable_le_scan(sock)

    #gotData = 0
    #while (gotData == 0):

    returnedList = blescan.parse_events(sock, 10)

    for beacon in returnedList:  #returnedList is a list datatype of string datatypes seperated by commas (,)
        output = beacon.split(
            ',')  #split the list into individual strings in an array
        if output[1] == green:  #Change this to the colour of you tilt

            #gotData = 1
            tiltSG = int(output[3], 16) / 1000
            print("testing")
            print(tiltSG)
            print("-----")

    blescan.hci_disable_le_scan(sock)
    return tiltSG
コード例 #18
0
def bluetooth_init ():

    dev_id = 0
    try:
        sock = bluez.hci_open_dev(dev_id)
    except:
        print("error accessing bluetooth device...")
        sys.exit(1)

    try:
        mode = read_inquiry_mode(sock)
    except Exception as e:
        print("error reading inquiry mode.  ")
        print("bluetooth is OFF, please turn it ON")
        print(e)
        sys.exit(1)
    #print("current inquiry mode is %d" % mode)

    if mode != 1:
        print("writing inquiry mode...")
        try:
            result = write_inquiry_mode(sock, 1)
        except Exception as e:
            print("error writing inquiry mode.  Are you sure you're root?")
            print(e)
            sys.exit(1)
        if result != 0:
            print("error while setting inquiry mode")
        print("result: %d" % result)
    
    return sock
コード例 #19
0
ファイル: testblescan.py プロジェクト: jiazhongchen/RPiBLE2
def main():

	dev_id = 0
	loadXML()

	try:
		sock = bluez.hci_open_dev(dev_id)
		print "ble thread started"

	except:
		print "error accessing bluetooth device..."
		sys.exit(1)

	blescan.hci_le_set_scan_parameters(sock)
	print "set ble scan parameters"
	blescan.hci_enable_le_scan(sock)
	print "enable ble"

	#blescan.initSerial()

	thread1 = threading.Thread(target = blescan.parse_events, args = (sock, ))
	thread1.start()

	thread2 = threading.Thread(target = blescan.checkAndPrint, args = ( ))
	thread2.start()

	while True:
		time.sleep(1)

		if len(blescan.postList) > 0: #and internet_on():
			#print "now start to post ..."
			lock1 = threading.Lock()
			lock1.acquire()
			#postXML(blescan.postList)
			lock1.release()
コード例 #20
0
def bcm_write_local_bdaddr(adapter: int, dsbtaddr: str) -> None:
    import bluetooth._bluetooth as _bt

    try:
        # Open hci socket
        hci_sock = _bt.hci_open_dev(adapter)

        # Get bytes from bluetooth address
        baddrtospoof = bytearray.fromhex(dsbtaddr.replace(":", ""))
        baddrtospoof.reverse()

        # Send HCI request
        cmd_pkt = bytes(baddrtospoof)

        # BCM WRITE ADDR command
        # https://github.com/pauloborges/bluez/blob/master/tools/bdaddr.c
        _bt.hci_send_req(
            hci_sock,
            _bt.OGF_VENDOR_CMD,
            0x0001,  #OCF_BCM_WRITE_BD_ADDR
            0x00000000,
            1000,
            cmd_pkt)

        hci_sock.close()

    except _bt.error as e:
        raise BluetoothError(*e.args)
コード例 #21
0
    def lookup_name(self,address, device=-1, timeout=10):
      """
      Linux only

      Tries to determine the friendly name (human readable) of the device with
      the specified bluetooth address.  Returns the name on success, and None
      on failure.

      timeout=10   how many seconds to search before giving up.
      """
      logger.debug("Device: %s " % (device))
      if sys.platform == "linux2":
        # NOTE: I had to rewrite this for the latest bluez, 
        # the reason this is complicated is because I need to select the device,
        # before making the call.
        # http://code.google.com/p/pybluez/source/detail?spec=svn27&r=22
        if not bluetooth.is_valid_address(address): 
            raise ValueError("%s is not a valid Bluetooth address" % address)
        
        try:
            sock = _bt.hci_open_dev (device)
        except:
            raise ValueError("error accessing bluetooth device")

        timeoutms = int (timeout * 1000)
        try: 
            name = _bt.hci_read_remote_name (sock, address, timeoutms)
        except _bt.error, e:
            # name lookup failed.  either a timeout, or I/O error
            name = None
            sock.close()
        return name          
コード例 #22
0
    def read_remote_supported_features(self, cmd_params: dict) -> dict:
        '''
        cmd_params -- {'Connection_Handle': 0x0000 to 0x0EFF}
        '''
        dd = hci_open_dev(self.devid)

        bin_cmd_params = cmd_params['Connection_Handle'].to_bytes(2, 'little')

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_READ_REMOTE_FEATURES_COMPLETE)
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_LINK_CTL, OCF_READ_REMOTE_FEATURES,
                     bin_cmd_params)

        while True:
            event_params = dd.recv(3 +
                                   EVT_READ_REMOTE_FEATURES_COMPLETE_SIZE)[3:]
            status, conn_handle, lmp_features = struct.unpack(
                '<BH8s', event_params)
            event_params = {
                'Status': status,
                'Connection_Handle': conn_handle,
                'LMP_Features': lmp_features
            }

            if event_params['Connection_Handle'] == cmd_params[
                    'Connection_Handle']:
                break

        hci_close_dev(dd.fileno())
        return event_params
コード例 #23
0
    def set_event_filter(self, cmd_params: dict) -> dict:
        '''A little complicated. see the core specification 
        BLUETOOTH CORE SPECIFICATION Version 5.2 | Vol 4, Part E page 2078. 
        Only support Filter_Type = 0x00 now.
        '''
        dd = hci_open_dev(self.devid)

        bin_cmd_params = cmd_params['Filter_Type'].to_bytes(1, 'little')

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_CMD_COMPLETE)
        hci_filter_set_opcode(flt,
                              cmd_opcode_pack(OGF_HOST_CTL, OCF_SET_EVENT_FLT))
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_HOST_CTL, OCF_SET_EVENT_FLT, bin_cmd_params)
        event_params = dd.recv(3 + EVT_CMD_COMPLETE_SIZE + 1)[3:]
        num_hci_cmd_pkts, cmd_opcode, status = struct.unpack(
            '<BHB', event_params)
        event_params = {
            'Num_HCI_Command_Packets': num_hci_cmd_pkts,
            'Command_Opcode': cmd_opcode,
            'Status': status
        }

        hci_close_dev(dd.fileno())
        return event_params
コード例 #24
0
    def create_connection_cancel(self, cmd_params: dict) -> dict:
        '''
        cmd_params -- {
            'BD_ADDR': str
        }
        '''
        dd = hci_open_dev(self.devid)

        bin_cmd_params = bytes.fromhex(cmd_params['BD_ADDR'].replace(':',
                                                                     '')[::-1])

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_CMD_COMPLETE)
        hci_filter_set_opcode(
            flt, cmd_opcode_pack(OGF_LINK_CTL, OCF_CREATE_CONN_CANCEL))
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_LINK_CTL, OCF_CREATE_CONN_CANCEL, bin_cmd_params)

        event_params = dd.recv(3 + EVT_CMD_COMPLETE_SIZE + 7)[3:]
        num_hci_cmd_pkts, cmd_opcode, status, \
            bdaddr = struct.unpack('<BHB6s', event_params)

        hci_close_dev(dd.fileno())
        return event_params
コード例 #25
0
    def disconnect(self, cmd_params: dict) -> dict:
        '''
        cmd_params -- {
            'Connection_Handle': int, 2 bytes,
            'Reason': int, 1 bytes
        }
        '''
        dd = hci_open_dev(self.devid)

        flt = hci_filter_new()
        hci_filter_clear(flt)
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_DISCONN_COMPLETE)
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        bin_cmd_params = cmd_params['Connection_Handle'].to_bytes(2, 'little') + \
            cmd_params['Reason'].to_bytes(1, 'little')

        hci_send_cmd(dd, OGF_LINK_CTL, OCF_DISCONNECT, bin_cmd_params)

        # Receive and exclude HCI packet type (1 B)
        event_params = dd.recv(3 + EVT_DISCONN_COMPLETE_SIZE)[3:]
        status, conn_handle, reason, = struct.unpack('<BHB', event_params)

        event_params = {
            'Status': status,
            'Connection_Handle': conn_handle,
            'Reason': reason
        }

        hci_close_dev(dd.fileno())
        return event_params
コード例 #26
0
    def exit_periodic_inquiry_mode(self) -> dict:
        '''
        Return -- {
            'Num_HCI_Command_Packets': int,
            'Command_Opcode': int,
            'Status': int
        }
        '''
        dd = hci_open_dev(self.devid)

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_CMD_COMPLETE)
        hci_filter_set_opcode(
            flt, cmd_opcode_pack(OGF_LINK_CTL, OCF_EXIT_PERIODIC_INQUIRY))
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_LINK_CTL, OCF_EXIT_PERIODIC_INQUIRY)

        event_params = dd.recv(3 + EVT_CMD_COMPLETE_SIZE + 1)[3:]
        num_hci_cmd_pkts, cmd_opcode, status = struct.unpack(
            '<BHB', event_params)
        event_params = {
            'Num_HCI_Command_Packets': num_hci_cmd_pkts,
            'Command_Opcode': cmd_opcode,
            'Status': status
        }

        hci_close_dev(dd.fileno())
        return status
コード例 #27
0
    def read_bd_addr(self) -> dict:
        r"""'Return BD_ADDR string "XX:XX:XX:XX:XX:XX'"""
        dd = hci_open_dev(self.devid)

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_CMD_COMPLETE)
        hci_filter_set_opcode(
            flt, cmd_opcode_pack(OGF_INFO_PARAM, OCF_READ_BD_ADDR))
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_INFO_PARAM, OCF_READ_BD_ADDR)
        event_params = dd.recv(HCI_MAX_EVENT_SIZE)[3:]
        num_hci_cmd_pkts, cmd_opcode, status, bd_addr = struct.unpack(
            "<BHB6s", event_params)
        bd_addr = ["%02X" % b for b in bd_addr]
        bd_addr.reverse()
        event_params = {
            'Num_HCI_Command_Packets': num_hci_cmd_pkts,
            'Command_Opcode': cmd_opcode,
            'Status': status,
            'BD_ADDR': ':'.join(bd_addr)
        }

        hci_close_dev(dd.fileno())
        return event_params
コード例 #28
0
def read_local_bdaddr():
    try:
        hci_sock = _bt.hci_open_dev(0)
        old_filter = hci_sock.getsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, 14)
        flt = _bt.hci_filter_new()
        opcode = _bt.cmd_opcode_pack(_bt.OGF_INFO_PARAM, _bt.OCF_READ_BD_ADDR)
        _bt.hci_filter_set_ptype(flt, _bt.HCI_EVENT_PKT)
        _bt.hci_filter_set_event(flt, _bt.EVT_CMD_COMPLETE)
        _bt.hci_filter_set_opcode(flt, opcode)
        hci_sock.setsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, flt)

        _bt.hci_send_cmd(hci_sock, _bt.OGF_INFO_PARAM, _bt.OCF_READ_BD_ADDR)

        pkt = hci_sock.recv(255)

        status, raw_bdaddr = struct.unpack("xxxxxxB6s", pkt)
        assert status == 0

        t = ["%02X" % get_byte(b) for b in raw_bdaddr]
        t.reverse()
        bdaddr = ":".join(t)

        # restore old filter
        hci_sock.setsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, old_filter)
        return [bdaddr]
    except _bt.error as e:
        raise BluetoothError(*e.args)
コード例 #29
0
    def getRSSI(self):
        """Detects whether the device is near by or not using RSSI"""
        addr = self.address
		
        # Open hci socket
        hci_sock = bt.hci_open_dev()
        hci_fd = hci_sock.fileno()

        # Connect to device (to whatever you like)
        bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
        bt_sock.settimeout(10)
        result = bt_sock.connect_ex((addr, 1))	# PSM 1 - Service Discovery

        try:
            # Get ConnInfo
            reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
            request = array.array("c", reqstr )
            handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
            handle = struct.unpack("8xH14x", request.tostring())[0]

            # Get RSSI
            cmd_pkt=struct.pack('H', handle)
            rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                         bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
            rssi = struct.unpack('b', rssi[3])[0]

            # Close sockets
            bt_sock.close()
            hci_sock.close()

            return rssi

        except Exception, e:
            #self.logger.error("<Bluetooth> (getRSSI) %s" % (repr(e)))
            return None
コード例 #30
0
ファイル: nuki.py プロジェクト: dauden1184/nukiPyBridge
	def isNewNukiStateAvailable(self):
		if self.device != None:
			self.device.disconnect()
			self.device = None
		dev_id = 0
		try:
			sock = bluez.hci_open_dev(dev_id)
		except:
			print "error accessing bluetooth device..."
			sys.exit(1)
		blescan.hci_le_set_scan_parameters(sock)
		blescan.hci_enable_le_scan(sock)
		returnedList = blescan.parse_events(sock, 10)
		newStateAvailable = -1
		print "isNewNukiStateAvailable() -> search through %d received beacons..." % len(returnedList)
		for beacon in returnedList:
			beaconElements = beacon.split(',')
			if beaconElements[0] == self.macAddress.lower() and beaconElements[1] == "a92ee200550111e4916c0800200c9a66":
				print "Nuki beacon found, new state element: %s" % beaconElements[4]
				if beaconElements[4] == '-60':
					newStateAvailable = 0
				else:
					newStateAvailable = 1
				break
			else:
				print "non-Nuki beacon found: mac=%s, signature=%s" % (beaconElements[0],beaconElements[1])
		print "isNewNukiStateAvailable() -> result=%d" % newStateAvailable
		return newStateAvailable
コード例 #31
0
        def lookup_name(self, address, device=-1, timeout=10):
            """
      Linux only

      Tries to determine the friendly name (human readable) of the device with
      the specified bluetooth address.  Returns the name on success, and None
      on failure.

      timeout=10   how many seconds to search before giving up.
      """
            logger.debug("Device: %s " % (device))
            if sys.platform == "linux2":
                # NOTE: I had to rewrite this for the latest bluez,
                # the reason this is complicated is because I need to select the device,
                # before making the call.
                # http://code.google.com/p/pybluez/source/detail?spec=svn27&r=22
                if not bluetooth.is_valid_address(address):
                    raise ValueError("%s is not a valid Bluetooth address" %
                                     address)

                try:
                    sock = _bt.hci_open_dev(device)
                except:
                    raise ValueError("error accessing bluetooth device")

                timeoutms = int(timeout * 1000)
                try:
                    name = _bt.hci_read_remote_name(sock, address, timeoutms)
                except _bt.error, e:
                    # name lookup failed.  either a timeout, or I/O error
                    name = None
                    sock.close()
                return name
コード例 #32
0
ファイル: scanner.py プロジェクト: bassie8881/ROS_stuff
    def __init__(self):
        rospy.init_node("blescanner", anonymous=True)

        dev_id = 0
        try:
            self.sock = bluez.hci_open_dev(dev_id)
            print "ble thread started"
        except:
            print "error accessing bluetooth device..."
            sys.exit(1)

        blescan.hci_le_set_scan_parameters(self.sock)
        blescan.hci_enable_le_scan(self.sock)

        self.pub = rospy.Publisher('ble_data', BLEData, queue_size=10, latch=True)

        while not rospy.is_shutdown():
            self.returnedList = blescan.parse_events(self.sock, 10)
            msg = BLEData()
            msg.header.stamp = rospy.Time.now()
            for beacon in self.returnedList:
                submsg = BLEBeacon()
                submsg.mac_address = beacon[0:17]
                submsg.rssi = int(beacon[-3:])
                msg.data.append(submsg)
                # print submsg
                # print "MAC ADDRESS: ", beacon[0:17]
                # print "RSSI: ", beacon[-3:]
                # print beacon

            self.pub.publish(msg)
コード例 #33
0
ファイル: TiltHydrometer.py プロジェクト: rorikmelberg/Hub
    def scan(self):
        try:
            sock = bluez.hci_open_dev(self.dev_id)

        except Exception, e:
            print "ERROR: Accessing bluetooth device: " + e.message
            sys.exit(1)
コード例 #34
0
def bluetooth_rssi(addr):
    # Open hci socket
    hci_sock = bt.hci_open_dev()
    hci_fd = hci_sock.fileno()

    # Connect to device (to whatever you like)
    bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bt_sock.settimeout(10)
    result = bt_sock.connect_ex((addr, 1))  # PSM 1 - Service Discovery

    try:
        # Get ConnInfo
        reqstr = struct.pack("6sB17s", bt.str2ba(addr), bt.ACL_LINK, "\0" * 17)
        request = array.array("c", reqstr)
        handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
        handle = struct.unpack("8xH14x", request.tostring())[0]

        # Get RSSI
        cmd_pkt = struct.pack('H', handle)
        rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM, bt.OCF_READ_RSSI,
                               bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
        rssi = struct.unpack('b', rssi[3])[0]

        # Close sockets
        bt_sock.close()
        hci_sock.close()

        return rssi

    except:
        return None
コード例 #35
0
    def scan(self):
        try:
            sock = bluez.hci_open_dev(self.dev_id)

        except:
            print "error accessing bluetooth device..."
            sys.exit(1)

        blescan.hci_le_set_scan_parameters(sock)
        blescan.hci_enable_le_scan(sock)
        
        #Keep scanning until the manager is told to stop.
        while self.scanning:
            
            returnedList = blescan.parse_events(sock, 10)
            
            for beacon in returnedList:
                beaconParts = beacon.split(",")
                
                #Resolve whether the received BLE event is for a brewometer by looking at the UUID.
                name = self.brewometerName(beaconParts[1])
                
                #If the event is for a brewometer, process the data
                if name is not None:
                    #Get the temperature and convert to C if needed.
                    temperature = beaconParts[2]
                    if not self.inFarenheight:
                        temperature = self.convertFtoC(temperature)
                    
                    #Get the gravity.
                    gravity = self.convertSG(beaconParts[3])
                    
                    #Store the retrieved values in the relevant brewometer object.
                    self.storeValue(name, temperature, gravity)
コード例 #36
0
    def scan(self):
        try:
            sock = bluez.hci_open_dev(self.dev_id)

        except:
            print "error accessing bluetooth device..."
            sys.exit(1)

        blescan.hci_le_set_scan_parameters(sock)
        blescan.hci_enable_le_scan(sock)

        #Keep scanning until the manager is told to stop.
        while self.scanning:

            returnedList = blescan.parse_events(sock, 10)

            for beacon in returnedList:
                beaconParts = beacon.split(",")

                #Resolve whether the received BLE event is for a brewometer by looking at the UUID.
                name = self.brewometerName(beaconParts[1])

                #If the event is for a brewometer, process the data
                if name is not None:
                    #Get the temperature and convert to C if needed.
                    temperature = beaconParts[2]
                    if not self.inFarenheight:
                        temperature = self.convertFtoC(temperature)

                    #Get the gravity.
                    gravity = self.convertSG(beaconParts[3])

                    #Store the retrieved values in the relevant brewometer object.
                    self.storeValue(name, temperature, gravity)
コード例 #37
0
    def le_set_advertising_enable(self,
                                  cmd_params={'Advertising_Enable':
                                              0x00}) -> dict:
        dd = hci_open_dev(self.devid)

        bin_cmd_params = cmd_params['Advertising_Enable'].to_bytes(1, 'little')

        flt = hci_filter_new()
        hci_filter_set_ptype(flt, HCI_EVENT_PKT)
        hci_filter_set_event(flt, EVT_CMD_COMPLETE)
        hci_filter_set_opcode(
            flt, cmd_opcode_pack(OGF_LE_CTL, OCF_LE_SET_ADVERTISING_ENABLE))
        dd.setsockopt(SOL_HCI, HCI_FILTER, flt)

        hci_send_cmd(dd, OGF_LE_CTL, OCF_LE_SET_ADVERTISING_ENABLE,
                     bin_cmd_params)
        event_params = dd.recv(3 + EVT_CMD_COMPLETE_SIZE + 1)[3:]
        num_hci_cmd_pkts, cmd_opcode, status = struct.unpack(
            '<BHB', event_params)
        event_params = {
            'Num_HCI_Command_Packets': num_hci_cmd_pkts,
            'Command_Opcode': cmd_opcode,
            'Status': status
        }

        hci_close_dev(dd.fileno())
        return event_params
コード例 #38
0
def get_RSSI_and_TX(iterations, authorized):
    # Value containers
    rssi_list = []
    tx_power_list = []
    rssi = 0
    tx_power = 0

    # Open BLE socket
    try:
        sock = bluez.hci_open_dev(0)
        print("Start BLE communication")

    except:
        print("error accessing bluetooth device...")
        sys.exit(1)

    hci_le_set_scan_parameters(sock)
    hci_enable_le_scan(sock)

    # Loop to scan the beacons
    for x in range(iterations):
        returnedList = parse_events(sock, 10)
        for beacon in returnedList:
            details = beacon.split(',')
            #print(details)
            if details[0] in authorized:
                rssi_list.append(details[5])
                tx_power_list.append(details[4])

    if len(rssi_list) > 0 or len(tx_power_list) > 0:
        rssi = max(set(rssi_list), key=rssi_list.count)
        tx_power = max(set(tx_power_list), key=tx_power_list.count)

    return int(rssi), int(tx_power)
コード例 #39
0
    def _find_local_bdaddr(self):
        dev_id = 0
        hci_sock = _bt.hci_open_dev(dev_id)

        old_filter = hci_sock.getsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, 14)
        flt = _bt.hci_filter_new()
        opcode = _bt.cmd_opcode_pack(_bt.OGF_INFO_PARAM, _bt.OCF_READ_BD_ADDR)
        _bt.hci_filter_set_ptype(flt, _bt.HCI_EVENT_PKT)
        _bt.hci_filter_set_event(flt, _bt.EVT_CMD_COMPLETE)
        _bt.hci_filter_set_opcode(flt, opcode)
        hci_sock.setsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, flt)

        _bt.hci_send_cmd(hci_sock, _bt.OGF_INFO_PARAM, _bt.OCF_READ_BD_ADDR)

        pkt = hci_sock.recv(255)

        status, raw_bdaddr = struct.unpack("xxxxxxB6s", pkt)
        assert status == 0

        t = ["%X" % ord(b) for b in raw_bdaddr]
        t.reverse()
        bdaddr = ":".join(t)

        # restore old filter
        hci_sock.setsockopt(_bt.SOL_HCI, _bt.HCI_FILTER, old_filter)
        return bdaddr
コード例 #40
0
    def scan(self):
        try:
            sock = bluez.hci_open_dev(self.dev_id)

        except Exception, e:
            print "ERROR: Accessing bluetooth device: " + e.message
            sys.exit(1)
コード例 #41
0
def bluetooth_rssi(addr):
    # Open hci socket
    hci_sock = bt.hci_open_dev()
    hci_fd = hci_sock.fileno()

    # Connect to device (to whatever you like)
    bt_sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
    bt_sock.settimeout(10)
    result = bt_sock.connect_ex((addr, 1))  # PSM 1 - Service Discovery

    try:
        # Get ConnInfo
        reqstr = struct.pack('6sB17s', bt.str2ba(addr), bt.ACL_LINK, '\0' * 17)
        request = array.array('c', reqstr )
        handle = fcntl.ioctl(hci_fd, bt.HCIGETCONNINFO, request, 1)
        handle = struct.unpack('8xH14x', request.tostring())[0]

        # Get RSSI
        cmd_pkt=struct.pack('H', handle)
        rssi = bt.hci_send_req(hci_sock, bt.OGF_STATUS_PARAM,
                     bt.OCF_READ_RSSI, bt.EVT_CMD_COMPLETE, 4, cmd_pkt)
        rssi = struct.unpack('b', rssi[3])[0]

        # Close sockets
        bt_sock.close()
        hci_sock.close()

        return rssi

    except:
        return None
コード例 #42
0
def _gethcisock(device_id=-1):
    try:
        sock = _bt.hci_open_dev(device_id)
    except _bt.error as e:
        raise BluetoothError(e.args[0],
                             "error accessing bluetooth device: " + e.args[1])
    return sock
コード例 #43
0
def main():
	#connect to cloudant database
	client = Cloudant("<account>",
			"<password>", 
			account="<account>", 
			connect=True,
            auto_renew=True,
            timeout=300)

	dev_id = 0
	try:
		sock = bluez.hci_open_dev(dev_id)
	except:
		print("error accessing bluetooth device...")
		sys.exit(1)

	blescan.hci_le_set_scan_parameters(sock)
	blescan.hci_enable_le_scan(sock)

	count = 0
	my_document = client['present']['<ble Device UDID>']
	while count < 30:
		returnedList = blescan.parse_events(sock, 10)
		for beacon in returnedList:
			if beacon.split(",")[1] == "<ble Device UDID>":
				my_document['present'] = True
				my_document.save()
				return
			count += 1
	my_document['present'] = False
	my_document.save()
コード例 #44
0
    def runLeash(self):
        dev_id = 0

        # Set we have not found the device for the next pass
        self.setFoundDevice(False)

        # try to open the dev via the dev id, if not exit
        try:
            sock = bluez.hci_open_dev(dev_id)
        except:
            print("error accessing bluetooth device...")
            sys.exit(1)

        # Try to check the inqury mode
        try:
            mode = self.read_inquiry_mode(sock)
        except Exception as e:
            print("error reading inquiry mode.  ")
            print(e)
            sys.exit(1)
       # print("current inquiry mode is %d" % mode)
        
        
        # inquiry the devices to find the target
        print('Attempting to Find Device')
        self.device_inquiry_with_with_rssi(sock)
コード例 #45
0
def hci_cc(adapter: int, ps4btaddr: str) -> None:
    import bluetooth._bluetooth as _bt

    try:
        hci_sock = _bt.hci_open_dev(adapter)

        # Get bytes from bluetooth address
        baps4addr = bytearray.fromhex(ps4btaddr.replace(":", ""))
        baps4addr.reverse()
        # HCI CONNECT
        # BLUETOOTH SPECIFICATION Version 5.0 | Vol 2, Part E page 774
        # https://github.com/pauloborges/bluez/blob/master/tools/hcitool.c => cmd_cc
        # https://github.com/pauloborges/bluez/blob/master/lib/hci.c => hci_create_connection
        cmd_pkt = bytes(
            baps4addr
        ) + bytes([  # Target BTADDR on 6 bytes reverse order,
            0x18,
            0xCC,  # pkt_type HCI_DM1 | HCI_DM3 | HCI_DM5 | HCI_DH1 | HCI_DH3 | HCI_DH5
            0x02,  # pscan_rep_mode
            0x00,  # pscan_mode (reserved)
            0x00,
            0x00,  # clock_offset
            0x01
        ])  # role_switch

        # Send HCI request
        _bt.hci_send_req(hci_sock, _bt.OGF_LINK_CTL, _bt.OCF_CREATE_CONN,
                         _bt.EVT_CONN_COMPLETE, 1000, cmd_pkt)
        hci_sock.close()

    except _bt.error as e:
        raise BluetoothError(*e.args)
コード例 #46
0
 def open_bt_sock():
     dev_id = 0
     try:
         sock = bluez.hci_open_dev(dev_id)
     except:
         print "error accessing bluetooth device..."
         sys.exit(1)
     return sock
コード例 #47
0
    def __init__(self):
        subprocess.call(["/usr/sbin/hciconfig", "hci0", "down"])
        subprocess.check_call(["/usr/sbin/hciconfig", "hci0", "up"])

        dev_id = 0
        self.sock = bluez.hci_open_dev(dev_id)
        self.old_filter = self.sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)

        self.hci_disable_le_scan()
コード例 #48
0
ファイル: proximity.py プロジェクト: GerritSe/py-beacon
 def __init__(self, deviceId = 0, loops = 1):
     self.deviceId = deviceId
     self.loops = loops
     try:
         self.sock = bluez.hci_open_dev(self.deviceId)
         blescan.hci_le_set_scan_parameters(self.sock)
         blescan.hci_enable_le_scan(self.sock)
     except Exception, e:
         print e   
コード例 #49
0
def init_connection():
    dev_id = 0
    connection = -1
    try:
	sock = bluez.hci_open_dev(dev_id)
    except:
	print "error accessing bluetooth device..."
	sys.exit(1)
    return sock
コード例 #50
0
ファイル: medic.py プロジェクト: dkirker/PyMetaWatch
    def __init__(self, watchaddr = None, verbose = False,debug=True):
        self.CRC=CRC_CCITT();
        self._last_tx_time = time.clock()
        self.verbose = verbose
        self.debug=debug
	self.invertDisplay=False
        while watchaddr == None or watchaddr == "none":
            print "performing inquiry..."
            if bluetooth:
                nearby_devices = bluetooth.discover_devices(lookup_names = True)
            else:
                # Need to strip the third "device class" tuple element from results
                nearby_devices = map(lambda x:x[:2], lightblue.finddevices())

            print "found %d devices" % len(nearby_devices)
            for addr, name in nearby_devices:
                print "  %s - '%s'" % (addr, name)
                if name and ('MetaWatch Digital' in name or 'Fossil Digital' in name) :
                    watchaddr=addr;
                    print "Identified Watch at %s" % watchaddr;

        # MetaWatch doesn't run the Service Discovery Protocol.
        # Instead we manually use the portnumber.
        port=1;

        print "Connecting to %s on port %i." % (watchaddr, port);
        if bluetooth:
            sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM);
            # print rssi
            print "Computing rssi"
	    dev_id = 0
	    try:
		self.sock_monitor = bluez.hci_open_dev(dev_id)
	    except:
		print "error accessing bluetooth device..."
		sys.exit(1)
	    try:
		mode = read_inquiry_mode(self.sock_monitor)
	    except Exception, e:
		print "error reading inquiry mode.  "
		print "Are you sure this a bluetooth 1.2 device?"
		print e
		sys.exit(1)
	    print "current inquiry mode is %d" % mode

	    if mode != 1:
		print "writing inquiry mode..."
		try:
		    result = write_inquiry_mode(sock_monitor, 1)
		except Exception, e:
		    print "error writing inquiry mode.  Are you sure you're root?"
		    print e
		    sys.exit(1)
		if result != 0:
		    print "error while setting inquiry mode"
		print "result: %d" % result            
コード例 #51
0
ファイル: test3.py プロジェクト: Eragon666/netcentric-2
def write_flush_timeout( addr, timeout ):
    hci_sock = bt.hci_open_dev()
    # get the ACL connection handle to the remote device
    handle = __get_acl_conn_handle(hci_sock, addr)
    pkt = struct.pack("HH", handle, bt.htobs(timeout))
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 
        0x0028, bt.EVT_CMD_COMPLETE, 3, pkt)
    status = struct.unpack("B", response[0])[0]
    rhandle = struct.unpack("H", response[1:3])[0]
    assert rhandle == handle 
    assert status == 0
コード例 #52
0
 def __init__(self, deviceId=0, loops=1):
     """Initialize scanner."""
     self.deviceId = deviceId
     self.loops = loops
     try:
         self.sock = bluez.hci_open_dev(self.deviceId)
         blescan.hci_le_set_scan_parameters(self.sock)
         blescan.hci_enable_le_scan(self.sock)
     except Exception, e:
         logger.critical('Scan failed: {}'.format(str(e)))
         print e
コード例 #53
0
	def __init__(self) :
		try:
			self.sock = bluez.hci_open_dev(self.dev_id)
			old_filter = self.sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14)
			enable = 1
			cmd_pkt = struct.pack("<BB", enable, 0x00)
			bluez.hci_send_cmd(self.sock, OGF_LE_CTL, OCF_LE_SET_SCAN_ENABLE, cmd_pkt)
			
		except:
			print "error accessing blue tooth device..."
			sys.exit(1)
コード例 #54
0
ファイル: blescanner.py プロジェクト: jdye64/residence-web
def setup(device_id):
    """ Setup a BLE scanner on a device """

    try:
        sock = bluez.hci_open_dev(device_id)
    except:
        sys.exit('Error: Unable to open device %s' % device_id)

    hci_le_set_scan_parameters(sock)
    hci_enable_le_scan(sock)

    return sock
コード例 #55
0
ファイル: testble.py プロジェクト: kaiyi/kaiyi
def init_ble():
	try:
		sock = bluez.hci_open_dev(devid)
		print "ble thread started"
	except:
		print "error accessing bluetooth device..."
		sys.exit(1)

	blescan.hci_le_set_scan_parameters(sock)
	blescan.hci_enable_le_scan(sock)

	return sock
コード例 #56
0
ファイル: Car_discovery.py プロジェクト: mrow4a/UNI
def init_BLE_thread():
    dev_id = 0
    try:
        sock = bluez.hci_open_dev(dev_id)
        hci_le_set_scan_parameters(sock)
        hci_enable_le_scan(sock)
        ## NEW THREAD ##
        thread.start_new_thread( Catch_and_Store_advertisement_meassages, (sock,) )
        BLE_thread_init = "OK - accessing bluetooth device..."
    except Exception,e:
        BLE_thread_init = ("ERROR - accessing bluetooth device and catch thread..." + str(e))
        error_reporting(BLE_thread_init)
コード例 #57
0
    def init(self):
        """
        Initialise the Bluetooth device used for scanning.

        @return  0 on success, 1 on failure.
        """
        try:
            self.sock = bluez.hci_open_dev(self.device_id)
        except:
            s = 'Error opening Bluetooth device %i' % self.device_id
            self.mgr.main.log_error('Error', '%s.' % s)
            self.mgr.debug(s)
            return 1

        try:
            mode = self._read_inquiry_mode()
        except:
            s = 'Error reading inquiry mode on device %i. ' % self.device_id + \
                'We need a 1.2+ Bluetooth device'
            self.mgr.main.log_error('Error', '%s.' % s)
            self.mgr.debug(s)
            return 1

        if mode != 1:
            try:
                result = self._write_inquiry_mode(1)
            except:
                s = 'Error writing inquiry mode on device %i' % self.device_id
                self.mgr.main.log_error('Error', '%s.' % s)
                self.mgr.debug(s)
                return 1

            if result != 0:
                s = 'Adapter %s does not support RSSI enabled ' % self.mac \
                    + 'inquiries, disabling RSSI detections'
                self.mgr.log_info(s)
                try:
                    result = self._write_inquiry_mode(0)
                except:
                    s = 'Error writing inquiry mode on device %i' % \
                        self.device_id
                    self.mgr.main.log_error('Error', '%s.' % s)
                    self.mgr.debug(s)
                    return 1

                if result != 0:
                    s = 'Error setting inquiry mode on ' + \
                        'device %i' % self.device_id
                    self.mgr.main.log_error('Error', '%s.' % s)
                    self.mgr.debug(s)
                    return 1

        return 0
コード例 #58
0
ファイル: sliding.py プロジェクト: pbustos/beacons
 def __init__(self,app):
     self.app = app
     pg.setConfigOptions(antialias=True)        
     self.win = pg.GraphicsWindow(title="Basic plotting examples")
     self.win.resize(800,800)
     self.win.setWindowTitle('SmartPolyTech Beacon System')
     
     self.p = self.win.addPlot(title='RSSI graph')
     self.graphView = self.win.addViewBox(row=1,col=0)
     #self.graphView.setLimits(xMin=-5, xMax=5, yMin = -5, yMax=5)
     self.graphView.setAspectLocked()
     self.graphView.setRange(rect=QtCore.QRectF(-6,6,12,-12))
    
     box = QtGui.QGraphicsRectItem(-10, 5, 20, -10)
     box.setPen(pg.mkPen("w"))
     box.setBrush(pg.mkBrush(None))
     self.graphView.addItem(box)
     self.graphView.show()
     self.graph = pg.GraphItem()
     self.graphView.addItem(self.graph)
     
     self.bufferLength = 20
     self.p.setRange(QtCore.QRectF(0, 0, self.bufferLength, 100)) 
     self.p.setLabel('bottom', 'Samples')
     self.p.setLabel('left', 'Signal Strength')
     self.p.setAutoVisible(y=True)
     
     #cross hair
     try:
         dev_id = 0
         self.sock = bluez.hci_open_dev(dev_id)
         print "ble thread started"
     except:
         print "error accessing bluetooth device..."
         sys.exit(1)
     
     #Variables
     self.lastTime = time()
     self.fps = None
     
     #Timers
     self.timerBluetooth = QtCore.QTimer()
     self.timerBluetooth.timeout.connect(self.updateBluetooth)
     self.timerBluetooth.start(300)       
     
     self.timer = QtCore.QTimer()
     self.timer.timeout.connect(self.compute)
     self.timer.start(100)
    
     #self.p.scene().sigMouseMoved.connect(self.mouseMoved)
     
     self.signalList = {}
     self.curveList = {}
コード例 #59
0
ファイル: test3.py プロジェクト: Eragon666/netcentric-2
def read_flush_timeout( addr ):
    hci_sock = bt.hci_open_dev()
    # get the ACL connection handle to the remote device
    handle = __get_acl_conn_handle(hci_sock, addr)
    pkt = struct.pack("H", handle)
    response = bt.hci_send_req(hci_sock, bt.OGF_HOST_CTL, 
        0x0027, bt.EVT_CMD_COMPLETE, 5, pkt)
    status = struct.unpack("B", response[0])[0]
    rhandle = struct.unpack("H", response[1:3])[0]
    assert rhandle == handle
    assert status == 0
    fto = struct.unpack("H", response[3:5])[0]
    return fto