bolar_2 backup

This commit is contained in:
2026-11-27 16:38:11 +08:00
commit e96d6d19df
305 changed files with 43350 additions and 0 deletions

View File

@@ -0,0 +1,173 @@
#include "schedule/alarm_schedule.h"
#include <algorithm>
#include <cstring>
namespace borla {
namespace {
bool IsBuiltIn(const AlarmEntry& alarm)
{
return alarm.id == kBuiltInFirstDayAlarmId;
}
AlarmEntry BuiltInAlarm()
{
AlarmEntry alarm;
alarm.id = kBuiltInFirstDayAlarmId;
alarm.hour = 20;
alarm.minute = 30;
alarm.repeat_mask = 0x7F;
alarm.enabled = true;
std::strncpy(
alarm.label.data(),
"first_day_sleep_prompt",
alarm.label.size() - 1);
return alarm;
}
} // namespace
bool AlarmSchedule::Validate(const AlarmEntry& alarm)
{
return alarm.id != 0 &&
alarm.hour < 24 &&
alarm.minute < 60 &&
alarm.repeat_mask <= 0x7F &&
alarm.label.back() == '\0' &&
(alarm.repeat_mask != 0 || alarm.fire_epoch >= 0);
}
bool AlarmSchedule::Upsert(const AlarmEntry& alarm)
{
if (!Validate(alarm)) {
return false;
}
for (size_t i = 0; i < alarms_.count; ++i) {
if (alarms_.entries[i].id == alarm.id) {
alarms_.entries[i] = alarm;
return true;
}
}
if (alarms_.count >= alarms_.entries.size()) {
return false;
}
alarms_.entries[alarms_.count++] = alarm;
return true;
}
bool AlarmSchedule::Delete(int32_t id)
{
for (size_t i = 0; i < alarms_.count; ++i) {
if (alarms_.entries[i].id != id) {
continue;
}
std::move(
alarms_.entries.begin() + i + 1,
alarms_.entries.begin() + alarms_.count,
alarms_.entries.begin() + i);
alarms_.entries[--alarms_.count] = {};
if (id == kBuiltInFirstDayAlarmId) {
first_day_consumed_ = true;
}
return true;
}
return false;
}
bool AlarmSchedule::Replace(const AlarmList& alarms)
{
if (alarms.count > alarms.entries.size()) {
return false;
}
AlarmList replacement;
for (size_t i = 0; i < alarms.count; ++i) {
if (!Validate(alarms.entries[i]) ||
replacement.count >= replacement.entries.size()) {
return false;
}
bool duplicate = false;
for (size_t j = 0; j < replacement.count; ++j) {
duplicate |=
replacement.entries[j].id == alarms.entries[i].id;
}
if (duplicate) {
return false;
}
replacement.entries[replacement.count++] = alarms.entries[i];
}
alarms_ = replacement;
return true;
}
bool AlarmSchedule::EnsureBuiltInFirstDay(bool consumed)
{
first_day_consumed_ = consumed;
if (consumed) {
Delete(kBuiltInFirstDayAlarmId);
first_day_consumed_ = true;
return true;
}
// The built-in first-day prompt is optional. When the user list already
// fills every slot there is no room for it, but that must not fail the
// whole sync or boot; first_day_consumed_ stays false so a later sync with
// free capacity can still install it.
Upsert(BuiltInAlarm());
return true;
}
bool AlarmSchedule::Matches(
const AlarmEntry& alarm,
const CalendarMinute& local_time,
int64_t epoch_seconds)
{
if (!Validate(alarm) || !alarm.enabled ||
alarm.hour != local_time.hour ||
alarm.minute != local_time.minute) {
return false;
}
if (alarm.repeat_mask != 0) {
return (alarm.repeat_mask &
(1U << local_time.week_day)) != 0;
}
if (alarm.fire_epoch == 0) {
return true;
}
const int64_t difference =
epoch_seconds - alarm.fire_epoch;
return difference >= 0 && difference < 60;
}
AlarmFireBatch AlarmSchedule::TakeDue(
const CalendarMinute& local_time,
int64_t epoch_seconds)
{
AlarmFireBatch result;
const int64_t minute_key = epoch_seconds / 60;
if (minute_key == last_fired_minute_key_) {
return result;
}
for (size_t i = 0; i < alarms_.count; ++i) {
AlarmEntry& alarm = alarms_.entries[i];
if (!Matches(alarm, local_time, epoch_seconds)) {
continue;
}
result.ids[result.count++] = alarm.id;
if (IsBuiltIn(alarm)) {
result.built_in_first_day = true;
first_day_consumed_ = true;
alarm.enabled = false;
} else {
result.play_audio = true;
}
if (alarm.repeat_mask == 0) {
alarm.enabled = false;
}
}
if (result.count > 0) {
last_fired_minute_key_ = minute_key;
}
return result;
}
} // namespace borla

