forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppTask.cpp
675 lines (577 loc) · 19.5 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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*
*
* Copyright (c) 2021 Project CHIP Authors
* Copyright (c) 2021 Google LLC.
* 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 "AppTask.h"
#include "AppEvent.h"
#include <app/server/Server.h>
#include <lib/support/ErrorStr.h>
#include <app/server/OnboardingCodesUtil.h>
#include <credentials/DeviceAttestationCredsProvider.h>
#include <credentials/examples/DeviceAttestationCredsExample.h>
#include <lib/support/ThreadOperationalDataset.h>
#include <platform/CHIPDeviceLayer.h>
#include <platform/internal/DeviceNetworkInfo.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/util/attribute-storage.h>
/* OTA related includes */
#include "OTAImageProcessorImpl.h"
#include "OtaSupport.h"
#include <app/clusters/ota-requestor/BDXDownloader.h>
#include <app/clusters/ota-requestor/GenericOTARequestorDriver.h>
#include <app/clusters/ota-requestor/OTARequestor.h>
#include "Keyboard.h"
#include "LED.h"
#include "LEDWidget.h"
#include "TimersManager.h"
#include "app_config.h"
#if CHIP_CRYPTO_HSM
#include <crypto/hsm/CHIPCryptoPALHsm.h>
#endif
#ifdef ENABLE_HSM_DEVICE_ATTESTATION
#include "DeviceAttestationSe05xCredsExample.h"
#endif
#define FACTORY_RESET_TRIGGER_TIMEOUT 6000
#define FACTORY_RESET_CANCEL_WINDOW_TIMEOUT 3000
#define APP_TASK_STACK_SIZE (4096)
#define APP_TASK_PRIORITY 2
#define APP_EVENT_QUEUE_SIZE 10
TimerHandle_t sFunctionTimer; // FreeRTOS app sw timer.
static QueueHandle_t sAppEventQueue;
static LEDWidget sStatusLED;
static LEDWidget sLightLED;
static bool sIsThreadProvisioned = false;
static bool sIsThreadEnabled = false;
static bool sHaveBLEConnections = false;
static uint32_t eventMask = 0;
#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI
extern "C" void K32WUartProcess(void);
#endif
using namespace ::chip::Credentials;
using namespace ::chip::DeviceLayer;
using namespace chip;
;
AppTask AppTask::sAppTask;
/* OTA related variables */
static OTARequestor gRequestorCore;
DeviceLayer::GenericOTARequestorDriver gRequestorUser;
static BDXDownloader gDownloader;
static OTAImageProcessorImpl gImageProcessor;
CHIP_ERROR AppTask::StartAppTask()
{
CHIP_ERROR err = CHIP_NO_ERROR;
sAppEventQueue = xQueueCreate(APP_EVENT_QUEUE_SIZE, sizeof(AppEvent));
if (sAppEventQueue == NULL)
{
err = APP_ERROR_EVENT_QUEUE_FAILED;
K32W_LOG("Failed to allocate app event queue");
assert(err == CHIP_NO_ERROR);
}
return err;
}
CHIP_ERROR AppTask::Init()
{
CHIP_ERROR err = CHIP_NO_ERROR;
// Init ZCL Data Model and start server
chip::Server::GetInstance().Init();
// Initialize device attestation config
#ifdef ENABLE_HSM_DEVICE_ATTESTATION
SetDeviceAttestationCredentialsProvider(Examples::GetExampleSe05xDACProvider());
#else
SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
#endif
// Initialize and interconnect the Requestor and Image Processor objects -- START
SetRequestorInstance(&gRequestorCore);
gRequestorCore.Init(&(chip::Server::GetInstance()), &gRequestorUser, &gDownloader);
gRequestorUser.Init(&gRequestorCore, &gImageProcessor);
// WARNING: this is probably not realistic to know such details of the image or to even have an OTADownloader instantiated at
// the beginning of program execution. We're using hardcoded values here for now since this is a reference application.
// TODO: instatiate and initialize these values when QueryImageResponse tells us an image is available
// TODO: add API for OTARequestor to pass QueryImageResponse info to the application to use for OTADownloader init
OTAImageProcessorParams ipParams;
ipParams.imageFile = CharSpan("test.txt");
gImageProcessor.SetOTAImageProcessorParams(ipParams);
gImageProcessor.SetOTADownloader(&gDownloader);
// Connect the gDownloader and Image Processor objects
gDownloader.SetImageProcessorDelegate(&gImageProcessor);
// Initialize and interconnect the Requestor and Image Processor objects -- END
// QR code will be used with CHIP Tool
PrintOnboardingCodes(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE));
TMR_Init();
/* HW init leds */
LED_Init();
if (LightingMgr().Init() != 0)
{
K32W_LOG("LightingMgr().Init() failed");
assert(0);
}
LightingMgr().SetCallbacks(ActionInitiated, ActionCompleted);
/* start with all LEDS turnedd off */
sStatusLED.Init(SYSTEM_STATE_LED);
sLightLED.Init(LIGHT_STATE_LED);
sLightLED.Set(!LightingMgr().IsTurnedOff());
UpdateClusterState();
/* intialize the Keyboard and button press calback */
KBD_Init(KBD_Callback);
// Create FreeRTOS sw timer for Function Selection.
sFunctionTimer = xTimerCreate("FnTmr", // Just a text name, not used by the RTOS kernel
1, // == default timer period (mS)
false, // no timer reload (==one-shot)
(void *) this, // init timer id = app task obj context
TimerEventHandler // timer callback handler
);
if (sFunctionTimer == NULL)
{
err = APP_ERROR_CREATE_TIMER_FAILED;
K32W_LOG("app_timer_create() failed");
assert(err == CHIP_NO_ERROR);
}
// Print the current software version
char currentSoftwareVer[ConfigurationManager::kMaxSoftwareVersionStringLength + 1] = { 0 };
err = ConfigurationMgr().GetSoftwareVersionString(currentSoftwareVer, sizeof(currentSoftwareVer));
if (err != CHIP_NO_ERROR)
{
K32W_LOG("Get version error");
assert(err == CHIP_NO_ERROR);
}
K32W_LOG("Current Software Version: %s", currentSoftwareVer);
#if CONFIG_CHIP_NFC_COMMISSIONING
PlatformMgr().AddEventHandler(ThreadProvisioningHandler, 0);
#endif
return err;
}
void AppTask::AppTaskMain(void * pvParameter)
{
AppEvent event;
CHIP_ERROR err = sAppTask.Init();
if (err != CHIP_NO_ERROR)
{
K32W_LOG("AppTask.Init() failed");
assert(err == CHIP_NO_ERROR);
}
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())
{
#if CHIP_DEVICE_CONFIG_THREAD_ENABLE_CLI
K32WUartProcess();
#endif
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)
{
sStatusLED.Blink(950, 50);
}
else if (sHaveBLEConnections)
{
sStatusLED.Blink(100, 100);
}
else
{
sStatusLED.Blink(50, 950);
}
}
sStatusLED.Animate();
sLightLED.Animate();
HandleKeyboard();
if (gDownloader.GetState() == OTADownloader::State::kInProgress)
{
OTA_TransactionResume();
if (!EEPROM_isBusy())
{
gDownloader.FetchNextData();
}
}
}
}
void AppTask::ButtonEventHandler(uint8_t pin_no, uint8_t button_action)
{
if ((pin_no != RESET_BUTTON) && (pin_no != LIGHT_BUTTON) && (pin_no != OTA_BUTTON) && (pin_no != BLE_BUTTON))
{
return;
}
AppEvent button_event;
button_event.Type = AppEvent::kEventType_Button;
button_event.ButtonEvent.PinNo = pin_no;
button_event.ButtonEvent.Action = button_action;
if (pin_no == RESET_BUTTON)
{
button_event.Handler = ResetActionEventHandler;
}
else if (pin_no == LIGHT_BUTTON)
{
button_event.Handler = LightActionEventHandler;
}
else if (pin_no == OTA_BUTTON)
{
button_event.Handler = OTAHandler;
}
else if (pin_no == BLE_BUTTON)
{
button_event.Handler = BleHandler;
#if !(defined OM15082)
if (button_action == RESET_BUTTON_PUSH)
{
button_event.Handler = ResetActionEventHandler;
}
#endif
}
sAppTask.PostEvent(&button_event);
}
void AppTask::KBD_Callback(uint8_t events)
{
eventMask = eventMask | (uint32_t)(1 << events);
}
void AppTask::HandleKeyboard(void)
{
uint8_t keyEvent = 0xFF;
uint8_t pos = 0;
while (eventMask)
{
for (pos = 0; pos < (8 * sizeof(eventMask)); pos++)
{
if (eventMask & (1 << pos))
{
keyEvent = pos;
eventMask = eventMask & ~(1 << pos);
break;
}
}
switch (keyEvent)
{
case gKBD_EventPB1_c:
#if (defined OM15082)
ButtonEventHandler(RESET_BUTTON, RESET_BUTTON_PUSH);
break;
#else
ButtonEventHandler(BLE_BUTTON, BLE_BUTTON_PUSH);
break;
#endif
case gKBD_EventPB2_c:
ButtonEventHandler(LIGHT_BUTTON, LIGHT_BUTTON_PUSH);
break;
case gKBD_EventPB3_c:
ButtonEventHandler(OTA_BUTTON, OTA_BUTTON_PUSH);
break;
case gKBD_EventPB4_c:
ButtonEventHandler(BLE_BUTTON, BLE_BUTTON_PUSH);
break;
#if !(defined OM15082)
case gKBD_EventLongPB1_c:
ButtonEventHandler(BLE_BUTTON, RESET_BUTTON_PUSH);
break;
#endif
default:
break;
}
}
}
void AppTask::TimerEventHandler(TimerHandle_t xTimer)
{
AppEvent event;
event.Type = AppEvent::kEventType_Timer;
event.TimerEvent.Context = (void *) xTimer;
event.Handler = FunctionTimerEventHandler;
sAppTask.PostEvent(&event);
}
void AppTask::FunctionTimerEventHandler(AppEvent * aEvent)
{
if (aEvent->Type != AppEvent::kEventType_Timer)
return;
K32W_LOG("Device will factory reset...");
// Actually trigger Factory Reset
chip::Server::GetInstance().ScheduleFactoryReset();
}
void AppTask::ResetActionEventHandler(AppEvent * aEvent)
{
if (aEvent->ButtonEvent.PinNo != RESET_BUTTON && aEvent->ButtonEvent.PinNo != BLE_BUTTON)
return;
if (sAppTask.mResetTimerActive)
{
sAppTask.CancelTimer();
sAppTask.mFunction = kFunction_NoneSelected;
/* restore initial state for the LED indicating Lighting state */
if (LightingMgr().IsTurnedOff())
{
sLightLED.Set(false);
}
else
{
sLightLED.Set(true);
}
K32W_LOG("Factory Reset was cancelled!");
}
else
{
uint32_t resetTimeout = FACTORY_RESET_TRIGGER_TIMEOUT;
if (sAppTask.mFunction != kFunction_NoneSelected)
{
K32W_LOG("Another function is scheduled. Could not initiate Factory Reset!");
return;
}
K32W_LOG("Factory Reset Triggered. Push the RESET button within %u ms to cancel!", resetTimeout);
sAppTask.mFunction = kFunction_FactoryReset;
/* LEDs will start blinking to signal that a Factory Reset was scheduled */
sStatusLED.Set(false);
sLightLED.Set(false);
sStatusLED.Blink(500);
sLightLED.Blink(500);
sAppTask.StartTimer(FACTORY_RESET_TRIGGER_TIMEOUT);
}
}
void AppTask::LightActionEventHandler(AppEvent * aEvent)
{
LightingManager::Action_t action;
CHIP_ERROR err = CHIP_NO_ERROR;
int32_t actor = 0;
bool initiated = false;
if (sAppTask.mFunction != kFunction_NoneSelected)
{
K32W_LOG("Another function is scheduled. Could not initiate ON/OFF Light command!");
return;
}
if (aEvent->Type == AppEvent::kEventType_TurnOn)
{
action = static_cast<LightingManager::Action_t>(aEvent->LightEvent.Action);
actor = aEvent->LightEvent.Actor;
}
else if (aEvent->Type == AppEvent::kEventType_Button)
{
if (LightingMgr().IsTurnedOff())
{
action = LightingManager::TURNON_ACTION;
}
else
{
action = LightingManager::TURNOFF_ACTION;
}
}
else
{
err = APP_ERROR_UNHANDLED_EVENT;
action = LightingManager::INVALID_ACTION;
}
if (err == CHIP_NO_ERROR)
{
initiated = LightingMgr().InitiateAction(actor, action);
if (!initiated)
{
K32W_LOG("Action is already in progress or active.");
}
}
}
void AppTask::OTAHandler(AppEvent * aEvent)
{
if (aEvent->ButtonEvent.PinNo != OTA_BUTTON)
return;
if (sAppTask.mFunction != kFunction_NoneSelected)
{
K32W_LOG("Another function is scheduled. Could not initiate OTA!");
return;
}
static_cast<OTARequestor *>(GetRequestorInstance())->TriggerImmediateQuery();
}
void AppTask::BleHandler(AppEvent * aEvent)
{
if (aEvent->ButtonEvent.PinNo != BLE_BUTTON)
return;
if (sAppTask.mFunction != kFunction_NoneSelected)
{
K32W_LOG("Another function is scheduled. Could not toggle BLE state!");
return;
}
if (ConnectivityMgr().IsBLEAdvertisingEnabled())
{
ConnectivityMgr().SetBLEAdvertisingEnabled(false);
K32W_LOG("Stopped BLE Advertising!");
}
else
{
ConnectivityMgr().SetBLEAdvertisingEnabled(true);
if (chip::Server::GetInstance().GetCommissioningWindowManager().OpenBasicCommissioningWindow() == CHIP_NO_ERROR)
{
K32W_LOG("Started BLE Advertising!");
}
else
{
K32W_LOG("OpenBasicCommissioningWindow() failed");
}
}
}
#if CONFIG_CHIP_NFC_COMMISSIONING
void AppTask::ThreadProvisioningHandler(const ChipDeviceEvent * event, intptr_t)
{
if (event->Type == DeviceEventType::kCHIPoBLEAdvertisingChange && event->CHIPoBLEAdvertisingChange.Result == kActivity_Stopped)
{
if (!NFCMgr().IsTagEmulationStarted())
{
K32W_LOG("NFC Tag emulation is already stopped!");
}
else
{
NFCMgr().StopTagEmulation();
K32W_LOG("Stopped NFC Tag Emulation!");
}
}
else if (event->Type == DeviceEventType::kCHIPoBLEAdvertisingChange &&
event->CHIPoBLEAdvertisingChange.Result == kActivity_Started)
{
if (NFCMgr().IsTagEmulationStarted())
{
K32W_LOG("NFC Tag emulation is already started!");
}
else
{
ShareQRCodeOverNFC(chip::RendezvousInformationFlags(chip::RendezvousInformationFlag::kBLE));
K32W_LOG("Started NFC Tag Emulation!");
}
}
}
#endif
void AppTask::CancelTimer()
{
if (xTimerStop(sFunctionTimer, 0) == pdFAIL)
{
K32W_LOG("app timer stop() failed");
}
mResetTimerActive = false;
}
void AppTask::StartTimer(uint32_t aTimeoutInMs)
{
if (xTimerIsTimerActive(sFunctionTimer))
{
K32W_LOG("app timer already started!");
CancelTimer();
}
// timer is not active, change its period to required value (== restart).
// FreeRTOS- Block for a maximum of 100 ticks if the change period command
// cannot immediately be sent to the timer command queue.
if (xTimerChangePeriod(sFunctionTimer, aTimeoutInMs / portTICK_PERIOD_MS, 100) != pdPASS)
{
K32W_LOG("app timer start() failed");
}
mResetTimerActive = true;
}
void AppTask::ActionInitiated(LightingManager::Action_t aAction, int32_t aActor)
{
// start flashing the LEDs rapidly to indicate action initiation.
if (aAction == LightingManager::TURNON_ACTION)
{
K32W_LOG("Turn on Action has been initiated")
}
else if (aAction == LightingManager::TURNOFF_ACTION)
{
K32W_LOG("Turn off Action has been initiated")
}
if (aActor == AppEvent::kEventType_Button)
{
sAppTask.mSyncClusterToButtonAction = true;
}
sAppTask.mFunction = kFunctionTurnOnTurnOff;
}
void AppTask::ActionCompleted(LightingManager::Action_t aAction)
{
// Turn on the light LED if in a TURNON state OR
// Turn off the light LED if in a TURNOFF state.
if (aAction == LightingManager::TURNON_ACTION)
{
K32W_LOG("Turn on action has been completed")
sLightLED.Set(true);
}
else if (aAction == LightingManager::TURNOFF_ACTION)
{
K32W_LOG("Turn off action has been completed")
sLightLED.Set(false);
}
if (sAppTask.mSyncClusterToButtonAction)
{
sAppTask.UpdateClusterState();
sAppTask.mSyncClusterToButtonAction = false;
}
sAppTask.mFunction = kFunction_NoneSelected;
}
void AppTask::PostTurnOnActionRequest(int32_t aActor, LightingManager::Action_t aAction)
{
AppEvent event;
event.Type = AppEvent::kEventType_TurnOn;
event.LightEvent.Actor = aActor;
event.LightEvent.Action = aAction;
event.Handler = LightActionEventHandler;
PostEvent(&event);
}
void AppTask::PostEvent(const AppEvent * aEvent)
{
if (sAppEventQueue != NULL)
{
if (!xQueueSend(sAppEventQueue, aEvent, 1))
{
K32W_LOG("Failed to post event to app task event queue");
}
}
}
void AppTask::DispatchEvent(AppEvent * aEvent)
{
if (aEvent->Handler)
{
aEvent->Handler(aEvent);
}
else
{
K32W_LOG("Event received with no handler. Dropping event.");
}
}
void AppTask::UpdateClusterState(void)
{
uint8_t newValue = !LightingMgr().IsTurnedOff();
// 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 %x", status);
}
}