Skip to content

Commit

Permalink
add class 13 material
Browse files Browse the repository at this point in the history
  • Loading branch information
DeqingSun committed Dec 2, 2018
1 parent ca24c25 commit d816edb
Show file tree
Hide file tree
Showing 10 changed files with 787 additions and 0 deletions.
Binary file added class13/Adafruit_Python_BluefruitLE-master.zip
Binary file not shown.
161 changes: 161 additions & 0 deletions class13/bleFunctions.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
<!DOCTYPE HTML>
<html>

<head>
<title>webBluetooth for reading</title>
<script>
//generate template on https://beaufortfrancois.github.io/sandbox/web-bluetooth/generator/

class TestBLEDevice {

constructor() {
this.device = null;
this.onDisconnected = this.onDisconnected.bind(this);
}

request() {
let options = {
"filters": [{
"services": [0x1111]
}]
};
return navigator.bluetooth.requestDevice(options)
.then(device => {
this.device = device;
this.device.addEventListener('gattserverdisconnected', this.onDisconnected);
});
}

connect() {
if (!this.device) {
return Promise.reject('Device is not connected.');
}
return this.device.gatt.connect();
}

readTestService() {
return this.device.gatt.getPrimaryService(0x1111)
.then(service => service.getCharacteristic(0x2222))
.then(characteristic => characteristic.readValue());
}

writeTestService(data) {
return this.device.gatt.getPrimaryService(0x1111)
.then(service => service.getCharacteristic(0x3333))
.then(characteristic => characteristic.writeValue(data));
}

startNotifyTestServive(listener) {
return this.device.gatt.getPrimaryService(0x1111)
.then(service => service.getCharacteristic(0x4444))
.then(characteristic => characteristic.startNotifications())
.then(characteristic => characteristic.addEventListener('characteristicvaluechanged', listener));
}

disconnect() {
if (!this.device) {
return Promise.reject('Device is not connected.');
}
return this.device.gatt.disconnect();
}

onDisconnected() {
console.log('Device is disconnected.');
}
}

var testBLEDevice = new TestBLEDevice();

document.addEventListener("DOMContentLoaded", function (event) {

document.getElementById('connectButton').addEventListener('click', event => {
testBLEDevice.request()
.then(_ => testBLEDevice.connect())
.then(_ => { /* Do something with testBLEDevice... */ })
.catch(error => {
console.log(error)
});
});

document.getElementById('readButton').addEventListener('click', event => {
testBLEDevice.readTestService()
.then(result => {
var dataStr = "Hex:"
for (var i = 0; i < result.byteLength; i++) {
var byteStr = result.getUint8(i).toString(16);
if (byteStr.length == 1) byteStr = "0" + byteStr;
dataStr = dataStr + byteStr;
}
document.getElementById('resultLabel').innerHTML = dataStr;
})
.catch(error => {
console.log(error)
});
});

document.getElementById('writeButton').addEventListener('click', event => {
var bytes = [];
var str = document.getElementById('writeText').value;
while (str.length > 0) {
var segment = str.substr(-2);
if (str.length >= 2) {
str = str.substr(0, str.length - 2);
} else {
str = "";
}
bytes.unshift(parseInt(segment, 16) || 0);
}

var buffer = new Uint8Array(bytes).buffer;
var data = new DataView(buffer);
//console.log(data);
testBLEDevice.writeTestService(data)
.then(result => {})
.catch(error => {
console.log(error)
});
});

function handleNotifications(event) {
let value = event.target.value;
let a = [];
// Convert raw data bytes to hex values just for the sake of showing something.
// In the "real" world, you'd use data.getUint8, data.getUint16 or even
// TextDecoder to process raw data bytes.
for (let i = 0; i < value.byteLength; i++) {
a.push(('00' + value.getUint8(i).toString(16)).slice(-2));
}
document.getElementById('notifyLabel').innerHTML = ('Hex: ' + a.join(""));
}

document.getElementById('notifyButton').addEventListener('click', event => {
testBLEDevice.startNotifyTestServive(handleNotifications)
.then(result => {})
.catch(error => {
console.log(error)
});
});

});
</script>

</head>

<body>
<button type="button" id='connectButton'>Connect</button>
<br>
<br>
<button type="button" id='readButton'>Read value</button>&nbsp; &nbsp; &nbsp;
<label id="resultLabel"></label>
<br>
<br> Hex:
<input type="text" id="writeText" value="123">&nbsp; &nbsp; &nbsp;
<button type="button" id='writeButton'>Write value</button>
<br>
<br>
<button type="button" id='notifyButton'>Enable Notify</button>&nbsp; &nbsp; &nbsp;
<label id="notifyLabel"></label>

</body>

</html>
Binary file added class13/iBeacon Scanner.zip
Binary file not shown.
100 changes: 100 additions & 0 deletions class13/python_access_code/basicNotifyCharacteristics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import DeviceInformation
import uuid
import time
import binascii

#modify name to your's
PERIPHERAL_NAME = 'DeqingDevice'

# Define service and characteristic UUIDs used by the UART service.
READ_UUID = uuid.UUID('00002222-0000-1000-8000-00805F9B34FB')
WRITE_UUID = uuid.UUID('00003333-0000-1000-8000-00805F9B34FB')
NOTIFY_UUID = uuid.UUID('00004444-0000-1000-8000-00805F9B34FB')
MY_SERVICE_UUID = uuid.UUID('00001111-0000-1000-8000-00805F9B34FB')
# '0000XXXX-0000-1000-8000-00805F9B34FB'
# If you use 16bit/4HEX UUID, replace XXXX with your hex

def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

def bytes2int(i):
hex_string = binascii.hexlify(i)
if (hex_string==""):
return 0
return int(hex_string,16)