View File

@@ -0,0 +1,35 @@
#pragma once
#include "schedule/schedule_types.h"
#include <cstddef>
#include <cstdint>
namespace borla {
class AlarmSchedule final {
public:
bool Upsert(const AlarmEntry& alarm);
bool Delete(int32_t id);
bool Replace(const AlarmList& alarms);
bool EnsureBuiltInFirstDay(bool consumed);
AlarmFireBatch TakeDue(
const CalendarMinute& local_time,
int64_t epoch_seconds);
const AlarmList& list() const { return alarms_; }
bool first_day_consumed() const { return first_day_consumed_; }
static bool Validate(const AlarmEntry& alarm);
static bool Matches(
const AlarmEntry& alarm,
const CalendarMinute& local_time,
int64_t epoch_seconds);
private:
AlarmList alarms_{};
bool first_day_consumed_ = false;
int64_t last_fired_minute_key_ = -1;
};
} // namespace borla

View File

@@ -0,0 +1,236 @@
#include "schedule/alarm_service.h"
#include "core/psram_object.h"
#include <algorithm>
#include <ctime>
#include <esp_log.h>
namespace borla {
namespace {
constexpr const char* kTag = "AlarmService2";
constexpr int64_t kMinimumValidEpoch = 1700000000;
constexpr int64_t kMaximumWakeSearchSeconds =
8LL * 24LL * 60LL * 60LL;
class Lock final {
public:
explicit Lock(SemaphoreHandle_t mutex) : mutex_(mutex)
{
xSemaphoreTake(mutex_, portMAX_DELAY);
}
~Lock() { xSemaphoreGive(mutex_); }
private:
SemaphoreHandle_t mutex_;
};
bool ToneValid(int8_t index)
{
return index >= -1 && index <= 15;
}
} // namespace
bool AlarmService::Initialize(
IEventPublisher& publisher,
IScheduleEventSink& event_sink)
{
if (running_.load()) {
return true;
}
publisher_ = &publisher;
event_sink_ = &event_sink;
mutex_ = xSemaphoreCreateMutexStatic(&mutex_control_);
if (mutex_ == nullptr) {
return false;
}
AlarmStoreSnapshot stored;
if (!store_.Load(&stored) ||
!schedule_.Replace(stored.alarms) ||
!schedule_.EnsureBuiltInFirstDay(
stored.first_day_consumed)) {
ESP_LOGE(kTag, "persisted alarm initialization failed");
return false;
}
set_tone_index_.store(stored.set_tone_index);
wake_tone_index_.store(stored.wake_tone_index);
if (!SaveLocked()) {
return false;
}
running_.store(true);
task_ = xTaskCreateStatic(
&AlarmService::TaskEntry,
"alarm2",
task_stack_.size(),
this,
4,
task_stack_.data(),
&task_control_);
if (task_ == nullptr) {
running_.store(false);
return false;
}
return true;
}
void AlarmService::Stop()
{
running_.store(false);
}
bool AlarmService::Set(const AlarmEntry& alarm)
{
if (mutex_ == nullptr) {
return false;
}
Lock lock(mutex_);
return schedule_.Upsert(alarm) && SaveLocked();
}
void AlarmService::Delete(int32_t id)
{
if (mutex_ == nullptr) {
return;
}
Lock lock(mutex_);
if (schedule_.Delete(id)) {
SaveLocked();
}
}
bool AlarmService::Sync(const AlarmList& alarms)
{
if (mutex_ == nullptr) {
return false;
}
Lock lock(mutex_);
const bool consumed = schedule_.first_day_consumed();
return schedule_.Replace(alarms) &&
schedule_.EnsureBuiltInFirstDay(consumed) &&
SaveLocked();
}
void AlarmService::SetToneIndices(
int8_t set_tone_index,
int8_t wake_tone_index)
{
if (mutex_ == nullptr ||
!ToneValid(set_tone_index) ||
!ToneValid(wake_tone_index)) {
return;
}
Lock lock(mutex_);
set_tone_index_.store(set_tone_index);
wake_tone_index_.store(wake_tone_index);
SaveLocked();
}
uint64_t AlarmService::NextWakeupDelayUs() const
{
const int64_t now = static_cast<int64_t>(std::time(nullptr));
if (mutex_ == nullptr || now < kMinimumValidEpoch) {
return 0;
}
Lock lock(mutex_);
const AlarmList alarms = schedule_.list();
int64_t candidate = now - now % 60 + 60;
const int64_t end = now + kMaximumWakeSearchSeconds;
for (; candidate <= end; candidate += 60) {
CalendarMinute calendar;
if (!MakeCalendar(candidate, &calendar)) {
return 0;
}
for (size_t i = 0; i < alarms.count; ++i) {
if (AlarmSchedule::Matches(
alarms.entries[i], calendar, candidate)) {
return static_cast<uint64_t>(
std::max<int64_t>(1, candidate - now)) *
1000000ULL;
}
}
}
return 0;
}
void AlarmService::TaskEntry(void* context)
{
static_cast<AlarmService*>(context)->Run();
}
void AlarmService::Run()
{
while (running_.load()) {
const int64_t now =
static_cast<int64_t>(std::time(nullptr));
if (now >= kMinimumValidEpoch) {
CalendarMinute calendar;
AlarmFireBatch due;
if (MakeCalendar(now, &calendar)) {
Lock lock(mutex_);
due = schedule_.TakeDue(calendar, now);
if (due.count > 0) {
SaveLocked();
}
}
for (size_t i = 0; i < due.count; ++i) {
if (due.ids[i] > 0 && event_sink_ != nullptr) {
event_sink_->SendAlarmFired(due.ids[i], now);
}
}
if (due.play_audio && publisher_ != nullptr) {
publisher_->Publish(
AppEvent::Make(AppEventType::kAlarmDue));
} else if (due.built_in_first_day &&
publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kFirstDayAlarmDue));
}
}
vTaskDelay(pdMS_TO_TICKS(500));
}
task_ = nullptr;
vTaskDelete(nullptr);
}
bool AlarmService::SaveLocked()
{
auto snapshot = MakePsramObject<AlarmStoreSnapshot>();
if (!snapshot) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
return false;
}
snapshot->alarms = schedule_.list();
snapshot->first_day_consumed =
schedule_.first_day_consumed();
snapshot->set_tone_index = set_tone_index_.load();
snapshot->wake_tone_index = wake_tone_index_.load();
return store_.Save(*snapshot);
}
bool AlarmService::MakeCalendar(
int64_t epoch_seconds,
CalendarMinute* calendar)
{
if (calendar == nullptr) {
return false;
}
const time_t value = static_cast<time_t>(epoch_seconds);
tm local{};
if (localtime_r(&value, &local) == nullptr) {
return false;
}
*calendar = {
.year = local.tm_year,
.year_day = local.tm_yday,
.week_day = local.tm_wday,
.hour = local.tm_hour,
.minute = local.tm_min,
};
return true;
}
} // namespace borla

