#include <TensorFlowLite_ESP32.h>
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "model_data.h"
// Hardware settings
const int tensor_arena_size = 4 * 1024;
uint8_t tensor_arena[tensor_arena_size];
// TFLite globals
tflite::MicroErrorReporter error_reporter;
tflite::AllOpsResolver resolver;
const tflite::Model* model = nullptr;
tflite::MicroInterpreter* interpreter = nullptr;
TfLiteTensor* input = nullptr;
TfLiteTensor* output = nullptr;
// Scaling constants
float s_min[] = {-32.0978, -37.7407, -0.7648, -0.2195, 0.0};
float s_scale[] = {0.1086, 0.1234, 0.0006, 0.0174, 0.0040};
void setup() {
Serial.begin(115200);
model = tflite::GetModel(anomaly_model);
static tflite::MicroInterpreter static_interpreter(model, resolver, tensor_arena, tensor_arena_size, &error_reporter);
interpreter = &static_interpreter;
interpreter->AllocateTensors();
input = interpreter->input(0);
output = interpreter->output(0);
Serial.println("System Initialized: Anomaly Detection Active");
}
void loop() {
// Mock 'Normal' Data
float raw[] = {300.0, 310.0, 1500.0, 40.0, 50.0};
// Apply Scaling
for (int i = 0; i < 5; i++) {
input->data.f[i] = (raw[i] + s_min[i]) * s_scale[i];
}
interpreter->Invoke();
float mae = 0;
for (int i = 0; i < 5; i++) {
mae += abs(input->data.f[i] - output->data.f[i]);
}
mae /= 5.0;
Serial.print("Score: "); Serial.println(mae, 4);
if(mae > 0.05) Serial.println("!!! ANOMALY !!!");
delay(2000);
}