• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021-2022 Google LLC
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#      https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15
16# -----------------------------------------------------------------------------
17# Imports
18# -----------------------------------------------------------------------------
19from ..gatt_client import ProfileServiceProxy
20from ..gatt import (
21    GATT_BATTERY_SERVICE,
22    GATT_BATTERY_LEVEL_CHARACTERISTIC,
23    TemplateService,
24    Characteristic,
25    CharacteristicValue,
26    PackedCharacteristicAdapter,
27)
28
29
30# -----------------------------------------------------------------------------
31class BatteryService(TemplateService):
32    UUID = GATT_BATTERY_SERVICE
33    BATTERY_LEVEL_FORMAT = 'B'
34
35    def __init__(self, read_battery_level):
36        self.battery_level_characteristic = PackedCharacteristicAdapter(
37            Characteristic(
38                GATT_BATTERY_LEVEL_CHARACTERISTIC,
39                Characteristic.READ | Characteristic.NOTIFY,
40                Characteristic.READABLE,
41                CharacteristicValue(read=read_battery_level),
42            ),
43            pack_format=BatteryService.BATTERY_LEVEL_FORMAT,
44        )
45        super().__init__([self.battery_level_characteristic])
46
47
48# -----------------------------------------------------------------------------
49class BatteryServiceProxy(ProfileServiceProxy):
50    SERVICE_CLASS = BatteryService
51
52    def __init__(self, service_proxy):
53        self.service_proxy = service_proxy
54
55        if characteristics := service_proxy.get_characteristics_by_uuid(
56            GATT_BATTERY_LEVEL_CHARACTERISTIC
57        ):
58            self.battery_level = PackedCharacteristicAdapter(
59                characteristics[0], pack_format=BatteryService.BATTERY_LEVEL_FORMAT
60            )
61        else:
62            self.battery_level = None
63