コード例 #1
0
    def update_dicts(self):
        """
        update the mac_dict with the latest set of bluetooth address
        strengths
        :return: None
        """
        while True:
            try:
                for m in self.mac_dict.keys():
                    #time.sleep(1)
                    b = BluetoothRSSI(addr=m)
                    rssi = b.get_rssi()
                    temp = self.mac_dict[m]
                    self.dict_lock.acquire()
                    self.mac_dict[m] = rssi
                    self.dict_lock.release()
                    if self.mac_dict[m] != temp:
                        if self.mac_dict[m] is None:
                            self.log_leave(m)
                        elif temp is None:
                            self.log_arrive(m)

            except (KeyboardInterrupt):
                message = "Exception raised in Sensor run loop, method update_dict: either Keyboard Interrupt or System exit"
                print message
                #self.dict_lock.release()
                break
            print self.mac_dict
            print "#" * 30
コード例 #2
0
def main():
    if len(sys.argv) > 1:
        addr = sys.argv[1]
    elif BT_ADDR:
        addr = BT_ADDR
    else:
        print_usage()
        return
    if len(sys.argv) == 3:
        num = int(sys.argv[2])
    else:
        num = NUM_LOOP
    btrssi = BluetoothRSSI(addr=addr)
    for i in range(0, num):
        print btrssi.get_rssi()
        time.sleep(1)
コード例 #3
0
def bt_distmedia_paired(BTaddr, repeticao, A0, actual_dist):
    n = 1.5  # Path loss exponent(n) = 1.5
    c = 10  # Constante ambiental(C) = 10
    sum_error = 0
    count = 0
    avg_error = 0
    btrssi = BluetoothRSSI(addr=BTaddr)

    for i in range(repeticao):
        rssi_bt = float(btrssi.get_rssi())
        if (
                rssi_bt != 0 and i > 10
        ):  # reduces initial false values of RSSI using initial delay of 10sec
            count = count + 1
            x = float(
                (rssi_bt - A0) /
                (-10 *
                 n))  # Log Normal Shadowing Model considering d0 =1m where
            distance = (math.pow(10, x) * 100) + c
            error = abs(actual_dist - distance)
            sum_error = sum_error + error
            avg_error = sum_error / count
            print "Average Error=  " + str(avg_error)
            print "Error=  " + str(error)
            print "Approximate Distance:" + str(distance)
            print "RSSI: " + str(rssi_bt)
            print "Count: " + str(count)
            print " "
        time.sleep(1)
    return avg_error
コード例 #4
0
def calc_dist(dev, num):
    btrssi = BluetoothRSSI(dev)
    n = 1.5  #Path loss exponent(n) = 1.5
    c = 10  #Environment constant(C) = 10
    A0 = 2  #Average RSSI value at d0
    actual_dist = 37  #Static distance between transmitter and Receiver in cm
    sum_error = 0
    count = 0

    for i in range(0, num):
        rssi_bt = float(btrssi.get_rssi())
        if (i > 10):
            count = count + 1
            x = float((rssi_bt - A0) / (-10 * n))
            distance = (math.pow(10, x) * 100) + c
            error = abs(actual_dist - distance)
            sum_error = sum_error + error
            avg_error = sum_error / count

            print("[+] Average Error=  " + str(avg_error))
            print("[+] Error=  " + str(error))
            print("[+] Approximate Distance:" + str(distance))
            print("[+] RSSI: " + str(rssi_bt))
            print("[+] Count: " + str(count))

        time.sleep(1)
コード例 #5
0
ファイル: testes.py プロジェクト: igorprata/multiradioDrone
def unique_bt_scan(BTaddr):
    b = BluetoothRSSI(BTaddr)
    bt_rssi = b.get_rssi()
    print "addr: {}, rssi: {}".format(BTaddr, bt_rssi)
    if bt_rssi is None:
        time.sleep(1)
        print "Falha na coleta"
    return bt_rssi