View File

@@ -0,0 +1,64 @@
#pragma once
#include "core/task_stack_budget.h"
#include "ports/event_publisher.h"
#include "schedule/alarm_schedule.h"
#include "schedule/alarm_store.h"
#include "schedule/schedule_types.h"
#include <array>
#include <atomic>
#include <cstdint>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class AlarmService final {
public:
explicit AlarmService(IAlarmStore& store) : store_(store) {}
bool Initialize(
IEventPublisher& publisher,
IScheduleEventSink& event_sink);
void Stop();
bool Set(const AlarmEntry& alarm);
void Delete(int32_t id);
bool Sync(const AlarmList& alarms);
void SetToneIndices(
int8_t set_tone_index,
int8_t wake_tone_index);
int8_t wake_tone_index() const
{
return wake_tone_index_.load();
}
uint64_t NextWakeupDelayUs() const;
private:
static void TaskEntry(void* context);
void Run();
bool SaveLocked();
static bool MakeCalendar(
int64_t epoch_seconds,
CalendarMinute* calendar);
IAlarmStore& store_;
IEventPublisher* publisher_ = nullptr;
IScheduleEventSink* event_sink_ = nullptr;
mutable SemaphoreHandle_t mutex_ = nullptr;
mutable StaticSemaphore_t mutex_control_{};
AlarmSchedule schedule_;
std::atomic<int8_t> set_tone_index_{-1};
std::atomic<int8_t> wake_tone_index_{-1};
std::atomic<bool> running_{false};
TaskHandle_t task_ = nullptr;
StaticTask_t task_control_{};
std::array<
StackType_t,
task_stack_budget::kAlarmServiceBytes> task_stack_{};
};
} // namespace borla

