-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathAppTask.cpp
512 lines (438 loc) · 16.2 KB
/
AppTask.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
*
* Copyright (c) 2020-2021 Project CHIP Authors
* All rights reserved.
*
* 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 "qvIO.h"
#include "AppConfig.h"
#include "AppEvent.h"
#include "AppTask.h"
#include <app/server/OnboardingCodesUtil.h>
#include <app-common/zap-generated/attribute-id.h>
#include <app-common/zap-generated/attribute-type.h>
#include <app-common/zap-generated/cluster-id.h>
#include <app/server/Dnssd.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <credentials/DeviceAttestationCredsProvider.h>
#include <credentials/examples/DeviceAttestationCredsExample.h>
#include <setup_payload/QRCodeSetupPayloadGenerator.h>
#include <setup_payload/SetupPayload.h>
using namespace chip::TLV;
using namespace chip::Credentials;
using namespace chip::DeviceLayer;
#include <platform/CHIPDeviceLayer.h>
#if CHIP_ENABLE_OPENTHREAD
#include <platform/OpenThread/OpenThreadUtils.h>
#include <platform/ThreadStackManager.h>
#include <platform/qpg/ThreadStackManagerImpl.h>
#define JOINER_START_TRIGGER_TIMEOUT 1500
#endif
#define FACTORY_RESET_TRIGGER_TIMEOUT 3000
#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000
#define APP_TASK_STACK_SIZE (3072)
#define APP_TASK_PRIORITY 2
#define APP_EVENT_QUEUE_SIZE 10
namespace {
TaskHandle_t sAppTaskHandle;
QueueHandle_t sAppEventQueue;
bool sIsThreadProvisioned = false;
bool sIsThreadEnabled = false;
bool sHaveBLEConnections = false;
uint8_t sAppEventQueueBuffer[APP_EVENT_QUEUE_SIZE * sizeof(AppEvent)];
StaticQueue_t sAppEventQueueStruct;
StackType_t appStack[APP_TASK_STACK_SIZE / sizeof(StackType_t)];
StaticTask_t appTaskStruct;
} // namespace
AppTask AppTask::sAppTask;
namespace {
constexpr int extDiscTimeoutSecs = 20;
}
CHIP_ERROR AppTask::StartAppTask()
{
sAppEventQueue = xQueueCreateStatic(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent), sAppEventQueueBuffer, &sAppEventQueueStruct);
if (sAppEventQueue == NULL)
{
ChipLogError(NotSpecified, "Failed to allocate app event queue");
return CHIP_ERROR_NO_MEMORY;
}
// Start App task.
sAppTaskHandle = xTaskCreateStatic(AppTaskMain, APP_TASK_NAME, ArraySize(appStack), NULL, 1, appStack, &appTaskStruct);
if (sAppTaskHandle == NULL)
{
return CHIP_ERROR_NO_MEMORY;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR AppTask::Init()
{
CHIP_ERROR err = CHIP_NO_ERROR;
ChipLogProgress(NotSpecified, "Current Software Version: %s", CHIP_DEVICE_CONFIG_DEVICE_SOFTWARE_VERSION_STRING);
err = BoltLockMgr().Init();
if (err != CHIP_NO_ERROR)
{
ChipLogError(NotSpecified, "BoltLockMgr().Init() failed");
return err;
}
BoltLockMgr().SetCallbacks(ActionInitiated, ActionCompleted);
// Subscribe with our button callback to the qvCHIP button handler.
qvIO_SetBtnCallback(ButtonEventHandler);
qvIO_LedSet(LOCK_STATE_LED, !BoltLockMgr().IsUnlocked());
#if CHIP_DEVICE_CONFIG_ENABLE_EXTENDED_DISCOVERY
chip::app::DnssdServer::Instance().SetExtendedDiscoveryTimeoutSecs(extDiscTimeoutSecs);
#endif
// Init ZCL Data Model
chip::Server::GetInstance().Init();
// Initialize device attestation config
SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
UpdateClusterState();
ConfigurationMgr().LogDeviceConfig();
PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE));
return err;
}
void AppTask::AppTaskMain(void * pvParameter)
{
AppEvent event;
CHIP_ERROR err = sAppTask.Init();
if (err != CHIP_NO_ERROR)
{
ChipLogError(NotSpecified, "AppTask.Init() failed: %" CHIP_ERROR_FORMAT, err.Format());
// appError(err);
}
ChipLogProgress(NotSpecified, "App Task started");
while (true)
{
BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10));
while (eventReceived == pdTRUE)
{
sAppTask.DispatchEvent(&event);
eventReceived = xQueueReceive(sAppEventQueue, &event, 0);
}
// Collect connectivity and configuration state from the CHIP stack. Because
// the CHIP event loop is being run in a separate task, the stack must be
// locked while these values are queried. However we use a non-blocking
// lock request (TryLockCHIPStack()) to avoid blocking other UI activities
// when the CHIP task is busy (e.g. with a long crypto operation).
if (PlatformMgr().TryLockChipStack())
{
sIsThreadProvisioned = ConnectivityMgr().IsThreadProvisioned();
sIsThreadEnabled = ConnectivityMgr().IsThreadEnabled();
sHaveBLEConnections = (ConnectivityMgr().NumBLEConnections() != 0);
PlatformMgr().UnlockChipStack();
}
// Update the status LED if factory reset has not been initiated.
//
// If system has "full connectivity", keep the LED On constantly.
//
// If thread and service provisioned, but not attached to the thread network
// yet OR no connectivity to the service OR subscriptions are not fully
// established THEN blink the LED Off for a short period of time.
//
// If the system has ble connection(s) uptill the stage above, THEN blink
// the LEDs at an even rate of 100ms.
//
// Otherwise, blink the LED ON for a very short time.
if (sAppTask.mFunction != kFunction_FactoryReset)
{
if (sIsThreadProvisioned && sIsThreadEnabled)
{
qvIO_LedBlink(SYSTEM_STATE_LED, 950, 50);
}
else if (sHaveBLEConnections)
{
qvIO_LedBlink(SYSTEM_STATE_LED, 100, 100);
}
else
{
qvIO_LedBlink(SYSTEM_STATE_LED, 50, 950);
}
}
}
}
void AppTask::LockActionEventHandler(AppEvent * aEvent)
{
bool initiated = false;
BoltLockManager::Action_t action;
int32_t actor;
CHIP_ERROR err = CHIP_NO_ERROR;
if (aEvent->Type == AppEvent::kEventType_Lock)
{
action = static_cast<BoltLockManager::Action_t>(aEvent->LockEvent.Action);
actor = aEvent->LockEvent.Actor;
}
else if (aEvent->Type == AppEvent::kEventType_Button)
{
if (BoltLockMgr().IsUnlocked())
{
action = BoltLockManager::LOCK_ACTION;
}
else
{
action = BoltLockManager::UNLOCK_ACTION;
}
actor = AppEvent::kEventType_Button;
}
else
{
err = CHIP_ERROR_INTERNAL;
}
if (err == CHIP_NO_ERROR)
{
initiated = BoltLockMgr().InitiateAction(actor, action);
if (!initiated)
{
ChipLogProgress(NotSpecified, "Action is already in progress or active.");
}
}
}
void AppTask::ButtonEventHandler(uint8_t btnIdx, bool btnPressed)
{
if (btnIdx != APP_LOCK_BUTTON && btnIdx != APP_FUNCTION_BUTTON)
{
return;
}
AppEvent button_event = {};
button_event.Type = AppEvent::kEventType_Button;
button_event.ButtonEvent.ButtonIdx = btnIdx;
button_event.ButtonEvent.Action = btnPressed;
if (btnIdx == APP_LOCK_BUTTON && btnPressed == true)
{
button_event.Handler = LockActionEventHandler;
sAppTask.PostEvent(&button_event);
}
else if (btnIdx == APP_FUNCTION_BUTTON)
{
button_event.Handler = FunctionHandler;
sAppTask.PostEvent(&button_event);
}
}
void AppTask::TimerEventHandler(chip::System::Layer * aLayer, void * aAppState)
{
AppEvent event;
event.Type = AppEvent::kEventType_Timer;
event.TimerEvent.Context = aAppState;
event.Handler = FunctionTimerEventHandler;
sAppTask.PostEvent(&event);
}
void AppTask::FunctionTimerEventHandler(AppEvent * aEvent)
{
if (aEvent->Type != AppEvent::kEventType_Timer)
{
return;
}
// If we reached here, the button was held past FACTORY_RESET_TRIGGER_TIMEOUT,
// initiate factory reset
if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_StartBleAdv)
{
#if CHIP_ENABLE_OPENTHREAD
ChipLogProgress(NotSpecified, "Release button now to Start Thread Joiner");
ChipLogProgress(NotSpecified, "Hold to trigger Factory Reset");
sAppTask.mFunction = kFunction_Joiner;
sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT);
}
else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_Joiner)
{
#endif
ChipLogProgress(NotSpecified, "Factory Reset Triggered. Release button within %ums to cancel.",
FACTORY_RESET_CANCEL_WINDOW_TIMEOUT);
// Start timer for FACTORY_RESET_CANCEL_WINDOW_TIMEOUT to allow user to
// cancel, if required.
sAppTask.StartTimer(FACTORY_RESET_CANCEL_WINDOW_TIMEOUT);
sAppTask.mFunction = kFunction_FactoryReset;
// Turn off all LEDs before starting blink to make sure blink is
// co-ordinated.
qvIO_LedSet(SYSTEM_STATE_LED, false);
qvIO_LedSet(LOCK_STATE_LED, false);
qvIO_LedBlink(SYSTEM_STATE_LED, 500, 500);
qvIO_LedBlink(LOCK_STATE_LED, 500, 500);
}
else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_FactoryReset)
{
// Actually trigger Factory Reset
sAppTask.mFunction = kFunction_NoneSelected;
ConfigurationMgr().InitiateFactoryReset();
}
}
void AppTask::FunctionHandler(AppEvent * aEvent)
{
if (aEvent->ButtonEvent.ButtonIdx != APP_FUNCTION_BUTTON)
{
return;
}
// To trigger BLE advertising: press the APP_FUNCTION_BUTTON button briefly (<
// FACTORY_RESET_TRIGGER_TIMEOUT) To initiate factory reset: press the
// APP_FUNCTION_BUTTON for FACTORY_RESET_TRIGGER_TIMEOUT +
// FACTORY_RESET_CANCEL_WINDOW_TIMEOUT All LEDs start blinking after
// FACTORY_RESET_TRIGGER_TIMEOUT to signal factory reset has been initiated.
// To cancel factory reset: release the APP_FUNCTION_BUTTON once all LEDs
// start blinking within the FACTORY_RESET_CANCEL_WINDOW_TIMEOUT
if (aEvent->ButtonEvent.Action == true)
{
if (!sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_NoneSelected)
{
#if CHIP_ENABLE_OPENTHREAD
sAppTask.StartTimer(JOINER_START_TRIGGER_TIMEOUT);
#else
sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT);
#endif
sAppTask.mFunction = kFunction_StartBleAdv;
}
}
else
{
// If the button was released before factory reset got initiated, trigger BLE advertising.
if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_StartBleAdv)
{
sAppTask.CancelTimer();
sAppTask.mFunction = kFunction_NoneSelected;
if (ConnectivityMgr().IsBLEAdvertisingEnabled())
{
ChipLogProgress(NotSpecified, "BLE advertising already in progress.");
}
else
{
if (!ConnectivityMgr().IsThreadProvisioned())
{
// Enable BLE advertisements and pairing window
if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR)
{
ChipLogProgress(NotSpecified, "BLE advertising started. Waiting for Pairing.");
}
}
else
{
ChipLogError(NotSpecified, "Network is already provisioned, BLE advertisement not enabled");
}
}
}
#if CHIP_ENABLE_OPENTHREAD
else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_Joiner)
{
sAppTask.CancelTimer();
sAppTask.mFunction = kFunction_NoneSelected;
CHIP_ERROR error = ThreadStackMgr().JoinerStart();
ChipLogProgress(NotSpecified, "Thread joiner triggered: %s", chip::ErrorStr(error));
}
#endif
else if (sAppTask.mFunctionTimerActive && sAppTask.mFunction == kFunction_FactoryReset)
{
// Set lock status LED back to show state of lock.
qvIO_LedSet(LOCK_STATE_LED, !BoltLockMgr().IsUnlocked());
sAppTask.CancelTimer();
// Change the function to none selected since factory reset has been
// canceled.
sAppTask.mFunction = kFunction_NoneSelected;
ChipLogProgress(NotSpecified, "Factory Reset has been Canceled");
}
}
}
void AppTask::CancelTimer()
{
chip::DeviceLayer::SystemLayer().CancelTimer(TimerEventHandler, this);
mFunctionTimerActive = false;
}
void AppTask::StartTimer(uint32_t aTimeoutInMs)
{
CHIP_ERROR err;
chip::DeviceLayer::SystemLayer().CancelTimer(TimerEventHandler, this);
err = chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Milliseconds32(aTimeoutInMs), TimerEventHandler, this);
SuccessOrExit(err);
mFunctionTimerActive = true;
exit:
if (err != CHIP_NO_ERROR)
{
ChipLogError(NotSpecified, "StartTimer failed %s: ", chip::ErrorStr(err));
}
}
void AppTask::ActionInitiated(BoltLockManager::Action_t aAction, int32_t aActor)
{
// If the action has been initiated by the lock, update the bolt lock trait
// and start flashing the LEDs rapidly to indicate action initiation.
if (aAction == BoltLockManager::LOCK_ACTION)
{
ChipLogProgress(NotSpecified, "Lock Action has been initiated");
}
else if (aAction == BoltLockManager::UNLOCK_ACTION)
{
ChipLogProgress(NotSpecified, "Unlock Action has been initiated");
}
if (aActor == AppEvent::kEventType_Button)
{
sAppTask.mSyncClusterToButtonAction = true;
}
qvIO_LedBlink(LOCK_STATE_LED, 50, 50);
}
void AppTask::ActionCompleted(BoltLockManager::Action_t aAction)
{
// if the action has been completed by the lock, update the bolt lock trait.
// Turn on the lock LED if in a LOCKED state OR
// Turn off the lock LED if in an UNLOCKED state.
if (aAction == BoltLockManager::LOCK_ACTION)
{
ChipLogProgress(NotSpecified, "Lock Action has been completed");
qvIO_LedSet(LOCK_STATE_LED, true);
}
else if (aAction == BoltLockManager::UNLOCK_ACTION)
{
ChipLogProgress(NotSpecified, "Unlock Action has been completed");
qvIO_LedSet(LOCK_STATE_LED, false);
}
if (sAppTask.mSyncClusterToButtonAction)
{
sAppTask.UpdateClusterState();
sAppTask.mSyncClusterToButtonAction = false;
}
}
void AppTask::PostLockActionRequest(int32_t aActor, BoltLockManager::Action_t aAction)
{
AppEvent event;
event.Type = AppEvent::kEventType_Lock;
event.LockEvent.Actor = aActor;
event.LockEvent.Action = aAction;
event.Handler = LockActionEventHandler;
PostEvent(&event);
}
void AppTask::PostEvent(const AppEvent * aEvent)
{
if (sAppEventQueue != NULL)
{
if (!xQueueSend(sAppEventQueue, aEvent, 1))
{
ChipLogError(NotSpecified, "Failed to post event to app task event queue");
}
}
}
void AppTask::DispatchEvent(AppEvent * aEvent)
{
if (aEvent->Handler)
{
aEvent->Handler(aEvent);
}
else
{
ChipLogError(NotSpecified, "Event received with no handler. Dropping event.");
}
}
void AppTask::UpdateClusterState(void)
{
uint8_t newValue = !BoltLockMgr().IsUnlocked();
// write the new on/off value
EmberAfStatus status = emberAfWriteAttribute(1, ZCL_ON_OFF_CLUSTER_ID, ZCL_ON_OFF_ATTRIBUTE_ID, CLUSTER_MASK_SERVER,
(uint8_t *) &newValue, ZCL_BOOLEAN_ATTRIBUTE_TYPE);
if (status != EMBER_ZCL_STATUS_SUCCESS)
{
ChipLogError(NotSpecified, "ERR: updating on/off %" PRIx8, status);
}
}