コード例 #6
0
def main():

    print("Autonomous Door starting...")
    # Always keep your door locked
    os.system("python3 LockDoor.py")
    addr = BT_ADDR
    # Arguments for specify actions
    if (len(sys.argv) > 1):
        if sys.argv[1] == "-e":
            execution()
            quit()
        elif sys.argv[1] == "-u":
            os.system("python3 UnlockDoor.py")
            quit()
        elif sys.argv[1] == "-l":
            os.system("python3 LockDoor.py")
            quit()
        elif sys.argv[1] == "-o":
            os.system("python3 UnlockDoor.py")
            time.sleep(3)
            os.system("python OpenDoor.py")
            quit()
        elif sys.argv[1] == "-c":
            os.system("python3 UnlockDoor.py")
            time.sleep(2)
            os.system("python CloseDoor.py")
            time.sleep(7)
            os.system("python3 LockDoor.py")
            quit()
        
        else:
            print(sys.argv[1])
            addr = sys.argv[1]
    
    btrssi = BluetoothRSSI(addr=addr)    
    while True:
        print btrssi.get_rssi()
        time.sleep(1)
        if (btrssi.get_rssi() == None):
            btrssi = BluetoothRSSI(BT_ADDR)
            print("Not in range")
            time.sleep(5)
        elif (btrssi.get_rssi() > -10):
            execution()
            time.sleep(5)
            print("Safe to proceed")
コード例 #7
0
def bluetooth_listen(addr,
                     threshold,
                     callback,
                     sleep=1,
                     daily=True,
                     debug=False):
    """Scans for RSSI value of bluetooth address in a loop. When the value is
    within the threshold, calls the callback function.

    @param: addr: Bluetooth address
    @type: addr: str

    @param: threshold: Tuple of integer values (low, high), e.g. (-10, 10)
    @type: threshold: tuple

    @param: callback: Callback function to invoke when RSSI value is within
                      the threshold
    @type: callback: function

    @param: sleep: Number of seconds to wait between measuring RSSI
    @type: sleep: int

    @param: daily: Set to True to invoke callback only once per day
    @type: daily: bool

    @param: debug: Set to True to print out debug messages and does not
                   actually sleep until tomorrow if `daily` is True.
    @type: debug: bool
    """
    b = BluetoothRSSI(addr=addr)
    while True:
        rssi = b.get_rssi()
        if debug:
            print "---"
            print "addr: {}, rssi: {}".format(addr, rssi)
        # Sleep and then skip to next iteration if device not found
        if rssi is None:
            time.sleep(sleep)
            continue
        # Trigger if RSSI value is within threshold
        if threshold[0] < rssi < threshold[1]:
            callback()
            if daily:
                # Calculate the time remaining until next day
                now = datetime.datetime.now()
                tomorrow = datetime.datetime(
                    now.year, now.month, now.day, 0, 0, 0, 0) + \
                    datetime.timedelta(days=1)
                until_tomorrow = (tomorrow - now).seconds
                if debug:
                    print "Seconds until tomorrow: {}".format(until_tomorrow)
                else:
                    time.sleep(until_tomorrow)
        # Delay between iterations
        time.sleep(sleep)
コード例 #8
0
ファイル: distance.py プロジェクト: AndrewMwakibinga/IoTFinal
def main():
    b_list = getBDevices()
    n = 4  #Path loss exponent(n) = 1.5
    c = 10  #Environment constant(C) = 10
    A0 = -5  #Average RSSI value at d0
    num = len(b_list)
    data_list = []
    for i in range(num):
        btrssi = BluetoothRSSI(addr=b_list[i][0])
        avg_distance = float(0)
        for j in range(3):
            #btrssi = BluetoothRSSI(addr='AC:EE:9E:D8:89:4E')
            if (i == 0 and j == 0):
                time.sleep(10)
            rssi_bt = float(btrssi.get_rssi())
            while (rssi_bt == 0):
                rssi_bt = float(btrssi.get_rssi())
            x = float((rssi_bt - A0) / (-10 * n))
            distance = (math.pow(10, x) * 100) + c
            # print rssi_bt
            avg_distance += distance
        avg_distance /= 300
        temp = b_list[i][1], avg_distance
        data_list.append(temp)
#for d in data_list:


