blob: ae683cc92f86b5f812048863650cacb352319c25 [file] [log] [blame]
/*
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2019 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 "AppConfig.h"
#include "AppEvent.h"
#if defined(ENABLE_CHIP_SHELL)
#include "EventHandlerLibShell.h"
#endif // ENABLE_CHIP_SHELL
#ifdef ENABLE_WSTK_LEDS
#include "LEDWidget.h"
#include "sl_simple_led_instances.h"
#endif // ENABLE_WSTK_LEDS
#ifdef DISPLAY_ENABLED
#include "lcd.h"
#ifdef QR_CODE_ENABLED
#include "qrcodegen.h"
#endif // QR_CODE_ENABLED
#endif // DISPLAY_ENABLED
#include <app-common/zap-generated/af-structs.h>
#include <app-common/zap-generated/attribute-id.h>
#include <app-common/zap-generated/attribute-type.h>
#include <app-common/zap-generated/attributes/Accessors.h>
#include <app-common/zap-generated/cluster-id.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app/clusters/door-lock-server/door-lock-server.h>
#include <app/clusters/identify-server/identify-server.h>
#include <app/server/OnboardingCodesUtil.h>
#include <app/server/Server.h>
#include <app/util/attribute-storage.h>
#include <assert.h>
#include <setup_payload/QRCodeSetupPayloadGenerator.h>
#include <setup_payload/SetupPayload.h>
#include <lib/support/CodeUtils.h>
#include <platform/CHIPDeviceLayer.h>
#ifdef ENABLE_WSTK_LEDS
#define SYSTEM_STATE_LED &sl_led_led0
#define LOCK_STATE_LED &sl_led_led1
#endif // ENABLE_WSTK_LEDS
#define APP_FUNCTION_BUTTON &sl_button_btn0
#define APP_LOCK_SWITCH &sl_button_btn1
using chip::app::Clusters::DoorLock::DlLockState;
using chip::app::Clusters::DoorLock::DlOperationError;
using chip::app::Clusters::DoorLock::DlOperationSource;
using namespace chip;
using namespace ::chip::DeviceLayer;
using namespace ::chip::DeviceLayer::Internal;
using namespace EFR32DoorLock::LockInitParams;
namespace {
#ifdef ENABLE_WSTK_LEDS
LEDWidget sLockLED;
#endif // ENABLE_WSTK_LEDS
EmberAfIdentifyEffectIdentifier sIdentifyEffect = EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT;
} // namespace
/**********************************************************
* Identify Callbacks
*********************************************************/
namespace {
void OnTriggerIdentifyEffectCompleted(chip::System::Layer * systemLayer, void * appState)
{
ChipLogProgress(Zcl, "Trigger Identify Complete");
sIdentifyEffect = EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT;
#if CHIP_DEVICE_CONFIG_ENABLE_SED == 1
AppTask::GetAppTask().StopStatusLEDTimer();
#endif
}
void OnTriggerIdentifyEffect(Identify * identify)
{
sIdentifyEffect = identify->mCurrentEffectIdentifier;
if (identify->mCurrentEffectIdentifier == EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE)
{
ChipLogProgress(Zcl, "IDENTIFY_EFFECT_IDENTIFIER_CHANNEL_CHANGE - Not supported, use effect varriant %d",
identify->mEffectVariant);
sIdentifyEffect = static_cast<EmberAfIdentifyEffectIdentifier>(identify->mEffectVariant);
}
#if CHIP_DEVICE_CONFIG_ENABLE_SED == 1
AppTask::GetAppTask().StartStatusLEDTimer();
#endif
switch (sIdentifyEffect)
{
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BLINK:
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_BREATHE:
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_OKAY:
(void) chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(5), OnTriggerIdentifyEffectCompleted,
identify);
break;
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_FINISH_EFFECT:
(void) chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerIdentifyEffectCompleted, identify);
(void) chip::DeviceLayer::SystemLayer().StartTimer(chip::System::Clock::Seconds16(1), OnTriggerIdentifyEffectCompleted,
identify);
break;
case EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT:
(void) chip::DeviceLayer::SystemLayer().CancelTimer(OnTriggerIdentifyEffectCompleted, identify);
sIdentifyEffect = EMBER_ZCL_IDENTIFY_EFFECT_IDENTIFIER_STOP_EFFECT;
break;
default:
ChipLogProgress(Zcl, "No identifier effect");
}
}
Identify gIdentify = {
chip::EndpointId{ 1 },
AppTask::GetAppTask().OnIdentifyStart,
AppTask::GetAppTask().OnIdentifyStop,
EMBER_ZCL_IDENTIFY_IDENTIFY_TYPE_VISIBLE_LED,
OnTriggerIdentifyEffect,
};
} // namespace
using namespace chip::TLV;
using namespace ::chip::DeviceLayer;
AppTask AppTask::sAppTask;
CHIP_ERROR AppTask::Init()
{
CHIP_ERROR err = CHIP_NO_ERROR;
#ifdef DISPLAY_ENABLED
GetLCD().Init((uint8_t *) "Lock-App", true);
#endif
err = BaseApplication::Init(&gIdentify);
if (err != CHIP_NO_ERROR)
{
EFR32_LOG("BaseApplication::Init() failed");
appError(err);
}
#if defined(ENABLE_CHIP_SHELL)
err = RegisterLockEvents();
if (err != CHIP_NO_ERROR)
{
EFR32_LOG("RegisterLockEvents() failed");
appError(err);
}
#endif // ENABLE_CHIP_SHELL
// Initial lock state
chip::app::DataModel::Nullable<chip::app::Clusters::DoorLock::DlLockState> state;
chip::EndpointId endpointId{ 1 };
chip::DeviceLayer::PlatformMgr().LockChipStack();
chip::app::Clusters::DoorLock::Attributes::LockState::Get(endpointId, state);
uint8_t numberOfCredentialsPerUser = 0;
if (!DoorLockServer::Instance().GetNumberOfCredentialsSupportedPerUser(endpointId, numberOfCredentialsPerUser))
{
ChipLogError(Zcl,
"Unable to get number of credentials supported per user when initializing lock endpoint, defaulting to 5 "
"[endpointId=%d]",
endpointId);
numberOfCredentialsPerUser = 5;
}
uint16_t numberOfUsers = 0;
if (!DoorLockServer::Instance().GetNumberOfUserSupported(endpointId, numberOfUsers))
{
ChipLogError(Zcl,
"Unable to get number of supported users when initializing lock endpoint, defaulting to 10 [endpointId=%d]",
endpointId);
numberOfUsers = 10;
}
uint8_t numberOfWeekdaySchedulesPerUser = 0;
if (!DoorLockServer::Instance().GetNumberOfWeekDaySchedulesPerUserSupported(endpointId, numberOfWeekdaySchedulesPerUser))
{
ChipLogError(
Zcl,
"Unable to get number of supported weekday schedules when initializing lock endpoint, defaulting to 10 [endpointId=%d]",
endpointId);
numberOfWeekdaySchedulesPerUser = 10;
}
uint8_t numberOfYeardaySchedulesPerUser = 0;
if (!DoorLockServer::Instance().GetNumberOfYearDaySchedulesPerUserSupported(endpointId, numberOfYeardaySchedulesPerUser))
{
ChipLogError(
Zcl,
"Unable to get number of supported yearday schedules when initializing lock endpoint, defaulting to 10 [endpointId=%d]",
endpointId);
numberOfYeardaySchedulesPerUser = 10;
}
uint8_t numberOfHolidaySchedules = 0;
if (!DoorLockServer::Instance().GetNumberOfHolidaySchedulesSupported(endpointId, numberOfHolidaySchedules))
{
ChipLogError(
Zcl,
"Unable to get number of supported holiday schedules when initializing lock endpoint, defaulting to 10 [endpointId=%d]",
endpointId);
numberOfHolidaySchedules = 10;
}
chip::DeviceLayer::PlatformMgr().UnlockChipStack();
err = LockMgr().Init(state,
ParamBuilder()
.SetNumberOfUsers(numberOfUsers)
.SetNumberOfCredentialsPerUser(numberOfCredentialsPerUser)
.SetNumberOfWeekdaySchedulesPerUser(numberOfWeekdaySchedulesPerUser)
.SetNumberOfYeardaySchedulesPerUser(numberOfYeardaySchedulesPerUser)
.SetNumberOfHolidaySchedules(numberOfHolidaySchedules)
.GetLockParam());
if (err != CHIP_NO_ERROR)
{
EFR32_LOG("LockMgr().Init() failed");
appError(err);
}
LockMgr().SetCallbacks(ActionInitiated, ActionCompleted);
#ifdef ENABLE_WSTK_LEDS
// Initialize LEDs
sLockLED.Init(LOCK_STATE_LED);
sLockLED.Set(state.Value() == DlLockState::kUnlocked);
#endif // ENABLE_WSTK_LEDS
chip::DeviceLayer::PlatformMgr().ScheduleWork(UpdateClusterState, reinterpret_cast<intptr_t>(nullptr));
ConfigurationMgr().LogDeviceConfig();
return err;
}
CHIP_ERROR AppTask::StartAppTask()
{
return BaseApplication::StartAppTask(AppTaskMain);
}
void AppTask::AppTaskMain(void * pvParameter)
{
AppEvent event;
QueueHandle_t sAppEventQueue = *(static_cast<QueueHandle_t *>(pvParameter));
CHIP_ERROR err = sAppTask.Init();
if (err != CHIP_NO_ERROR)
{
EFR32_LOG("AppTask.Init() failed");
appError(err);
}
#if !(defined(CHIP_DEVICE_CONFIG_ENABLE_SED) && CHIP_DEVICE_CONFIG_ENABLE_SED)
sAppTask.StartStatusLEDTimer();
#endif
EFR32_LOG("App Task started");
// Users and credentials should be checked once from nvm flash on boot
LockMgr().ReadConfigValues();
while (true)
{
BaseType_t eventReceived = xQueueReceive(sAppEventQueue, &event, pdMS_TO_TICKS(10));
while (eventReceived == pdTRUE)
{
sAppTask.DispatchEvent(&event);
eventReceived = xQueueReceive(sAppEventQueue, &event, 0);
}
}
}
void AppTask::OnIdentifyStart(Identify * identify)
{
ChipLogProgress(Zcl, "onIdentifyStart");
#if CHIP_DEVICE_CONFIG_ENABLE_SED == 1
sAppTask.StartStatusLEDTimer();
#endif
}
void AppTask::OnIdentifyStop(Identify * identify)
{
ChipLogProgress(Zcl, "onIdentifyStop");
#if CHIP_DEVICE_CONFIG_ENABLE_SED == 1
sAppTask.StopStatusLEDTimer();
#endif
}
void AppTask::LockActionEventHandler(AppEvent * aEvent)
{
bool initiated = false;
LockManager::Action_t action;
int32_t actor;
CHIP_ERROR err = CHIP_NO_ERROR;
if (aEvent->Type == AppEvent::kEventType_Lock)
{
action = static_cast<LockManager::Action_t>(aEvent->LockEvent.Action);
actor = aEvent->LockEvent.Actor;
}
else if (aEvent->Type == AppEvent::kEventType_Button)
{
if (LockMgr().NextState() == true)
{
action = LockManager::LOCK_ACTION;
}
else
{
action = LockManager::UNLOCK_ACTION;
}
actor = AppEvent::kEventType_Button;
}
else
{
err = APP_ERROR_UNHANDLED_EVENT;
}
if (err == CHIP_NO_ERROR)
{
initiated = LockMgr().InitiateAction(actor, action);
if (!initiated)
{
EFR32_LOG("Action is already in progress or active.");
}
}
}
void AppTask::ButtonEventHandler(const sl_button_t * buttonHandle, uint8_t btnAction)
{
if (buttonHandle == NULL)
{
return;
}
AppEvent button_event = {};
button_event.Type = AppEvent::kEventType_Button;
button_event.ButtonEvent.Action = btnAction;
if (buttonHandle == APP_LOCK_SWITCH && btnAction == SL_SIMPLE_BUTTON_PRESSED)
{
button_event.Handler = LockActionEventHandler;
sAppTask.PostEvent(&button_event);
}
else if (buttonHandle == APP_FUNCTION_BUTTON)
{
button_event.Handler = BaseApplication::ButtonHandler;
sAppTask.PostEvent(&button_event);
}
}
void AppTask::ActionInitiated(LockManager::Action_t aAction, int32_t aActor)
{
if (aAction == LockManager::UNLOCK_ACTION || aAction == LockManager::LOCK_ACTION)
{
bool locked = (aAction == LockManager::LOCK_ACTION);
EFR32_LOG("%s Action has been initiated", (locked) ? "Lock" : "Unlock");
#ifdef ENABLE_WSTK_LEDS
sLockLED.Set(!locked);
#endif // ENABLE_WSTK_LEDS
#ifdef DISPLAY_ENABLED
sAppTask.GetLCD().WriteDemoUI(locked);
#endif // DISPLAY_ENABLED
}
if (aActor == AppEvent::kEventType_Button)
{
sAppTask.mSyncClusterToButtonAction = true;
}
}
void AppTask::ActionCompleted(LockManager::Action_t aAction)
{
// if the action has been completed by the lock, update the lock trait.
// Turn off the lock LED if in a LOCKED state OR
// Turn on the lock LED if in an UNLOCKED state.
if (aAction == LockManager::LOCK_ACTION)
{
EFR32_LOG("Lock Action has been completed")
}
else if (aAction == LockManager::UNLOCK_ACTION)
{
EFR32_LOG("Unlock Action has been completed")
}
if (sAppTask.mSyncClusterToButtonAction)
{
chip::DeviceLayer::PlatformMgr().ScheduleWork(UpdateClusterState, reinterpret_cast<intptr_t>(nullptr));
sAppTask.mSyncClusterToButtonAction = false;
}
}
void AppTask::ActionRequest(int32_t aActor, LockManager::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::UpdateClusterState(intptr_t context)
{
bool unlocked = LockMgr().NextState();
DlLockState newState = unlocked ? DlLockState::kUnlocked : DlLockState::kLocked;
DlOperationSource source = DlOperationSource::kUnspecified;
// write the new lock value
EmberAfStatus status =
DoorLockServer::Instance().SetLockState(1, newState, source) ? EMBER_ZCL_STATUS_SUCCESS : EMBER_ZCL_STATUS_FAILURE;
if (status != EMBER_ZCL_STATUS_SUCCESS)
{
EFR32_LOG("ERR: updating lock state %x", status);
}
}