View File

@@ -0,0 +1,157 @@
#include "schedule/alarm_store.h"
#include "core/psram_object.h"
#include "schedule/alarm_schedule.h"
#include <cstddef>
#include <cstdint>
#include <esp_err.h>
#include <esp_log.h>
#include <nvs.h>
namespace borla {
namespace {
constexpr const char* kTag = "AlarmStore2";
constexpr const char* kNamespace = "alarm_v2";
constexpr const char* kSnapshotKey = "snapshot";
constexpr uint32_t kMagic = 0x324D5241;
constexpr uint16_t kVersion = 1;
struct PersistedAlarmSnapshot {
uint32_t magic = kMagic;
uint16_t version = kVersion;
uint16_t count = 0;
uint8_t first_day_consumed = 0;
int8_t set_tone_index = -1;
int8_t wake_tone_index = -1;
uint8_t reserved = 0;
AlarmEntry entries[kMaximumAlarmCount]{};
uint32_t checksum = 0;
};
uint32_t Checksum(
const void* data,
size_t size)
{
const auto* bytes = static_cast<const uint8_t*>(data);
uint32_t value = 2166136261U;
for (size_t i = 0; i < size; ++i) {
value ^= bytes[i];
value *= 16777619U;
}
return value;
}
bool ToneIndexValid(int8_t index)
{
return index >= -1 && index <= 15;
}
} // namespace
bool NvsAlarmStore::Load(AlarmStoreSnapshot* snapshot) const
{
if (snapshot == nullptr) {
return false;
}
*snapshot = {};
snapshot->set_tone_index = -1;
snapshot->wake_tone_index = -1;
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNamespace, NVS_READONLY, &handle);
if (result == ESP_ERR_NVS_NOT_FOUND) {
return true;
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "open failed: %s", esp_err_to_name(result));
return false;
}
auto stored = MakePsramObject<PersistedAlarmSnapshot>();
if (!stored) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
nvs_close(handle);
return false;
}
size_t size = sizeof(*stored);
result = nvs_get_blob(
handle, kSnapshotKey, stored.get(), &size);
nvs_close(handle);
if (result == ESP_ERR_NVS_NOT_FOUND) {
return true;
}
const uint32_t expected = Checksum(
stored.get(), offsetof(PersistedAlarmSnapshot, checksum));
if (result != ESP_OK || size != sizeof(*stored) ||
stored->magic != kMagic ||
stored->version != kVersion ||
stored->count > kMaximumAlarmCount ||
stored->checksum != expected ||
!ToneIndexValid(stored->set_tone_index) ||
!ToneIndexValid(stored->wake_tone_index)) {
ESP_LOGE(kTag, "invalid persisted alarm snapshot");
return false;
}
snapshot->alarms.count = stored->count;
for (size_t i = 0; i < stored->count; ++i) {
if (!AlarmSchedule::Validate(stored->entries[i])) {
ESP_LOGE(kTag, "invalid persisted alarm index=%u",
static_cast<unsigned int>(i));
return false;
}
snapshot->alarms.entries[i] = stored->entries[i];
}
snapshot->first_day_consumed =
stored->first_day_consumed != 0;
snapshot->set_tone_index = stored->set_tone_index;
snapshot->wake_tone_index = stored->wake_tone_index;
return true;
}
bool NvsAlarmStore::Save(const AlarmStoreSnapshot& snapshot)
{
if (snapshot.alarms.count > kMaximumAlarmCount ||
!ToneIndexValid(snapshot.set_tone_index) ||
!ToneIndexValid(snapshot.wake_tone_index)) {
return false;
}
auto stored = MakePsramObject<PersistedAlarmSnapshot>();
if (!stored) {
ESP_LOGE(kTag, "PSRAM work-buffer allocation failed");
return false;
}
stored->count = static_cast<uint16_t>(snapshot.alarms.count);
stored->first_day_consumed =
snapshot.first_day_consumed ? 1 : 0;
stored->set_tone_index = snapshot.set_tone_index;
stored->wake_tone_index = snapshot.wake_tone_index;
for (size_t i = 0; i < snapshot.alarms.count; ++i) {
stored->entries[i] = snapshot.alarms.entries[i];
}
stored->checksum = Checksum(
stored.get(), offsetof(PersistedAlarmSnapshot, checksum));
nvs_handle_t handle = 0;
esp_err_t result =
nvs_open(kNamespace, NVS_READWRITE, &handle);
if (result == ESP_OK) {
result = nvs_set_blob(
handle, kSnapshotKey, stored.get(), sizeof(*stored));
}
if (result == ESP_OK) {
result = nvs_commit(handle);
}
if (handle != 0) {
nvs_close(handle);
}
if (result != ESP_OK) {
ESP_LOGE(kTag, "save failed: %s", esp_err_to_name(result));
return false;
}
return true;
}
} // namespace borla