#	print(d[0], d[1])
#    print
    d2_list = data_list
    final_list = []
    for x in range(len(data_list)):
        for y in range(len(d2_list)):
            if (data_list[x][0] == data_list[y][0]):
                continue
            diff = data_list[x][1] - d2_list[y][1]
            diff = math.fabs(diff)
            temp = data_list[x][0], d2_list[y][0], diff
            final_list.append(temp)
    for d2 in final_list:
        print(d2[0], d2[1], d2[2])
    return final_list
コード例 #9
0
ファイル: distance.py プロジェクト: AndrewMwakibinga/IoTFinal
def main():
    b_temp = getBDevices()
    b_list = []
    for b in b_temp:
        b_list.append(b[0])
    n = 4  #Path loss exponent(n) = 1.5
    c = 0  #Environment constant(C) = 10
    A0 = 1  #Average RSSI value at d0
    actual_dist = 37  #Static distance between transmitter and Receiver in cm
    sum_error = 0
    count = 0
    num = len(b_list)
    for i in range(10):
        btrssi = BluetoothRSSI(addr='AC:EE:9E:D8:89:4E')
        rssi_bt = float(btrssi.get_rssi())
        x = float((rssi_bt - A0) / (-10 * n))
        distance = (math.pow(10, x) * 100) + c
        #print btrssi.get_addr()
        print 'A0:', float(btrssi.get_rssi())
        print "Approximate Distance:" + str(distance)
        print "RSSI: " + str(rssi_bt)
コード例 #10
0
def main():
    if BT_ADDR:
        addr = BT_ADDR
    else:
        print(
            'No Bluetooth Address Found')  # Check whether address can be found
        return
    btrssi = BluetoothRSSI(addr=addr)
    for i in range(0, BIN_SIZE):  # Populate initial list up to BIN_SIZE
        rssi = btrssi.get_rssi()
        rssiList.append(rssi)
    while (True):  # Performs continual updates at an interval of TIME_DELAY
        led.off()  # Reset output device
        rssi = btrssi.get_rssi()  # Get current RSSI
        rssiList.insert(0, rssi)  # Add RSSI to list
        del rssiList[-1]  # Pop last element off list
        if (
                getAverage(rssiList) < THRESHOLD
        ):  # Check if running average is beneath THRESHOLD - if yes, turn on output
            led.on()
            print('ALARM')
        time.sleep(1)
コード例 #11
0
ファイル: publish_rssi.py プロジェクト: KylerF/bt_proximity
class Device:
    def __init__(self, device_id, mac, name, track=False):
        self.id = device_id
        self.mac = mac
        self.name = name
        self.track = track
        self.btrssi = BluetoothRSSI(addr=mac)

    # Query received bluetooth power (RSSI)
    def get_rssi(self):
        # Attempt connection to device and query RSSI
        rssi = self.btrssi.get_rssi()

        return rssi
コード例 #12
0
class phonePositionEstimate:
    def __init__(self, BTname, BTaddress, BTclass):
        #info about estimated phone position
        self.cumPos = np.array([0.0, 0.0, 0.0], dtype=np.float32)
        self.maxRSSI = -np.inf
        self.statusRSSI = 0
        self.currentRSSI = -np.inf
        self.dataNum = 0
        self.lastRSSITime = rospy.get_rostime()
        self.reported = False

        #some properties about the bluetooth device
        self.BTname = BTname
        self.BTaddress = BTaddress
        self.BTclass = BTclass

        #the object for getting RSSI value of a bluetooth device
        self.btrssi = BluetoothRSSI(BTaddress)

    def updatePhonePosition(self):
        #get the current RSSI of BT device
        infoRSSI = self.btrssi.get_rssi()

        #For error code definition, please refer to bluetooth core specifications
        if infoRSSI == None:
            #phone not visible
            self.statusRSSI = 8  #bluetooth connection failure error code
            self.currentRSSI = -np.inf  #if fail, make current RSSI -inf
            return False
        elif infoRSSI[0] != 0:
            #having error getting RSSI
            self.statusRSSI = infoRSSI[0]
            self.currentRSSI = -np.inf
            return False
        else:
            self.statusRSSI = infoRSSI[0]
            self.currentRSSI = infoRSSI[1]

        if self.currentRSSI == self.maxRSSI:
            self.cumPos = self.cumPos + currentVehiclePosition
            self.dataNum += 1

        elif self.currentRSSI > self.maxRSSI:
            self.maxRSSI = self.currentRSSI
            self.cumPos = currentVehiclePosition
            self.dataNum = 1

        return True
