-
Notifications
You must be signed in to change notification settings - Fork 118
/
main.cpp
374 lines (327 loc) · 12.4 KB
/
main.cpp
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/* mbed Microcontroller Library
* Copyright (c) 2017-2019 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "platform/Callback.h"
#include "events/EventQueue.h"
#include "ble/BLE.h"
#include "gatt_server_process.h"
#include "mbed-trace/mbed_trace.h"
using mbed::callback;
using namespace std::literals::chrono_literals;
/**
* A Clock service that demonstrate the GattServer features.
*
* The clock service host three characteristics that model the current hour,
* minute and second of the clock. The value of the second characteristic is
* incremented automatically by the system.
*
* A client can subscribe to updates of the clock characteristics and get
* notified when one of the value is changed. Clients can also change value of
* the second, minute and hour characteristric.
*/
class ClockService : public ble::GattServer::EventHandler {
public:
ClockService() :
_hour_char("485f4145-52b9-4644-af1f-7a6b9322490f", 0),
_minute_char("0a924ca7-87cd-4699-a3bd-abdcd9cf126a", 0),
_second_char("8dd6a1b7-bc75-4741-8a26-264af75807de", 0),
_clock_service(
/* uuid */ "51311102-030e-485f-b122-f8f381aa84ed",
/* characteristics */ _clock_characteristics,
/* numCharacteristics */ sizeof(_clock_characteristics) /
sizeof(_clock_characteristics[0])
)
{
/* update internal pointers (value, descriptors and characteristics array) */
_clock_characteristics[0] = &_hour_char;
_clock_characteristics[1] = &_minute_char;
_clock_characteristics[2] = &_second_char;
/* setup authorization handlers */
_hour_char.setWriteAuthorizationCallback(this, &ClockService::authorize_client_write);
_minute_char.setWriteAuthorizationCallback(this, &ClockService::authorize_client_write);
_second_char.setWriteAuthorizationCallback(this, &ClockService::authorize_client_write);
}
void start(BLE &ble, events::EventQueue &event_queue)
{
_server = &ble.gattServer();
_event_queue = &event_queue;
printf("Registering demo service\r\n");
ble_error_t err = _server->addService(_clock_service);
if (err) {
printf("Error %u during demo service registration.\r\n", err);
return;
}
/* register handlers */
_server->setEventHandler(this);
printf("clock service registered\r\n");
printf("service handle: %u\r\n", _clock_service.getHandle());
printf("hour characteristic value handle %u\r\n", _hour_char.getValueHandle());
printf("minute characteristic value handle %u\r\n", _minute_char.getValueHandle());
printf("second characteristic value handle %u\r\n", _second_char.getValueHandle());
_event_queue->call_every(1000ms, callback(this, &ClockService::increment_second));
}
/* GattServer::EventHandler */
private:
/**
* Handler called when a notification or an indication has been sent.
*/
void onDataSent(const GattDataSentCallbackParams ¶ms) override
{
printf("sent updates\r\n");
}
/**
* Handler called after an attribute has been written.
*/
void onDataWritten(const GattWriteCallbackParams ¶ms) override
{
printf("data written:\r\n");
printf("connection handle: %u\r\n", params.connHandle);
printf("attribute handle: %u", params.handle);
if (params.handle == _hour_char.getValueHandle()) {
printf(" (hour characteristic)\r\n");
} else if (params.handle == _minute_char.getValueHandle()) {
printf(" (minute characteristic)\r\n");
} else if (params.handle == _second_char.getValueHandle()) {
printf(" (second characteristic)\r\n");
} else {
printf("\r\n");
}
printf("write operation: %u\r\n", params.writeOp);
printf("offset: %u\r\n", params.offset);
printf("length: %u\r\n", params.len);
printf("data: ");
for (size_t i = 0; i < params.len; ++i) {
printf("%02X", params.data[i]);
}
printf("\r\n");
}
/**
* Handler called after an attribute has been read.
*/
void onDataRead(const GattReadCallbackParams ¶ms) override
{
printf("data read:\r\n");
printf("connection handle: %u\r\n", params.connHandle);
printf("attribute handle: %u", params.handle);
if (params.handle == _hour_char.getValueHandle()) {
printf(" (hour characteristic)\r\n");
} else if (params.handle == _minute_char.getValueHandle()) {
printf(" (minute characteristic)\r\n");
} else if (params.handle == _second_char.getValueHandle()) {
printf(" (second characteristic)\r\n");
} else {
printf("\r\n");
}
}
/**
* Handler called after a client has subscribed to notification or indication.
*
* @param handle Handle of the characteristic value affected by the change.
*/
void onUpdatesEnabled(const GattUpdatesEnabledCallbackParams ¶ms) override
{
printf("update enabled on handle %d\r\n", params.attHandle);
}
/**
* Handler called after a client has cancelled his subscription from
* notification or indication.
*
* @param handle Handle of the characteristic value affected by the change.
*/
void onUpdatesDisabled(const GattUpdatesDisabledCallbackParams ¶ms) override
{
printf("update disabled on handle %d\r\n", params.attHandle);
}
/**
* Handler called when an indication confirmation has been received.
*
* @param handle Handle of the characteristic value that has emitted the
* indication.
*/
void onConfirmationReceived(const GattConfirmationReceivedCallbackParams ¶ms) override
{
printf("confirmation received on handle %d\r\n", params.attHandle);
}
private:
/**
* Handler called when a write request is received.
*
* This handler verify that the value submitted by the client is valid before
* authorizing the operation.
*/
void authorize_client_write(GattWriteAuthCallbackParams *e)
{
printf("characteristic %u write authorization\r\n", e->handle);
if (e->offset != 0) {
printf("Error invalid offset\r\n");
e->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_OFFSET;
return;
}
if (e->len != 1) {
printf("Error invalid len\r\n");
e->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_INVALID_ATT_VAL_LENGTH;
return;
}
if ((e->data[0] >= 60) ||
((e->data[0] >= 24) && (e->handle == _hour_char.getValueHandle()))) {
printf("Error invalid data\r\n");
e->authorizationReply = AUTH_CALLBACK_REPLY_ATTERR_WRITE_NOT_PERMITTED;
return;
}
e->authorizationReply = AUTH_CALLBACK_REPLY_SUCCESS;
}
/**
* Increment the second counter.
*/
void increment_second(void)
{
uint8_t second = 0;
ble_error_t err = _second_char.get(*_server, second);
if (err) {
printf("read of the second value returned error %u\r\n", err);
return;
}
second = (second + 1) % 60;
err = _second_char.set(*_server, second);
if (err) {
printf("write of the second value returned error %u\r\n", err);
return;
}
if (second == 0) {
increment_minute();
}
}
/**
* Increment the minute counter.
*/
void increment_minute(void)
{
uint8_t minute = 0;
ble_error_t err = _minute_char.get(*_server, minute);
if (err) {
printf("read of the minute value returned error %u\r\n", err);
return;
}
minute = (minute + 1) % 60;
err = _minute_char.set(*_server, minute);
if (err) {
printf("write of the minute value returned error %u\r\n", err);
return;
}
if (minute == 0) {
increment_hour();
}
}
/**
* Increment the hour counter.
*/
void increment_hour(void)
{
uint8_t hour = 0;
ble_error_t err = _hour_char.get(*_server, hour);
if (err) {
printf("read of the hour value returned error %u\r\n", err);
return;
}
hour = (hour + 1) % 24;
err = _hour_char.set(*_server, hour);
if (err) {
printf("write of the hour value returned error %u\r\n", err);
return;
}
}
private:
/**
* Read, Write, Notify, Indicate Characteristic declaration helper.
*
* @tparam T type of data held by the characteristic.
*/
template<typename T>
class ReadWriteNotifyIndicateCharacteristic : public GattCharacteristic {
public:
/**
* Construct a characteristic that can be read or written and emit
* notification or indication.
*
* @param[in] uuid The UUID of the characteristic.
* @param[in] initial_value Initial value contained by the characteristic.
*/
ReadWriteNotifyIndicateCharacteristic(const UUID & uuid, const T& initial_value) :
GattCharacteristic(
/* UUID */ uuid,
/* Initial value */ &_value,
/* Value size */ sizeof(_value),
/* Value capacity */ sizeof(_value),
/* Properties */ GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY |
GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE,
/* Descriptors */ nullptr,
/* Num descriptors */ 0,
/* variable len */ false
),
_value(initial_value) {
}
/**
* Get the value of this characteristic.
*
* @param[in] server GattServer instance that contain the characteristic
* value.
* @param[in] dst Variable that will receive the characteristic value.
*
* @return BLE_ERROR_NONE in case of success or an appropriate error code.
*/
ble_error_t get(GattServer &server, T& dst) const
{
uint16_t value_length = sizeof(dst);
return server.read(getValueHandle(), &dst, &value_length);
}
/**
* Assign a new value to this characteristic.
*
* @param[in] server GattServer instance that will receive the new value.
* @param[in] value The new value to set.
* @param[in] local_only Flag that determine if the change should be kept
* locally or forwarded to subscribed clients.
*/
ble_error_t set(GattServer &server, const uint8_t &value, bool local_only = false) const
{
return server.write(getValueHandle(), &value, sizeof(value), local_only);
}
private:
uint8_t _value;
};
private:
GattServer *_server = nullptr;
events::EventQueue *_event_queue = nullptr;
GattService _clock_service;
GattCharacteristic* _clock_characteristics[3];
ReadWriteNotifyIndicateCharacteristic<uint8_t> _hour_char;
ReadWriteNotifyIndicateCharacteristic<uint8_t> _minute_char;
ReadWriteNotifyIndicateCharacteristic<uint8_t> _second_char;
};
int main()
{
mbed_trace_init();
BLE &ble = BLE::Instance();
events::EventQueue event_queue;
ClockService demo_service;
/* this process will handle basic ble setup and advertising for us */
GattServerProcess ble_process(event_queue, ble);
/* once it's done it will let us continue with our demo */
ble_process.on_init(callback(&demo_service, &ClockService::start));
ble_process.start();
return 0;
}