114 lines
2.8 KiB
C++
114 lines
2.8 KiB
C++
#include "star_code.h"
|
|
|
|
#include <vector>
|
|
#include <algorithm>
|
|
#include <string.h>
|
|
#include <stdint.h>
|
|
#include <esp_log.h>
|
|
|
|
static const char* TAG = "star_code";
|
|
|
|
static std::vector<StarCodeEntry> star_codes;
|
|
|
|
/// Checks if a triggered code matches an expected code.
|
|
/// @return true iff the codes match, where '*'s in the expected code can match any character in the triggered code
|
|
static bool check_code_match(const char* triggered, const char* expected) {
|
|
size_t triggered_len = strlen(triggered);
|
|
size_t match_len = strlen(triggered);
|
|
|
|
if (triggered_len != match_len)
|
|
return false;
|
|
|
|
for (int i = 0; i < triggered_len; i++) {
|
|
if (!(expected[i] == '*' || expected[i] == triggered[i])) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
bool add_star_code(StarCodeEntry code) {
|
|
if (code.code == nullptr || strlen(code.code) > 8) {
|
|
return false;
|
|
}
|
|
if (code.display_text != nullptr && strlen(code.display_text) > 9) {
|
|
return false;
|
|
}
|
|
|
|
// check for a existing entry
|
|
auto it = std::find_if(star_codes.begin(), star_codes.end(), [&](const StarCodeEntry& other) {
|
|
return check_code_match(code.code, other.code);
|
|
});
|
|
|
|
if (it != star_codes.end()) {
|
|
// existing star code found!
|
|
ESP_LOGW(TAG, "Failed to add star code %s", code.code);
|
|
return false;
|
|
}
|
|
|
|
star_codes.push_back(code);
|
|
return true;
|
|
}
|
|
|
|
bool add_star_codes(const StarCodeEntry* codes, size_t len) {
|
|
bool success = true;
|
|
for (int i = 0; i < len; i++) {
|
|
if (!add_star_code(codes[i])) {
|
|
success = false;
|
|
}
|
|
}
|
|
return success;
|
|
}
|
|
|
|
bool rm_star_code(const char* code){
|
|
auto it = std::find_if(star_codes.begin(), star_codes.end(), [&](const StarCodeEntry& star_code) {
|
|
return strcmp(code, star_code.code) == 0;
|
|
});
|
|
|
|
if (it == star_codes.end()) {
|
|
ESP_LOGW(TAG, "Failed to remove star code %s", code);
|
|
return false;
|
|
}
|
|
|
|
star_codes.erase(it);
|
|
return true;
|
|
}
|
|
|
|
bool rm_star_codes(const StarCodeEntry* codes, size_t len) {
|
|
bool success = true;
|
|
for (int i = 0; i < len; i++) {
|
|
if (!rm_star_code(codes[i].code)) {
|
|
success = false;
|
|
}
|
|
}
|
|
return success;
|
|
}
|
|
|
|
bool rm_star_codes_str(const char** codes, size_t len) {
|
|
bool success = true;
|
|
for (int i = 0; i < len; i++) {
|
|
if (!rm_star_code(codes[i])) {
|
|
success = false;
|
|
}
|
|
}
|
|
return success;
|
|
}
|
|
|
|
void clear_star_codes() {
|
|
star_codes.clear();
|
|
}
|
|
|
|
bool trigger_star_code(const char* code) {
|
|
auto it = std::find_if(star_codes.begin(), star_codes.end(), [&](const StarCodeEntry& other) {
|
|
return check_code_match(code, other.code);
|
|
});
|
|
|
|
if (it == star_codes.end()) {
|
|
return false;
|
|
}
|
|
|
|
(it->callback)();
|
|
return true;
|
|
}
|