コード例 #13
0
ファイル: main.py プロジェクト: djmarx/bt_rssi
def main():

    time.sleep(10)
    start_time = datetime.datetime.now()
    addr = BT_ADDR
    num = NUM_LOOP
    count = 0

    while (count < num):
        btrssi = BluetoothRSSI(addr=addr)
        current_time = time_diff(start_time)
        record = (btrssi.get_rssi(), current_time)
        records.append(record)
        count += 1
        time.sleep(.5)
    write(records, count)
コード例 #14
0
def main():
    if len(sys.argv) > 1:
        addr = sys.argv[1]
    elif BT_ADDR:
        addr = BT_ADDR
    else:
        print_usage()
        return
    if len(sys.argv) == 3:
        num = int(sys.argv[2])
    else:
        num = NUM_LOOP

    btrssi = BluetoothRSSI(addr=addr)
    
    n=1.5    #Path loss exponent(n) = 1.5
    c = 10   #Environment constant(C) = 10
    A0 = 2   #Average RSSI value at d0
    actual_dist = 37   #Static distance between transmitter and Receiver in cm
    sum_error = 0
    count = 0
    
    for i in range(1, num):
        rssi = btrssi.get_rssi()
        if rssi is None:
            continue    
        rssi_bt = float(rssi)
        if(rssi_bt!=0 and i>10):                    #reduces initial false values of RSSI using initial delay of 10sec
            count=count+1
            x = float((rssi_bt-A0)/(-10*n))         #Log Normal Shadowing Model considering d0 =1m where  
            distance = (math.pow(10,x) * 100) + c
            error = abs(actual_dist - distance)
            sum_error = sum_error + error
            avg_error = sum_error/count
            #print "Average Error=  " + str(avg_error)
            #print "Error=  " + str(error)
            print "Approximate Distance:" + str(distance)
            print "RSSI: " + str(rssi_bt)
            #print "Count: " + str(count)
            print " "
        if(rssi_bt < -50):
            break    
        time.sleep(1)
コード例 #15
0
def main():

    print("found %d devices" % len(nearby_devices))

    for addr, name in nearby_devices:
        try:
            print("  %s - %s" % (addr, name))
        except UnicodeEncodeError:
            print("  %s - %s" % (addr, name.encode('utf-8', 'replace')))

    for addr, name in nearby_devices:
        btrssi = BluetoothRSSI(addr=addr)

        n = 1.5  #Path loss exponent(n) = 1.5
        c = 10  #Environment constant(C) = 10
        A0 = 2  #Average RSSI value at d0
        count = 0
        total_dist = 0

        for i in range(1, NUM_LOOP):
            rssi = btrssi.get_rssi()
            if rssi is None:
                continue
            rssi_bt = float(rssi)
            if (
                    rssi_bt != 0 and i > 10
            ):  #reduces initial false values of RSSI using initial delay of 10sec
                count = count + 1
                x = float(
                    (rssi_bt - A0) /
                    (-10 *
                     n))  #Log Normal Shadowing Model considering d0 =1m where
                distance = (math.pow(10, x) * 100) + c
                total_dist += distance
                print "Approximate Distance:" + name + str(distance)
                print "RSSI: " + str(rssi_bt)
                time.sleep(.2)
        if count is 0:
            count = 1
        avg_distance = total_dist / count
        print "%s %s %s" % (addr, name, str(avg_distance))