View File

@@ -0,0 +1,29 @@
#pragma once
#include "schedule/schedule_types.h"
#include <cstdint>
namespace borla {
struct AlarmStoreSnapshot {
AlarmList alarms{};
bool first_day_consumed = false;
int8_t set_tone_index = -1;
int8_t wake_tone_index = -1;
};
class IAlarmStore {
public:
virtual ~IAlarmStore() = default;
virtual bool Load(AlarmStoreSnapshot* snapshot) const = 0;
virtual bool Save(const AlarmStoreSnapshot& snapshot) = 0;
};
class NvsAlarmStore final : public IAlarmStore {
public:
bool Load(AlarmStoreSnapshot* snapshot) const override;
bool Save(const AlarmStoreSnapshot& snapshot) override;
};
} // namespace borla

View File

@@ -0,0 +1,117 @@
#include "schedule/alert_ringer.h"
#include <esp_log.h>
#include <esp_timer.h>
namespace borla {
namespace {
constexpr const char* kTag = "AlertRinger2";
constexpr uint32_t kMaximumRingMs = 60000;
constexpr uint32_t kRingPeriodMs = 2500;
uint64_t NowMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace
void AlertRinger::Start(AlertKind kind)
{
kind_.store(kind);
if (!EnsureWorker()) {
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kAlertFinished));
}
return;
}
if (running_.exchange(true)) {
return;
}
generation_.fetch_add(1);
xSemaphoreGive(request_);
}
void AlertRinger::Stop()
{
running_.store(false);
audio_.CancelPlayback(0);
}
bool AlertRinger::EnsureWorker()
{
if (task_ != nullptr) {
return true;
}
if (request_ == nullptr) {
request_ = xSemaphoreCreateBinaryStatic(&request_storage_);
if (request_ == nullptr) {
ESP_LOGE(kTag, "alert request semaphore creation failed");
return false;
}
}
task_ = xTaskCreateStatic(
&AlertRinger::TaskEntry,
"alert_ringer2",
task_stack_.size(),
this,
4,
task_stack_.data(),
&task_control_);
if (task_ == nullptr) {
ESP_LOGE(kTag, "alert ringer worker creation failed");
return false;
}
return true;
}
void AlertRinger::TaskEntry(void* context)
{
static_cast<AlertRinger*>(context)->Run();
}
[[noreturn]] void AlertRinger::Run()
{
for (;;) {
if (xSemaphoreTake(request_, portMAX_DELAY) != pdTRUE) {
continue;
}
RunOneAlert(generation_.load());
}
}
void AlertRinger::RunOneAlert(uint32_t generation)
{
const uint64_t deadline = NowMs() + kMaximumRingMs;
while (running_.load() &&
generation_.load() == generation &&
NowMs() < deadline) {
audio_.PlayLocalPrompt(
LocalPrompt::kAlarmWake,
PlaybackPriority::kAlarm,
alarms_.wake_tone_index());
for (uint32_t waited = 0;
running_.load() &&
generation_.load() == generation &&
waited < kRingPeriodMs;
waited += 50) {
vTaskDelay(pdMS_TO_TICKS(50));
}
}
if (generation_.load() != generation) {
// A newer Start() already owns the ringing state. Its pending request
// token drives the next cycle, so this one must not finish it.
return;
}
if (running_.exchange(false)) {
ESP_LOGI(kTag, "alert ringing timed out");
}
if (publisher_ != nullptr) {
publisher_->Publish(AppEvent::Make(
AppEventType::kAlertFinished));
}
}
} // namespace borla

