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()
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 _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 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 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 __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 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 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 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 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 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 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 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 _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 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 init(bt_id): try: sock = bluez.hci_open_dev(bt_id) except: print('error accessing bluetooth device...') sys.exit(1) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock)
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
def init(self): try: self.sock = bluez.hci_open_dev(self.dev_id) self.logger.info("Loading Scanner ...") except: self.logger.error("No bluetooth controller found ...") sys.exit(1) blescan.hci_le_set_scan_parameters(self.sock) blescan.hci_enable_le_scan(self.sock)
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 as e: print(e)
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 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 __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
def scanble(comp): dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) except: error("error accessing bluetooth device... in ble.py") sys.exit(1) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) stop = 0 savebeacon = [] c = open("scanble.csv", "w") while stop != 1: returnedList = blescan.parse_events(sock, 30) finalList = [] for beacon in returnedList: if str(beacon[0:17]) not in str(finalList): finalList.append(str(beacon)) else: pass savebeacon = finalList for beacon in finalList: stamp = time.time() beacon = beacon.replace("\"", "") macID = getserial() c.write( str(macID) + "," + str(stamp) + "," + beacon + ",ble_" + str(comp) + "\n") stop = stop + 1 c.close() bcj('scanble.csv') o = 0 if checkInternet() == True: try: send('scanble.json') except: error('error while sending in ble.py') else: try: while os.path.isfile('saveble' + str(o) + '.csv') == True: o = o + 1 saveble = open('saveble' + str(o) + '.csv', 'a') z = o for beacon in savebeacon: stamp = time.time() fichtre = getserial() saveble.write( str(fichtre) + "," + str(stamp) + "," + beacon + ",sb_" + str(z) + "\n") saveble.close() except: error('Can\'t save ble in ble.py')
def get_data(): 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) return monitor_tilt(sock)
def __init__(self, deviceId=0, loops=1): self.deviceId = deviceId self.loops = loops try: self.sock = bluez.hci_open_dev( self.deviceId) #Abre uma conexao com o bluetooth blescan.hci_le_set_scan_parameters( self.sock) #Configura os paramentos para o escaneamento blescan.hci_enable_le_scan( self.sock) #Escaneia dispositivos proximos except Exception, e: print e
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
def init(): dev_id = 0 try: sock = bluez.hci_open_dev(dev_id) print('Starting pytilt logger') except: print('error accessing bluetooth device...') sys.exit(1) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) print("Started physical device..") return sock
def init_ble(): try: # open hci0 interface sock = bluez.hci_open_dev(0) print "ble thread started" except: print "error accessing bluetooth device..." sys.exit(1) blescan.hci_le_set_scan_parameters(sock) # set scan params blescan.hci_enable_le_scan(sock) # start scanning return sock
def startScan(self): dev_id = 0 try: self.sock = bluez.hci_open_dev(dev_id) blescan.hci_le_set_scan_parameters(self.sock) blescan.hci_enable_le_scan(self.sock) blescan.cbLog = self.cbLog return True except Exception as ex: self.cbLog( "warning", "Problem starting Bluetooth scan, type: " + str(type(ex)) + ", args: " + str(ex.args)) return False
def print_beacons(): 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) return blescan.parse_events(sock, 20)
def scanble(comp): dev_id = 0 id = getserial() try: sock = bluez.hci_open_dev(dev_id) except: error("error accessing bluetooth device... in ble.py") sys.exit(1) while os.path.isfile('ble_' + str(comp) + '.json') == True or os.path.isfile('sb_' + str(comp) + '.json') == True: comp = comp + 1 lb = threading.Thread(target=lookBack, args=(comp, )) if checkInternet() == True: file = 'ble_' + str(comp) + '.csv' idp = 'ble_' + str(comp) else: file = 'sb_' + str(comp) + '.csv' idp = 'sb_' + str(comp) f = open(file, 'w') t1 = time.time() blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) stop = 0 savebeacon = [] while stop != 1: returnedList = blescan.parse_events(sock, 30) t2 = time.time() print "scan ble : " + str(t2 - t1) finalList = [] for beacon in returnedList: if str(beacon[0:17]) not in str(finalList): finalList.append(str(beacon)) savebeacon = finalList for beacon in finalList: stamp = time.time() beacon = beacon.replace("\"", "") f.write( str(id) + "," + str(stamp) + "," + beacon + "," + idp + "\n") stop = stop + 1 f.close() f = open(file, 'r') jfile = bcj(file) if checkInternet() == True: send(jfile) # lb.start() lookBack(comp)
def init(): 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) return sock
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 init(): 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) return sock
def start_scanner(): 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) return sock
def scan_bl(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) temp_list = [] n = 0 while (n < 10): for beacon in returnedList: cur_scanned_beacons = [] # print(beacon) beacon_parsed_list = beacon.split(',') beacon_MAC = beacon_parsed_list[0] beacon_RSSI = beacon_parsed_list[5] 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"] beacon.temp_rssi_list.append(beacon.rssi) if (beacon not in temp_list): temp_list.append(beacon) n += 1 if not temp_list: self.cur_beacon = self.default return max = 1000 for beacon in temp_list: temp_total = 0 aver_count = 0 for v in beacon.temp_rssi_list: temp_total += 1 aver_count += abs(int(v)) if (temp_total != 0): aver_count = aver_count / temp_total print aver_count, "aver", max, "max" if (aver_count < max): max = aver_count self.cur_beacon = beacon print "cur", self.cur_beacon beacon.temp_rssi_list = [] self.update_menu(1)
def xy(minor): 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: pollBLE(sock,minor)
def __init__(self): threading.Thread.__init__(self) self.beaconsList =[] self.running = 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)
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 createSocket(port_id): try: sock = bluez.hci_open_dev(port_id) print "ble thread started on ", port_id blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) flt = bluez.hci_filter_new() bluez.hci_filter_all_events(flt) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) test.append(sock) except: print "error accessing bluetooth device on ", port_id
def __init__(self, device_name, rest_url, beacons): """Gets configuration""" self.device_name = device_name self.rest_url = rest_url self.beacons = beacons if not mock: dev_id = 0 try: self.sock_bt = 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_bt) blescan.hci_enable_le_scan(self.sock_bt)
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 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 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 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 main(): try: global sock 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) global q q = Queue.Queue() t = threading.Thread(target=submitWorker) t.daemon = True t.start() run() q.join()
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 createSocket(port_id): try: sock = bluez.hci_open_dev(port_id) print "ble thread started on ", port_id blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) old_filter = sock.getsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, 14) # print "Bluez hci filter:", bluez.HCI_FILTER # print "Old filter", old_filter, "end" flt = bluez.hci_filter_new() # print "New filter", flt, "end" # bluez.hci_filter_set_event(bluez.SCAN_RSP) bluez.hci_filter_all_events(flt) # print "All events", flt, "end" # printpacket(flt) bluez.hci_filter_set_ptype(flt, bluez.HCI_EVENT_PKT) sock.setsockopt( bluez.SOL_HCI, bluez.HCI_FILTER, flt ) socketList.append(sock) except: print "error accessing bluetooth device on ", port_id
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): #Keep scanning until the manager is told to stop. while self.scanning: try: sock = bluez.hci_open_dev(self.dev_id) except Exception, e: print "ERROR: Accessing bluetooth device: " + e.message sys.exit(1) blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) try: #Keep scanning until the manager is told to stop. while self.scanning: self.processSocket(sock) reloaded = self.reloadSettings(); if (reloaded): break except Exception, e: print "ERROR: Accessing bluetooth device whilst scanning: " + e.message print "Resetting Bluetooth device"
m = 1 dev_ids = [0, 1, 2] socks = {} try: for dev_id in dev_ids: socks[dev_id] = bluez.hci_open_dev(dev_id) print "ble thread started" except: print "error accessing bluetooth device..." sys.exit(1) for dev_id in dev_ids: blescan.hci_le_set_scan_parameters(socks[dev_id]) blescan.hci_enable_le_scan(socks[dev_id]) rssi = [[] for i in dev_ids] while True: for dev_id in dev_ids: returnedList = blescan.parse_events(socks[dev_id], 1) for beacon in returnedList: fields = beacon.split(',') if fields[0] == "ea:2e:a4:78:79:26": rssi[dev_id].append(int(fields[5])) #print dev_id, beacon if sum([len(rssi[i]) >= m for i in dev_ids]) == len(dev_ids): rssi_avg = [float(sum(a)) / len(a) for a in rssi] avg = sum(rssi_avg) / len(rssi_avg) print avg, rssi_avg, rssi rssi = [[] for i in dev_ids]
def main(): """Loop forever getting Vera devices, scanning beacons and phones.""" known_beacons = {} known_phones = {} next_Vera_sync = time.time() next_beacon_scan = time.time() while True: # Get Vera devices if it is time if time.time() >= next_Vera_sync: while True: known_beacons, known_phones = ( configure_known_devices(known_beacons, known_phones)) if known_beacons or known_phones: break logger.debug('No devices to search for, sleeping for %d secs' % VERA_SYNC_RETRY) time.sleep(VERA_SYNC_RETRY) next_Vera_sync = time.time() + VERA_SYNC_PERIOD # Scan for iBeacons if it is time if known_beacons and (time.time() >= next_beacon_scan): try: sock = bluez.hci_open_dev() blescan.hci_le_set_scan_parameters(sock) blescan.hci_enable_le_scan(sock) except: logger.debug( "Error accessing bluetooth device for beacon scan") return 1 sock.settimeout(BEACON_LISTEN_TIMEOUT) try: returnedList = blescan.parse_events(sock, BEACON_LISTEN_QTY) except: returnedList = [] sock.close() # Check for beacons reporting found_beacons = {} for advert in returnedList: advert = advert.split(',') MAC = advert[0].upper() UUID = advert[1] + ',' + advert[2] + ',' + advert[3] UUID = UUID.upper() if MAC in found_beacons or UUID in found_beacons: continue if MAC in known_beacons: address = MAC elif UUID in known_beacons: address = UUID else: continue found_beacons[address] = True if not known_beacons[address]['last_state']: known_beacons[address]['last_state'] = True logger.debug('iBeacon %s now present' % address) if (known_beacons[address]['last_report'] + MIN_REPORT_IDLE_TIME) < time.time(): value = (SCANNER_NAME + ',' + str(FOUND_HOLD_TIME) + ',' + advert[5]) msg_vera('data_request?id=action' + '&DeviceNum=' + known_beacons[address]['id'] + '&serviceId=' + SVC_ID + '&action=SetPresent&newPresentValue=' + value) known_beacons[address]['last_report'] = time.time() known_beacons[address]['last_seen'] = time.time() # Check for beacons that have disappeared for address, beacon in known_beacons.items(): if address in found_beacons: continue if (beacon['last_state'] and beacon['last_seen'] + FOUND_HOLD_TIME < time.time()): known_beacons[address]['last_state'] = False logger.debug('iBeacon %s is now not present' % address) next_beacon_scan = time.time() + BEACON_LISTEN_PERIOD # Scan for phones if it is time for address, phone in known_phones.items(): if phone['next_poll'] > time.time(): continue RSSI = get_RSSI(address) found = RSSI != None if found: if not phone['last_state']: known_phones[address]['last_state'] = True logger.debug('Bluetooth %s now present' % address) value = (SCANNER_NAME + ',' + str(FOUND_HOLD_TIME) + ',' + str(RSSI)) msg_vera('data_request?id=action' + '&DeviceNum=' + known_phones[address]['id'] + '&serviceId=' + SVC_ID + '&action=SetPresent&newPresentValue=' + value) known_phones[address]['last_seen'] = time.time() known_phones[address]['next_poll'] = (time.time() + POLLPERIOD_LIVE) else: if (phone['last_state'] and phone['last_seen'] + FOUND_HOLD_TIME < time.time()): known_phones[address]['last_state'] = False logger.debug('Bluetooth %s is now not present' % address) known_phones[address]['next_poll'] = (time.time() + POLLPERIOD_DEAD) # Sleep 'til next event ready next_event = next_Vera_sync if (next_beacon_scan < next_event) and known_beacons: next_event = next_beacon_scan for _, phone in known_phones.items(): if phone['next_poll'] < next_event: next_event = phone['next_poll'] sleep_time = next_event - time.time() if sleep_time > 0: time.sleep(math.ceil(sleep_time))
def calculateDistance2(txs, rss, const): if rss==0: return -1 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])
elif left[1] > default_position[2]: s.write("st\n") # Servo test command s.write("serr\n") # Wrong command to stop servo test try: sensor_1 = bluez.hci_open_dev(0) sensor_2 = bluez.hci_open_dev(1) sensor_3 = bluez.hci_open_dev(2) except: print "error accessing bluetooth device..." sys.exit(1) blescan.hci_le_set_scan_parameters(sensor_1) 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)