├── OralBlue ├── __init__.py ├── BrushInfo.py ├── BrushBattery.py ├── BrushMode.py ├── BrushState.py ├── BrushSector.py ├── BrushSignal.py ├── OralBDate.py ├── BrushSession.py ├── OralBAdvertise.py └── OralBToothbrush.py ├── requirements.txt ├── README.md ├── OralBScanMain.py ├── test ├── OralBDate.py ├── BrushSessionTest.py └── OralBAdvertiseTest.py ├── OralBConnectMain.py ├── .gitignore ├── Protocol.md └── LICENSE /OralBlue/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | bluepy==1.2.0 2 | -------------------------------------------------------------------------------- /OralBlue/BrushInfo.py: -------------------------------------------------------------------------------- 1 | from typing import NamedTuple 2 | 3 | class BrushInfo(NamedTuple): 4 | type:int 5 | protocolVersion:int = -1 6 | fwversion:int = 1 7 | -------------------------------------------------------------------------------- /OralBlue/BrushBattery.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | from typing import NamedTuple 3 | 4 | class BrushBattery(NamedTuple): 5 | level:int 6 | remainingSec:timedelta = None 7 | -------------------------------------------------------------------------------- /OralBlue/BrushMode.py: -------------------------------------------------------------------------------- 1 | from enum import IntEnum 2 | 3 | 4 | class BrushMode(IntEnum): 5 | OFF = 0x00 6 | DAILY_CLEAN = 0x01 7 | SENSITIVE = 0x02 8 | MASSAGE = 0x03 9 | WHITENING = 0x04 10 | DEEP_CLEAN = 0x05 11 | TONGUE_CLEANING = 0x06 12 | TURBO = 0x07 13 | UNKNOWN = 0xFF 14 | 15 | @classmethod 16 | def _missing_(cls, value): 17 | return BrushMode.UNKNOWN 18 | -------------------------------------------------------------------------------- /OralBlue/BrushState.py: -------------------------------------------------------------------------------- 1 | from enum import IntEnum 2 | 3 | 4 | class BrushState(IntEnum): 5 | UNKNOWN = 0x00 6 | INIT = 0x01 7 | IDLE = 0x02 8 | RUN = 0x03 9 | CHARGE = 0x4 10 | SETUP = 0x05 11 | FLIGHT_MENU = 0x06 12 | FINAL_TEST = 0x71 13 | PCB_TEST = 0x72 14 | SLEEP = 0x73 15 | TRANSPORT = 0x74 16 | 17 | @classmethod 18 | def _missing_(cls, value): 19 | return BrushState.UNKNOWN 20 | -------------------------------------------------------------------------------- /OralBlue/BrushSector.py: -------------------------------------------------------------------------------- 1 | from enum import IntEnum 2 | 3 | 4 | class BrushSector(IntEnum): 5 | SECTOR_1 = 0x00 6 | SECTOR_2 = 0x01 7 | SECTOR_3 = 0x02, 8 | SECTOR_4 = 0x03, 9 | SECTOR_5 = 0x04 10 | SECTOR_6 = 0x05 11 | SECTOR_7 = 0x07 12 | SECTOR_8 = 0x08 13 | LAST_SECTOR = 0xFE 14 | NO_SECTOR = 0xFF 15 | 16 | @classmethod 17 | def _missing_(cls, value): 18 | return BrushSector.NO_SECTOR 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OralBlue_python 2 | Python library to read the data from an OralB toothbrush 3 | 4 | #Installation 5 | This project is developed with Python 3.6. 6 | 7 | Install the dependecy with: 8 | 9 | `pip install -r requirements.txt` 10 | 11 | # Run 12 | 13 | ## [OralBScanMain](OralBScanMain.py) 14 | This project must be run as a root (bluepy require the root acces to do a ble scan). 15 | 16 | This program scann for the toothbush, and display the available information inside the advertise 17 | 18 | ## [OralBConnectMain](OralBConnectMain.py) 19 | 20 | If this program works we are 10m away! 21 | 22 | This program, connect to a specific toothbrush and start reading data or changing the settings. 23 | It hasn't any utility is done just to test the API 24 | 25 | -------------------------------------------------------------------------------- /OralBlue/BrushSignal.py: -------------------------------------------------------------------------------- 1 | from typing import NamedTuple 2 | 3 | class BrushSignal(NamedTuple): 4 | vibrate:bool = False 5 | finalVibrate:bool = False 6 | visualSignal:bool = False 7 | finalVisualSignal:bool = False 8 | 9 | @staticmethod 10 | def fromInt(value:int)->'BrushSignal': 11 | return BrushSignal( 12 | vibrate = bool(value & 0x01), 13 | finalVibrate = bool(value & 0x02), 14 | visualSignal = bool(value & 0x04), 15 | finalVisualSignal = bool(value & 0x08) 16 | ) 17 | 18 | def toInt(self)->int: 19 | value = 0 20 | if self.vibrate: 21 | value = value | 1 22 | if self.finalVibrate: 23 | value = value | 2 24 | if self.visualSignal: 25 | value = value | 4 26 | if self.finalVisualSignal: 27 | value = value | 8 28 | return value -------------------------------------------------------------------------------- /OralBlue/OralBDate.py: -------------------------------------------------------------------------------- 1 | import struct 2 | from datetime import timedelta, datetime 3 | 4 | 5 | class OralBDate(object): 6 | _BASEDATE = datetime(year=2000, month=1, day=1) 7 | 8 | def __init__(self, data: bytes): 9 | if len(data) != 4: 10 | raise ValueError 11 | secAfter2000 = struct.unpack("bytes: 20 | return OralBDate._toBytes(self.datetime) 21 | 22 | @staticmethod 23 | def _toBytes(date:datetime)->bytes: 24 | secAfter2000 = (date - OralBDate._BASEDATE).total_seconds() 25 | return struct.pack("'OralBDate': 29 | return OralBDate(OralBDate._toBytes(date)) 30 | -------------------------------------------------------------------------------- /OralBScanMain.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | from bluepy.btle import Scanner, DefaultDelegate, ScanEntry 3 | 4 | from OralBlue.OralBAdvertise import OralBAdvertise 5 | 6 | # create a delegate class to receive the BLE broadcast packets 7 | class OralBScanDelegate(DefaultDelegate): 8 | 9 | def handleNotification(self, cHandle, data): 10 | pass 11 | 12 | @staticmethod 13 | def _printNewDevice(device: ScanEntry, adv: OralBAdvertise): 14 | printMe = "New device detected:\n" \ 15 | "Address: {}\n" \ 16 | "Type: {}\n" \ 17 | "FwVersion: {}\n".format(device.addr, str(adv.typeId), adv.fwVersion) 18 | print(printMe) 19 | print(str(adv)) 20 | 21 | # when this python script discovers a BLE broadcast packet, print a message with the device's MAC address 22 | def handleDiscovery(self, dev: ScanEntry, isNewDev: bool, isNewData): 23 | advertise = OralBAdvertise.buildFromScanEntry(dev) 24 | 25 | if advertise is None: 26 | return 27 | 28 | if isNewDev: 29 | OralBScanDelegate._printNewDevice(dev,advertise) 30 | elif isNewData: 31 | print(str(advertise)) 32 | 33 | 34 | if __name__ == '__main__': 35 | # create a scanner object that sends BLE broadcast packets to the ScanDelegate 36 | scanner = Scanner().withDelegate(OralBScanDelegate()) 37 | 38 | # start the scanner and keep the process running 39 | scanner.start() 40 | while True: 41 | print("Still running...") 42 | scanner.process() 43 | -------------------------------------------------------------------------------- /test/OralBDate.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import datetime 3 | 4 | from OralBlue.OralBDate import OralBDate 5 | 6 | 7 | class OralBDateTestCase(unittest.TestCase): 8 | 9 | def test_theConstructorThrowIfTheDataAreLessThan4Bytes(self): 10 | with self.assertRaises(ValueError): 11 | OralBDate(b"\x00") 12 | 13 | def test_theConstructorThrowIfTheDataAreMoreThan4Bytes(self): 14 | with self.assertRaises(ValueError): 15 | OralBDate(b"\x00\x00\x00\x00\x00") 16 | 17 | def test_theBytesAreTheSecondAfter2000gen1(self): 18 | date = OralBDate(b"\x00\x00\x00\x00") 19 | self.assertEqual(date.datetime, datetime(year=2000, month=1, day=1)) 20 | 21 | def test_theBytesAreInLittleEndian(self): 22 | date = OralBDate(b"\x01\x00\x00\x00") 23 | self.assertEqual(date.datetime, datetime(year=2000, month=1, day=1,second=1)) 24 | 25 | def test_toByteReturnTheOriginalSequence(self): 26 | byteSeq = b"\x01\x02\x03\x04" 27 | date = OralBDate(byteSeq) 28 | self.assertEqual(byteSeq,date.toBytes()) 29 | 30 | def test_fromDatetimeConvertToOralBDate(self): 31 | byteSeq1 = b"\x00\x00\x00\x00" 32 | date1 = datetime(year=2000,month=1,day=1) 33 | oralb1 = OralBDate(byteSeq1) 34 | self.assertEqual(oralb1.toBytes(),byteSeq1) 35 | byteSeq2 = b"\x05\x00\x00\x00" 36 | date2 = datetime(year=2000, month=1, day=1,second=5) 37 | oralb2 = OralBDate(byteSeq2) 38 | self.assertEqual(oralb2.toBytes(), byteSeq2) 39 | 40 | if __name__ == '__main__': 41 | unittest.main() -------------------------------------------------------------------------------- /OralBConnectMain.py: -------------------------------------------------------------------------------- 1 | # import the necessary parts of the bluepy library 2 | from datetime import datetime 3 | 4 | from bluepy.btle import BTLEException 5 | 6 | from OralBlue.BrushBattery import BrushBattery 7 | from OralBlue.BrushSignal import BrushSignal 8 | from OralBlue.OralBToothbrush import OralBToothbrush 9 | 10 | if __name__ == '__main__': 11 | device = OralBToothbrush("10:CE:A9:28:93:24",protocolVersion=3) 12 | #device.readBrushMode(lambda x: print("Mode: {}".format(str(x)))) 13 | #device.readBrushState(lambda x: print("State: {}".format(str(x)))) 14 | #device.setBatteryUpdateCallback(lambda x: print("Battery: {} {}".format(x.level,x.remainingSec))) 15 | device.setBrushingTimeUpdateCallback(lambda x: print("Time: {}s".format(x))) 16 | # device.setBrushStateUpdateCallback(lambda x: print("State: {}".format(str(x)))) 17 | # device.setBrushModeUpdateCallback(lambda x: print("Mode: {}".format(str(x)))) 18 | #device.writeAvailableModes([BrushMode.DAILY_CLEAN,BrushMode.WHITENING,BrushMode.SENSITIVE]) 19 | #print(str(device.readModelId())) 20 | #print(str(device.readBatteryStatus())) 21 | #device.setBrushButtonPressedCallback(lambda x: print(str(x))) 22 | 23 | #print(device.readAvailableModes()) 24 | # device.setSectorTimer([30,30,30,30]) 25 | # session = device.readSectorTimer() 26 | # [print(s) for s in session] 27 | # device.setUserId(10) 28 | # print(device.gerUserId()) 29 | #device.writeSignalStatus(BrushSignal(vibrate=True,visualSignal=True)) 30 | while True: 31 | try: 32 | print("wait") 33 | device.waitForNotifications(2) 34 | 35 | except BTLEException as e: 36 | print(e) 37 | break 38 | -------------------------------------------------------------------------------- /OralBlue/BrushSession.py: -------------------------------------------------------------------------------- 1 | import struct 2 | from datetime import datetime, timedelta 3 | from typing import Optional 4 | 5 | from OralBlue.BrushMode import BrushMode 6 | from OralBlue.OralBDate import OralBDate 7 | 8 | 9 | class BrushSession(object): 10 | 11 | def __init__(self,data:bytes,protocolVersion: int = 1): 12 | if len(data) != 16: 13 | raise ValueError 14 | 15 | self._startDate = OralBDate(data[0:4]).datetime 16 | 17 | durationS = struct.unpack("> 13 # 3 bits 50 | temp = struct.unpack("> 13 # 3 bits 53 | 54 | def _parseProtocolV4(self,data:bytes): 55 | self._parseProtocolV2Or3(data) 56 | durationMS = (struct.unpack("datetime: 61 | return self._startDate 62 | 63 | @property 64 | def duration(self) -> timedelta: 65 | return self._duration 66 | 67 | @property 68 | def prefMode(self)->BrushMode: 69 | return self._prefMode 70 | 71 | @property 72 | def nPressure(self)->int: 73 | return self._nPressure 74 | 75 | @property 76 | def timeUnderPressure(self)->timedelta: 77 | return self._timeUnderPressure 78 | 79 | @property 80 | def finalBatteryState(self)->int: 81 | return self._finalBatteryState 82 | 83 | @property 84 | def lastCharge(self)->Optional[timedelta]: 85 | return self._lastCharge 86 | 87 | @property 88 | def sessionId(self)->int: 89 | return self._sessionId 90 | 91 | @property 92 | def userId(self) -> int: 93 | return self._userId 94 | 95 | @property 96 | def numberOfSector(self) -> int: 97 | return self._numberOfSectors 98 | 99 | @property 100 | def sessionTargetTime(self) -> int: 101 | return self._sessionTargetTime 102 | 103 | 104 | def __str__(self): 105 | return "Start: {}\n\tDuration:{}\n\tMode:{}\n\tN pressure:{}\n\ttime underPressure:{}" \ 106 | "\n\tbattery:{}\n\tlastCharge:{}\n\tSessionId:{}\n\tUserId:{}\n\tnSection:{}\n\t" \ 107 | "sessionTargetTime:{}"\ 108 | .format(self._startDate, 109 | self.duration.total_seconds(), 110 | self.prefMode, 111 | self._nPressure, 112 | self._timeUnderPressure, 113 | self._finalBatteryState, 114 | self._lastCharge, 115 | self._sessionId, 116 | self._userId, 117 | self._numberOfSectors, 118 | self._sessionTargetTime) -------------------------------------------------------------------------------- /OralBlue/OralBAdvertise.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from bluepy.btle import ScanEntry 4 | 5 | from OralBlue.BrushMode import BrushMode 6 | from OralBlue.BrushSector import BrushSector 7 | from OralBlue.BrushState import BrushState 8 | 9 | 10 | class OralBAdvertise(object): 11 | 12 | @staticmethod 13 | def buildFromScanEntry(scanEntry: ScanEntry) -> Optional["OralBAdvertise"]: 14 | vendorSpecificData = scanEntry.getValueText(ScanEntry.MANUFACTURER) 15 | parser = OralBAdvertise(vendorSpecificData) 16 | if parser.isValid: 17 | return parser 18 | else: 19 | return None 20 | 21 | def _extractByte(self, data: str, offset: int) -> int: 22 | return int(data[2 * offset: 2 * offset + 2], 16) 23 | 24 | def _extractShort(self, data: str, offset: int) -> int: 25 | return int(data[2 * offset: 2 * offset + 4], 16) 26 | 27 | def __init__(self, advertiseData: str): 28 | if len(advertiseData) not in [22, 26]: 29 | self._isValid = False 30 | return 31 | 32 | if self._extractShort(advertiseData,0) != 0xDC00: 33 | self._isValid = False 34 | return 35 | 36 | self._isValid = True 37 | 38 | self._protocolVersion = self._extractByte(advertiseData,2) 39 | self._typeId = self._extractByte(advertiseData, 3) 40 | self._fwVersion = self._extractByte(advertiseData,4) 41 | self._state = BrushState(self._extractByte(advertiseData, 5)) 42 | self._highPressureDetected = (self._extractByte(advertiseData, 6) & 0x80) != 0 43 | self._hasReducedMotorSpeed = (self._extractByte(advertiseData, 6) & 0x40) != 0 44 | self._hasProfesionalTimer = (self._extractByte(advertiseData, 6) & 0x1) == 0 45 | self._brushTimeSec = self._extractByte(advertiseData,7)*60+self._extractByte(advertiseData,8) 46 | self._brushMode = BrushMode(self._extractByte(advertiseData,9)) 47 | self._sector = OralBAdvertise.toBrushSecotr(self._extractByte(advertiseData,10) & 0x7) 48 | self._smiley = (self._extractByte(advertiseData,10) & 0x38) >> 3 49 | 50 | 51 | @staticmethod 52 | def toBrushSecotr(value:int) -> BrushSector: 53 | if value == 0x07: 54 | return BrushSector.LAST_SECTOR 55 | elif 0x00 <= value <= 0x06: 56 | return BrushSector(value-1) 57 | else: 58 | return BrushSector.NO_SECTOR 59 | 60 | def __str__(self): 61 | return str(self.__dict__) 62 | 63 | @property 64 | def isValid(self)->bool: 65 | return self._isValid 66 | 67 | @property 68 | def hightPressureDetected(self) -> bool: 69 | return self._highPressureDetected 70 | 71 | @property 72 | def protocolVersion(self)->int: 73 | return self._protocolVersion 74 | 75 | @property 76 | def typeId(self)->int: 77 | return self._typeId 78 | 79 | @property 80 | def fwVersion(self)->int: 81 | return self._fwVersion 82 | 83 | @property 84 | def brushingTimeS(self)->int: 85 | return self._brushTimeSec 86 | 87 | @property 88 | def sector(self)->BrushSector: 89 | return self._sector 90 | 91 | @property 92 | def brushingMode(self)->BrushMode: 93 | return self._brushMode 94 | 95 | @property 96 | def state(self)->BrushState: 97 | return self._state 98 | 99 | @property 100 | def smiley(self)->int: 101 | return self._smiley 102 | 103 | @property 104 | def hasProfesionalTimer(self)->bool: 105 | return self._hasProfesionalTimer 106 | 107 | @property 108 | def hasReducedMotorSpeed(self)->bool: 109 | return self._hasReducedMotorSpeed 110 | 111 | def __str__(self) -> str: 112 | return "Status: {}\n" \ 113 | "Brush time: {} s\n" \ 114 | "Brush mode: {}\n" \ 115 | "Sector: {}\n" \ 116 | "Pressure detected: {}\n"\ 117 | "Protocol Version: {}\n" \ 118 | "TypeId: {}\n" \ 119 | "Has reduced motor speed: {}\n" \ 120 | "Has professional timer: {}\n" \ 121 | "Smiley: {}\n"\ 122 | .format(str(self.state), self.brushingTimeS, str(self.brushingMode), str(self.sector), 123 | self.hightPressureDetected,self.protocolVersion,self.typeId,self.hasReducedMotorSpeed, 124 | self.hasProfesionalTimer,self.smiley) 125 | -------------------------------------------------------------------------------- /test/BrushSessionTest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import datetime, timedelta 3 | 4 | from OralBlue import OralBAdvertise 5 | from OralBlue.BrushMode import BrushMode 6 | from OralBlue.BrushSession import BrushSession 7 | from OralBlue.BrushState import BrushState 8 | 9 | 10 | class BrushSessionTestCase(unittest.TestCase): 11 | 12 | def test_anExceptionIsThrownWhenTheDataAreLessThan16Bytes(self): 13 | with self.assertRaises(ValueError): 14 | BrushSession(b"\x00") 15 | 16 | def test_anExceptionIsThrownWhenTheDataAreMoreThan16Bytes(self): 17 | with self.assertRaises(ValueError): 18 | BrushSession(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 19 | 20 | def test_first4byteAreTheStartDate(self): 21 | session = BrushSession(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 22 | self.assertEqual(session.startDate,datetime(year=2000,month=1,day=1)) 23 | 24 | session = BrushSession(b"\x0A\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 25 | self.assertEqual(session.startDate, datetime(year=2000, month=1, day=1,second=10)) 26 | 27 | def test_byte5and6areTheDuration(self): 28 | session = BrushSession(b"\x00\x01\x02\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 29 | self.assertEqual(session.duration,timedelta(seconds=1)) 30 | session = BrushSession(b"\x00\x00\x00\x00\xb4\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 31 | self.assertEqual(session.duration, timedelta(seconds=180)) 32 | session = BrushSession(b"\x00\x00\x00\x00\x00\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") 33 | self.assertEqual(session.duration, timedelta(seconds=0x2000)) 34 | 35 | def test_byte8IsThePrefMode(self): 36 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x01\x00\x00\x00\x00\x00\x00\x00\x00") 37 | self.assertEqual(session.prefMode,BrushMode(0x01)) 38 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x04\x00\x00\x00\x00\x00\x00\x00\x00") 39 | self.assertEqual(session.prefMode, BrushMode(0x04)) 40 | 41 | def test_byte9And10IsSecondsUnderPressure(self): 42 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x00\x00\x00\x00\x00") 43 | self.assertEqual(session.timeUnderPressure,timedelta(seconds=0x0908)) 44 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x01\x00\x00\x00\x00\x00\x00\x00") 45 | self.assertEqual(session.timeUnderPressure, timedelta(seconds=1)) 46 | 47 | def test_byte10IsNumberOfPressure(self): 48 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x00\x00\x00\x00\x00") 49 | self.assertEqual(session.nPressure, 10) 50 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x00\x00\x00\x00\x00\x00") 51 | self.assertEqual(session.nPressure,0) 52 | 53 | def test_byte11IsBatteryCharge(self): 54 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x00\x00\x00\x00") 55 | self.assertEqual(session.finalBatteryState, 11) 56 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x32\x00\x00\x00\x00") 57 | self.assertEqual(session.finalBatteryState,50) 58 | 59 | def test_last4BytesAreTheLastCharge(self): 60 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x00\x00\x00\x00") 61 | self.assertEqual(session.lastCharge,datetime(year=2000,month=1,day=1)) 62 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x3B\x0A\x00\x00\x00") 63 | self.assertEqual(session.lastCharge,datetime(year=2000, month=1, day=1,second=10)) 64 | 65 | class BrushSessionV2Or3TestCase(unittest.TestCase): 66 | 67 | def test_bytes12AsNSectionAndTargetTime(self): 68 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x00\x00\x00\x00",protocolVersion=3) 69 | self.assertEqual(session.lastCharge,None) 70 | self.assertEqual(session.numberOfSector,0) 71 | self.assertEqual(session.sessionTargetTime, 0) 72 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x3B\x78\x80\x00\x00",protocolVersion=3) 73 | self.assertEqual(session.lastCharge, None) 74 | self.assertEqual(session.numberOfSector, 4) 75 | self.assertEqual(session.sessionTargetTime, 120) 76 | 77 | def test_bytes14AsSessionIdAndUserId(self): 78 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x00\x00",protocolVersion=3) 79 | self.assertEqual(session.lastCharge,None) 80 | self.assertEqual(session.sessionId,0) 81 | self.assertEqual(session.userId, 0) 82 | session = BrushSession(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x3B\x78\x80\x03\x20",protocolVersion=3) 83 | self.assertEqual(session.lastCharge, None) 84 | self.assertEqual(session.sessionId, 3) 85 | self.assertEqual(session.userId, 1) 86 | 87 | if __name__ == '__main__': 88 | unittest.main() 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/venv,linux,python,pycharm+all 3 | # Edit at https://www.gitignore.io/?templates=venv,linux,python,pycharm+all 4 | 5 | ### Linux ### 6 | *~ 7 | 8 | # temporary files which can be created if a process still has a handle open of a deleted file 9 | .fuse_hidden* 10 | 11 | # KDE directory preferences 12 | .directory 13 | 14 | # Linux trash folder which might appear on any partition or disk 15 | .Trash-* 16 | 17 | # .nfs files are created when an open file is removed but is still being accessed 18 | .nfs* 19 | 20 | ### PyCharm+all ### 21 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 22 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 23 | 24 | # User-specific stuff 25 | .idea/**/workspace.xml 26 | .idea/**/tasks.xml 27 | .idea/**/usage.statistics.xml 28 | .idea/**/dictionaries 29 | .idea/**/shelf 30 | 31 | # Generated files 32 | .idea/**/contentModel.xml 33 | 34 | # Sensitive or high-churn files 35 | .idea/**/dataSources/ 36 | .idea/**/dataSources.ids 37 | .idea/**/dataSources.local.xml 38 | .idea/**/sqlDataSources.xml 39 | .idea/**/dynamic.xml 40 | .idea/**/uiDesigner.xml 41 | .idea/**/dbnavigator.xml 42 | 43 | # Gradle 44 | .idea/**/gradle.xml 45 | .idea/**/libraries 46 | 47 | # Gradle and Maven with auto-import 48 | # When using Gradle or Maven with auto-import, you should exclude module files, 49 | # since they will be recreated, and may cause churn. Uncomment if using 50 | # auto-import. 51 | # .idea/modules.xml 52 | # .idea/*.iml 53 | # .idea/modules 54 | 55 | # CMake 56 | cmake-build-*/ 57 | 58 | # Mongo Explorer plugin 59 | .idea/**/mongoSettings.xml 60 | 61 | # File-based project format 62 | *.iws 63 | 64 | # IntelliJ 65 | out/ 66 | 67 | # mpeltonen/sbt-idea plugin 68 | .idea_modules/ 69 | 70 | # JIRA plugin 71 | atlassian-ide-plugin.xml 72 | 73 | # Cursive Clojure plugin 74 | .idea/replstate.xml 75 | 76 | # Crashlytics plugin (for Android Studio and IntelliJ) 77 | com_crashlytics_export_strings.xml 78 | crashlytics.properties 79 | crashlytics-build.properties 80 | fabric.properties 81 | 82 | # Editor-based Rest Client 83 | .idea/httpRequests 84 | 85 | # Android studio 3.1+ serialized cache file 86 | .idea/caches/build_file_checksums.ser 87 | 88 | ### PyCharm+all Patch ### 89 | # Ignores the whole .idea folder and all .iml files 90 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 91 | 92 | .idea/ 93 | 94 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 95 | 96 | *.iml 97 | modules.xml 98 | .idea/misc.xml 99 | *.ipr 100 | 101 | ### Python ### 102 | # Byte-compiled / optimized / DLL files 103 | __pycache__/ 104 | *.py[cod] 105 | *$py.class 106 | 107 | # C extensions 108 | *.so 109 | 110 | # Distribution / packaging 111 | .Python 112 | build/ 113 | develop-eggs/ 114 | dist/ 115 | downloads/ 116 | eggs/ 117 | .eggs/ 118 | lib/ 119 | lib64/ 120 | parts/ 121 | sdist/ 122 | var/ 123 | wheels/ 124 | share/python-wheels/ 125 | *.egg-info/ 126 | .installed.cfg 127 | *.egg 128 | MANIFEST 129 | 130 | # PyInstaller 131 | # Usually these files are written by a python script from a template 132 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 133 | *.manifest 134 | *.spec 135 | 136 | # Installer logs 137 | pip-log.txt 138 | pip-delete-this-directory.txt 139 | 140 | # Unit test / coverage reports 141 | htmlcov/ 142 | .tox/ 143 | .nox/ 144 | .coverage 145 | .coverage.* 146 | .cache 147 | nosetests.xml 148 | coverage.xml 149 | *.cover 150 | .hypothesis/ 151 | .pytest_cache/ 152 | 153 | # Translations 154 | *.mo 155 | *.pot 156 | 157 | # Django stuff: 158 | *.log 159 | local_settings.py 160 | db.sqlite3 161 | 162 | # Flask stuff: 163 | instance/ 164 | .webassets-cache 165 | 166 | # Scrapy stuff: 167 | .scrapy 168 | 169 | # Sphinx documentation 170 | docs/_build/ 171 | 172 | # PyBuilder 173 | target/ 174 | 175 | # Jupyter Notebook 176 | .ipynb_checkpoints 177 | 178 | # IPython 179 | profile_default/ 180 | ipython_config.py 181 | 182 | # pyenv 183 | .python-version 184 | 185 | # celery beat schedule file 186 | celerybeat-schedule 187 | 188 | # SageMath parsed files 189 | *.sage.py 190 | 191 | # Environments 192 | .env 193 | .venv 194 | env/ 195 | venv/ 196 | ENV/ 197 | env.bak/ 198 | venv.bak/ 199 | 200 | # Spyder project settings 201 | .spyderproject 202 | .spyproject 203 | 204 | # Rope project settings 205 | .ropeproject 206 | 207 | # mkdocs documentation 208 | /site 209 | 210 | # mypy 211 | .mypy_cache/ 212 | .dmypy.json 213 | dmypy.json 214 | 215 | # Pyre type checker 216 | .pyre/ 217 | 218 | ### Python Patch ### 219 | .venv/ 220 | 221 | ### venv ### 222 | # Virtualenv 223 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 224 | [Bb]in 225 | [Ii]nclude 226 | [Ll]ib 227 | [Ll]ib64 228 | [Ll]ocal 229 | [Ss]cripts 230 | pyvenv.cfg 231 | pip-selfcheck.json 232 | 233 | # End of https://www.gitignore.io/api/venv,linux,python,pycharm+all 234 | -------------------------------------------------------------------------------- /Protocol.md: -------------------------------------------------------------------------------- 1 | # OralB Smart Toothbrush protocol 2 | 3 | ## Advertise 4 | length must be >=16 5 | 6 | byte 0 must be 0 and byte 3 must be 0xC (12) or 0xE(14) 7 | byte 3 is the length of the vendor specific part + 1 -> 11 or 13 bytes 8 | byte 5 and 6 must be 0xDC00 9 | 10 | byte 7 is the protocol version (1,2,3,4) 11 | 12 | byte 8 is device type and can be: 13 | 14 | - 0 -> D36 (X Mode) 15 | - 1 -> D36 (6 Mode) 16 | - 2 -> D36 (5 Mode) 17 | - 32 -> D701 (X Mode) 18 | - 33 -> D701 (6 Mode) 19 | - 34 -> D701 (5 Mode) 20 | - 39 -> D700 (5 Mode) 21 | - 40 -> D700 (4 Mode) 22 | - 41 -> D700 (6 Mode) 23 | - 63 -> D36 (Experimental) 24 | - 64 -> D21 (X Mode) 25 | - 65 -> D21 (4 Mode) 26 | - 66 -> D21 (3a Mode) 27 | - 67 -> D21 (2a Mode) 28 | - 68 -> D21 (2b Mode) 29 | - 69 -> D21 (3b Mode) 30 | - 70 -> D21 (1 Mode) 31 | - 80 -> D601 (X Mode) 32 | - 81 -> D601 (5 Mode) 33 | - 82 -> D601 (4 Mode) 34 | - 83 -> D601 (3A Mode) 35 | - 84 -> D601 (2A Mode) 36 | - 85 -> D601 (2B Mode) 37 | - 86 -> D601 (3B Mode) 38 | - 87 -> D601 (1 Mode) 39 | 40 | byte 9 is the fwVersion 41 | 42 | byte 10 brush state (see #State) 43 | 44 | byte 11 45 | 46 | - bit 8: high pressure 0 = normal 1 = high 47 | - bit 7: motor speed, 0 = normal 1 = reduced 48 | - bit 3: mode button pressed 49 | - bit 2: power button pressed 50 | - bit 1: timer mode, 0 = profesional (each 30s) 1= only end 51 | 52 | byte 12 brushing time min 53 | 54 | byte 13 brushing time sec 55 | 56 | byte 14 brush mode (see #Mode) 57 | 58 | byte 15: 59 | bit 0,1,2: quadrant 60 | bit 3,4,5: smiley 61 | 62 | # Mode 63 | |Id |Mode| 64 | |---|---| 65 | | 0x00 | OFF | 66 | | 0x01 | DAILY_CLEAN | 67 | | 0x02 | SENSITIVE | 68 | | 0x03 | MASSAGE | 69 | | 0x04 | WHITENING | 70 | | 0x05 | DEEP_CLEAN | 71 | | 0x06 | TONGUE_CLEANING | 72 | | 0x07 | TURBO | 73 | | 0xFF | UNKNOWN | 74 | 75 | # States 76 | |Id |State| 77 | |---|---| 78 | | 0x00 | UNKNOWN | 79 | | 0x01 | INIT | 80 | | 0x02 | IDLE | 81 | | 0x03 | RUN | 82 | | 0x04 | CHARGE | 83 | | 0x05 | SETUP | 84 | | 0x06 | FLIGHT_MENU | 85 | | 0x71 | FINAL_TEST | 86 | | 0x72 | PCB_TEST | 87 | | 0x73 | SLEEP | 88 | | 0x74 | TRANSPORT | 89 | | 0xFF | UNKNOWN | 90 | 91 | ## Charateristics 92 | 93 | ### ToothbrushID 94 | UUID: a0f0ff01-5047-4d53-8208-4f72616c2d42 95 | 96 | data: uint32 little endian 97 | an id different for each toothbrush?? 98 | 99 | ### ModelId 100 | UUID: a0f0ff02-5047-4d53-8208-4f72616c2d42 101 | 102 | data: 3 bytes: [modeId, protocolVersion, fwVersion] 103 | 104 | Node: protocol version and fwVersion are available only if protocolVersion >=3 105 | 106 | ### UserId 107 | UUID: a0f0ff03-5047-4d53-8208-4f72616c2d42 108 | 109 | data: 1 byte current user id, can be change with a simple write 110 | 111 | ### Status 112 | UUID: A0F0FF04-5047-4D53-8208-4F72616C2D42 113 | 114 | data: 2 bytes [state, unknown] as in the advertise 115 | 116 | ### Battery level: 117 | UUID: A0F0FF05-5047-4D53-8208-4F72616C2D42 118 | 119 | data: 4 bytes [ battery level (%), seconds left (2bytes le), unknown] 120 | 121 | Node: seconds left available only with protocol version > 3 122 | 123 | ### Button State: 124 | UUID: a0f0ff06-5047-4d53-8208-4f72616c2d42 125 | 126 | data: 2 bytes: [powerButtonState, modeButtonState] , 1 = pressed 127 | 128 | ### Brushing mode 129 | UUID: A0F0FF07-5047-4D53-8208-4F72616C2D42 130 | 131 | data: 1 byte -> 0..6 as in the advertise 132 | 133 | ### Brushing time: 134 | UUID: A0F0FF08-5047-4D53-8208-4F72616C2D42 135 | 136 | data: 2 bytes [min, sec] 137 | 138 | 139 | ### Sector 140 | UUID: a0f0ff09-5047-4d53-8208-4f72616c2d42 141 | 142 | data 1 byte -> 0..8 as in the advertise 143 | 144 | 145 | ### Control Char 146 | UUID: a0f0ff21-5047-4d53-8208-4f72616c2d42 147 | 148 | write here before change some configuration 149 | 150 | ### Current time 151 | UUID: a0f0ff22-5047-4d53-8208-4f72616c2d42 152 | 153 | Access: R/W 154 | 155 | data: 4 bytes little endian seconds after 1/1/2000 156 | 157 | Note: To change it you have to write [0x37,0x26] into the control characteristics before write the new value 158 | 159 | ### Signals 160 | UUID: a0f0ff24-5047-4d53-8208-4f72616c2d42 161 | 162 | Access: R/W 163 | data: 1 byte: tell the status of the user notification: 164 | - bit 1 = is vibrating (as a sector end) 165 | - bit 2 = is vibrating (as a session end) 166 | - bit 3 = light on (as high pressure) 167 | - bit 4 = light on (as session end) 168 | 169 | note: before write it, write [0x37,0x28] in the control characteristics 170 | 171 | node: writing is not working :( 172 | 173 | ### Available modes 174 | UUID: a0f0ff25-5047-4d53-8208-4f72616c2d42 175 | Access: R/W 176 | 177 | Data: 8 byte, each byte is a possible motor mode, it can be used to reordered the available modes 178 | 179 | Note: To change it you have to write [0x37,0x29] into the control characteristics before write the new value 180 | 181 | ### Sector timer 182 | UUID: a0f0ff26-5047-4d53-8208-4f72616c2d42 183 | Access: R/W 184 | 185 | Data: 8 uint16 le, timeout for each sector, to update it all the 8 value must be present 186 | 187 | Node: write [0x37,0x2A] into the control characteristics before change the values 188 | 189 | 190 | ### Session Info 191 | UUID: a0f0ff29-5047-4d53-8208-4f72616c2d42 192 | Access:R 193 | 194 | from this value the session data can be read. 195 | 196 | To select the session, write [0x02, index] into the control characteristics. 197 | 198 | The number of stored session are: 199 | - 20 for protocol version 1 200 | - 30 for protocol version 2,3,4 201 | 202 | #### Session Format 203 | - Start time: 4 bytes le, seconds after 1/1/2000 204 | - duration : 2 bytes le, duration in seconds 205 | - event count: 1 byte ?? 206 | - mode: 1 byte, as in the advertise, mode used for the majority of time during the session 207 | - time under pressure: 2 byte le seconds with the hight pressure warning on 208 | - pressure warnings: 1 byte, # pressure warnings 209 | - final battery state: 1 byte % of battery when the session ends 210 | 211 | the last 4 byte has a different meaning with different protocol versions: 212 | if protocol version == 1 213 | - last full charge: 4 bytes seconds after 1/1/2000 214 | 215 | if protocol version == 2,3,4 216 | - 2 byte: as uint16 le, 3 bit = # sector, 13 bit total target time 217 | - 2 byte: as uint16 le, 3 bit = # user id, 13 bit session id 218 | 219 | if protocol version ==4 220 | time under pressure is in 1/10 seconds 221 | -------------------------------------------------------------------------------- /test/OralBAdvertiseTest.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from OralBlue import OralBAdvertise 3 | from OralBlue.BrushMode import BrushMode 4 | from OralBlue.BrushSector import BrushSector 5 | from OralBlue.BrushState import BrushState 6 | 7 | 8 | class AdvertiseParserTestCase(unittest.TestCase): 9 | 10 | def test_advertiseMustStartWithDC00(self): 11 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 12 | self.assertTrue(validParser.isValid) 13 | 14 | invalidParser = OralBAdvertise.OralBAdvertise("dd000000000000000000000000") 15 | self.assertFalse(invalidParser.isValid) 16 | 17 | def test_advetiseLengthIs11or13Bytes(self): 18 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 19 | self.assertTrue(validParser.isValid) 20 | validParser = OralBAdvertise.OralBAdvertise("dc00000000000000000000") 21 | self.assertTrue(validParser.isValid) 22 | 23 | invalidParser = OralBAdvertise.OralBAdvertise("dc0000000000000000000000") 24 | self.assertFalse(invalidParser.isValid) 25 | 26 | def test_the3thByteIsProtocolVersion(self): 27 | validParser = OralBAdvertise.OralBAdvertise("dc000300000000000000000000") 28 | self.assertEqual(validParser.protocolVersion, 3) 29 | validParser = OralBAdvertise.OralBAdvertise("dc001000000000000000000000") 30 | self.assertEqual(validParser.protocolVersion, 16) 31 | 32 | def test_the4thByteIsTypeId(self): 33 | validParser = OralBAdvertise.OralBAdvertise("dc000056000000000000000000") 34 | self.assertEqual(validParser.typeId, 0x56) 35 | validParser = OralBAdvertise.OralBAdvertise("dc000041000000000000000000") 36 | self.assertEqual(validParser.typeId, 0x41) 37 | 38 | def test_the5thByteIsFwVersion(self): 39 | validParser = OralBAdvertise.OralBAdvertise("dc000000040000000000000000") 40 | self.assertEqual(validParser.fwVersion, 0x04) 41 | validParser = OralBAdvertise.OralBAdvertise("dc000000200000000000000000") 42 | self.assertEqual(validParser.fwVersion, 0x20) 43 | 44 | def test_the6thByteIsState(self): 45 | validParser = OralBAdvertise.OralBAdvertise("dc000000000200000000000000") 46 | self.assertEqual(validParser.state, BrushState.IDLE) 47 | validParser = OralBAdvertise.OralBAdvertise("dc000000000300000000000000") 48 | self.assertEqual(validParser.state, BrushState.RUN) 49 | 50 | def test_invalidStateAreMappedToUnknown(self): 51 | # state 0x18 doesn't exist 52 | validParser = OralBAdvertise.OralBAdvertise("dc00000000FF00000000000000") 53 | self.assertEqual(validParser.state, BrushState.UNKNOWN) 54 | 55 | def test_the7thByteHasTheHighPressureDetectorBit(self): 56 | validParser = OralBAdvertise.OralBAdvertise("dc000000000080000000000000") 57 | self.assertTrue(validParser.hightPressureDetected) 58 | validParser = OralBAdvertise.OralBAdvertise("dc0000000000FF000000000000") 59 | self.assertTrue(validParser.hightPressureDetected) 60 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 61 | self.assertFalse(validParser.hightPressureDetected) 62 | validParser = OralBAdvertise.OralBAdvertise("dc00000000007F000000000000") 63 | self.assertFalse(validParser.hightPressureDetected) 64 | 65 | def test_the6thByteHasMotorSpeedBit(self): 66 | validParser = OralBAdvertise.OralBAdvertise("dc000000000040000000000000") 67 | self.assertTrue(validParser.hasReducedMotorSpeed) 68 | validParser = OralBAdvertise.OralBAdvertise("dc0000000000FF000000000000") 69 | self.assertTrue(validParser.hasReducedMotorSpeed) 70 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 71 | self.assertFalse(validParser.hasReducedMotorSpeed) 72 | validParser = OralBAdvertise.OralBAdvertise("dc0000000000BF000000000000") 73 | self.assertFalse(validParser.hasReducedMotorSpeed) 74 | 75 | def test_the1stBitIsTheTimerMode(self): 76 | validParser = OralBAdvertise.OralBAdvertise("dc000000000001000000000000") 77 | self.assertFalse(validParser.hasProfesionalTimer) 78 | validParser = OralBAdvertise.OralBAdvertise("dc0000000000FF000000000000") 79 | self.assertFalse(validParser.hasProfesionalTimer) 80 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 81 | self.assertTrue(validParser.hasProfesionalTimer) 82 | validParser = OralBAdvertise.OralBAdvertise("dc0000000000FE000000000000") 83 | self.assertTrue(validParser.hasProfesionalTimer) 84 | 85 | def test_the8thByteIsBrushingTime(self): 86 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 87 | self.assertEqual(validParser.brushingTimeS, 0) 88 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000100000000") 89 | self.assertEqual(validParser.brushingTimeS, 1) 90 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000010000000000") 91 | self.assertEqual(validParser.brushingTimeS, 60) 92 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000010100000000") 93 | self.assertEqual(validParser.brushingTimeS, 61) 94 | 95 | def test_the10thByteIsTheBrushMode(self): 96 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000002000000") 97 | self.assertEqual(validParser.brushingMode, BrushMode.SENSITIVE) 98 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000003000000") 99 | self.assertEqual(validParser.brushingMode, BrushMode.MASSAGE) 100 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000007000000") 101 | self.assertEqual(validParser.brushingMode, BrushMode.TURBO) 102 | 103 | def test_invalidBrushModeAreMapedAsUnknown(self): 104 | validParser = OralBAdvertise.OralBAdvertise("dc0000000000000000FF000000") 105 | self.assertEqual(validParser.brushingMode, BrushMode.UNKNOWN) 106 | 107 | def test_theLast3bitsOf11thByteIsCurrentSector(self): 108 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 109 | self.assertEqual(validParser.sector, BrushSector.NO_SECTOR) 110 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000010000") 111 | self.assertEqual(validParser.sector, BrushSector.SECTOR_1) 112 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000020000") 113 | self.assertEqual(validParser.sector, BrushSector.SECTOR_2) 114 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000FF0000") 115 | self.assertEqual(validParser.sector, BrushSector.LAST_SECTOR) 116 | 117 | def test_thecentral3bitsOf11thByteIsCurrentSmily(self): 118 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000000000") 119 | self.assertEqual(validParser.smiley, 0x00) 120 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000080000") 121 | self.assertEqual(validParser.smiley, 0x01) 122 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000100000") 123 | self.assertEqual(validParser.smiley, 0x02) 124 | validParser = OralBAdvertise.OralBAdvertise("dc000000000000000000FF0000") 125 | self.assertEqual(validParser.smiley, 0x07) 126 | 127 | if __name__ == '__main__': 128 | unittest.main() 129 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /OralBlue/OralBToothbrush.py: -------------------------------------------------------------------------------- 1 | import struct 2 | from datetime import datetime, timedelta 3 | from typing import Callable, Iterable, Optional, NamedTuple 4 | 5 | from bluepy.btle import Peripheral, UUID, Characteristic, DefaultDelegate 6 | 7 | from OralBlue.BrushBattery import BrushBattery 8 | from OralBlue.BrushInfo import BrushInfo 9 | from OralBlue.BrushMode import BrushMode 10 | from OralBlue.BrushSector import BrushSector 11 | from OralBlue.BrushSession import BrushSession 12 | from OralBlue.BrushSignal import BrushSignal 13 | from OralBlue.BrushState import BrushState 14 | from OralBlue.OralBDate import OralBDate 15 | 16 | 17 | class OralBButtonStatus(NamedTuple): 18 | powerButtonPressed: bool = False 19 | modeButtonPressed: bool = False 20 | 21 | #todo add sensor data 22 | #todo set signal not working? 23 | class OralBToothbrush(Peripheral, DefaultDelegate): 24 | _TOOTHBRUSH_ID_TIME_CHAR = UUID("a0f0ff01-5047-4d53-8208-4f72616c2d42") 25 | _MODEL_ID_CHAR = UUID("a0f0ff02-5047-4d53-8208-4f72616c2d42") 26 | _USER_ID_CHAR = UUID("a0f0ff03-5047-4d53-8208-4f72616c2d42") 27 | _STATUS_CHAR = UUID("a0f0ff04-5047-4d53-8208-4f72616c2d42") 28 | _BATTERY_CHAR = UUID("a0f0ff05-5047-4d53-8208-4f72616c2d42") 29 | _BUTTON_CHAR = UUID("a0f0ff06-5047-4d53-8208-4f72616c2d42") 30 | _MODE_CHAR = UUID("a0f0ff07-5047-4d53-8208-4f72616c2d42") 31 | _BRUSING_TIME_CHAR = UUID("a0f0ff08-5047-4d53-8208-4f72616c2d42") 32 | _CURRENT_SECTOR_CHAR = UUID("a0f0ff09-5047-4d53-8208-4f72616c2d42") 33 | _CONTROL_CHAR = UUID("a0f0ff21-5047-4d53-8208-4f72616c2d42") 34 | _CURRENT_DATE_CHAR = UUID("a0f0ff22-5047-4d53-8208-4f72616c2d42") 35 | _SIGNAL_CHAR = UUID("a0f0ff24-5047-4d53-8208-4f72616c2d42") 36 | _AVAILABLE_MODES_CHAR = UUID("a0f0ff25-5047-4d53-8208-4f72616c2d42") 37 | _SECTOR_TIME_CHAR = UUID("a0f0ff26-5047-4d53-8208-4f72616c2d42") 38 | _SESSION_INFO_CHAR = UUID("a0f0ff29-5047-4d53-8208-4f72616c2d42") 39 | 40 | BatteryStatusCallback = Callable[[BrushBattery], None] 41 | BrushingTimeCallback = Callable[[int], None] 42 | BrushStateCallback = Callable[[BrushState], None] 43 | BrushModeCallback = Callable[[BrushMode], None] 44 | BrushButtonCallback = Callable[[OralBButtonStatus], None] 45 | BrushCurrentSectorCallback = Callable[[BrushSector], None] 46 | 47 | def handleNotification(self, cHandle, data): 48 | print("notify {} -> {}", cHandle, data) 49 | if cHandle in self._callbackMap: 50 | self._callbackMap[cHandle](data) 51 | 52 | @staticmethod 53 | def _findChar(uuid: UUID, chars: Iterable[Characteristic]) -> Optional[Characteristic]: 54 | results = filter(lambda x: x.uuid == uuid, chars) 55 | for result in results: # return the first match 56 | return result 57 | return None 58 | 59 | def __init__(self, address: str, protocolVersion: int = 1): 60 | super().__init__(address) 61 | self._protocolVersion = protocolVersion 62 | self.withDelegate(self) 63 | allChars = self.getCharacteristics() 64 | self._batteryChar = OralBToothbrush._findChar(OralBToothbrush._BATTERY_CHAR, allChars) 65 | self._brushingTimeChar = OralBToothbrush._findChar(OralBToothbrush._BRUSING_TIME_CHAR, allChars) 66 | self._statusChar = OralBToothbrush._findChar(OralBToothbrush._STATUS_CHAR, allChars) 67 | self._modeChar = OralBToothbrush._findChar(OralBToothbrush._MODE_CHAR, allChars) 68 | self._modelIdChar = OralBToothbrush._findChar(OralBToothbrush._MODEL_ID_CHAR, allChars) 69 | self._controlChar = OralBToothbrush._findChar(OralBToothbrush._CONTROL_CHAR, allChars) 70 | self._currentDateChar = OralBToothbrush._findChar(OralBToothbrush._CURRENT_DATE_CHAR, allChars) 71 | self._availableModesChar = OralBToothbrush._findChar(OralBToothbrush._AVAILABLE_MODES_CHAR, allChars) 72 | self._sessionInfoChar = OralBToothbrush._findChar(OralBToothbrush._SESSION_INFO_CHAR, allChars) 73 | self._signalChar = OralBToothbrush._findChar(OralBToothbrush._SIGNAL_CHAR, allChars) 74 | self._buttonChar = OralBToothbrush._findChar(OralBToothbrush._BUTTON_CHAR, allChars) 75 | self._currentSectorChar = OralBToothbrush._findChar(OralBToothbrush._CURRENT_SECTOR_CHAR, allChars) 76 | self._sectorTimeChar = OralBToothbrush._findChar(OralBToothbrush._SECTOR_TIME_CHAR, allChars) 77 | self._userIdChar = OralBToothbrush._findChar(OralBToothbrush._USER_ID_CHAR, allChars) 78 | self._toothbrushIdChar = OralBToothbrush._findChar(OralBToothbrush._TOOTHBRUSH_ID_TIME_CHAR, allChars) 79 | self._callbackMap = {} 80 | 81 | def _writeCharDescriptor(self, characteristic: Characteristic, data): 82 | notify_handle = characteristic.getHandle() + 1 83 | self.writeCharacteristic(notify_handle, data, withResponse=True) 84 | 85 | def _enableNotification(self, characteristic: Characteristic): 86 | if not (characteristic.properties & Characteristic.props["NOTIFY"]): 87 | return 88 | self._writeCharDescriptor(characteristic, b"\x01\x00") 89 | 90 | def _disableNotification(self, characteristic: Characteristic): 91 | self._writeCharDescriptor(characteristic, b"\x00\x00") 92 | 93 | def _registerCallback(self, characteristic: Characteristic, callback: Callable): 94 | handle = characteristic.getHandle() 95 | self._callbackMap[handle] = callback 96 | self._enableNotification(characteristic) 97 | 98 | def _removeCallback(self, characteristic: Characteristic): 99 | handle = characteristic.getHandle() 100 | del self._callbackMap[handle] 101 | self._disableNotification(characteristic) 102 | 103 | @staticmethod 104 | def _parseBatteryStatysResponse(data) -> BrushBattery: 105 | if len(data) >= 3: 106 | remainingSec = struct.unpack(" int: 113 | return int(data[0]) * 60 + int(data[1]) 114 | 115 | @staticmethod 116 | def _parseBrushStateResponse(data) -> BrushState: 117 | return BrushState(data[0]) 118 | 119 | @staticmethod 120 | def _parseBrushModeResponse(data) -> BrushMode: 121 | return BrushMode(data[0]) 122 | 123 | @staticmethod 124 | def _parseButtonStateResponse(data) -> OralBButtonStatus: 125 | return OralBButtonStatus( 126 | powerButtonPressed=bool(data[0]), 127 | modeButtonPressed=bool(data[1]) 128 | ) 129 | 130 | def readModelId(self) ->BrushInfo: 131 | data = self._modelIdChar.read() 132 | if len(data) == 3: 133 | return BrushInfo(type=data[0],protocolVersion=data[1],fwversion=data[2]) 134 | else: 135 | return BrushInfo(type=data[0]) 136 | 137 | def readBatteryStatus(self)->BrushBattery: 138 | data = self._batteryChar.read() 139 | return OralBToothbrush._parseBatteryStatysResponse(data) 140 | 141 | def setBatteryUpdateCallback(self, callback: Optional[BatteryStatusCallback]): 142 | if callback is None: 143 | self._removeCallback(self._batteryChar) 144 | else: 145 | self._registerCallback(self._batteryChar, 146 | lambda data: callback(OralBToothbrush._parseBatteryStatysResponse(data))) 147 | 148 | def readBrushingTime(self) -> int: 149 | data = self._brushingTimeChar.read() 150 | return OralBToothbrush._parseBrushingTimeResponse(data) 151 | 152 | def setBrushingTimeUpdateCallback(self, callback: Optional[BrushingTimeCallback]): 153 | if callback is None: 154 | self._removeCallback(self._brushingTimeChar) 155 | else: 156 | self._registerCallback(self._brushingTimeChar, 157 | lambda data: callback( 158 | OralBToothbrush._parseBrushingTimeResponse(data))) 159 | 160 | def readBrushState(self) -> BrushState: 161 | data = self._statusChar.read() 162 | return OralBToothbrush._parseBrushStateResponse(data) 163 | 164 | def setBrushStateUpdateCallback(self, callback: Optional[BrushStateCallback]): 165 | if callback is None: 166 | self._removeCallback(self._statusChar) 167 | else: 168 | self._registerCallback(self._statusChar, 169 | lambda data: callback( 170 | OralBToothbrush._parseBrushStateResponse(data))) 171 | 172 | def setBrushButtonPressedCallback(self, callback: Optional[BrushButtonCallback]): 173 | if callback is None: 174 | self._removeCallback(self._buttonChar) 175 | else: 176 | self._registerCallback(self._buttonChar, 177 | lambda data: callback( 178 | OralBToothbrush._parseButtonStateResponse(data))) 179 | 180 | def setBrushCurrentSectorCallback(self, callback: Optional[BrushCurrentSectorCallback]): 181 | if callback is None: 182 | self._removeCallback(self._currentSectorChar) 183 | else: 184 | self._registerCallback(self._currentSectorChar, 185 | lambda data: callback(BrushSector(data[0]))) 186 | 187 | def readBrushMode(self) -> BrushMode: 188 | data = self._modeChar.read() 189 | return OralBToothbrush._parseBrushModeResponse(data) 190 | 191 | def setBrushModeUpdateCallback(self, callback: Optional[BrushModeCallback]): 192 | if callback is None: 193 | self._removeCallback(self._modeChar) 194 | else: 195 | self._registerCallback(self._modeChar, 196 | lambda data: callback( 197 | OralBToothbrush._parseBrushModeResponse(data))) 198 | 199 | def _writeControl(self, commandId: int, param: int): 200 | data = bytearray(2) 201 | data[0] = commandId 202 | data[1] = param 203 | self._controlChar.write(data) 204 | 205 | def readCurrentTime(self) -> datetime: 206 | # self._writeControl(0x01,0x00) #seemsnot needed... 207 | rawSecAfter2000 = self._currentDateChar.read() 208 | return OralBDate(rawSecAfter2000).datetime 209 | 210 | def setCurrentTime(self, now=datetime.now()): 211 | self._writeControl(0x37, 0x26) 212 | date = OralBDate.fromDatetime(now) 213 | self._currentDateChar.write(date.toBytes()) 214 | 215 | def readAvailableModes(self) -> [BrushMode]: 216 | rawModes = self._availableModesChar.read() 217 | return [BrushMode(mode) for mode in rawModes] 218 | 219 | def writeAvailableModes(self, newOrder: [BrushMode]): 220 | self._writeControl(0x37, 0x29) 221 | rawData = bytearray(8) 222 | nMode = len(newOrder) 223 | rawData[0:nMode] = [mode.value for mode in newOrder] 224 | self._availableModesChar.write(rawData) 225 | 226 | def _nAvailableSessions(self) -> int: 227 | if 2 <= self._protocolVersion <= 4: 228 | return 30 229 | else: 230 | return 20 231 | 232 | def readSession(self) -> [BrushSession]: 233 | session = [] 234 | for i in range(0, self._nAvailableSessions()): 235 | self._writeControl(2, i) 236 | data = self._sessionInfoChar.read() 237 | session.append(BrushSession(data,self._protocolVersion)) 238 | return session 239 | 240 | def readSignalStatus(self) -> BrushSignal: 241 | rawData = self._signalChar.read() 242 | return BrushSignal.fromInt(rawData) 243 | 244 | def writeSignalStatus(self, newStatus: BrushSignal): 245 | self._writeControl(0x37, 0x28) 246 | rawData = struct.pack("I",newStatus.toInt()) 247 | self._signalChar.write(rawData) 248 | 249 | def readSectorTimer(self) -> [int]: 250 | rawData = self._sectorTimeChar.read() 251 | nSector = len(rawData) >> 1 # /2 252 | return struct.unpack("<" + "H" * nSector, rawData) 253 | 254 | def setSectorTimer(self, time: [int]): 255 | missingValue = 8 - len(time) 256 | print(missingValue) 257 | time += [0] * missingValue 258 | print(time) 259 | rawTime = struct.pack("<" + "H" * 8, *time) 260 | self._writeControl(0x37, 0x2A) 261 | self._sectorTimeChar.write(rawTime) 262 | 263 | def gerUserId(self) -> int: 264 | return self._userIdChar.read()[0] 265 | 266 | def setUserId(self, newId: int): 267 | rawTime = struct.pack("B", newId) 268 | self._userIdChar.write(rawTime) 269 | 270 | def readToothbrushId(self) -> int: 271 | rawData = self._toothbrushIdChar.read() 272 | return struct.unpack("