View File

@@ -0,0 +1,57 @@
#pragma once
#include "ports/alert_ringer.h"
#include "ports/audio_engine.h"
#include "ports/event_publisher.h"
#include "schedule/alarm_service.h"
#include <array>
#include <atomic>
#include <cstdint>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class AlertRinger final : public IAlertRinger {
public:
AlertRinger(
IAudioEngine& audio,
AlarmService& alarms)
: audio_(audio), alarms_(alarms)
{
}
void SetEventPublisher(IEventPublisher& publisher)
{
publisher_ = &publisher;
}
void Start(AlertKind kind) override;
void Stop() override;
private:
static constexpr uint32_t kTaskStackDepth = 3072;
static void TaskEntry(void* context);
// The worker is created once and then parks on request_. A static task
// control block and stack must not be recycled while the previous task is
// still being torn down, so this worker is never deleted.
bool EnsureWorker();
[[noreturn]] void Run();
void RunOneAlert(uint32_t generation);
IAudioEngine& audio_;
AlarmService& alarms_;
IEventPublisher* publisher_ = nullptr;
std::atomic<bool> running_{false};
std::atomic<uint32_t> generation_{0};
std::atomic<AlertKind> kind_{AlertKind::kReminder};
SemaphoreHandle_t request_ = nullptr;
StaticSemaphore_t request_storage_{};
TaskHandle_t task_ = nullptr;
StaticTask_t task_control_{};
std::array<StackType_t, kTaskStackDepth> task_stack_{};
};
} // namespace borla

View File

@@ -0,0 +1,62 @@
#include "schedule/reminder_schedule.h"
#include <algorithm>
namespace borla {
bool ReminderSchedule::Add(uint64_t deadline_ms)
{
if (deadline_ms == 0 || count_ >= deadlines_.size()) {
return false;
}
const auto begin = deadlines_.begin();
const auto position = std::lower_bound(
begin, begin + count_, deadline_ms);
std::move_backward(
position, begin + count_, begin + count_ + 1);
*position = deadline_ms;
count_++;
return true;
}
void ReminderSchedule::CancelAll()
{
count_ = 0;
deadlines_.fill(0);
}
bool ReminderSchedule::CancelNext()
{
if (count_ == 0) {
return false;
}
std::move(
deadlines_.begin() + 1,
deadlines_.begin() + count_,
deadlines_.begin());
deadlines_[--count_] = 0;
return true;
}
size_t ReminderSchedule::PopDue(uint64_t now_ms)
{
size_t due = 0;
while (due < count_ && deadlines_[due] <= now_ms) {
due++;
}
if (due == 0) {
return 0;
}
std::move(
deadlines_.begin() + due,
deadlines_.begin() + count_,
deadlines_.begin());
count_ -= due;
std::fill(
deadlines_.begin() + count_,
deadlines_.end(),
0);
return due;
}
} // namespace borla

View File

@@ -0,0 +1,28 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
namespace borla {
class ReminderSchedule final {
public:
static constexpr size_t kCapacity = 16;
bool Add(uint64_t deadline_ms);
void CancelAll();
bool CancelNext();
size_t PopDue(uint64_t now_ms);
size_t count() const { return count_; }
uint64_t next_deadline_ms() const
{
return count_ == 0 ? 0 : deadlines_[0];
}
private:
size_t count_ = 0;
std::array<uint64_t, kCapacity> deadlines_{};
};
} // namespace borla

View File

@@ -0,0 +1,139 @@
#include "schedule/reminder_service.h"
#include <esp_log.h>
#include <esp_timer.h>
namespace borla {
namespace {
constexpr const char* kTag = "ReminderService2";
constexpr uint32_t kMaximumDurationSeconds = 7U * 24U * 60U * 60U;
class Lock final {
public:
explicit Lock(SemaphoreHandle_t mutex) : mutex_(mutex)
{
xSemaphoreTake(mutex_, portMAX_DELAY);
}
~Lock() { xSemaphoreGive(mutex_); }
private:
SemaphoreHandle_t mutex_;
};
} // namespace
bool ReminderService::Initialize(IEventPublisher& publisher)
{
if (running_.load()) {
return true;
}
publisher_ = &publisher;
mutex_ = xSemaphoreCreateMutexStatic(&mutex_control_);
if (mutex_ == nullptr) {
return false;
}
running_.store(true);
task_ = xTaskCreateStatic(
&ReminderService::TaskEntry,
"reminder2",
task_stack_.size(),
this,
4,
task_stack_.data(),
&task_control_);
if (task_ == nullptr) {
running_.store(false);
return false;
}
return true;
}
void ReminderService::Stop()
{
running_.store(false);
}
bool ReminderService::Add(uint32_t duration_seconds)
{
if (duration_seconds == 0 ||
duration_seconds > kMaximumDurationSeconds ||
mutex_ == nullptr) {
return false;
}
Lock lock(mutex_);
return schedule_.Add(
NowMs() +
static_cast<uint64_t>(duration_seconds) * 1000);
}
void ReminderService::Cancel(TimerCancelScope scope)
{
if (mutex_ == nullptr) {
return;
}
Lock lock(mutex_);
if (scope == TimerCancelScope::kAll) {
schedule_.CancelAll();
} else {
schedule_.CancelNext();
}
}
size_t ReminderService::count() const
{
if (mutex_ == nullptr) {
return 0;
}
Lock lock(mutex_);
return schedule_.count();
}
uint64_t ReminderService::NextWakeupDelayUs() const
{
if (mutex_ == nullptr) {
return 0;
}
Lock lock(mutex_);
const uint64_t deadline = schedule_.next_deadline_ms();
const uint64_t now = NowMs();
if (deadline == 0) {
return 0;
}
const uint64_t delay_ms = deadline > now ? deadline - now : 1;
return delay_ms * 1000ULL;
}
void ReminderService::TaskEntry(void* context)
{
static_cast<ReminderService*>(context)->Run();
}
void ReminderService::Run()
{
while (running_.load()) {
size_t due = 0;
{
Lock lock(mutex_);
due = schedule_.PopDue(NowMs());
}
if (due > 0 && publisher_ != nullptr) {
ESP_LOGI(kTag, "%u reminder(s) due",
static_cast<unsigned int>(due));
publisher_->Publish(AppEvent::Make(
AppEventType::kReminderDue,
0,
static_cast<int32_t>(due)));
}
vTaskDelay(pdMS_TO_TICKS(100));
}
task_ = nullptr;
vTaskDelete(nullptr);
}
uint64_t ReminderService::NowMs()
{
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
}
} // namespace borla

View File

@@ -0,0 +1,42 @@
#pragma once
#include "ports/event_publisher.h"
#include "schedule/reminder_schedule.h"
#include "schedule/schedule_types.h"
#include <array>
#include <atomic>
#include <cstdint>
#include <freertos/FreeRTOS.h>
#include <freertos/semphr.h>
#include <freertos/task.h>
namespace borla {
class ReminderService final {
public:
bool Initialize(IEventPublisher& publisher);
void Stop();
bool Add(uint32_t duration_seconds);
void Cancel(TimerCancelScope scope);
size_t count() const;
uint64_t NextWakeupDelayUs() const;
private:
static constexpr uint32_t kTaskStackDepth = 2048;
static void TaskEntry(void* context);
void Run();
static uint64_t NowMs();
IEventPublisher* publisher_ = nullptr;
mutable SemaphoreHandle_t mutex_ = nullptr;
mutable StaticSemaphore_t mutex_control_{};
ReminderSchedule schedule_;
std::atomic<bool> running_{false};
TaskHandle_t task_ = nullptr;
StaticTask_t task_control_{};
std::array<StackType_t, kTaskStackDepth> task_stack_{};
};
} // namespace borla

