Skip to content

Instantly share code, notes, and snippets.

@tnlogy
Created April 14, 2022 17:58
Show Gist options
  • Save tnlogy/eb7a958d9216f335d117d85b5402da3b to your computer and use it in GitHub Desktop.
Save tnlogy/eb7a958d9216f335d117d85b5402da3b to your computer and use it in GitHub Desktop.
Connect to PineTime on ios with bluetooth on Pythonista 3
import cb
import struct
MOTION_SERVICE = "00030000-78fc-48fe-8e23-433b3a1942d0"
HR_SERVICE = '180d'
STEP = "00030001-78fc-48fe-8e23-433b3a1942d0"
RAW_MOTION = "00030002-78fc-48fe-8e23-433b3a1942d0"
HEART_RATE = '2a37'
CHARACTERISTICS = [STEP, RAW_MOTION, HEART_RATE]
class PineHub:
def __init__(self):
self.peripheral = None
def did_discover_peripheral(self, p):
#print(p.name)
if p.name and 'InfiniTime' in p.name and not self.peripheral:
self.peripheral = p
print('Connecting to PineTime...')
cb.connect_peripheral(p)
def did_connect_peripheral(self, p):
print('Connected:', p.name)
p.discover_services()
def did_fail_to_connect_peripheral(self, p, error):
print('Failed to connect:', error)
def did_disconnect_peripheral(self, p, error):
print('Disconnected, error:', error)
self.peripheral = None
def did_discover_services(self, p, error):
for s in p.services:
#print("service",s.uuid)
if s.uuid.lower() == HR_SERVICE:
print('Discovered heart rate service.')
p.discover_characteristics(s)
elif s.uuid.lower() == MOTION_SERVICE:
print("Discovered Motion Service")
p.discover_characteristics(s)
def did_discover_characteristics(self, s, error):
print('Did discover characteristics...')
for c in s.characteristics:
if c.uuid.lower() in CHARACTERISTICS:
self.peripheral.set_notify_value(c, True)
def did_update_value(self, c, error):
#print("update", c.value, c.uuid)
if c.uuid.lower() == HEART_RATE:
heart_rate = struct.unpack('BB', c.value)[1]
print('Heart rate:', heart_rate)
elif c.uuid.lower() == STEP:
steps = struct.unpack('I', c.value)[0]
print("Steps", steps)
elif c.uuid.lower() == RAW_MOTION:
x,y,z = struct.unpack('hhh', c.value)
print("raw motion:", x,y,z)
ph = PineHub()
cb.set_central_delegate(ph)
cb.scan_for_peripherals()
try:
while True: pass
except KeyboardInterrupt:
cb.reset()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment