summaryrefslogtreecommitdiffstats
path: root/sensor_firmware/btsensors.py
blob: 22523f6eb58a27265071fd7d3862a900dc13fda3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#
# Bluetooth LE sensor peripheral
# Copyright (c) 2020 Michael Büsch <m@bues.ch>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#

import bluetooth as bt
import ubinascii
from logging import printInfo, printError
from micropython import const
from struct import pack
from util import lim

# org.bluetooth.characteristic.pressure
_PRES_CHAR = (bt.UUID(0x2A6D), bt.FLAG_READ | bt.FLAG_NOTIFY | bt.FLAG_INDICATE,)
# org.bluetooth.characteristic.temperature
_TEMP_CHAR = (bt.UUID(0x2A6E), bt.FLAG_READ | bt.FLAG_NOTIFY | bt.FLAG_INDICATE,)
# org.bluetooth.characteristic.humidity
_HUM_CHAR  = (bt.UUID(0x2A6F), bt.FLAG_READ | bt.FLAG_NOTIFY | bt.FLAG_INDICATE,)
# org.bluetooth.characteristic.string
_STR_CHAR  = (bt.UUID(0x2A3D), bt.FLAG_READ | bt.FLAG_NOTIFY | bt.FLAG_INDICATE,)

# org.bluetooth.service.environmental_sensing
_ENV_SENSE_UUID = bt.UUID(0x181A)
_ENV_SENSE_SERVICE = (_ENV_SENSE_UUID, (_TEMP_CHAR, _HUM_CHAR, _STR_CHAR, _PRES_CHAR),)
_SERVICES = (_ENV_SENSE_SERVICE,)

_ADV_APPEARANCE_UNKNOWN             = const(0)
_ADV_APPEARANCE_GENERIC_THERMOMETER = const(768)

_ADV_TYPE_FLAGS                     = const(0x01)
_ADV_TYPE_NAME                      = const(0x09)
_ADV_TYPE_UUID16_COMPLETE           = const(0x3)
_ADV_TYPE_UUID32_COMPLETE           = const(0x5)
_ADV_TYPE_UUID128_COMPLETE          = const(0x7)
_ADV_TYPE_UUID16_MORE               = const(0x2)
_ADV_TYPE_UUID32_MORE               = const(0x4)
_ADV_TYPE_UUID128_MORE              = const(0x6)
_ADV_TYPE_APPEARANCE                = const(0x19)

# Interrupt vectors
_IRQ_CENTRAL_CONNECT                = const(1)
_IRQ_CENTRAL_DISCONNECT             = const(2)
_IRQ_GATTS_WRITE                    = const(3)
_IRQ_GATTS_READ_REQUEST             = const(4)
_IRQ_SCAN_RESULT                    = const(5)
_IRQ_SCAN_DONE                      = const(6)
_IRQ_PERIPHERAL_CONNECT             = const(7)
_IRQ_PERIPHERAL_DISCONNECT          = const(8)
_IRQ_GATTC_SERVICE_RESULT           = const(9)
_IRQ_GATTC_SERVICE_DONE             = const(10)
_IRQ_GATTC_CHARACTERISTIC_RESULT    = const(11)
_IRQ_GATTC_CHARACTERISTIC_DONE      = const(12)
_IRQ_GATTC_DESCRIPTOR_RESULT        = const(13)
_IRQ_GATTC_DESCRIPTOR_DONE          = const(14)
_IRQ_GATTC_READ_RESULT              = const(15)
_IRQ_GATTC_READ_DONE                = const(16)
_IRQ_GATTC_WRITE_DONE               = const(17)
_IRQ_GATTC_NOTIFY                   = const(18)
_IRQ_GATTC_INDICATE                 = const(19)
_IRQ_GATTS_INDICATE_DONE            = const(20)

class BtSensors(object):
    """Bluetooth LE sensor peripheral.
    """

    def __init__(self):
        printInfo("Initializing BLE...")

        self.__resetCache()
        self.__conn = set()
        self.__ble = ble = bt.BLE()

        ble.active(True)
        ble.config(gap_name="envsensors")
        addrType, addr = ble.config("mac")
        addr = ubinascii.hexlify(addr, ":").decode("ascii")
        addrType = {
            0: "(public)",
            1: "(random)",
            2: "(rpa)",
            3: "(nrpa)",
        }[addrType]
        printInfo("BLE MAC:", addr, addrType)
        ble.irq(self.__isr)

        srv = ble.gatts_register_services(_SERVICES)
        self.__hndTemp, self.__hndHumRel, self.__hndHumAbs, self.__hndPres = srv[0]

        self.__advPl = self.__advPayload(name="envsensors",
                                         limitedDiscoverable=True,
                                         br_edr=False,
                                         serviceUUIDs=(_ENV_SENSE_UUID,),
                                         appearance=_ADV_APPEARANCE_GENERIC_THERMOMETER)
        self.__advertise()

        printInfo("BLE initialized.")

    @staticmethod
    def __advPayload(name,
                     limitedDiscoverable=False,
                     br_edr=False,
                     serviceUUIDs=(),
                     appearance=_ADV_APPEARANCE_UNKNOWN):
        """Generate advertisement payload.
        name: Name string.
        limitedDiscoverable: Discoverable for limited period of time.
        br_edr: Supports Basic Rate / Enhanced Data Rate.
        servicesUUIDs: List of service UUIDs.
        appearance: Appearance ID.
        """
        pl = bytearray()
        def add(advType, value):
            pl.extend(pack("BB", len(value) + 1, advType))
            pl.extend(value)
        flags = 0x01 if limitedDiscoverable else 0x02
        flags |= 0x18 if br_edr else 0x04
        add(_ADV_TYPE_FLAGS, pack("B", flags))
        add(_ADV_TYPE_NAME, name.encode("UTF-8"))
        for uuid in serviceUUIDs:
            uuid = bytes(uuid)
            if len(uuid) == 2:
                add(_ADV_TYPE_UUID16_COMPLETE, uuid)
            elif len(uuid) == 4:
                add(_ADV_TYPE_UUID32_COMPLETE, uuid)
            elif len(uuid) == 16:
                add(_ADV_TYPE_UUID128_COMPLETE, uuid)
            else:
                assert False
        add(_ADV_TYPE_APPEARANCE, pack("<h", appearance))
        return pl

    def __isr(self, event, data):
        """Interrupt service routine.
        """
        ble = self.__ble
        def enter(name):
            printInfo("BLE IRQ:", name)
        if event == _IRQ_CENTRAL_CONNECT:
            enter("_IRQ_CENTRAL_CONNECT")
            conn, _, _, = data
            self.__conn.add(conn)
            self.__resetCache()
        elif event == _IRQ_CENTRAL_DISCONNECT:
            enter("_IRQ_CENTRAL_DISCONNECT")
            conn, _, _, = data
            self.__conn.remove(conn)
            self.__advertise()
        elif event == _IRQ_GATTS_INDICATE_DONE:
            conn, handle, status, = data
            enter("_IRQ_GATTS_INDICATE_DONE")
        else:
            printError("BtSensTemp unhandled IRQ: event=%s  data=%s" % (
                       repr(event), repr(data)))

    def __advertise(self):
        """Start advertising.
        """
        self.__ble.gap_advertise(500000, adv_data=self.__advPl)

    def __resetCache(self):
        self.__prevTemp = self.__prevHumRel = self.__prevHumAbs = self.__prevPres = None

    def __setValue(self, handle, prev, val):
        ble = self.__ble
        if val != prev:
            ble.gatts_write(handle, val)
            for conn in self.__conn:
                ble.gatts_notify(conn, handle)
                ble.gatts_indicate(conn, handle)
        return val

    def setValues(self, temp, relHum, absHum, pres):
        """Set new sensor values.
        temp: Temperature, in degree Celsius.
        hum: Relative humidity range 0.0 - 1.0.
        absHum: Absolute humidity in g/m3.
        pres: Pressure in Pascal.
        """
        if temp is not None:
            self.__prevTemp = self.__setValue(
                    self.__hndTemp,
                    self.__prevTemp,
                    pack("<h", lim(round(temp * 1e2), -27315, 32767)))

        if relHum is not None:
            self.__prevHumRel = self.__setValue(
                    self.__hndHumRel,
                    self.__prevHumRel,
                    pack("<H", lim(round(relHum * 1e4), 0, 10000)))

        if absHum is not None:
            self.__prevHumAbs = self.__setValue(
                    self.__hndHumAbs,
                    self.__prevHumAbs,
                    ("Humidity %.1f g/m³" % absHum).encode("UTF-8"))

        if pres is not None:
            self.__prevPres = self.__setValue(
                    self.__hndPres,
                    self.__prevPres,
                    pack("<I", lim(round(pres * 1e1), 0, 0xFFFFFFFF)))

# vim: ts=4 sw=4 expandtab
bues.ch cgit interface