bolar_2 backup
This commit is contained in:
130
main/sensor/battery_estimator.cc
Normal file
130
main/sensor/battery_estimator.cc
Normal file
@@ -0,0 +1,130 @@
|
||||
#include "sensor/battery_estimator.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
struct CurvePoint {
|
||||
uint16_t millivolts;
|
||||
uint8_t percent;
|
||||
};
|
||||
|
||||
constexpr std::array<CurvePoint, 12> kDischargeCurve{{
|
||||
{4090, 100},
|
||||
{4040, 95},
|
||||
{3990, 90},
|
||||
{3920, 80},
|
||||
{3850, 65},
|
||||
{3770, 50},
|
||||
{3670, 35},
|
||||
{3570, 20},
|
||||
{3470, 10},
|
||||
{3370, 5},
|
||||
{3270, 2},
|
||||
{3000, 0},
|
||||
}};
|
||||
|
||||
constexpr uint16_t kMinimumPlausibleMillivolts = 2500;
|
||||
constexpr uint16_t kMaximumPlausibleMillivolts = 4500;
|
||||
|
||||
} // namespace
|
||||
|
||||
void BatteryEstimator::Reset()
|
||||
{
|
||||
initialized_ = false;
|
||||
charging_ = false;
|
||||
last_millivolts_ = 0;
|
||||
smoothed_millivolts_ = 0;
|
||||
rising_samples_ = 0;
|
||||
falling_samples_ = 0;
|
||||
}
|
||||
|
||||
bool BatteryEstimator::IsPlausibleVoltage(uint16_t millivolts)
|
||||
{
|
||||
return millivolts >= kMinimumPlausibleMillivolts &&
|
||||
millivolts <= kMaximumPlausibleMillivolts;
|
||||
}
|
||||
|
||||
void BatteryEstimator::Update(uint16_t battery_millivolts)
|
||||
{
|
||||
if (!initialized_) {
|
||||
initialized_ = true;
|
||||
last_millivolts_ = battery_millivolts;
|
||||
smoothed_millivolts_ = battery_millivolts;
|
||||
// Voltage alone cannot prove USB presence. Only use the high CV
|
||||
// region as a conservative boot-time hint.
|
||||
charging_ = battery_millivolts >= 4150;
|
||||
return;
|
||||
}
|
||||
|
||||
const int delta =
|
||||
static_cast<int>(battery_millivolts) -
|
||||
static_cast<int>(last_millivolts_);
|
||||
last_millivolts_ = battery_millivolts;
|
||||
if (delta >= 12) {
|
||||
rising_samples_ = std::min<uint8_t>(rising_samples_ + 1, 3);
|
||||
falling_samples_ = 0;
|
||||
} else if (delta <= -20) {
|
||||
falling_samples_ =
|
||||
std::min<uint8_t>(falling_samples_ + 1, 3);
|
||||
rising_samples_ = 0;
|
||||
} else {
|
||||
if (rising_samples_ > 0) {
|
||||
rising_samples_--;
|
||||
}
|
||||
if (falling_samples_ > 0) {
|
||||
falling_samples_--;
|
||||
}
|
||||
}
|
||||
|
||||
if (rising_samples_ >= 2 || battery_millivolts >= 4150) {
|
||||
charging_ = true;
|
||||
} else if (falling_samples_ >= 2 ||
|
||||
battery_millivolts < 3950) {
|
||||
charging_ = false;
|
||||
}
|
||||
|
||||
const uint32_t incoming_weight = charging_ ? 3U : 1U;
|
||||
const uint32_t previous_weight = charging_ ? 7U : 4U;
|
||||
smoothed_millivolts_ = static_cast<uint16_t>(
|
||||
(battery_millivolts * incoming_weight +
|
||||
smoothed_millivolts_ * previous_weight) /
|
||||
(incoming_weight + previous_weight));
|
||||
}
|
||||
|
||||
uint8_t BatteryEstimator::percent() const
|
||||
{
|
||||
return initialized_
|
||||
? VoltageToPercent(smoothed_millivolts_)
|
||||
: 0;
|
||||
}
|
||||
|
||||
uint8_t BatteryEstimator::VoltageToPercent(uint16_t millivolts)
|
||||
{
|
||||
if (millivolts >= kDischargeCurve.front().millivolts) {
|
||||
return 100;
|
||||
}
|
||||
if (millivolts <= kDischargeCurve.back().millivolts) {
|
||||
return 0;
|
||||
}
|
||||
for (size_t i = 0; i + 1 < kDischargeCurve.size(); ++i) {
|
||||
const CurvePoint high = kDischargeCurve[i];
|
||||
const CurvePoint low = kDischargeCurve[i + 1];
|
||||
if (millivolts <= high.millivolts &&
|
||||
millivolts > low.millivolts) {
|
||||
const uint32_t voltage_span =
|
||||
high.millivolts - low.millivolts;
|
||||
const uint32_t percent_span =
|
||||
high.percent - low.percent;
|
||||
return static_cast<uint8_t>(
|
||||
low.percent +
|
||||
(millivolts - low.millivolts) *
|
||||
percent_span / voltage_span);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
33
main/sensor/battery_estimator.h
Normal file
33
main/sensor/battery_estimator.h
Normal file
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class BatteryEstimator final {
|
||||
public:
|
||||
void Reset();
|
||||
void Update(uint16_t battery_millivolts);
|
||||
|
||||
uint16_t smoothed_millivolts() const
|
||||
{
|
||||
return smoothed_millivolts_;
|
||||
}
|
||||
uint8_t percent() const;
|
||||
bool charging() const { return charging_; }
|
||||
bool initialized() const { return initialized_; }
|
||||
|
||||
static bool IsPlausibleVoltage(uint16_t millivolts);
|
||||
static uint8_t VoltageToPercent(uint16_t millivolts);
|
||||
|
||||
private:
|
||||
bool initialized_ = false;
|
||||
bool charging_ = false;
|
||||
uint16_t last_millivolts_ = 0;
|
||||
uint16_t smoothed_millivolts_ = 0;
|
||||
uint8_t rising_samples_ = 0;
|
||||
uint8_t falling_samples_ = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
248
main/sensor/imu_processor.cc
Normal file
248
main/sensor/imu_processor.cc
Normal file
@@ -0,0 +1,248 @@
|
||||
#include "sensor/imu_processor.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
float Magnitude(const ImuSample& sample)
|
||||
{
|
||||
return std::sqrt(
|
||||
sample.ax * sample.ax +
|
||||
sample.ay * sample.ay +
|
||||
sample.az * sample.az);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ImuProcessor::ImuProcessor()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
void ImuProcessor::Reset()
|
||||
{
|
||||
filter_initialized_ = false;
|
||||
filtered_ = {};
|
||||
still_ = false;
|
||||
still_frame_count_ = 0;
|
||||
pending_batch_ = {};
|
||||
next_sequence_ = 0;
|
||||
next_gravity_sequence_ = 0;
|
||||
freefall_candidate_ = false;
|
||||
freefall_confirmed_ = false;
|
||||
freefall_started_ms_ = 0;
|
||||
last_freefall_active_ms_ = 0;
|
||||
landing_window_ = false;
|
||||
landing_deadline_ms_ = 0;
|
||||
landing_duration_ms_ = 0;
|
||||
landing_peak_g_ = 0.0F;
|
||||
last_gravity_event_ms_.fill(0);
|
||||
}
|
||||
|
||||
ImuProcessorOutput ImuProcessor::Process(
|
||||
const ImuSample& raw,
|
||||
uint64_t now_ms)
|
||||
{
|
||||
ImuProcessorOutput output{};
|
||||
const ImuSample current = Filter(raw);
|
||||
const float deviation_g = std::fabs(Magnitude(current) - 1.0F);
|
||||
|
||||
if (still_) {
|
||||
if (deviation_g >= kResumeDeviationG) {
|
||||
still_ = false;
|
||||
still_frame_count_ = 0;
|
||||
}
|
||||
} else if (deviation_g < kStillDeviationG) {
|
||||
still_frame_count_++;
|
||||
if (still_frame_count_ >= kStillFrameCount) {
|
||||
still_ = true;
|
||||
still_frame_count_ = 0;
|
||||
FlushPartialBatch(&output);
|
||||
}
|
||||
} else {
|
||||
still_frame_count_ = 0;
|
||||
}
|
||||
|
||||
if (!still_) {
|
||||
UpdateBatch(current, now_ms, &output);
|
||||
}
|
||||
UpdateGravity(raw, now_ms, &output);
|
||||
return output;
|
||||
}
|
||||
|
||||
ImuSample ImuProcessor::Filter(const ImuSample& raw)
|
||||
{
|
||||
if (!filter_initialized_) {
|
||||
filtered_ = raw;
|
||||
filter_initialized_ = true;
|
||||
return filtered_;
|
||||
}
|
||||
const float incoming = 1.0F - kFilterAlpha;
|
||||
filtered_.ax = kFilterAlpha * filtered_.ax + incoming * raw.ax;
|
||||
filtered_.ay = kFilterAlpha * filtered_.ay + incoming * raw.ay;
|
||||
filtered_.az = kFilterAlpha * filtered_.az + incoming * raw.az;
|
||||
filtered_.gx = kFilterAlpha * filtered_.gx + incoming * raw.gx;
|
||||
filtered_.gy = kFilterAlpha * filtered_.gy + incoming * raw.gy;
|
||||
filtered_.gz = kFilterAlpha * filtered_.gz + incoming * raw.gz;
|
||||
return filtered_;
|
||||
}
|
||||
|
||||
void ImuProcessor::UpdateBatch(
|
||||
const ImuSample& filtered,
|
||||
uint64_t now_ms,
|
||||
ImuProcessorOutput* output)
|
||||
{
|
||||
if (pending_batch_.count == 0) {
|
||||
pending_batch_.sequence = next_sequence_++;
|
||||
pending_batch_.timestamp_ms_base = now_ms;
|
||||
pending_batch_.sample_rate_hz = 50;
|
||||
}
|
||||
pending_batch_.samples[pending_batch_.count++] = filtered;
|
||||
if (pending_batch_.count == pending_batch_.samples.size()) {
|
||||
output->has_batch = true;
|
||||
output->batch = pending_batch_;
|
||||
pending_batch_ = {};
|
||||
}
|
||||
}
|
||||
|
||||
void ImuProcessor::FlushPartialBatch(ImuProcessorOutput* output)
|
||||
{
|
||||
if (pending_batch_.count == 0 || output->has_batch) {
|
||||
return;
|
||||
}
|
||||
output->has_batch = true;
|
||||
output->batch = pending_batch_;
|
||||
pending_batch_ = {};
|
||||
}
|
||||
|
||||
void ImuProcessor::UpdateGravity(
|
||||
const ImuSample& raw,
|
||||
uint64_t now_ms,
|
||||
ImuProcessorOutput* output)
|
||||
{
|
||||
const float magnitude_g = Magnitude(raw);
|
||||
|
||||
if (magnitude_g < kFreefallThresholdG) {
|
||||
if (!freefall_candidate_) {
|
||||
freefall_candidate_ = true;
|
||||
freefall_started_ms_ = now_ms;
|
||||
}
|
||||
const uint64_t duration = now_ms - freefall_started_ms_;
|
||||
if (!freefall_confirmed_ && duration >= kFreefallConfirmMs) {
|
||||
freefall_confirmed_ = true;
|
||||
last_freefall_active_ms_ = now_ms;
|
||||
TryEmitGravity(
|
||||
GravityAction::kFreefall,
|
||||
now_ms,
|
||||
static_cast<uint32_t>(duration),
|
||||
magnitude_g,
|
||||
output);
|
||||
} else if (freefall_confirmed_ &&
|
||||
now_ms - last_freefall_active_ms_ >=
|
||||
kFreefallActivePeriodMs) {
|
||||
last_freefall_active_ms_ = now_ms;
|
||||
TryEmitGravity(
|
||||
GravityAction::kFreefallActive,
|
||||
now_ms,
|
||||
static_cast<uint32_t>(duration),
|
||||
magnitude_g,
|
||||
output);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (freefall_candidate_) {
|
||||
const uint64_t duration = now_ms - freefall_started_ms_;
|
||||
if (freefall_confirmed_) {
|
||||
landing_window_ = true;
|
||||
landing_deadline_ms_ = now_ms + kLandingWindowMs;
|
||||
landing_duration_ms_ = static_cast<uint32_t>(duration);
|
||||
landing_peak_g_ = magnitude_g;
|
||||
}
|
||||
freefall_candidate_ = false;
|
||||
freefall_confirmed_ = false;
|
||||
}
|
||||
|
||||
if (landing_window_) {
|
||||
landing_peak_g_ = std::max(landing_peak_g_, magnitude_g);
|
||||
if (landing_peak_g_ >= kSevereThresholdG) {
|
||||
landing_window_ = false;
|
||||
TryEmitGravity(
|
||||
GravityAction::kSevereImpact,
|
||||
now_ms,
|
||||
landing_duration_ms_,
|
||||
landing_peak_g_,
|
||||
output);
|
||||
return;
|
||||
}
|
||||
if (landing_peak_g_ >= kDroppedThresholdG) {
|
||||
landing_window_ = false;
|
||||
TryEmitGravity(
|
||||
GravityAction::kDropped,
|
||||
now_ms,
|
||||
landing_duration_ms_,
|
||||
landing_peak_g_,
|
||||
output);
|
||||
return;
|
||||
}
|
||||
if (now_ms >= landing_deadline_ms_) {
|
||||
landing_window_ = false;
|
||||
if (landing_peak_g_ >= kCaughtThresholdG) {
|
||||
TryEmitGravity(
|
||||
GravityAction::kCaught,
|
||||
now_ms,
|
||||
landing_duration_ms_,
|
||||
landing_peak_g_,
|
||||
output);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (magnitude_g >= kSevereThresholdG) {
|
||||
TryEmitGravity(
|
||||
GravityAction::kSevereImpact,
|
||||
now_ms,
|
||||
0,
|
||||
magnitude_g,
|
||||
output);
|
||||
} else if (magnitude_g >= kDroppedThresholdG) {
|
||||
TryEmitGravity(
|
||||
GravityAction::kImpact,
|
||||
now_ms,
|
||||
0,
|
||||
magnitude_g,
|
||||
output);
|
||||
}
|
||||
}
|
||||
|
||||
void ImuProcessor::TryEmitGravity(
|
||||
GravityAction action,
|
||||
uint64_t now_ms,
|
||||
uint32_t duration_ms,
|
||||
float peak_g,
|
||||
ImuProcessorOutput* output)
|
||||
{
|
||||
if (output->has_gravity_event) {
|
||||
return;
|
||||
}
|
||||
const size_t index = static_cast<size_t>(action);
|
||||
const uint64_t previous = last_gravity_event_ms_[index];
|
||||
if (previous != 0 && now_ms - previous < kActionCooldownMs) {
|
||||
return;
|
||||
}
|
||||
last_gravity_event_ms_[index] = now_ms;
|
||||
output->has_gravity_event = true;
|
||||
output->gravity_event = {
|
||||
.action = action,
|
||||
.sequence = next_gravity_sequence_++,
|
||||
.timestamp_ms = now_ms,
|
||||
.duration_ms = duration_ms,
|
||||
.magnitude_g = peak_g,
|
||||
.peak_g = peak_g,
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
81
main/sensor/imu_processor.h
Normal file
81
main/sensor/imu_processor.h
Normal file
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
|
||||
#include "sensor/sensor_types.h"
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
struct ImuProcessorOutput {
|
||||
bool has_batch = false;
|
||||
ImuBatch batch{};
|
||||
bool has_gravity_event = false;
|
||||
GravityEvent gravity_event{};
|
||||
};
|
||||
|
||||
class ImuProcessor final {
|
||||
public:
|
||||
ImuProcessor();
|
||||
|
||||
void Reset();
|
||||
ImuProcessorOutput Process(
|
||||
const ImuSample& raw,
|
||||
uint64_t now_ms);
|
||||
|
||||
bool still() const { return still_; }
|
||||
|
||||
private:
|
||||
static constexpr float kFilterAlpha = 0.75F;
|
||||
static constexpr float kStillDeviationG = 0.010F;
|
||||
static constexpr float kResumeDeviationG = 0.050F;
|
||||
static constexpr uint16_t kStillFrameCount = 50;
|
||||
static constexpr float kFreefallThresholdG = 0.30F;
|
||||
static constexpr uint32_t kFreefallConfirmMs = 60;
|
||||
static constexpr uint32_t kFreefallActivePeriodMs = 500;
|
||||
static constexpr uint32_t kLandingWindowMs = 800;
|
||||
static constexpr float kCaughtThresholdG = 1.40F;
|
||||
static constexpr float kDroppedThresholdG = 4.50F;
|
||||
static constexpr float kSevereThresholdG = 7.00F;
|
||||
static constexpr uint32_t kActionCooldownMs = 1000;
|
||||
|
||||
ImuSample Filter(const ImuSample& raw);
|
||||
void UpdateBatch(
|
||||
const ImuSample& filtered,
|
||||
uint64_t now_ms,
|
||||
ImuProcessorOutput* output);
|
||||
void FlushPartialBatch(ImuProcessorOutput* output);
|
||||
void UpdateGravity(
|
||||
const ImuSample& raw,
|
||||
uint64_t now_ms,
|
||||
ImuProcessorOutput* output);
|
||||
void TryEmitGravity(
|
||||
GravityAction action,
|
||||
uint64_t now_ms,
|
||||
uint32_t duration_ms,
|
||||
float peak_g,
|
||||
ImuProcessorOutput* output);
|
||||
|
||||
bool filter_initialized_ = false;
|
||||
ImuSample filtered_{};
|
||||
bool still_ = false;
|
||||
uint16_t still_frame_count_ = 0;
|
||||
ImuBatch pending_batch_{};
|
||||
uint32_t next_sequence_ = 0;
|
||||
uint32_t next_gravity_sequence_ = 0;
|
||||
|
||||
bool freefall_candidate_ = false;
|
||||
bool freefall_confirmed_ = false;
|
||||
uint64_t freefall_started_ms_ = 0;
|
||||
uint64_t last_freefall_active_ms_ = 0;
|
||||
bool landing_window_ = false;
|
||||
uint64_t landing_deadline_ms_ = 0;
|
||||
uint32_t landing_duration_ms_ = 0;
|
||||
float landing_peak_g_ = 0.0F;
|
||||
std::array<
|
||||
uint64_t,
|
||||
static_cast<size_t>(GravityAction::kCount)>
|
||||
last_gravity_event_ms_{};
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
131
main/sensor/sensor_message_codec.cc
Normal file
131
main/sensor/sensor_message_codec.cc
Normal file
@@ -0,0 +1,131 @@
|
||||
#include "sensor/sensor_message_codec.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
bool Finish(int written, size_t capacity, size_t* output_size)
|
||||
{
|
||||
if (written < 0 ||
|
||||
static_cast<size_t>(written) >= capacity ||
|
||||
output_size == nullptr) {
|
||||
return false;
|
||||
}
|
||||
*output_size = static_cast<size_t>(written);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool SensorMessageCodec::BuildTouch(
|
||||
const TouchEvent& event,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if (output == nullptr || capacity == 0 || output_size == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const int written =
|
||||
event.action == TouchAction::kDown
|
||||
? std::snprintf(
|
||||
output,
|
||||
capacity,
|
||||
"{\"type\":\"sensor\",\"event\":\"touch\","
|
||||
"\"touch_zone\":\"%s\",\"touch_action\":\"down\","
|
||||
"\"timestamp\":%llu}",
|
||||
ToString(event.zone),
|
||||
static_cast<unsigned long long>(
|
||||
event.timestamp_ms))
|
||||
: std::snprintf(
|
||||
output,
|
||||
capacity,
|
||||
"{\"type\":\"sensor\",\"event\":\"touch\","
|
||||
"\"touch_zone\":\"%s\",\"touch_action\":\"up\","
|
||||
"\"timestamp\":%llu,\"duration_ms\":%lu}",
|
||||
ToString(event.zone),
|
||||
static_cast<unsigned long long>(
|
||||
event.timestamp_ms),
|
||||
static_cast<unsigned long>(
|
||||
event.duration_ms));
|
||||
return Finish(written, capacity, output_size);
|
||||
}
|
||||
|
||||
bool SensorMessageCodec::BuildImu(
|
||||
const ImuBatch& batch,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if (output == nullptr || capacity == 0 || output_size == nullptr ||
|
||||
batch.count == 0 || batch.count > batch.samples.size()) {
|
||||
return false;
|
||||
}
|
||||
int written = std::snprintf(
|
||||
output,
|
||||
capacity,
|
||||
"{\"type\":\"sensor\",\"event\":\"imu\","
|
||||
"\"seq\":%lu,\"ts_ms_base\":%llu,\"hz\":%u,\"samples\":[",
|
||||
static_cast<unsigned long>(batch.sequence),
|
||||
static_cast<unsigned long long>(batch.timestamp_ms_base),
|
||||
static_cast<unsigned int>(batch.sample_rate_hz));
|
||||
if (written < 0 || static_cast<size_t>(written) >= capacity) {
|
||||
return false;
|
||||
}
|
||||
size_t used = static_cast<size_t>(written);
|
||||
for (size_t i = 0; i < batch.count; ++i) {
|
||||
const ImuSample& sample = batch.samples[i];
|
||||
written = std::snprintf(
|
||||
output + used,
|
||||
capacity - used,
|
||||
"%s[%.4f,%.4f,%.4f,%.3f,%.3f,%.3f]",
|
||||
i == 0 ? "" : ",",
|
||||
static_cast<double>(sample.ax),
|
||||
static_cast<double>(sample.ay),
|
||||
static_cast<double>(sample.az),
|
||||
static_cast<double>(sample.gx),
|
||||
static_cast<double>(sample.gy),
|
||||
static_cast<double>(sample.gz));
|
||||
if (written < 0 ||
|
||||
static_cast<size_t>(written) >= capacity - used) {
|
||||
return false;
|
||||
}
|
||||
used += static_cast<size_t>(written);
|
||||
}
|
||||
written = std::snprintf(output + used, capacity - used, "]}");
|
||||
if (written < 0 ||
|
||||
static_cast<size_t>(written) >= capacity - used) {
|
||||
return false;
|
||||
}
|
||||
used += static_cast<size_t>(written);
|
||||
*output_size = used;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SensorMessageCodec::BuildGravity(
|
||||
const GravityEvent& event,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size)
|
||||
{
|
||||
if (output == nullptr || capacity == 0 || output_size == nullptr) {
|
||||
return false;
|
||||
}
|
||||
const int written = std::snprintf(
|
||||
output,
|
||||
capacity,
|
||||
"{\"type\":\"sensor\",\"event\":\"gravity\","
|
||||
"\"seq\":%lu,\"timestamp\":%llu,"
|
||||
"\"gravity_zone\":\"body\",\"gravity_action\":\"%s\","
|
||||
"\"duration_ms\":%lu,\"magnitude\":%.3f,\"peak_g\":%.3f}",
|
||||
static_cast<unsigned long>(event.sequence),
|
||||
static_cast<unsigned long long>(event.timestamp_ms),
|
||||
ToString(event.action),
|
||||
static_cast<unsigned long>(event.duration_ms),
|
||||
static_cast<double>(event.magnitude_g),
|
||||
static_cast<double>(event.peak_g));
|
||||
return Finish(written, capacity, output_size);
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
28
main/sensor/sensor_message_codec.h
Normal file
28
main/sensor/sensor_message_codec.h
Normal file
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "sensor/sensor_types.h"
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace borla {
|
||||
|
||||
class SensorMessageCodec final {
|
||||
public:
|
||||
static bool BuildTouch(
|
||||
const TouchEvent& event,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
static bool BuildImu(
|
||||
const ImuBatch& batch,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
static bool BuildGravity(
|
||||
const GravityEvent& event,
|
||||
char* output,
|
||||
size_t capacity,
|
||||
size_t* output_size);
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
351
main/sensor/sensor_service.cc
Normal file
351
main/sensor/sensor_service.cc
Normal file
@@ -0,0 +1,351 @@
|
||||
#include "sensor/sensor_service.h"
|
||||
|
||||
#include "sensor/sensor_message_codec.h"
|
||||
|
||||
#include <array>
|
||||
|
||||
#include <esp_log.h>
|
||||
#include <esp_timer.h>
|
||||
|
||||
namespace borla {
|
||||
namespace {
|
||||
|
||||
constexpr const char* kTag = "SensorService2";
|
||||
constexpr uint32_t kTouchWarmupMs = 500;
|
||||
constexpr uint32_t kTouchCalibrationSamples = 10;
|
||||
constexpr uint32_t kTouchCalibrationIntervalMs = 20;
|
||||
constexpr uint32_t kTouchPollMs = 50;
|
||||
constexpr uint32_t kImuPollMs = 20;
|
||||
constexpr uint32_t kBatteryPollMs = 10000;
|
||||
|
||||
uint64_t NowMs()
|
||||
{
|
||||
return static_cast<uint64_t>(esp_timer_get_time() / 1000);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
SensorService::SensorService(
|
||||
CapacitiveTouchInput& touch,
|
||||
Bmi270Sensor& imu,
|
||||
BatteryMonitor& battery,
|
||||
ISensorMessageSink& sink)
|
||||
: touch_(touch),
|
||||
imu_(imu),
|
||||
battery_(battery),
|
||||
sink_(sink)
|
||||
{
|
||||
}
|
||||
|
||||
bool SensorService::Initialize()
|
||||
{
|
||||
if (running_.load()) {
|
||||
return true;
|
||||
}
|
||||
stopped_events_ =
|
||||
xEventGroupCreateStatic(&stopped_events_control_);
|
||||
if (stopped_events_ == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
touch_enabled_ = touch_.Initialize();
|
||||
imu_enabled_ = imu_.Initialize();
|
||||
battery_enabled_ = battery_.Initialize();
|
||||
running_.store(true);
|
||||
|
||||
if (touch_enabled_) {
|
||||
touch_task_ = xTaskCreateStaticPinnedToCore(
|
||||
&SensorService::TouchTaskEntry,
|
||||
"touch_sensor2",
|
||||
touch_task_stack_.size(),
|
||||
this,
|
||||
kTaskPriority,
|
||||
touch_task_stack_.data(),
|
||||
&touch_task_control_,
|
||||
0);
|
||||
touch_enabled_ = touch_task_ != nullptr;
|
||||
}
|
||||
if (imu_enabled_) {
|
||||
imu_task_ = xTaskCreateStaticPinnedToCore(
|
||||
&SensorService::ImuTaskEntry,
|
||||
"imu_sensor2",
|
||||
imu_task_stack_.size(),
|
||||
this,
|
||||
kTaskPriority + 1,
|
||||
imu_task_stack_.data(),
|
||||
&imu_task_control_,
|
||||
1);
|
||||
imu_enabled_ = imu_task_ != nullptr;
|
||||
}
|
||||
if (battery_enabled_) {
|
||||
battery_task_ = xTaskCreateStatic(
|
||||
&SensorService::BatteryTaskEntry,
|
||||
"battery_sensor2",
|
||||
battery_task_stack_.size(),
|
||||
this,
|
||||
kTaskPriority,
|
||||
battery_task_stack_.data(),
|
||||
&battery_task_control_);
|
||||
battery_enabled_ = battery_task_ != nullptr;
|
||||
}
|
||||
|
||||
const bool any_enabled =
|
||||
touch_enabled_ || imu_enabled_ || battery_enabled_;
|
||||
if (!any_enabled) {
|
||||
running_.store(false);
|
||||
ESP_LOGE(kTag, "no sensor adapter available");
|
||||
return false;
|
||||
}
|
||||
ESP_LOGI(kTag, "started touch=%d imu=%d battery=%d",
|
||||
touch_enabled_, imu_enabled_, battery_enabled_);
|
||||
return true;
|
||||
}
|
||||
|
||||
void SensorService::Stop()
|
||||
{
|
||||
if (!running_.exchange(false) || stopped_events_ == nullptr) {
|
||||
return;
|
||||
}
|
||||
EventBits_t expected = 0;
|
||||
if (touch_enabled_) {
|
||||
expected |= kTouchStoppedBit;
|
||||
}
|
||||
if (imu_enabled_) {
|
||||
expected |= kImuStoppedBit;
|
||||
}
|
||||
if (battery_enabled_) {
|
||||
expected |= kBatteryStoppedBit;
|
||||
}
|
||||
if (expected != 0) {
|
||||
xEventGroupWaitBits(
|
||||
stopped_events_,
|
||||
expected,
|
||||
pdFALSE,
|
||||
pdTRUE,
|
||||
pdMS_TO_TICKS(12000));
|
||||
}
|
||||
ESP_LOGI(kTag, "stopped");
|
||||
}
|
||||
|
||||
BatteryStatus SensorService::GetBatteryStatus() const
|
||||
{
|
||||
portENTER_CRITICAL(&status_lock_);
|
||||
const BatteryStatus result = battery_status_;
|
||||
portEXIT_CRITICAL(&status_lock_);
|
||||
return result;
|
||||
}
|
||||
|
||||
SensorDiagnostics SensorService::GetDiagnostics() const
|
||||
{
|
||||
return {
|
||||
.touch_events_sent = touch_events_sent_.load(),
|
||||
.imu_batches_sent = imu_batches_sent_.load(),
|
||||
.gravity_events_sent = gravity_events_sent_.load(),
|
||||
.messages_dropped = messages_dropped_.load(),
|
||||
.touch_read_errors = touch_read_errors_.load(),
|
||||
.imu_read_errors = imu_read_errors_.load(),
|
||||
.battery_read_errors = battery_read_errors_.load(),
|
||||
};
|
||||
}
|
||||
|
||||
void SensorService::TouchTaskEntry(void* context)
|
||||
{
|
||||
static_cast<SensorService*>(context)->RunTouch();
|
||||
}
|
||||
|
||||
void SensorService::ImuTaskEntry(void* context)
|
||||
{
|
||||
static_cast<SensorService*>(context)->RunImu();
|
||||
}
|
||||
|
||||
void SensorService::BatteryTaskEntry(void* context)
|
||||
{
|
||||
static_cast<SensorService*>(context)->RunBattery();
|
||||
}
|
||||
|
||||
void SensorService::RunTouch()
|
||||
{
|
||||
vTaskDelay(pdMS_TO_TICKS(kTouchWarmupMs));
|
||||
for (TouchChannel& channel : touch_channels_) {
|
||||
channel.ResetCalibration();
|
||||
}
|
||||
for (uint32_t sample_index = 0;
|
||||
sample_index < kTouchCalibrationSamples && running_.load();
|
||||
++sample_index) {
|
||||
for (size_t channel = 0;
|
||||
channel < touch_channels_.size();
|
||||
++channel) {
|
||||
uint32_t raw = 0;
|
||||
if (touch_.Read(channel, &raw)) {
|
||||
touch_channels_[channel].AddCalibrationSample(raw);
|
||||
} else {
|
||||
touch_read_errors_.fetch_add(1);
|
||||
}
|
||||
}
|
||||
vTaskDelay(pdMS_TO_TICKS(kTouchCalibrationIntervalMs));
|
||||
}
|
||||
for (size_t channel = 0;
|
||||
channel < touch_channels_.size();
|
||||
++channel) {
|
||||
if (!touch_channels_[channel].FinishCalibration()) {
|
||||
ESP_LOGW(kTag, "touch calibration failed channel=%u",
|
||||
static_cast<unsigned int>(channel));
|
||||
} else {
|
||||
ESP_LOGI(kTag, "touch channel=%u baseline=%.0f threshold=%.0f",
|
||||
static_cast<unsigned int>(channel),
|
||||
static_cast<double>(
|
||||
touch_channels_[channel].baseline()),
|
||||
static_cast<double>(
|
||||
touch_channels_[channel].threshold()));
|
||||
}
|
||||
}
|
||||
|
||||
TickType_t next_tick = xTaskGetTickCount();
|
||||
while (running_.load()) {
|
||||
const uint64_t now_ms = NowMs();
|
||||
for (size_t channel = 0;
|
||||
channel < touch_channels_.size();
|
||||
++channel) {
|
||||
uint32_t raw = 0;
|
||||
if (!touch_.Read(channel, &raw)) {
|
||||
touch_read_errors_.fetch_add(1);
|
||||
continue;
|
||||
}
|
||||
TouchTransition transition{};
|
||||
if (touch_channels_[channel].Process(
|
||||
raw, now_ms, &transition)) {
|
||||
if (transition.action == TouchAction::kDown &&
|
||||
publisher_ != nullptr) {
|
||||
publisher_->Publish(AppEvent::Make(
|
||||
AppEventType::kUserActivityDetected,
|
||||
0,
|
||||
static_cast<int32_t>(channel)));
|
||||
}
|
||||
SendTouch({
|
||||
.zone = static_cast<TouchZone>(channel),
|
||||
.action = transition.action,
|
||||
.timestamp_ms = transition.timestamp_ms,
|
||||
.duration_ms = transition.duration_ms,
|
||||
});
|
||||
}
|
||||
}
|
||||
vTaskDelayUntil(
|
||||
&next_tick, pdMS_TO_TICKS(kTouchPollMs));
|
||||
}
|
||||
xEventGroupSetBits(stopped_events_, kTouchStoppedBit);
|
||||
touch_task_ = nullptr;
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
void SensorService::RunImu()
|
||||
{
|
||||
TickType_t next_tick = xTaskGetTickCount();
|
||||
while (running_.load()) {
|
||||
ImuSample sample{};
|
||||
if (imu_.Read(&sample)) {
|
||||
const ImuProcessorOutput output =
|
||||
imu_processor_.Process(sample, NowMs());
|
||||
if (output.has_gravity_event) {
|
||||
SendGravity(output.gravity_event);
|
||||
}
|
||||
if (output.has_batch) {
|
||||
SendImu(output.batch);
|
||||
}
|
||||
} else {
|
||||
imu_read_errors_.fetch_add(1);
|
||||
}
|
||||
vTaskDelayUntil(&next_tick, pdMS_TO_TICKS(kImuPollMs));
|
||||
}
|
||||
xEventGroupSetBits(stopped_events_, kImuStoppedBit);
|
||||
imu_task_ = nullptr;
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
void SensorService::RunBattery()
|
||||
{
|
||||
while (running_.load()) {
|
||||
BatteryStatus status{};
|
||||
if (battery_.Read(NowMs(), &status)) {
|
||||
portENTER_CRITICAL(&status_lock_);
|
||||
battery_status_ = status;
|
||||
portEXIT_CRITICAL(&status_lock_);
|
||||
// One line per actual change, not one per 10-second poll — the
|
||||
// steady-state repeat was pure noise in the conversation log.
|
||||
// Function-local statics are fine: there is one battery task.
|
||||
static int last_logged_percent = -1;
|
||||
static int last_logged_charging = -1;
|
||||
if (static_cast<int>(status.percent) != last_logged_percent ||
|
||||
static_cast<int>(status.charging) != last_logged_charging) {
|
||||
last_logged_percent = static_cast<int>(status.percent);
|
||||
last_logged_charging = static_cast<int>(status.charging);
|
||||
ESP_LOGI(kTag, "battery=%u%% voltage=%umV charging=%d",
|
||||
status.percent,
|
||||
status.millivolts,
|
||||
status.charging);
|
||||
}
|
||||
} else {
|
||||
battery_read_errors_.fetch_add(1);
|
||||
portENTER_CRITICAL(&status_lock_);
|
||||
battery_status_ = {};
|
||||
portEXIT_CRITICAL(&status_lock_);
|
||||
}
|
||||
for (uint32_t waited_ms = 0;
|
||||
running_.load() && waited_ms < kBatteryPollMs;
|
||||
waited_ms += 100) {
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
}
|
||||
xEventGroupSetBits(stopped_events_, kBatteryStoppedBit);
|
||||
battery_task_ = nullptr;
|
||||
vTaskDelete(nullptr);
|
||||
}
|
||||
|
||||
bool SensorService::SendTouch(const TouchEvent& event)
|
||||
{
|
||||
std::array<char, 256> message{};
|
||||
size_t size = 0;
|
||||
const bool sent =
|
||||
SensorMessageCodec::BuildTouch(
|
||||
event, message.data(), message.size(), &size) &&
|
||||
sink_.SendSensorMessage(message.data(), size);
|
||||
if (sent) {
|
||||
touch_events_sent_.fetch_add(1);
|
||||
} else {
|
||||
messages_dropped_.fetch_add(1);
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
bool SensorService::SendImu(const ImuBatch& batch)
|
||||
{
|
||||
std::array<char, 768> message{};
|
||||
size_t size = 0;
|
||||
const bool sent =
|
||||
SensorMessageCodec::BuildImu(
|
||||
batch, message.data(), message.size(), &size) &&
|
||||
sink_.SendSensorMessage(message.data(), size);
|
||||
if (sent) {
|
||||
imu_batches_sent_.fetch_add(1);
|
||||
} else {
|
||||
messages_dropped_.fetch_add(1);
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
bool SensorService::SendGravity(const GravityEvent& event)
|
||||
{
|
||||
std::array<char, 256> message{};
|
||||
size_t size = 0;
|
||||
const bool sent =
|
||||
SensorMessageCodec::BuildGravity(
|
||||
event, message.data(), message.size(), &size) &&
|
||||
sink_.SendSensorMessage(message.data(), size);
|
||||
if (sent) {
|
||||
gravity_events_sent_.fetch_add(1);
|
||||
} else {
|
||||
messages_dropped_.fetch_add(1);
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
109
main/sensor/sensor_service.h
Normal file
109
main/sensor/sensor_service.h
Normal file
@@ -0,0 +1,109 @@
|
||||
#pragma once
|
||||
|
||||
#include "platform/borla_s3/battery_monitor.h"
|
||||
#include "platform/borla_s3/bmi270_sensor.h"
|
||||
#include "platform/borla_s3/capacitive_touch_input.h"
|
||||
#include "ports/battery_status_provider.h"
|
||||
#include "ports/event_publisher.h"
|
||||
#include "ports/sensor_message_sink.h"
|
||||
#include "sensor/imu_processor.h"
|
||||
#include "sensor/touch_channel.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/event_groups.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
namespace borla {
|
||||
|
||||
struct SensorDiagnostics {
|
||||
uint32_t touch_events_sent = 0;
|
||||
uint32_t imu_batches_sent = 0;
|
||||
uint32_t gravity_events_sent = 0;
|
||||
uint32_t messages_dropped = 0;
|
||||
uint32_t touch_read_errors = 0;
|
||||
uint32_t imu_read_errors = 0;
|
||||
uint32_t battery_read_errors = 0;
|
||||
};
|
||||
|
||||
class SensorService final : public IBatteryStatusProvider {
|
||||
public:
|
||||
SensorService(
|
||||
CapacitiveTouchInput& touch,
|
||||
Bmi270Sensor& imu,
|
||||
BatteryMonitor& battery,
|
||||
ISensorMessageSink& sink);
|
||||
|
||||
bool Initialize();
|
||||
void SetEventPublisher(IEventPublisher* publisher)
|
||||
{
|
||||
publisher_ = publisher;
|
||||
}
|
||||
void Stop();
|
||||
|
||||
BatteryStatus GetBatteryStatus() const override;
|
||||
SensorDiagnostics GetDiagnostics() const;
|
||||
|
||||
private:
|
||||
static constexpr uint32_t kTouchTaskStackDepth = 3072;
|
||||
static constexpr uint32_t kImuTaskStackDepth = 4096;
|
||||
static constexpr uint32_t kBatteryTaskStackDepth = 3072;
|
||||
static constexpr UBaseType_t kTaskPriority = 4;
|
||||
static constexpr EventBits_t kTouchStoppedBit = BIT0;
|
||||
static constexpr EventBits_t kImuStoppedBit = BIT1;
|
||||
static constexpr EventBits_t kBatteryStoppedBit = BIT2;
|
||||
|
||||
static void TouchTaskEntry(void* context);
|
||||
static void ImuTaskEntry(void* context);
|
||||
static void BatteryTaskEntry(void* context);
|
||||
void RunTouch();
|
||||
void RunImu();
|
||||
void RunBattery();
|
||||
bool SendTouch(const TouchEvent& event);
|
||||
bool SendImu(const ImuBatch& batch);
|
||||
bool SendGravity(const GravityEvent& event);
|
||||
|
||||
CapacitiveTouchInput& touch_;
|
||||
Bmi270Sensor& imu_;
|
||||
BatteryMonitor& battery_;
|
||||
ISensorMessageSink& sink_;
|
||||
IEventPublisher* publisher_ = nullptr;
|
||||
std::array<TouchChannel, kTouchZoneCount> touch_channels_{};
|
||||
ImuProcessor imu_processor_;
|
||||
|
||||
std::atomic<bool> running_{false};
|
||||
bool touch_enabled_ = false;
|
||||
bool imu_enabled_ = false;
|
||||
bool battery_enabled_ = false;
|
||||
EventGroupHandle_t stopped_events_ = nullptr;
|
||||
StaticEventGroup_t stopped_events_control_{};
|
||||
|
||||
TaskHandle_t touch_task_ = nullptr;
|
||||
StaticTask_t touch_task_control_{};
|
||||
std::array<StackType_t, kTouchTaskStackDepth>
|
||||
touch_task_stack_{};
|
||||
TaskHandle_t imu_task_ = nullptr;
|
||||
StaticTask_t imu_task_control_{};
|
||||
std::array<StackType_t, kImuTaskStackDepth>
|
||||
imu_task_stack_{};
|
||||
TaskHandle_t battery_task_ = nullptr;
|
||||
StaticTask_t battery_task_control_{};
|
||||
std::array<StackType_t, kBatteryTaskStackDepth>
|
||||
battery_task_stack_{};
|
||||
|
||||
mutable portMUX_TYPE status_lock_ =
|
||||
portMUX_INITIALIZER_UNLOCKED;
|
||||
BatteryStatus battery_status_{};
|
||||
std::atomic<uint32_t> touch_events_sent_{0};
|
||||
std::atomic<uint32_t> imu_batches_sent_{0};
|
||||
std::atomic<uint32_t> gravity_events_sent_{0};
|
||||
std::atomic<uint32_t> messages_dropped_{0};
|
||||
std::atomic<uint32_t> touch_read_errors_{0};
|
||||
std::atomic<uint32_t> imu_read_errors_{0};
|
||||
std::atomic<uint32_t> battery_read_errors_{0};
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
56
main/sensor/sensor_types.cc
Normal file
56
main/sensor/sensor_types.cc
Normal file
@@ -0,0 +1,56 @@
|
||||
#include "sensor/sensor_types.h"
|
||||
|
||||
namespace borla {
|
||||
|
||||
const char* ToString(TouchZone zone)
|
||||
{
|
||||
switch (zone) {
|
||||
case TouchZone::kHead:
|
||||
return "touch_1";
|
||||
case TouchZone::kBack:
|
||||
return "touch_2";
|
||||
case TouchZone::kRightHand:
|
||||
return "touch_3";
|
||||
// case TouchZone::kLeftHand:
|
||||
// return "touch_4";
|
||||
// case TouchZone::kBelly:
|
||||
// return "touch_5";/////2026-9-4 ckkj mod
|
||||
case TouchZone::kCount:
|
||||
return "unknown";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* ToString(TouchAction action)
|
||||
{
|
||||
switch (action) {
|
||||
case TouchAction::kDown:
|
||||
return "down";
|
||||
case TouchAction::kUp:
|
||||
return "up";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
const char* ToString(GravityAction action)
|
||||
{
|
||||
switch (action) {
|
||||
case GravityAction::kFreefall:
|
||||
return "freefall";
|
||||
case GravityAction::kFreefallActive:
|
||||
return "freefall_active";
|
||||
case GravityAction::kCaught:
|
||||
return "caught";
|
||||
case GravityAction::kDropped:
|
||||
return "dropped";
|
||||
case GravityAction::kImpact:
|
||||
return "impact";
|
||||
case GravityAction::kSevereImpact:
|
||||
return "severe_impact";
|
||||
case GravityAction::kCount:
|
||||
return "unknown";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
85
main/sensor/sensor_types.h
Normal file
85
main/sensor/sensor_types.h
Normal file
@@ -0,0 +1,85 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
enum class TouchZone : uint8_t {
|
||||
kHead,
|
||||
kBack,
|
||||
kRightHand,
|
||||
// kLeftHand,
|
||||
// kBelly,
|
||||
kCount,
|
||||
};
|
||||
|
||||
inline constexpr size_t kTouchZoneCount =
|
||||
static_cast<size_t>(TouchZone::kCount);
|
||||
|
||||
const char* ToString(TouchZone zone);
|
||||
|
||||
enum class TouchAction : uint8_t {
|
||||
kDown,
|
||||
kUp,
|
||||
};
|
||||
|
||||
const char* ToString(TouchAction action);
|
||||
|
||||
struct TouchEvent {
|
||||
TouchZone zone = TouchZone::kHead;
|
||||
TouchAction action = TouchAction::kDown;
|
||||
uint64_t timestamp_ms = 0;
|
||||
uint32_t duration_ms = 0;
|
||||
};
|
||||
|
||||
struct ImuSample {
|
||||
float ax = 0.0F;
|
||||
float ay = 0.0F;
|
||||
float az = 0.0F;
|
||||
float gx = 0.0F;
|
||||
float gy = 0.0F;
|
||||
float gz = 0.0F;
|
||||
};
|
||||
|
||||
inline constexpr size_t kImuWifiBatchCapacity = 5;
|
||||
|
||||
struct ImuBatch {
|
||||
uint32_t sequence = 0;
|
||||
uint64_t timestamp_ms_base = 0;
|
||||
uint8_t sample_rate_hz = 50;
|
||||
size_t count = 0;
|
||||
std::array<ImuSample, kImuWifiBatchCapacity> samples{};
|
||||
};
|
||||
|
||||
enum class GravityAction : uint8_t {
|
||||
kFreefall,
|
||||
kFreefallActive,
|
||||
kCaught,
|
||||
kDropped,
|
||||
kImpact,
|
||||
kSevereImpact,
|
||||
kCount,
|
||||
};
|
||||
|
||||
const char* ToString(GravityAction action);
|
||||
|
||||
struct GravityEvent {
|
||||
GravityAction action = GravityAction::kFreefall;
|
||||
uint32_t sequence = 0;
|
||||
uint64_t timestamp_ms = 0;
|
||||
uint32_t duration_ms = 0;
|
||||
float magnitude_g = 0.0F;
|
||||
float peak_g = 0.0F;
|
||||
};
|
||||
|
||||
struct BatteryStatus {
|
||||
uint64_t timestamp_ms = 0;
|
||||
uint16_t millivolts = 0;
|
||||
uint8_t percent = 0;
|
||||
bool charging = false;
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
154
main/sensor/touch_channel.cc
Normal file
154
main/sensor/touch_channel.cc
Normal file
@@ -0,0 +1,154 @@
|
||||
#include "sensor/touch_channel.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace borla {
|
||||
|
||||
TouchChannel::TouchChannel(const TouchChannelConfig& config)
|
||||
: config_(config)
|
||||
{
|
||||
}
|
||||
|
||||
void TouchChannel::ResetCalibration()
|
||||
{
|
||||
calibration_count_ = 0;
|
||||
calibration_sum_ = 0.0;
|
||||
calibration_square_sum_ = 0.0;
|
||||
baseline_ = 0.0F;
|
||||
filtered_ = 0.0F;
|
||||
noise_deviation_ = 0.0F;
|
||||
threshold_ = 0.0F;
|
||||
press_count_ = 0;
|
||||
release_count_ = 0;
|
||||
calibrated_ = false;
|
||||
pressed_ = false;
|
||||
stuck_lockout_ = false;
|
||||
pressed_at_ms_ = 0;
|
||||
}
|
||||
|
||||
void TouchChannel::AddCalibrationSample(uint32_t raw)
|
||||
{
|
||||
calibration_count_++;
|
||||
calibration_sum_ += static_cast<double>(raw);
|
||||
calibration_square_sum_ +=
|
||||
static_cast<double>(raw) * static_cast<double>(raw);
|
||||
}
|
||||
|
||||
bool TouchChannel::FinishCalibration()
|
||||
{
|
||||
if (calibration_count_ < 2) {
|
||||
return false;
|
||||
}
|
||||
const double count = static_cast<double>(calibration_count_);
|
||||
const double mean = calibration_sum_ / count;
|
||||
const double variance = std::max(
|
||||
0.0, calibration_square_sum_ / count - mean * mean);
|
||||
baseline_ = static_cast<float>(mean);
|
||||
filtered_ = baseline_;
|
||||
noise_deviation_ = std::max(
|
||||
config_.minimum_noise_deviation,
|
||||
static_cast<float>(std::sqrt(variance)));
|
||||
UpdateThreshold();
|
||||
calibrated_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TouchChannel::Process(
|
||||
uint32_t raw,
|
||||
uint64_t now_ms,
|
||||
TouchTransition* transition)
|
||||
{
|
||||
if (!calibrated_ || transition == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
filtered_ = (filtered_ * 7.0F + static_cast<float>(raw)) / 8.0F;
|
||||
if (pressed_ && static_cast<float>(raw) < threshold_) {
|
||||
// A release must not inherit the long EMA tail of a touch.
|
||||
filtered_ = static_cast<float>(raw);
|
||||
}
|
||||
|
||||
if (!pressed_) {
|
||||
const float deviation = std::fabs(filtered_ - baseline_);
|
||||
const float outlier_limit = std::max(
|
||||
config_.minimum_threshold_delta,
|
||||
config_.outlier_multiplier * noise_deviation_);
|
||||
if (deviation < outlier_limit) {
|
||||
baseline_ +=
|
||||
(filtered_ - baseline_) /
|
||||
config_.baseline_follow_divisor;
|
||||
noise_deviation_ +=
|
||||
(deviation - noise_deviation_) /
|
||||
config_.noise_follow_divisor;
|
||||
noise_deviation_ = std::max(
|
||||
noise_deviation_,
|
||||
config_.minimum_noise_deviation);
|
||||
UpdateThreshold();
|
||||
}
|
||||
}
|
||||
|
||||
const bool touching = filtered_ > threshold_;
|
||||
if (stuck_lockout_ && static_cast<float>(raw) < threshold_) {
|
||||
stuck_lockout_ = false;
|
||||
}
|
||||
|
||||
if (!pressed_) {
|
||||
release_count_ = 0;
|
||||
if (touching && !stuck_lockout_) {
|
||||
if (press_count_ < std::numeric_limits<uint8_t>::max()) {
|
||||
press_count_++;
|
||||
}
|
||||
if (press_count_ >= config_.press_debounce_samples) {
|
||||
press_count_ = 0;
|
||||
pressed_ = true;
|
||||
pressed_at_ms_ = now_ms;
|
||||
transition->action = TouchAction::kDown;
|
||||
transition->timestamp_ms = now_ms;
|
||||
transition->duration_ms = 0;
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
press_count_ = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
press_count_ = 0;
|
||||
if (!touching) {
|
||||
if (release_count_ < std::numeric_limits<uint8_t>::max()) {
|
||||
release_count_++;
|
||||
}
|
||||
} else {
|
||||
release_count_ = 0;
|
||||
}
|
||||
|
||||
const uint64_t held_ms = now_ms - pressed_at_ms_;
|
||||
const bool forced_release =
|
||||
held_ms >= config_.maximum_press_ms &&
|
||||
static_cast<float>(raw) < threshold_;
|
||||
if (release_count_ < config_.release_debounce_samples &&
|
||||
!forced_release) {
|
||||
return false;
|
||||
}
|
||||
|
||||
release_count_ = 0;
|
||||
pressed_ = false;
|
||||
stuck_lockout_ = forced_release;
|
||||
transition->action = TouchAction::kUp;
|
||||
transition->timestamp_ms = now_ms;
|
||||
transition->duration_ms = static_cast<uint32_t>(
|
||||
std::min<uint64_t>(
|
||||
held_ms, std::numeric_limits<uint32_t>::max()));
|
||||
return true;
|
||||
}
|
||||
|
||||
void TouchChannel::UpdateThreshold()
|
||||
{
|
||||
threshold_ = baseline_ + std::max(
|
||||
config_.minimum_threshold_delta,
|
||||
config_.threshold_noise_multiplier * noise_deviation_);
|
||||
}
|
||||
|
||||
} // namespace borla
|
||||
65
main/sensor/touch_channel.h
Normal file
65
main/sensor/touch_channel.h
Normal file
@@ -0,0 +1,65 @@
|
||||
#pragma once
|
||||
|
||||
#include "sensor/sensor_types.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace borla {
|
||||
|
||||
struct TouchChannelConfig {
|
||||
float threshold_noise_multiplier = 5.0F;
|
||||
float minimum_threshold_delta = 300.0F;
|
||||
float minimum_noise_deviation = 50.0F;
|
||||
float baseline_follow_divisor = 256.0F;
|
||||
float noise_follow_divisor = 64.0F;
|
||||
float outlier_multiplier = 4.0F;
|
||||
uint8_t press_debounce_samples = 4;
|
||||
uint8_t release_debounce_samples = 1;
|
||||
uint32_t maximum_press_ms = 5000;
|
||||
};
|
||||
|
||||
struct TouchTransition {
|
||||
TouchAction action = TouchAction::kDown;
|
||||
uint64_t timestamp_ms = 0;
|
||||
uint32_t duration_ms = 0;
|
||||
};
|
||||
|
||||
class TouchChannel final {
|
||||
public:
|
||||
TouchChannel(
|
||||
const TouchChannelConfig& config = TouchChannelConfig{});
|
||||
|
||||
void ResetCalibration();
|
||||
void AddCalibrationSample(uint32_t raw);
|
||||
bool FinishCalibration();
|
||||
bool Process(
|
||||
uint32_t raw,
|
||||
uint64_t now_ms,
|
||||
TouchTransition* transition);
|
||||
|
||||
bool calibrated() const { return calibrated_; }
|
||||
bool pressed() const { return pressed_; }
|
||||
float baseline() const { return baseline_; }
|
||||
float threshold() const { return threshold_; }
|
||||
|
||||
private:
|
||||
void UpdateThreshold();
|
||||
|
||||
TouchChannelConfig config_;
|
||||
size_t calibration_count_ = 0;
|
||||
double calibration_sum_ = 0.0;
|
||||
double calibration_square_sum_ = 0.0;
|
||||
float baseline_ = 0.0F;
|
||||
float filtered_ = 0.0F;
|
||||
float noise_deviation_ = 0.0F;
|
||||
float threshold_ = 0.0F;
|
||||
uint8_t press_count_ = 0;
|
||||
uint8_t release_count_ = 0;
|
||||
bool calibrated_ = false;
|
||||
bool pressed_ = false;
|
||||
bool stuck_lockout_ = false;
|
||||
uint64_t pressed_at_ms_ = 0;
|
||||
};
|
||||
|
||||
} // namespace borla
|
||||
Reference in New Issue
Block a user