コード例 #16
0
def bt_sinalmedio_paired(BTaddr, repeticao):
    count = 0
    sum_rssi_bt = 0
    avg_rssi_bt = 0
    btrssi = BluetoothRSSI(addr=BTaddr)

    for i in range(repeticao):
        rssi_bt = float(btrssi.get_rssi())
        if (
                rssi_bt != 0 and i > 10
        ):  # reduz a possibilidade de valores iniciais falsos de RSSI esperando por x seg e elimina valores 0
            count = count + 1
            sum_rssi_bt = sum_rssi_bt + rssi_bt
            avg_rssi_bt = sum_rssi_bt / count
            print "Sinal médio:  " + str(avg_rssi_bt)
            print "RSSI: " + str(rssi_bt)
            print "Amostra número: " + str(count)
            print " "
        time.sleep(
            1)  # para aguardar por uma variação maior por parte do IWLIST
    return avg_rssi_bt
コード例 #17
0
ファイル: lnsm.py プロジェクト: jonathanrjpereira/Doze
def main():
    if len(sys.argv) > 1:
        addr = sys.argv[1]
    elif BT_ADDR:
        addr = BT_ADDR
    else:
        print_usage()
        return
    if len(sys.argv) == 3:
        num = int(sys.argv[2])
    else:
        num = NUM_LOOP
    btrssi = BluetoothRSSI(addr=addr)
    
    n=1.5    #Path loss exponent(n) = 1.5
    c = 10   #Environment constant(C) = 10
    A0 = 2   #Average RSSI value at d0
    actual_dist = 37   #Static distance between transmitter and Receiver in cm
    sum_error = 0
    count = 0
    
    for i in range(1, num):
        rssi_bt = float(btrssi.get_rssi())
        if(rssi_bt!=0 and i>10):                    #reduces initial false values of RSSI using initial delay of 10sec
            count=count+1
            x = float((rssi_bt-A0)/(-10*n))         #Log Normal Shadowing Model considering d0 =1m where  
            distance = (math.pow(10,x) * 100) + c
            error = abs(actual_dist - distance)
            sum_error = sum_error + error
            avg_error = sum_error/count
            print "Average Error=  " + str(avg_error)
            print "Error=  " + str(error)
            print "Approximate Distance:" + str(distance)
            print "RSSI: " + str(rssi_bt)
            print "Count: " + str(count)
            print " "
        time.sleep(1)
コード例 #18
0
def getRSSI(Target_MAC):
    btrssi = BluetoothRSSI(addr=Target_MAC)
    return btrssi.get_rssi()
コード例 #19
0
ファイル: testlock.py プロジェクト: mpocta30/DoorLock
		# divide down clock
		wiringpi.pwmSetClock(192)
		wiringpi.pwmSetRange(2000)

	def moveServo(self, lower, upper, step):
		for pulse in range(lower, upper, step):
			wiringpi.pwmWrite(18, pulse)
			time.sleep(self.delay_period)


if __name__ == '__main__':
	# Create item of type DoorLock
	lock = DoorLock()

	try:
		while True:
			btrssi = BluetoothRSSI(addr=lock.btaddr)
			lock.rssi = btrssi.get_rssi()

			# If door is locked and phone comes close to lock
			if not lock.open and lock.rssi != None:
				lock.moveServo(50, 250, 1)
				lock.open = True
			elif lock.open and lock.rssi == None:
				lock.moveServo(250, 50, -1)
				lock.open = False
	except:
		print("\nThanks for trying our Lock!")
	
コード例 #20
0
    total_count = 0
    total = 0
    for val in keys:
        if float(counter[val]) / float(maximum) > .60:
            total += counter[val] * val
            total_count += counter[val]
    return float(total) / float(total_count)


if len(sys.argv) < 2:
    print "usage: python bluetoothRSSI <address>"
else:
    while 1:
        try:
            rssi = BluetoothRSSI(addr=sys.argv[1])
            value = rssi.get_rssi()
            if value != 0:
                if mini > value:
                    mini = value
                if maxi < value:
                    maxi = value
                t1 = time.time()
                elapsed = elapsed + (t1 - t)
                print value, " after time ", elapsed, " seconds"
                t = time.time()
                dist = math.pow(10, -value)
                x.append(elapsed)
                y.append(value)
                count += 1
        except KeyboardInterrupt:
            print "Minimum: ", mini, " Maximum: ", maxi