View File

@@ -0,0 +1,37 @@
#include "schedule/schedule_coordinator.h"
namespace borla {
bool ScheduleCoordinator::AddReminder(uint32_t duration_seconds)
{
return reminders_.Add(duration_seconds);
}
void ScheduleCoordinator::CancelReminder(TimerCancelScope scope)
{
reminders_.Cancel(scope);
}
bool ScheduleCoordinator::SetAlarm(const AlarmEntry& alarm)
{
return alarms_.Set(alarm);
}
void ScheduleCoordinator::DeleteAlarm(int32_t id)
{
alarms_.Delete(id);
}
bool ScheduleCoordinator::SyncAlarms(const AlarmList& alarms)
{
return alarms_.Sync(alarms);
}
void ScheduleCoordinator::SetAlarmToneIndices(
int8_t set_tone_index,
int8_t wake_tone_index)
{
alarms_.SetToneIndices(set_tone_index, wake_tone_index);
}
} // namespace borla

View File

@@ -0,0 +1,32 @@
#pragma once
#include "schedule/alarm_service.h"
#include "schedule/reminder_service.h"
#include "schedule/schedule_types.h"
namespace borla {
class ScheduleCoordinator final : public IScheduleCommandHandler {
public:
ScheduleCoordinator(
ReminderService& reminders,
AlarmService& alarms)
: reminders_(reminders), alarms_(alarms)
{
}
bool AddReminder(uint32_t duration_seconds) override;
void CancelReminder(TimerCancelScope scope) override;
bool SetAlarm(const AlarmEntry& alarm) override;
void DeleteAlarm(int32_t id) override;
bool SyncAlarms(const AlarmList& alarms) override;
void SetAlarmToneIndices(
int8_t set_tone_index,
int8_t wake_tone_index) override;
private:
ReminderService& reminders_;
AlarmService& alarms_;
};
} // namespace borla

View File

@@ -0,0 +1,74 @@
#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <type_traits>
namespace borla {
inline constexpr size_t kMaximumAlarmCount = 16;
inline constexpr size_t kAlarmLabelCapacity = 48;
inline constexpr int32_t kBuiltInFirstDayAlarmId = -203000;
struct AlarmEntry {
int32_t id = 0;
uint8_t hour = 0;
uint8_t minute = 0;
uint8_t repeat_mask = 0;
bool enabled = true;
int64_t fire_epoch = 0;
std::array<char, kAlarmLabelCapacity> label{};
};
static_assert(
std::is_trivially_copyable<AlarmEntry>::value,
"AlarmEntry is persisted and must stay trivially copyable");
struct AlarmList {
size_t count = 0;
std::array<AlarmEntry, kMaximumAlarmCount> entries{};
};
struct CalendarMinute {
int year = 0;
int year_day = 0;
int week_day = 0;
int hour = 0;
int minute = 0;
};
struct AlarmFireBatch {
size_t count = 0;
std::array<int32_t, kMaximumAlarmCount> ids{};
bool play_audio = false;
bool built_in_first_day = false;
};
enum class TimerCancelScope : uint8_t {
kAll,
kNext,
};
class IScheduleCommandHandler {
public:
virtual ~IScheduleCommandHandler() = default;
virtual bool AddReminder(uint32_t duration_seconds) = 0;
virtual void CancelReminder(TimerCancelScope scope) = 0;
virtual bool SetAlarm(const AlarmEntry& alarm) = 0;
virtual void DeleteAlarm(int32_t id) = 0;
virtual bool SyncAlarms(const AlarmList& alarms) = 0;
virtual void SetAlarmToneIndices(
int8_t set_tone_index,
int8_t wake_tone_index) = 0;
};
class IScheduleEventSink {
public:
virtual ~IScheduleEventSink() = default;
virtual bool SendAlarmFired(
int32_t alarm_id,
int64_t fired_at_epoch) = 0;
};
} // namespace borla