# Get the BLE provider for the current platform.
ble = Adafruit_BluefruitLE.get_provider()

# Main function implements the program logic so it can run in a background
# thread. Most platforms require the main thread to handle GUI events and other
# asyncronous events like BLE actions. All of the threading logic is taken care
# of automatically though and you just need to provide a main function that uses
# the BLE provider.
def main():
# Clear any cached data because both bluez and CoreBluetooth have issues with
# caching data and it going stale.
ble.clear_cached_data()

# Get the first available BLE network adapter and make sure it's powered on.
adapter = ble.get_default_adapter()
adapter.power_on()
print('Using adapter: {0}'.format(adapter.name))

print('Searching for device...')
try:
adapter.start_scan()
# Search for the first UART device found (will time out after 60 seconds
# but you can specify an optional timeout_sec parameter to change it).
device = ble.find_device(name=PERIPHERAL_NAME,timeout_sec=10)
if device is None:
raise RuntimeError('Failed to find peripheral device!')
finally:
# Make sure scanning is stopped before exiting.
adapter.stop_scan()

print('Connecting to device...')
device.connect(timeout_sec=10) # Will time out after 60 seconds, specify timeout_sec parameter
# to change the timeout.

print('Connected to device')
print('Connected DEVICE: {0} [{1}]'.format(device.name, device.id))

# Once connected do everything else in a try/finally to make sure the device
# is disconnected when done.
try:
# Wait for service discovery to complete for at least the specified
# service and characteristic UUID lists. Will time out after 60 seconds
# (specify timeout_sec parameter to override).
print('Discovering services...')
device.discover([MY_SERVICE_UUID], [NOTIFY_UUID])

# Find the UART service and its characteristics.
serviceObj = device.find_service(MY_SERVICE_UUID)
notifyObj = serviceObj.find_characteristic(NOTIFY_UUID)
print('Nofity characteristic found')

def received(data):
print('Notified: '+hex(bytes2int(data)))

notifyObj.start_notify(received)
print('Waiting for notice')
print('Press Ctrl-C to quit (will take ~30 seconds on OSX).')
while True:
time.sleep(1)

finally:
# Make sure device is disconnected on exit.
device.disconnect()


# Initialize the BLE system. MUST be called before other BLE calls!
ble.initialize()

# Start the mainloop to process BLE events, and run the provided function in
# a background thread. When the provided main function stops running, returns
# an integer status code, or throws an error the program will exit.
ble.run_mainloop_with(main)
92 changes: 92 additions & 0 deletions class13/python_access_code/basicReadCharacteristics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import DeviceInformation
import uuid
import binascii

#modify name to your's
PERIPHERAL_NAME = 'DeqingDevice'

# Define service and characteristic UUIDs used by the UART service.
READ_UUID = uuid.UUID('00002222-0000-1000-8000-00805F9B34FB')
MY_SERVICE_UUID = uuid.UUID('00001111-0000-1000-8000-00805F9B34FB')
# '0000XXXX-0000-1000-8000-00805F9B34FB'
# If you use 16bit/4HEX UUID, replace XXXX with your hex

def int2bytes(i):
hex_string = '%x' % i
n = len(hex_string)
return binascii.unhexlify(hex_string.zfill(n + (n & 1)))

def bytes2int(i):
hex_string = binascii.hexlify(i)
if (hex_string==""):
return 0
return int(hex_string,16)

# Get the BLE provider for the current platform.
ble = Adafruit_BluefruitLE.get_provider()

# Main function implements the program logic so it can run in a background
# thread. Most platforms require the main thread to handle GUI events and other
# asyncronous events like BLE actions. All of the threading logic is taken care
# of automatically though and you just need to provide a main function that uses
# the BLE provider.
def main():
# Clear any cached data because both bluez and CoreBluetooth have issues with
# caching data and it going stale.
ble.clear_cached_data()

# Get the first available BLE network adapter and make sure it's powered on.
adapter = ble.get_default_adapter()
adapter.power_on()
print('Using adapter: {0}'.format(adapter.name))

print('Searching for device...')
try:
adapter.start_scan()
# Search for the first UART device found (will time out after 60 seconds
# but you can specify an optional timeout_sec parameter to change it).
device = ble.find_device(name=PERIPHERAL_NAME,timeout_sec=10)
if device is None:
raise RuntimeError('Failed to find peripheral device!')
finally:
# Make sure scanning is stopped before exiting.
adapter.stop_scan()

print('Connecting to device...')
device.connect(timeout_sec=10) # Will time out after 60 seconds, specify timeout_sec parameter
# to change the timeout.

print('Connected to device')
print('Connected DEVICE: {0} [{1}]'.format(device.name, device.id))

# Once connected do everything else in a try/finally to make sure the device
# is disconnected when done.
try:
# Wait for service discovery to complete for at least the specified
# service and characteristic UUID lists. Will time out after 60 seconds
# (specify timeout_sec parameter to override).
print('Discovering services...')
device.discover([MY_SERVICE_UUID], [READ_UUID])

# Find the UART service and its characteristics.
serviceObj = device.find_service(MY_SERVICE_UUID)
readObj = serviceObj.find_characteristic(READ_UUID)
response = readObj.read_value();
value=bytes2int(response)

print hex(value)

print('Access finished')
finally:
# Make sure device is disconnected on exit.
device.disconnect()


# Initialize the BLE system. MUST be called before other BLE calls!
ble.initialize()

# Start the mainloop to process BLE events, and run the provided function in
# a background thread. When the provided main function stops running, returns
# an integer status code, or throws an error the program will exit.
ble.run_mainloop_with(main)
Loading

0 comments on commit d816edb

Please sign in to comment.