def _funcRun(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) while (self.running == True): 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[0] == 'd4:54:01:07:45:60': #print('device found') self.IOdata.temp = ( float(output[2]) - 32 ) * 5 / 9 #convert the string for the temperature to a float type self.IOdata.sg = float(output[3]) / 1000 blescan.hci_disable_le_scan(sock)
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)
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 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)
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
def getdata(): 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] == blue: #Change this to the colour of you tilt tempf = float(output[2]) #convert the string for the temperature to a float type gotData = 1 tiltSG = float(output[3]) tiltTemp = tempf #assign values to a dictionary variable for the http POST to google sheet data= { "Time": datetime.now(), 'SG': tiltSG, 'Temp': tiltTemp, } blescan.hci_disable_le_scan(sock) return data
def monitor_tilt(): while True: beacons = distinct(blescan.parse_events(sock, 10)) print "tried" db = MySQLdb.connect(**DB_CONFIG) for beacon in beacons: if beacon['uuid'] in TILTS.keys(): beer = "beer" color = TILTS[beacon['uuid']] unit = "fahrenheit" #timestamp = datetime.datetime.now() gravity = beacon['minor'] temp = beacon['major'] if unit == "fahrenheit" else to_celsius( beacon['major']) cur = db.cursor() insert = ("INSERT INTO stats " "(beer, color, unit, timestamp, gravity, temp) " "VALUES (\"{beer}\", \"{color}\", \"{unit}\", now(), {gravity}, {temp})"\ .format(beer=beer, color=color, unit=unit, gravity=gravity, temp=temp)) print insert cur.execute(insert) db.commit() db.close() time.sleep(10)
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
def getFirstTilt(): dev_id = 0 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) blescan.hci_enable_le_scan(sock) tilts = { 'a495bb10c5b14b44b5121370f02d74de': 'Red', 'a495bb20c5b14b44b5121370f02d74de': 'Green', 'a495bb30c5b14b44b5121370f02d74de': 'Black', 'a495bb40c5b14b44b5121370f02d74de': 'Purple', 'a495bb50c5b14b44b5121370f02d74de': 'Orange', 'a495bb60c5b14b44b5121370f02d74de': 'Blue', 'a495bb70c5b14b44b5121370f02d74de': 'Pink' } result = {} returnedList = blescan.parse_events(sock, 100) for beacon in returnedList: if (beacon['uuid'] in tilts): tiltColor = tilts[beacon['uuid']] result = { 'Color': tiltColor, 'Temp': beacon['major'], 'Gravity': beacon['minor'] } return result
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) self.pub.publish(msg)
def ble_scan(sock): rssiDict = dict() # create a dictionary returnedList = blescan.parse_events(sock) for beacon in returnedList: #print beacon uuid = beacon.split(",")[1] if uuid == "00000000111111110000000000556601": major = beacon.split(",")[2] minor = beacon.split(",")[3] txpower = beacon.split(",")[4] rssi = beacon.split(",")[5] cof1 = 0.42093 cof2 = 6.9476 cof3 = 0.54992 ratio = 1.0 * float(rssi) / float(txpower) distance = 0 if ratio < 1.0: distance = pow(ratio, 10) else: distance = cof1 * pow(ratio, cof2) + cof3 print "uuid:", uuid print "major:", major, ", minor:", minor, ", txpower:", txpower print "rssi", rssi print "distance: ", str(distance) print "--------" return rssiDict
def ScanMAC(): global ListBT, ListSCAN global x,y ListBT = [] ListaMACs.delete(0,3) ListSCAN = [] RSSI = [] media = [] MAC = [] total = 0 size = len(MAC_ADDRESS) for x in range(0, size): media.append(0) RSSI.append(0) MAC.append(0) while total < (size*10): returnedList = blescan.parse_events(sock, 1) for x in range(0,size): if ((MAC_ADDRESS[x] in returnedList[0]) & (MAC[x] < NUM_MEDIDAS_MEDIA)): media[x] = media[x] + int(returnedList[0][62:]) MAC[x] = MAC[x] + 1 print MAC[x],returnedList[0][0:17]+" "+ returnedList[0][62:] total = total + 1 for z in range(0,(size)): RSSI[z] = int(media[z] / float(NUM_MEDIDAS_MEDIA)) ListSCAN.append(MAC_ADDRESS[z]+" "+str(RSSI[z])) contador = 0 for beacon in ListSCAN: ListaMACs.insert(contador, beacon[0:17]+" "+str(x)+" "+str(y)+" "+beacon[19:]) ListBT.append([beacon[0:17], x, y, int(beacon[19:])]) contador = contador + 1
def scan(self): #TODO - make this a "with" style context manager datalist = [] # Setup sock = bluez.hci_open_dev(self.devid) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) #returns a list of Beacons scan_results = blescan.parse_events(sock, 10) #pprint.pprint( scan_results ) for beacon in scan_results: try: color = self.uuidmap[beacon.uuid] except (KeyError) as e: continue #print( 'Found Tilt color: {}'.format( color ) ) data = { 'datetime': datetime.datetime.now(), 'SG': float(beacon.minor) / 1000, 'Temp': float(beacon.major), 'Color': color, } #pprint.pprint( data ) datalist.append(data) # Teardown blescan.hci_disable_le_scan(sock) return datalist
def ble_scan(sock): rssiDict = dict() # create a dictionary returnedList = blescan.parse_events(sock) for beacon in returnedList: #print beacon uuid = beacon.split(",")[1] if uuid == "67257b9224cd4db6bd9634b3e24a6bdb": major = beacon.split(",")[2] minor = beacon.split(",")[3] txpower = beacon.split(",")[4] rssi = beacon.split(",")[5] ratio = float(rssi) * 1.0 / float(txpower) if ratio < 1.0: distance = math.pow(ratio, 10) else: distance = 0.42093 * math.pow(ratio, 6.9476) + 0.54992 print "uuid:", uuid print "major:", major, ", minor:", minor, ", txpower:", txpower print "rssi", rssi print "dist", distance print "--------" return rssiDict
def scan(self): print("\nScanning...") returnedList = blescan.parse_events(self.sock, self.__numberOfBeaconsToWait) timestamp = str( time.time()) #all scanned beacons would have the same timestamp return timestamp, returnedList
def Beacon(): while True : returnedList = blescan.parse_events(sock, 10) print "----------" minDistance = 100 minID = " " for beaconid in returnedList: beaconarr= beaconid.split(',') txPower = beaconarr[4] txPowerint = int(txPower) rssi=beaconarr[5] rssiint = int(rssi) distance = calculateD(txPowerint,rssiint) if distance < minDistance : minID = beaconid minDistance = distance for beaconid2 in returnedList: for row in result : if row[0] == beaconid2[0:17] and beaconid2[0:17] == minID[0:17] : MAC_ADDRESS = row[0] Location = row[2] Severity = row[3] beaconarr = beaconid2.split(',') txPower = beaconarr[4] txPowerint = int(txPower) rssi = beaconarr[5] rssiint = int(rssi) distance = calculateD(txPowerint,rssiint) distanceTemp = round(distance, 2) distanceStr = str(distanceTemp) # print distance print row print str(MAC_ADDRESS) +", "+str(Location) + "," + str(distanceStr) + " meters left" distanceVoice = distanceStr +"meters left" if distance < 1.5 : if Severity == 1 : motorRight() print("Dangerous There is an obstacle") say("Dangerous There is an obstacle") # continue time.sleep(3) else : motorZero() if len(sys.argv)<=1: say(Location) say(distanceVoice) time.sleep(1) continue elif os.path.isfile(sys.argv[1]): fi=open(sys.argv[1],'r') text=fi.read() say(text) else: sentence="" for i in range(1,len(sys.argv)): sentence=sentence+sys.argv[i] say(sentence)
def updateBluetooth(self): returnedList = blescan.parse_events(self.sock, 1) for beacon in returnedList: words = beacon.split(',') mac = words[0] uid = words[1] major = words[2] minor = words[3] power = words[4] rssi = words[5] print mac, rssi, minor #print "dict lenght" ,len(self.signalList) if mac not in self.signalList: #self.signalList[mac] = np.zeros(self.bufferLength,'f') self.signalList[mac] = np.zeros(0,'f') self.curveList[mac] = self.p.plot(pen=QtGui.QPen(pg.intColor(self.nextColor))) self.nextColor += 1 s = self.signalList[mac] val = 100 + float(rssi) if s.size < self.bufferLength: s = np.append(s,val) # if s.size > 4: # s[-1] = self.runningMeanFast(s,3)[0] print "append" , val else: s = np.roll(s,-1) s[-1] = val # s[-1] = self.runningMeanFast(s,3)[0] self.curveList[mac].setData(s) self.signalList[mac] = s self.timeElapsed() self.app.processEvents() ## force complete redraw for every plot
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()
def processSocket(self, sock): returnedList = blescan.parse_events(sock, 10) for beacon in returnedList: beaconParts = beacon.split(",") #Resolve whether the received BLE event is for a Tilt Hydrometer by looking at the UUID. name = self.tiltHydrometerName(beaconParts[1]) #If the event is for a Tilt Hydrometer , process the data if name is not None: if (self.debug): print name + " Tilt Device Found (UUID " + str(beaconParts[1]) + "): " + str(beaconParts) #Get the temperature and convert to C if needed. temperature = int(beaconParts[2]) if not self.inFahrenheit: temperature = self.convertFtoC(temperature) #Get the gravity. gravity = self.convertSG(beaconParts[3]) #Store the retrieved values in the relevant Tilt Hydrometer object. self.storeValue(name, temperature, gravity) else: #Output what has been found. if (self.debug): print "UNKNOWN BLE Device Found: " + str(beaconParts)
def _scan(self): blescan.hci_le_set_scan_parameters(self.sock) blescan.hci_enable_le_scan(self.sock) while not self.__scan_stop: beaconlist = blescan.parse_events(self.sock, 10) for beacon in beaconlist: self.beacons.append(beacon)
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)
def scan_ble(self): sock = bluez.hci_open_dev(0) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) returnedList = blescan.parse_events(sock, 15) cur_scanned_beacons = [] for beacon in returnedList: # print(beacon) beacon_parsed_list = beacon.split(',') beacon_MAC = beacon_parsed_list[0] beacon_RSSI = beacon_parsed_list[5] temp_list = [] if (beacon_MAC in self.cur_macs): cur_scanned_beacons.append({ "MAC": beacon_MAC, "RSSI": beacon_RSSI }) for beacon in self.cur_beacons: for data in cur_scanned_beacons: if (data["MAC"] == beacon.mac and data['RSSI'] != 0): beacon.rssi = data["RSSI"] temp_list.append(beacon) min_beacon = self.cur_beacon for beacon in temp_list: if (int(beacon.rssi) > int(min_beacon.rssi) and int(beacon.rssi) != 0): min_beacon = beacon self.cur_beacon = min_beacon self.update_menu()
def scanbeacon(): sock = init() while True: returnedList = blescan.parse_events(sock, 10) print "----------" for beacon in returnedList: print beacon
def processSocket(self, sock): returnedList = blescan.parse_events(sock, 10) for beacon in returnedList: beaconParts = beacon.split(",") # Resolve whether the received BLE event is for a Tilt Hydrometer by looking at the UUID. name = self.tiltHydrometerName(beaconParts[1]) # If the event is for a Tilt Hydrometer , process the data if name is not None: if (self.debug): print(name + " Tilt Device Found (UUID " + str(beaconParts[1]) + "): " + str(beaconParts)) # Get the temperature and convert to C if needed. temperature = int(beaconParts[2]) if not self.inFahrenheit: temperature = self.convertFtoC(temperature) # Get the gravity. gravity = self.convertSG(beaconParts[3]) # Store the retrieved values in the relevant Tilt Hydrometer object. self.storeValue(name, temperature, gravity) else: # Output what has been found. if (self.debug): print("UNKNOWN BLE Device Found: " + str(beaconParts))
def iBeacon(): while True: returnedList = blescan.parse_events(sock, 10) # print "----------" if len(returnedList) != 0: sort_L = [] for i in returnedList: sum_L[int(i[i.index('x') + 1:i.index(',')])] = int( i[i.index(',') + 1:]) num_L = sum_L[:] copy_L = sum_L[:] for i in range(len(num_L) - 1, 0, -1): for j in range(i): if num_L[j] < num_L[j + 1]: temp = num_L[j] num_L[j] = num_L[j + 1] num_L[j + 1] = temp for i in num_L: for j in range(len(copy_L)): if i != 0 and i == copy_L[j]: string = int(copy_L.index(i)) #string+='_' string2 = int(i) #sort_L.append(copy_L.index(i)) #sort_L.append(i) two_L = [string, string2] sort_L.append(two_L) copy_L[j] = 0 #print(sum_L) #print(num_L) return sort_L
def scan(people): unique_nearby_devices = [] nearby_devices = blescan.parse_events(sock, 2) unique_nearby_devices = unique(nearby_devices, unique_nearby_devices) recv_data(unique_nearby_devices, HOST, PORT, client_list) unique_nearby_devices = unique(unique_nearby_devices, unique_nearby_devices) print "Devices: ", unique_nearby_devices for person in people: print people[person][2], "\n" if people[person][2] in unique_nearby_devices and person =="Tom's Tester": print "Checking if first time in" if people[person][1] != "in": people[person][1] = "in" clock(person, "in", people) else: if people[person][1] != "out": people[person][1] = "out" clock(person, "out", people)
def monitor_tilt(): streamer = Streamer(bucket_name="Boiling", bucket_key="HG9YAAUM5DX4", access_key="ist_QX41bivamY4BhpNUbQwSIfuePaW23bGb") temperature_buffer = [] gravity_buffer = [] while True: beacons = distinct(blescan.parse_events(sock, 100)) for beacon in beacons: print(temperature_buffer) print(gravity_buffer) if beacon['uuid'] in TILTS.keys(): temperature_buffer.append(beacon['major']) gravity_buffer.append(beacon['minor']) if len(temperature_buffer) >= 1: print("f") temperature_average = round( float(sum(temperature_buffer)) / float(len(temperature_buffer)), 3) gravity_average = round( float(sum(gravity_buffer)) / 1000 * float(len(gravity_buffer)), 3) print("Temp Avg:") print(temperature_average) print("Gravity Avg:") print(gravity_average) streamer.log("Temperature", temperature_average) streamer.log("Gravity", gravity_average) del temperature_buffer[:] del gravity_buffer[:] time.sleep(1)
def scan(people): unique_nearby_devices = [] nearby_devices = blescan.parse_events(sock, 2) unique_nearby_devices = unique(nearby_devices, unique_nearby_devices) recv_data(unique_nearby_devices, HOST, PORT) unique_nearby_devices = unique(unique_nearby_devices, unique_nearby_devices) for person in people: if person.bt.lower() in unique_nearby_devices: print "Checking if first time in" if person.status != "in": person.status = "in" darl = person.name + ".csv" print person.name, person.status writer(darl, "in") else: if person.status != "out": person.status = "out" darl = person.name + ".csv" print person.name, person.status writer(darl, "out")
def get_location(status): dev_id = 0 max_distance = 10.0 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) blescan.hci_enable_le_scan(sock) #while True: returnedList = blescan.parse_events(sock, 10) try: r1 = returnedList.get('12:3b:6a:1a:5f:46') r2 = returnedList.get('12:3b:6a:1a:62:36') r3 = returnedList.get('12:3b:6a:1a:62:38') while(r1 == None or r2 == None or r3 == None): returnedList = blescan.parse_events(sock, 10) r1 = returnedList.get('12:3b:6a:1a:5f:46') r2 = returnedList.get('12:3b:6a:1a:62:36') r3 = returnedList.get('12:3b:6a:1a:62:38') time.sleep(.2) for a in returnedList: print "key : " + a + "\tvalue : " + returnedList.get(a) if float(r1) > max_distance: r1 = max_distance if float(r2) > max_distance: r2 = max_distance if float(r3) > max_distance: r3 = max_distance print r1, r2, r3 #get the location of car. if(r1 != None and r2 != None and r3 != None): d = 10.0 i = 10.0 j = 10.0 x = (math.pow(float(r1), 2.0) - math.pow(float(r2), 2.0) + math.pow(d, 2.0)) / (2.0 * d) y = (pow(float(r1), 2.0) - pow(float(r3) ,2.0) - pow(x, 2.0) + (pow((x - i), 2.0)) + pow(j, 2.0)) / (2.0 * j) print "x : " + str(x) print "y : " + str(y) except: print "can't get device."
def getdata(): try: sock = bluez.hci_open_dev(dev_id) except: print "error accessing bluetooth device..." draw.rectangle((0, 0, width, height), outline=0, fill=0) draw.text((x, top), "error accessing bluetooth device...", font=font, fill=255) disp.image(image) disp.display() 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) #lcd.message(returnedList) #print returnedList ### 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] == purple: #Change this to the colour of you tilt tempf = float( output[2] ) #convert the string for the temperature to a float type gotData = 1 tiltTime = sheetsDate(datetime.datetime.now()) tiltSG = float(output[3]) / 1000 tiltTemp = tempf tiltColour = 'PURPLE' tiltBeer = 'test' #Change to an identifier of a particular brew #assign values to a dictionary variable for the http POST to google sheet data = { 'Timepoint': tiltTime, 'SG': tiltSG, 'Temp': tiltTemp, 'Color': tiltColour, 'Beer': tiltBeer, 'Comment': "Pi" } blescan.hci_disable_le_scan(sock) return data while True: data = getdata() #tempf = (float(data["Temp"]) #temp in f tempc = ( float(data["Temp"]) - 32 ) * 5 / 9 #convert from string to float and then farenheit to celcius just for the display tempc = round(tempc) #Round of the value to 2 decimal places tempf = tempc * 9 / 5 + 32 tiltSG = data['SG']
def run(self): while True: global list_room, beacon, watch_dict returnedList = blescan.parse_events(sock, 5) print "------------------------------------------------" for beacon in returnedList: ## print beacon ble_track(rssi_threshold)
def ble_scanner(queue): try: sock = bluez.hci_open_dev(__dev_id) __logger.info('BLE device started') except Exception: __logger.exception('BLE device failed to start:') __logger.critical('Will reboot RPi to see if it fixes the issue') # try to stop and start the BLE device somehow... # if that doesn't work, reboot the device. __logger.critical('Will reboot RPi to see if it fixes the issue') sys.exit(1) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) while blescan.is_running: blescan.parse_events(sock, queue, 50) # every 50 events 'refresh' the ble socket...whatever that means
def scan(): unique_nearby_devices = [] nearby_devices = blescan.parse_events(sock, 4) unique_nearby_devices = unique(nearby_devices, unique_nearby_devices) #send_data(unique_nearby_devices, HOST, PORT) for addr in unique_nearby_devices: print addr
def start(*args, **kwargs): """Main loop""" processor = processors.Kalman() gobject_thread = threading.Thread(target=mainloop.run) gobject_thread.daemon = True gobject_thread.start() dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) logger.info("ble thread started") except Exception as e: logger.error('Error accessing bluetooth device', exc_info=True) sys.exit(1) try: global locked counter = 0 while True: returnedList = blescan.parse_events(sock, 10) for beacon in returnedList: uuid, major, minor = beacon.split(',')[1:4] if major in const.ALLOWED_MAJOR and minor in const.ALLOWED_MINOR: beacon_id = beacon[:-8] if beacon_id[-2:] == ',,': # double comma at end of string beacon_id = beacon_id[:-1] txpower = int(beacon.split(',')[4]) rssi = int(beacon.split(',')[5]) rssi = -99 if rssi < -99 else rssi # rssi peak fix rssi_filtered = processor.filter(beacon_id, rssi) if rssi_filtered is None: continue beacon_dist = getrange(txpower, rssi_filtered) if not locked: if beacon_dist >= const.MAX_RANGE: counter += 1 else: counter = counter - 1 if counter > 1 else 0 if counter == 4: logger.info('screen is locked') call(const.LOCK_SCREEN, shell=True) locked = True counter = 0 sleep(.1) except KeyboardInterrupt: logger.warning("Ctrl-C pressed") sys.exit()
def monitor_tilt(): beacons = distinct(blescan.parse_events(sock, 10)) results = [] for beacon in beacons: if beacon['uuid'] in TILTS.keys(): results.append( Tilt(beacon['uuid'], TILTS[beacon['uuid']], datetime.datetime.now().isoformat(), beacon['major'], beacon['minor'])) return results
def get_ibeacon_distance(device): dev_id = 0 max_distance = 30.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) #while True: returnedList = blescan.parse_events(sock, 10) if(device=='fan'): try: fan = returnedList.get('12:3b:6a:1a:5f:4f') while(fan == None): returnedList = blescan.parse_events(sock, 10) fan = returnedList.get('12:3b:6a:1a:5f:4f') time.sleep(.2) #for a in returnedList: # print "key : " + a + "\tvalue : " + returnedList.get(a) print "fan Distance : ", fan show_ibeacon_distance(device, fan, fanSupport) return fan except: print "can't get device." elif(device=='home'): try: home = returnedList.get('12:3b:6a:1a:62:36') homeSupport = returnedList.get('12:3b:6a:1a:62:38') while(home == None or homeSupport == None): returnedList = blescan.parse_events(sock, 10) home = returnedList.get('12:3b:6a:1a:62:36') homeSupport = returnedList.get('12:3b:6a:1a:62:36') time.sleep(.2) print "home Distance : ", home print "home Support Distance : ", homeSupport show_ibeacon_distance(device, home, homeSupport) return home except: print "can't get device."
def beacon_close(): returnedList = blescan.parse_events(sock, 10) newlist = sorted(returnedList, key=lambda k: k['distance']) beacon = mashup(newlist) if(beacon is not None): things = Beacon.query.all() for x in things: if x.uuid.replace('-','') == beacon['uuid'] and x.major == beacon['major'] and x.major == beacon['major']: return True return False
def scan_a_minute(self): pkts = [] blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) t1 = time.time() while True: pkts.extend(blescan.parse_events(sock, 10)) #parse needed packets in blescan if time.time - t1 > 60: break blescan.hci_disable_le_scan(sock) return pkts
def scan(self): """ Scan length is optimised to number of beacons present, with aim of always getting result with 1s """ now = time.time() if now - self.lastScanTime > 0.8 and self.scanLength >= 1: self.scanLength -= 1 elif now - self.lastScanTime < 0.4: self.scanLength += 1 #self.cbLog("debug", "scan, time: " + str(now-self.lastScanTime) + " scanLength: " + str(self.scanLength)) self.lastScanTime = now returnedList = blescan.parse_events(self.sock, self.scanLength) return returnedList
def monitor_tilt(sock): while True: beacons = distinct(blescan.parse_events(sock, 10)) for beacon in beacons: if beacon['uuid'] in TILTS.keys(): data = { 'color': TILTS[beacon['uuid']], 'temp': beacon['major'], 'specificGravity': beacon['minor'] / 1000.0 } return json.dumps(data)
def loop(self): """Discover all BLE devices and update beacon list Send keepAlive message each {self.interval} seconds. """ now = time.time() time.sleep(1) if mock: discovered = b.parse_beacon_list([ 'c6:f8:b3:66:d1:95,e2c56db5dffb48d2b060d0f5a71096e0,0,0,-59,-37', ]) else: discovered = b.parse_beacon_list( blescan.parse_events(self.sock_bt, len(self.beacons))) # Update beacons by discovered beacons for beacon in discovered: try: index = self.beacons.index(beacon) self.beacons[index].tx_power.pop(0) self.beacons[index].tx_power.append(beacon.last_tx_power()) self.beacons[index].rssi.pop(0) self.beacons[index].rssi.append(beacon.last_rssi()) self.beacons[index].timestamp = now except ValueError: # print "unknown beacon " + str(beacon) pass for beacon in self.beacons: if beacon.timestamp < now - 20: if beacon.active: beacon.active = False self.send("/api/beacons", json.dumps(beacon.jsonify())) else: if beacon.is_inactive_long_time(now): if now - self.started_at > 10: self.send("/api/beacons", json.dumps(beacon.jsonify())) else: print("too early to send changed rssi") else: if not beacon.active: beacon.active = True self.send("/api/beacons", json.dumps(beacon.jsonify())) else: if beacon.is_active_long_time( now) or beacon.is_rssi_changed(): if now - self.started_at > 10: self.send("/api/beacons", json.dumps(beacon.jsonify())) else: print("too early to send changed rssi")
def loop(self): """Discover all BLE devices and update beacon list Send keepAlive message each {self.interval} seconds. """ now = time.time() time.sleep(1) if mock: discovered = b.parse_beacon_list([ 'c6:f8:b3:66:d1:95,e2c56db5dffb48d2b060d0f5a71096e0,0,0,-59,-37', ]) else: discovered = b.parse_beacon_list(blescan.parse_events( self.sock_bt, len(self.beacons) )) # Update beacons by discovered beacons for beacon in discovered: try: index = self.beacons.index(beacon) self.beacons[index].tx_power.pop(0) self.beacons[index].tx_power.append(beacon.last_tx_power()) self.beacons[index].rssi.pop(0) self.beacons[index].rssi.append(beacon.last_rssi()) self.beacons[index].timestamp = now except ValueError: # print "unknown beacon " + str(beacon) pass for beacon in self.beacons: if beacon.timestamp < now - 20: if beacon.active: beacon.active = False self.send("/api/beacons", json.dumps(beacon.jsonify())) else: if beacon.is_inactive_long_time(now): if now - self.started_at > 10: self.send("/api/beacons", json.dumps(beacon.jsonify())) else: print("too early to send changed rssi") else: if not beacon.active: beacon.active = True self.send("/api/beacons", json.dumps(beacon.jsonify())) else: if beacon.is_active_long_time(now) or beacon.is_rssi_changed(): if now - self.started_at > 10: self.send("/api/beacons", json.dumps(beacon.jsonify())) else: print("too early to send changed rssi")
def pollBLE(sock, minor): returnedList = blescan.parse_events(sock, 10) #print "----------" for beacon in returnedList: if beacon.split(',')[3]==minor: txCalebPow= int(beacon.split(',')[4]) rssi = int(beacon.split(',')[5]) ratioDb = (txCalebPow - rssi) ratioLin = math.pow(10, ratioDb / 10.0) rm = math.sqrt(ratioLin) rf = round(3.2808*rm) message= "%d feet, Db difference is %d, power ratio is 1/%d on beacon %s" % (rf , ratioDb, ratioLin, minor) return message return "that beacon is not reporting"
def scan_loop(sock): while True: returned_list = blescan.parse_events(sock, 10) if len(returned_list) > 0: keepalive.set_last_run() for beacon in returned_list: queue.queue_beacon(beacon) keepalive_message = keepalive.check_keepalive() if keepalive_message is not None: send.send(1, "KA:%s", keepalive_message)
def main(): try: sock = bluez.hci_open_dev() blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) except: print("Error accessing bluetooth device for beacon scan") return 1 sock.settimeout(5) returnedList = blescan.parse_events(sock, 20) sock.close() for address in returnedList: print(address)
def pollBLEjson(sock, minor): returnedList = blescan.parse_events(sock, 10) #print "----------" for beacon in returnedList: if beacon.split(',')[3]==minor: txCalebPow= int(beacon.split(',')[4]) rssi = int(beacon.split(',')[5]) ratioDb = (txCalebPow - rssi) ratioLin = math.pow(10, ratioDb / 10.0) rm = math.sqrt(ratioLin) rf = round(3.2808*rm) #message= "%d feet, Db difference is %d, power ratio is 1/%d on beacon %s" % (rf , ratioDb, ratioLin, minor) mdict= dict([('message', 'reporting'),('beacon', minor), ('distance', rf), ('dBdiff', ratioDb), ("powerRatio", ratioLin) ]) message = jsonify(mdict) return message return "that beacon is not reporting"
def pollAll(sock): returnedList = blescan.parse_events(sock, 10) print "----------" bigmess= "" for beacon in returnedList: minor= int(beacon.split(',')[3]) if int(minor > 1): txCalebPow= int(beacon.split(',')[4]) rssi = int(beacon.split(',')[5]) ratioDb = (txCalebPow - rssi) ratioLin = math.pow(10, ratioDb / 10.0) rm = math.sqrt(ratioLin) rf = round(3.2808*rm) message= "%d feet, Db difference is %d, power ratio is 1/%d on beacon %s \n %s \n" % (rf , ratioDb, ratioLin, minor, beacon) bigmess += message return bigmess
def ble_scan(sock, num): rssiDict = dict() returnedList = blescan.parse_events(sock, num) for beacon in returnedList: tmptuple = beacon.split(',') print tmptuple #uuid = tmptuple[1].lower() #print tmptuple[1][:4] #minor = tmptuple[3] #idnum = int(tmptuple[2])*100 + int(tmptuple[3]) #if (uuid == "1534516467ab3e49f9d6e29000000008"): #(uuid == 1534516467ab3e49f9d6e29000000008") and (int(minor) in minorlist): #rssi = tmptuple[5] #print idnum #rssiDict[str(idnum)] = rssi return rssiDict
def getPower(): # print "------------------" # print datetime.datetime.now() returnedList = blescan.parse_events(sock, 5) # print "----------" + datetime.datetime.now() # print datetime.datetime.now() # print magFunctions.read_bearing() # print datetime.datetime.now() # print returnedList[0]; for beacon in returnedList: # print beacon[0:17] # print beacon[0:2] if(beacon[0:2] == "d7"): return beacon[len(beacon)-2:len(beacon)] #print beacon return 0 #print datetime.datetime.now()
def funcion(self): dev_id = 0 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) blescan.hci_enable_le_scan(sock) cont = 0 #daydatetime timecurrent y luego el tiempo en cada tramo returnedList = blescan.parse_events(sock, 5) potencia = [] indice = [] for allbeacons in returnedList: words = allbeacons.split(',') idb = words[1][-3:] idbeacons,hayBeacon = self.dicc(int(words[2]),int(words[3]),idb) if hayBeacon == 0: idbeacons = [0] indice.append(int(cont)) potencia.append(0) cont = cont+1; if hayBeacon == 1: if int(idbeacons[0]) in indice: indice.append(int(cont)) potencia.append(0) else: indice.append(int(idbeacons[0])) aniadir = 100 + (int(words[5])) #potencia.append(-int(words[5])) potencia.append(aniadir) cont = cont+1; return potencia, indice
def scanloop(): dev_id = 0 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) blescan.hci_enable_le_scan(sock) while True: global beacon beacon = '' #if(beacon==''): #initMSGObj = {'TheKidLoc': "CHILD_DISAPPEAR", 'Control': 'BLE_SCAN', 'Source': "NODE-RPi", 'BLEUUID': beacon[18:50]} #initMSGSTR = json.dumps(initMSGObj) #nit.DirectMSG(beacon[18:50]+"/NODE-RPi", initMSGSTR) #time.sleep(1) returnedList = blescan.parse_events(sock, 1) #print("----------") for beacon in returnedList: #print(beacon[18:50]) pass #'TopicName': "fda50693a4e24fb1afcfc6eb07647825/NODE-RPi" if(beacon!=''): initMSGObj = {'TheKidLoc': NodeUUID, 'Control': 'BLE_SCAN', 'Source': "NODE-RPi", 'BLEUUID': beacon[18:50]} initMSGSTR = json.dumps(initMSGObj) #print("test--test--test") nit.DirectMSG(beacon[18:50]+"/NODE-RPi", initMSGSTR) time.sleep(1)
def bleDetect(source, repeatcount, queue): 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) while True: returnedList = blescan.parse_events(sock, repeatcount) #print "result put in queue" #print "returnList = ", returnedList queue.put(returnedList)
def run(): while True: returnedList = blescan.parse_events(sock, 5) currenttime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") measurements = {} results = [] #loop through all, get values for beacon in returnedList: beaconAsArray = beacon.split(",", 6) if beaconAsArray[0] in measurements: measurements[beaconAsArray[0]].append(beaconAsArray[5]) else: measurements[beaconAsArray[0]] = [beaconAsArray[5]] results.append({'datetime': currenttime, 'mac': beaconAsArray[0], 'uuid': beaconAsArray[1], 'major': beaconAsArray[2], 'minor': beaconAsArray[3], 'value': 0}) #calculate median and put result in results for k,v in measurements.iteritems(): for entry in results: if entry['mac'] == k: entry['value'] = median(v) #insert into queue q.put(results)
def main(): #Open and configure ble scanning devId = 0 try: sock = blescan.getBLESocket(devId) print("Now looking for iBeacon packets") except: print("Error accessing bluetooth device") sys.exit(1) blescan.hci_le_set_scan_parameters(sock) #Begin Scanning blescan.hci_enable_le_scan(sock) #Main Loop while True: returnedList = blescan.parse_events(sock, 10) #This line will only return when at least one packet is found print("----------") for beacon in returnedList: #print(beacon) respondToFoundPacket(beacon)
def getdata(): 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] == black: #Change this to the colour of you tilt tempf = float(output[2]) #convert the string for the temperature to a float type tempc = (float(output[2]) - 32)*5/9 #tempc = round(tempc) gotData = 1 tiltTime = sheetsDate(datetime.datetime.now()) tiltSG = float(output[3])/1000 tiltTemp = tempf tiltColour = 'BLACK' tiltBeer = 'test' #Change to an identifier of a particular brew #assign values to a dictionary variable for the http POST to google sheet data= { 'Timepoint': tiltTime, 'SG': tiltSG, 'Temp': tiltTemp, 'Color': tiltColour, 'Beer': tiltBeer, 'Comment': "" } blescan.hci_disable_le_scan(sock) return data
def default_page(): dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) app.logger.info("ble thread started") except: app.logger.info("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) app.logger.info(returnedList) print "----------" setti = set() stop_name = "" for beacon in returnedList: if '2f234454cf6d4a0fadf2f4911ba9ffa6' in beacon: app.logger.info("beacon loydetty") r = requests.get("http://stop2.herokuapp.com/stop/2f234454-cf6d-4a0f-adf2-f4911ba9ffa6") content = r.content content = json.loads(content) stop_name = content['stop_name'] palautus = "<h3>Press button to stop bus:</h3> " for asd in content['schedule']: setti.add(asd['line']) arrival = datetime.fromtimestamp(int(asd['arrival'])).strftime('%H:%M') palautus += " <div class='btn btn-lg stop_bus' style='margin:5px;color:white;background:#F092CD;' id='" + asd['line'] + "'>" + asd['line'] + " " + arrival \ + "</div> " content = palautus break else: content = "<h3>You're not near stop</h3>" app.logger.info("beacon EI loydetty") return render_template('index_templatelocal.html', content=content, setti=setti, stop_name=stop_name)
def scan(self): return blescan.parse_events(self.sock, self.loops)
ratio = -1*((txs - rss)/(10*const)) return pow(10, ratio) 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) blescan.hci_enable_le_scan(sock) while True: returnedList = blescan.parse_events(sock, 4) print "----------" for beacon in returnedList: s=beacon.split(',') if s[1].find('11111111')>-1: rssi[0] = int(s[5]) txString[0] = int(s[4]) propConst[0] = calculateN(txString[0], rssi[0]) distance[0] = calculateDistance(txString[0], rssi[0]) elif s[1].find('22222222')>-1: rssi[1] = int(s[5]) txString[1] = int(s[4]) propConst[1] = calculateN(txString[1], rssi[1]) distance[1] = calculateDistance(txString[1], rssi[1]) elif s[1].find('33333333')>-1: rssi[2] = int(s[5])
blescan.hci_enable_le_scan(sensor_1) blescan.hci_le_set_scan_parameters(sensor_2) blescan.hci_enable_le_scan(sensor_2) blescan.hci_le_set_scan_parameters(sensor_3) blescan.hci_enable_le_scan(sensor_3) rssi_1 = [] rssi_2 = [] rssi_3 = [] distance_1 = 0 distance_2 = 0 distance_3 = 0 while True: output_1 = blescan.parse_events(sensor_1, 1) if len(rssi_1) < 5: distance_1 = 0 if output_1 != '': rssi_1.append(output_1) else: rssi_1.remove(min(rssi_1)) rssi_1.remove(min(rssi_1)) distance_1 = calcDistance(min(rssi_1)) output_2 = blescan.parse_events(sensor_2, 1) if len(rssi_2) < 5: distance_2 = 0 if output_2 != '': rssi_2.append(output_2) else: