def _scan(self): """ This function scans for iBeacon packets, save them in a list, order packets by RSSI and update near beacons attrs accordingly """ def _scans_callback(bt_addr, rssi, packet, additional_info): beacon = IBeacon(bt_addr, packet.uuid, packet.major, packet.minor, packet.tx_power, rssi) if not self._is_beacon_in_list(beacon): self._beacons_list.append(beacon) while (self._run_flag): # clear beacon list self._beacons_list = [] # instance the scanner scanner = BeaconScanner( _scans_callback, device_filter=IBeaconFilter(uuid=self._uuid_filter)) # perform the scan scanner.start() time.sleep(self._scan_tick) scanner.stop() # order the beacons list by RSSI (Power received) if len(self._beacons_list) >= 1: self._order_beacons_list() self._last_nearest_beacon = self._nearest_beacon self._nearest_beacon = self._beacons_list[0] logging.info("Nearest beacon: {}".format(self._nearest_beacon)) else: self._last_nearest_beacon = self._nearest_beacon self._nearest_beacon = None logging.info("No beacons found in this scan") # evaluate if nearest beacon has changes, if so, invoke changes callback if self._check_if_nearest_beacon_changes(): self._invoke_changes_callback()
def scan_ibeacons(): # callback to show beacons read def callback(bt_addr, rssi, packet, additional_info): print("[ MAC: {} | RSSI: {} ] - {}".format(bt_addr, rssi, packet)) # intance the parser parser = argparse.ArgumentParser() # parse uuid argument parser.add_argument( '--uuid', action='store', dest='uuid', help='iBeacon UUID. Def: {}'.format(DEFAULT_BEACON_UUID)) # parse scan_time argument parser.add_argument('--time', action='store', dest='scan_time', help='Scan time. Def: {}'.format(DEFAULT_TIME_TO_SCAN)) # get result of parse arguments in args args = parser.parse_args() uuid = args.uuid if args.uuid is not None else DEFAULT_BEACON_UUID scan_time = args.scan_time if args.scan_time is not None else DEFAULT_TIME_TO_SCAN # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid=uuid)) # start scanning print("Starting to scan beacons with UUID={} for {} seconds".format( uuid, scan_time)) scanner.start() time.sleep(scan_time) scanner.stop() print("Scan beacons finished!")
def run(self): while True: scanner = BeaconScanner( callback, device_filter=IBeaconFilter( uuid='636f3f8f-6491-4bee-95f7-d8cc64a863b5') ) #"b9407f30-f5f8-466e-aff9-25556b57fe6d", major=30174, minor=5667)) #coconut2 #my rpi beacon uuid 636f3f8f-6491-4bee-95f7-d8cc64a863b5 scanner.start() time.sleep(5) scanner.stop()
def main(): # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid="e7d61ea3-f8dd-49c8-8f2f-f2484c07acb9", major=1, minor=81) ) scanner.start() time.sleep(120) scanner.stop() write_file(datalist) print('fin')
def listen(self, uuid, duration): uuid_filter = IBeaconFilter(uuid=uuid) scanner = BeaconScanner(self.record_data, device_filter=uuid_filter) start_time = dt.datetime.now(pytz.utc) self.log.info('Listening for BLE beacons for {}s'.format(duration)) scanner.start() while dt.datetime.now(pytz.utc) - start_time < duration: sleep(1) scanner.stop() self.log.info('Recorded {} temperature readings and {} gravity readings' .format(len(self.data[uuid]['T']), len(self.data[uuid]['SG'])))
def _scan_beacons(**kwargs): beacons_list = [] # read beaconstools callback def _scans_callback(bt_addr, rssi, packet, additional_info): beacon = IBeacon(bt_addr, packet.uuid, packet.major, packet.minor, packet.tx_power, rssi) if beacon not in beacons_list: beacons_list.append(beacon) # create and start scanner in each cycle beaconstools_scanner = BeaconScanner( _scans_callback, device_filter=IBeaconFilter(uuid=kwargs['uuid_filter']) ) beaconstools_scanner.start() time.sleep(kwargs['scan_tick']) beaconstools_scanner.stop() # return beacon_list return beacons_list
def test_process_packet_dev_filter3(self): """Test processing of a packet and callback execution with ibeacon device filter.""" callback = MagicMock() scanner = BeaconScanner(callback, device_filter=IBeaconFilter(major=1)) pkt = b"\x41\x3e\x41\x02\x01\x03\x01\x35\x94\xef\xcd\xd6\x1c\x19\x02\x01\x06\x1a\xff\x4c"\ b"\x00\x02\x15\x41\x42\x43\x44\x45\x46\x47\x48\x49\x40\x41\x42\x43\x44\x45\x46\x00"\ b"\x01\x00\x02\xf8\xdd" scanner._mon.process_packet(pkt) self.assertEqual(callback.call_count, 1) args = callback.call_args[0] self.assertEqual(args[0], "1c:d6:cd:ef:94:35") self.assertEqual(args[1], -35) self.assertIsInstance(args[2], IBeaconAdvertisement) self.assertEqual(args[3], { "uuid": "41424344-4546-4748-4940-414243444546", "major": 1, "minor": 2 })
import time from beacontools import BeaconScanner, IBeaconFilter def callback(bt_addr, rssi, packet, additional_info): if (rssi == 0): dist = -1.0 ratio = rssi*1.0/packet.tx_power dist = (0.89976)*pow(xh,7.7095)+0.111 print("bt_addr: %s " %bt_addr) print("rssi: %d " %rssi) print("Distance %d ",dist) print("tx Power: %s \n" %packet.tx_power) #1: b4:99:4c:4f:97:50 2:b4:99:4c:4f:4d:58 3:b4:99:4c:4f:9a:24 scanner = BeaconScanner(callback,device_filter=IBeaconFilter(uuid="e2c56db5-dffb-48d2-b060-d0f5a71096e0")) print("Zona 5") while(i<300): scanner.start() time.sleep(5) scanner.stop()
currentBeacon = '' startTime = '' with open('currentState.csv', newline='') as f: reader = csv.reader(f) for row in reader: currentState = row[0] currentBeacon = row[1] startTime = row[2] f.close() FigureItOut(minor, currentState, currentBeacon, startTime) # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid="636f3f8f-6491-4bee-95f7-d8cc64a863b5")) scanner.start() time.sleep(5) scanner.stop() # # print('begin') # print("<%s, %d> %s %s" % (bt_addr, rssi, packet, additional_info)) # print('bt_addr') # print(bt_addr) # print(type(bt_addr)) # print('rssi') # print(rssi) # print(type(rssi)) # print('packet') # print(packet)
import time from beacontools import BeaconScanner, IBeaconFilter def callback(bt_addr, rssi, packet, additional_info): print("<%s, %d> %s %s" % (bt_addr, rssi, packet, additional_info)) # scan for all iBeacon advertisements from beacons with the specified uuid if __name__ == "__main__": scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid=str(sys.argv[0]))) print("Scanner returned : ", scanner.start()) time.sleep(5) scanner.stop()
data = np.array([rssi1, rssi2, rssi3]) data = data.reshape(1, -1) predict = knn.predict(data) print(predict) k = cv2.waitKey(100) read1 = False read2 = False read3 = False i = i + 1 # scan for all iBeacon advertisements from beacons with the specified uuid #1: b4:99:4c:4f:97:50 2:b4:99:4c:4f:4d:58 3:b4:99:4c:4f:9a:24 scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid="e2c56db5-dffb-48d2-b060-d0f5a71096e0")) X_data = [] files = glob.glob("*.png") for myFile in files: print(myFile) image = cv2.imread(myFile) X_data.append(image) cv2.imshow('ims', X_data[3]) trainFile = open("TrainData.txt") outFile = open("TrainOut.txt") TrainIn = readData(trainFile) TrainOut = readData(outFile) print(len(TrainOut)) X = np.zeros((int(len(TrainIn) / 3), 3))
def mqtt_iBeacon(): scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid="426c7565-4368-6172-6d42-6561636f6e73")) scanner.start()
"distance": distance, "direction": direction } data_entries.append(entry) if __name__ == "__main__": for direc in direction_list: direction = direc scenario = obstacle + " " + distance + " " + transmission_power + " " + direction input("Press Enter then face " + str(direction)) scanner = BeaconScanner( callback, # remove the following line to see packets from all beacons device_filter=IBeaconFilter(minor=beacon_minor), packet_filter=None) time.sleep(3) print("Scan started at ", datetime.now()) scanner.start() #loop that stops scanning after 60 samples are collected. #uploads all entries to database after while True: if len(data_entries) == 60: scanner.stop() print("Reached 60 samples, trial completed at ", datetime.now()) break try: x = rawcol.insert_many(data_entries)
import time from beacontools import BeaconScanner, IBeaconFilter def callback(bt_addr, rssi, packet, additional_info): print("<%s, %d> %s %s" % (bt_addr, rssi, packet, additional_info)) # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid="e5b9e3a6-27e2-4c36-a257-7698da5fc140")) scanner.start() time.sleep(5) scanner.stop()
# 受信ペイロード長 PAYLOAD_LEN = 58 # デバイススキャンクラスを初期化 # index=0 が /dev/hci0 に対応 scanner = btle.Scanner(0) while True: try: logdate = datetime.datetime.today().strftime("%Y%m%d") # アドレス取得用スキャン # 対象UUIDのデバイスアドレス、RSSIを取得 iBeaconScanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid=UUID)) iBeaconScanner.start() time.sleep(SCAN_TIME) iBeaconScanner.stop() # スキャン結果が取得できなかった if len(deviceList) == 0: log.debug("Device not found") continue # データ取得用スキャン devices = scanner.scan(SCAN_TIME) for addr in deviceList.keys(): log.debug("Device:"+ addr )
csv.writer(f3).writerow(json_data[h] for h in header) def getSeries(df, option): #option is 'temperature' 'humidity' major_type = df.major.unique() series = '[' for i in range(len(major_type)): major = major_type[i] series += '{"name":"Major ' + str(major) + '","data":[' for index, row in df.iterrows(): if row['major'] == major: series += '[' + str(row['timestamp']) + ',' + str( int(row[option])) + '],' series = series[:-1] series += ']},' series = series[:-1] + ']' return series if __name__ == '__main__': scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid=CYPRESS_BEACON_DEFAULT_UUID)) scanner.start() app.run(debug=False, host=ip_addr, port=port)
write_to_influxdb(data) def write_to_influxdb(data): json_body = [{ 'measurement': 'result6', 'time': datetime.datetime.utcnow(), 'fields': data }] db.write_points(json_body) if __name__ == "__main__": #Get the current UNIX time start = time.time() weather_info = get_weather_info.weather_info() try: while True: scanner = BeaconScanner( callback, device_filter=IBeaconFilter( uuid="00050001-0000-1000-8000-00805f9b0131")) scanner.start() time.sleep(1) scanner.stop() except Exception as e: print(e)
import time from beacontools import BeaconScanner, IBeaconFilter, EddystoneTLMFrame, EddystoneFilter, EddystoneUIDFrame, \ EddystoneURLFrame def callback(bt_addr, rssi, packet, additional_info): print('----------------------------------------------------') # print("%s - %d - %s - %s\n-" % (bt_addr, rssi, packet, additional_info)) print(packet.namespace) beacon_type = input("iBeacon / Eddystone - (i/e)") if beacon_type == 'i': # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid="b9407f30-f5f8-466e-aff9-25556b57fe6d") ) scanner.start() while True: pass scanner.stop() elif beacon_type == 'e': try: if input("all/one (a/o): ") == 'o':
"tags": { "Sensor Number": id, "Sensor Type": type, "Location": Location }, "fields": { "value": mydict[meas] } } points.append(point) if debug_ble: print(points) return points if __name__ == "__main__": ''' Start this script in background with : " sudo beacontest.py & " ''' debug_ble = False site.ENABLE_USER_SITE = False al = [1555087419, "9999"] scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid="2332a4c2")) scanner.start() while True: time.sleep(5) # scanner.stop()
# スキャン回数:初期値 count = initCount while True: logdate = datetime.datetime.today().strftime("%Y%m%d") # デバイススキャン if sendCount == 0 and count == initCount: # デバイススキャンクラスを初期化 # index=0 が /dev/hci0 に対応 scanner = btle.Scanner(0) # 対象UUIDのデバイスアドレス、RSSIを取得 iBeaconScanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid=targetUuid)) iBeaconScanner.start() time.sleep(scantime) iBeaconScanner.stop() # スキャン結果が取得できなかった if len(deviceList) == 0: sendCount = 0 count = initCount continue # メイン処理実行 main(count) # スキャン回数上限チェック if count < getDataCount:
the_datetime2 = tz.localize(now + datetime.timedelta(minutes=10)) body = { "timeMin": the_datetime.isoformat(), "timeMax": the_datetime2.isoformat(), "timeZone": 'US/Eastern', "items": [{ "id": '*****@*****.**' }] } eventsResult = service.freebusy().query(body=body).execute() cal_dict = eventsResult[u'calendars'] busyResult = eventsResult["calendars"]["*****@*****.**"]["busy"] scanner = BeaconScanner(callback, device_filter=IBeaconFilter( uuid="61687109-905f-4436-91f8-e602f514c96d")) scanner.start() print("scanner started") time.sleep(5) scanner.stop() print("scanner stopped") if not present: print("Resident is not Present") if len(busyResult) == 0: print("Resident is also not busy") email(user, password, destination) else: print("Resident is Busy, no email sent") else: print("Resident is Present")
def callback(addr, rssi, packet, additional_info): global data_num time = datetime.now() if conf.SHOW_MSG: msg = "%s,%s,%s,%s,%s,%s,%s,%s" % (time, data_num, my_id, ids[addr], addr, packet.uuid, msgs[addr], rssi) else: msg = "%s,%s,%s,%s,%s,%s,%s" % (time, data_num, my_id, ids[addr], addr, packet.uuid, rssi) data_num += 1 logger.info(msg) s.sendall(msg.encode()) # server_reply = s.recv(1024).decode() # print(server_reply) scanner = None if conf.SCAN_ALL_TAGS: scanner = BeaconScanner(callback) else: device_filter = [] for id, prop in conf.BEACONS.items(): device_filter.append(IBeaconFilter(prop['UUID'])) scanner = BeaconScanner(callback, device_filter=device_filter) scanner.start() while True: time.sleep(10) s.close() # close connection
global topic rssi_list.append(rssi) if len(rssi_list) >= 10: rssi_list = rssi_list[-10:] avg_rssi = sum(sorted(rssi_list[1:8])) / 8 print("RSSI: " + str(avg_rssi)) print("Distance: " + str(calculateAccuracy(-64.0, avg_rssi))) message = {} message['ID'] = "PI-2" message['time'] = int(time.mktime(datetime.now().timetuple())) message['distance'] = str(calculateAccuracy(-64.0, avg_rssi)) message['message'] = "hello" messageJson = json.dumps(message) myAWSIoTMQTTClient.publish(topic, messageJson, 1) print('Published topic %s: %s\n' % (topic, messageJson)) #---------------------------------------------------------------------- while True: scanner = BeaconScanner(callback, device_filter=IBeaconFilter( uuid="426c7565-4368-6172-6d42-6561636f6e73")) scanner.start() time.sleep(30) scanner.stop()
lrssi2.clear() def callback3(bt_addr, rssi, packet, additional_info): #print("<%s, %d> %s %s" % (bt_addr, rssi, packet, additional_info)) lrssi3.append(rssi) if len(lrssi3) == 10: avg = sum(lrssi3) / float(len(lrssi3)) print("Beacon 3: %f\n" % caldis1(avg)) lrssi3.clear() # scan for all iBeacon advertisements from beacons with the specified uuid scanner1 = BeaconScanner( callback1, device_filter=IBeaconFilter(uuid="c401da18-6d38-4b61-9b3e-ff3790f0eeb2")) scanner2 = BeaconScanner( callback2, device_filter=IBeaconFilter(uuid="2f234454-cf6d-4a0f-adf2-f4911ba9ffa6")) scanner3 = BeaconScanner( callback3, device_filter=IBeaconFilter(uuid="2f4168bf-06f0-4832-8803-a8f8472d2479")) scanner1.start() scanner2.start() scanner3.start() while (1): time.sleep(5) scanner1.stop() scanner2.stop() scanner3.stop()
# # ) # IBeaconFilter(uuid="fda50693-a4e2-4fb1-afcf-c6eb07647825"), # IBeaconFilter(uuid="d546df97-4757-47ef-be09-3e2dcbdd0c77") # IBeaconFilter(uuid="426c7565-4368-6172-6d42-6561636f6e73"), # scanner.start() # time.sleep(10) # scanner.stop() # # scan for all iBeacon advertisements regardless from which beacon scanner1 = BeaconScanner( callback, packet_filter=IBeaconAdvertisement, device_filter=[ IBeaconFilter(uuid="fda50693-a4e2-4fb1-afcf-c6eb07647825"), IBeaconFilter(uuid="d546df97-4757-47ef-be09-3e2dcbdd0c77"), IBeaconFilter(uuid="426c7565-4368-6172-6d42-6561636f6e73"), IBeaconFilter(uuid="526c7565-4368-6172-6d42-6561636f6e73"), ], scan_parameters={ "interval_ms": 100, "window_ms": 90 }) # scanner2 = BeaconScanner(callback, # packet_filter=IBeaconAdvertisement, # device_filter=[IBeaconFilter(uuid="d546df97-4757-47ef-be09-3e2dcbdd0c77")], # scan_parameters={"interval_ms":100, "window_ms":90} # ) # scanner3 = BeaconScanner(callback, # packet_filter=IBeaconAdvertisement,
import websockets import asyncio SERVER = "localhost" PORT = 8081 async def post(output): uri = f"ws://{SERVER}:{PORT}" async with websockets.connect(uri) as websocket: await websocket.send(output) # print(await websocket.recv()) def callback(bt_addr, rssi, packet, additional_info): print(f"sending RSSI: {rssi}") output = json.dumps({ 'tool_id': f"{additional_info['major']}.{additional_info['minor']}", 'recv_bd_addr': bluetooth.read_local_bdaddr(), 'rssi': rssi }) asyncio.run(post(output)) scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid="b2ddeadb-eef0-0000-0000-000000000000")) scanner.start() time.sleep(600) scanner.stop()
#writer.DictWriteheader#for dat in data: #for dat in data: writer.writerow([ data['Minor'], data['RSSI'], data['Average_RSSI'], data['Distance'], data['time'] ]) except IOError: print("I/O error") def getdistance(rssi, txpower): txpower = int(txpower) #one meter away RSSI if rssi == 0: return -1 else: ratio = rssi * 1.0 / txpower if ratio < 1: return ratio**10 else: return 0.89976 * ratio**7.7095 + 0.111 scanner = BeaconScanner(callback, device_filter=IBeaconFilter( uuid="f7826da6-4fa2-4e98-8024-bc5b71e0893e", major=7142)) scanner.start() #time.sleep(5) #scanner.stop()
import time import webbrowser import sys,threading from beacontools import BeaconScanner, IBeaconFilter rangeMax = -38 def callback(bt_addr, rssi, packet, additional_info): print(threading.current_thread().) if rssi > rangeMax: print("aqui, <%d>" %(rssi)) #else: # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid="00000003-0000-0000-0000-000000000000")) scanner.start() # time.sleep(0.5) # scanner.stop()
def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except: ip = 'unknown' finally: s.close() return ip # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner(callback, device_filter=IBeaconFilter(uuid=filter_uuid, major=filter_major, minor=filter_minor)) ip_address = get_ip() print("ip: " + ip_address) try: scanner.start() while True: ping_server() time.sleep(5) except Exception as e: print(e) scanner.stop() except KeyboardInterrupt:
from beacontools import BeaconScanner, IBeaconFilter from datetime import datetime, timedelta import csv import platform def callback(bt_addr, rssi, packet, additional_info): print("<%s, %d> %s %s" % (bt_addr, rssi, packet, additional_info)) uuid = additional_info["uuid"] major = additional_info["major"] minor = additional_info["minor"] receiver = platform.uname()[1] timestamp = str(datetime.now()) with open('BeaconRecord_' + receiver + '.csv', 'a') as f: writer = csv.writer(f) writer.writerow([uuid, major, minor, rssi, receiver, timestamp]) time.sleep(5) # scan for all iBeacon advertisements from beacons with the specified uuid scanner = BeaconScanner( callback, device_filter=IBeaconFilter(uuid="00000000-b53c-1001-b000-001c4d5c1dd0")) scanner.start() while True: i = 0 scanner.stop()