From cf004e0a1d0684be4811de5e06febb81971213a0 Mon Sep 17 00:00:00 2001 From: hathach Date: Fri, 4 Jun 2021 00:17:15 +0700 Subject: [PATCH] update cmsis from 5.4.0 to 5.7.0, enable dsp libmath add initial (wip) tf4micro-motion-kit sketch --- .../tf4micro-motion-kit/data_provider.cpp | 160 +++++ .../tf4micro-motion-kit/data_provider.h | 29 + .../tf4micro-motion-kit/model_tester.cpp | 271 ++++++++ .../tf4micro-motion-kit/model_tester.h | 43 ++ .../tf4micro-motion-kit.ino | 591 ++++++++++++++++++ platform.txt | 6 +- 6 files changed, 1097 insertions(+), 3 deletions(-) create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.cpp create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.h create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.cpp create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.h create mode 100644 libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/tf4micro-motion-kit.ino diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.cpp b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.cpp new file mode 100644 index 00000000..f7f1bb95 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.cpp @@ -0,0 +1,160 @@ +/* Copyright 2021 Google LLC + +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 + + https://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. +==============================================================================*/ + +/* + * Namespaced methods for providing IMU data + * @author Rikard Lindstrom +*/ +#include "data_provider.h" +#include // change to Arduino_LSM6DS3.h for Nano 33 IoT or Uno WiFi Rev 2 + +namespace data_provider +{ +#define DATA_PROVIDER_CALIBRATION_THRESHOLD 10.0 +#define DATA_PROVIDER_CALIBRATION_STEPS 40 + + /************************************************************************ + * Calibration vars + ************************************************************************/ + + float lastMagneticFieldReading[3] = {0.0, 0.0, 0.0}; + float calibratedMagneticFieldHeading[3] = {0.0, 0.0, 0.0}; + int calibrationStep = 0; + bool calibrating = false; + + /************************************************************************ + * "Public" functions + ************************************************************************/ + + // Calibrate the magnetometer + void calibrate() + { + calibrating = true; + calibrationStep = 0; + } + + bool dataAvailable() + { + // Skip magnetometer since it's running a lot slower and always wanted + return IMU.accelerationAvailable() && IMU.gyroscopeAvailable(); + } + + bool setup() + { + + if (!IMU.begin()) + { + Serial.println("Failed to initialized IMU!"); + return false; + } + + // Experimental, enabling this will capture all readings + // from the IMU sensors and should be more accurate. However, + // it slows down the main loop by a lot when enabled. + + // IMU.setContinuousMode(); + + Serial.println("IMU sample rates: "); + Serial.print("Accelerometer sample rate = "); + Serial.println(IMU.accelerationSampleRate()); + Serial.print("Gyroscope sample rate = "); + Serial.println(IMU.gyroscopeSampleRate()); + Serial.print("Magnetometer sample rate = "); + Serial.println(IMU.magneticFieldSampleRate()); + + return true; + } + + void update(float *buffer, bool useMagnetometer) + { + + if (!dataAvailable()) + { + return; + } + + float ax, ay, az, gx, gy, gz; + + // read the acceleration and gyroscope data + IMU.readAcceleration(ax, ay, az); + IMU.readGyroscope(gx, gy, gz); + + // Accelorameter has a range of -4 – 4 + buffer[0] = ax / 4.0; + buffer[1] = ay / 4.0; + buffer[2] = az / 4.0; + + // Gyroscope has a range of -2000 – 2000 + buffer[3] = gx / 2000.0; + buffer[4] = gy / 2000.0; + buffer[5] = gz / 2000.0; + + if (useMagnetometer || calibrating) + { + float mx, my, mz; + + // The Magnetometer sample rate is only 20hz, so we'll use previous values + // if no new ones are available + if (IMU.magneticFieldAvailable()) + { + IMU.readMagneticField(mx, my, mz); + lastMagneticFieldReading[0] = mx; + lastMagneticFieldReading[1] = my; + lastMagneticFieldReading[2] = mz; + + if (calibrating) + { + // Running avarage + calibratedMagneticFieldHeading[0] += mx; + calibratedMagneticFieldHeading[1] += my; + calibratedMagneticFieldHeading[2] += mz; + calibratedMagneticFieldHeading[0] /= 2.0; + calibratedMagneticFieldHeading[1] /= 2.0; + calibratedMagneticFieldHeading[2] /= 2.0; + calibrationStep++; + if (calibrationStep > DATA_PROVIDER_CALIBRATION_STEPS && + abs(calibratedMagneticFieldHeading[0] - mx) < DATA_PROVIDER_CALIBRATION_THRESHOLD && + abs(calibratedMagneticFieldHeading[1] - my) < DATA_PROVIDER_CALIBRATION_THRESHOLD && + abs(calibratedMagneticFieldHeading[2] - mz) < DATA_PROVIDER_CALIBRATION_THRESHOLD) + { + calibrating = false; + data_provider_calibrationComplete(); + return; + } + } + } + else + { + mx = lastMagneticFieldReading[0]; + my = lastMagneticFieldReading[1]; + mz = lastMagneticFieldReading[2]; + } + + if (calibrating) + { + return; + } + + mx -= calibratedMagneticFieldHeading[0]; + my -= calibratedMagneticFieldHeading[1]; + mz -= calibratedMagneticFieldHeading[2]; + + // Raw magnetometer data + buffer[6] = mx / 50.0; + buffer[7] = my / 50.0; + buffer[8] = mz / 50.0; + } + } +} diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.h b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.h new file mode 100644 index 00000000..9903ace1 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/data_provider.h @@ -0,0 +1,29 @@ +/* Copyright 2021 Google LLC + +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 + + https://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. +==============================================================================*/ + +#ifndef DATA_PROVIDER_CPP +#define DATA_PROVIDER_CPP + +// Forward declare the function that will be called when data has been delivered to us. +void data_provider_calibrationComplete(); + +namespace data_provider { + bool setup(); + void update(float* buffer, bool useMagnetometer); + void calibrate(); + bool dataAvailable(); +} + +#endif diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.cpp b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.cpp new file mode 100644 index 00000000..b07f0eee --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.cpp @@ -0,0 +1,271 @@ +/* Copyright 2021 Google LLC + +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 + + https://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. +==============================================================================*/ + +/* + * Namespaced methods for loading a TF model and running inference + * @author Rikard Lindstrom +*/ +#include "model_tester.h" +#include +//#include + +namespace model_tester +{ + +/************************************************************************ +* Capture settings variables +************************************************************************/ + + int numSamples = 10; + int samplesRead = numSamples; + float accelerationThreshold = 0.167; + int captureDelay = 125; + unsigned char numClasses = 3; + bool disableMagnetometer = false; + + float maxVelocity = 0.; + int lastCaptureTimestamp = 0; + +/************************************************************************ +* Model loading / inference variables +************************************************************************/ + + bool isModelLoaded = false; + uint8_t interpreterBuffer[sizeof(tflite::MicroInterpreter)]; + + constexpr int tensorArenaSize = 8 * 1024; + byte tensorArena[tensorArenaSize]; + + // global variables used for TensorFlow Lite (Micro) + tflite::MicroErrorReporter tflErrorReporter; + + // pull in all the TFLM ops, you can remove this line and + // only pull in the TFLM ops you need, if would like to reduce + // the compiled size of the sketch. + tflite::AllOpsResolver tflOpsResolver; + + const tflite::Model *tflModel = nullptr; + tflite::MicroInterpreter *tflInterpreter = nullptr; + TfLiteTensor *tflInputTensor = nullptr; + TfLiteTensor *tflOutputTensor = nullptr; + + +/************************************************************************ +* Setters +************************************************************************/ + + void setCaptureDelay(int val){ + captureDelay = val; + } + + void setNumSamples(int val){ + numSamples = val; + samplesRead = val; + } + + void setThreshold(float val){ + accelerationThreshold = val; + } + + void setNumClasses(unsigned char val){ + numClasses = val; + } + + void setDisableMagnetometer(bool val){ + disableMagnetometer = val; + } + +/************************************************************************ +* Model loading +************************************************************************/ + + void loadModel(unsigned char model[]) + { + + // get the TFL representation of the model byte array + tflModel = tflite::GetModel(model); + if (tflModel->version() != TFLITE_SCHEMA_VERSION) + { + Serial.println("Model schema mismatch!"); + while (1) + ; + } + + // Create an interpreter to run the model + tflInterpreter = new (interpreterBuffer) tflite::MicroInterpreter(tflModel, tflOpsResolver, tensorArena, tensorArenaSize, &tflErrorReporter); + + // Allocate memory for the model's input and output tensors + tflInterpreter->AllocateTensors(); + + // Get pointers for the model's input and output tensors + tflInputTensor = tflInterpreter->input(0); + tflOutputTensor = tflInterpreter->output(0); + + isModelLoaded = true; + } + +/************************************************************************ +* Life cycle +************************************************************************/ + + // #define DEBUG - uncomment to log out each capture as CSV + + void update(float buffer[]) + { + + + int now = millis(); + + if (samplesRead == numSamples) + { + + // Honor captureDelay setting + if(now - lastCaptureTimestamp < captureDelay){ + return; + } + + const float aSum = (fabs(buffer[0]) + fabs(buffer[1]) + fabs(buffer[2]) + fabs(buffer[3]) + fabs(buffer[4]) + fabs(buffer[5])) / 6.0; + + // check if it's above the threshold + if (aSum >= accelerationThreshold) + { + #ifdef DEBUG + Serial.println("Capture started:"); + Serial.println("ax,ay,az,gx,gy,gz,mx,my,mz"); + #endif + + // reset the sample read count + samplesRead = 0; + maxVelocity = 0.; + } + } + + if (samplesRead < numSamples) + { + const int dataLen = disableMagnetometer ? 6 : 9; + + #ifdef DEBUG + for(int j = 0; j < dataLen; j++){ + Serial.print(buffer[j], 16); + if(j < dataLen - 1){ + Serial.print(","); + } + } + Serial.println(); + #endif + + const float velocity = (fabs(buffer[0]) + fabs(buffer[1]) + fabs(buffer[2])) / 3.0; + maxVelocity = max(maxVelocity, velocity); + + tflInputTensor->data.f[samplesRead * dataLen + 0] = buffer[0]; + tflInputTensor->data.f[samplesRead * dataLen + 1] = buffer[1]; + tflInputTensor->data.f[samplesRead * dataLen + 2] = buffer[2]; + tflInputTensor->data.f[samplesRead * dataLen + 3] = buffer[3]; + tflInputTensor->data.f[samplesRead * dataLen + 4] = buffer[4]; + tflInputTensor->data.f[samplesRead * dataLen + 5] = buffer[5]; + if(!disableMagnetometer){ + tflInputTensor->data.f[samplesRead * dataLen + 6] = buffer[6]; + tflInputTensor->data.f[samplesRead * dataLen + 7] = buffer[7]; + tflInputTensor->data.f[samplesRead * dataLen + 8] = buffer[8]; + } + + samplesRead++; + + if (samplesRead == numSamples) + { + // Run inferencing + TfLiteStatus invokeStatus = tflInterpreter->Invoke(); + if (invokeStatus != kTfLiteOk) + { + Serial.println("Invoke failed!"); + while (1) + ; + return; + } + #ifdef DEBUG + Serial.println(); + Serial.println("-----------------------------------------"); + #endif + + // Loop through the output tensor values from the model + unsigned char maxIndex = 0; + float maxValue = 0; + for (int i = 0; i < numClasses; i++) + { + float _value = tflOutputTensor->data.f[i]; + Serial.print("class: "); + Serial.println(i); + Serial.print(" score: "); + Serial.println(_value, 6); + + if (_value > maxValue) + { + maxValue = _value; + maxIndex = i; + } + } + + // callback + unsigned char velocity = (unsigned char )(((maxVelocity - accelerationThreshold) / (1.0 - accelerationThreshold)) * 255.999); + unsigned char score = (unsigned char)(maxValue * 255.999); + + model_tester_onInference(maxIndex, score, velocity); + + Serial.print("Winner: "); + Serial.print(maxIndex); + + // timestamp to follow the capture delay setting + lastCaptureTimestamp = now; + } + } + } + + void runTest(float *data, int len){ + const int numTests = len / numSamples; + const int dataLen = disableMagnetometer ? 6 : 9; + samplesRead = numSamples; + const int tmpCaptureDelay = captureDelay; + captureDelay = 0; + for(int i = 0; i < len; i+= dataLen){ + if(disableMagnetometer){ + float buffer[] = { + data[i + 0], + data[i + 1], + data[i + 2], + data[i + 3], + data[i + 4], + data[i + 5] + }; + update(buffer); + } else { + float buffer[] = { + data[i + 0], + data[i + 1], + data[i + 2], + data[i + 3], + data[i + 4], + data[i + 5], + data[i + 6], + data[i + 7], + data[i + 8] + }; + + //update(buffer); + } + } + + captureDelay = tmpCaptureDelay; + } +} diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.h b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.h new file mode 100644 index 00000000..50056b07 --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/model_tester.h @@ -0,0 +1,43 @@ +/* Copyright 2021 Google LLC + +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 + + https://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. +==============================================================================*/ + +#ifndef MODEL_TESTER_CPP +#define MODEL_TESTER_CPP + +#include +#include +#include +#include +#include +#include + +// Forward declare the function that will be called when data has been delivered to us. +void model_tester_onInference(unsigned char classIndex, unsigned char score, unsigned char velocity); + +namespace model_tester { + void loadModel(unsigned char model[]); + void update(float buffer[]); + extern bool isModelLoaded; + + // Setters + void setCaptureDelay(int val); + void setNumSamples(int val); + void setThreshold(float val); + void setNumClasses(unsigned char val); + void setDisableMagnetometer(bool val); + void runTest(float *testData, int len); +} + +#endif diff --git a/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/tf4micro-motion-kit.ino b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/tf4micro-motion-kit.ino new file mode 100644 index 00000000..686c6c1a --- /dev/null +++ b/libraries/Bluefruit52Lib/examples/Peripheral/tf4micro-motion-kit/tf4micro-motion-kit.ino @@ -0,0 +1,591 @@ +/* Copyright 2021 Google LLC + +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 + + https://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. +==============================================================================*/ + +/* +* @author Rikard Lindstrom +*/ + +#define VERSION 5 +#define FLOAT_BYTE_SIZE 4 + +//#include + +#include +#include +#include + +//#include "ble_file_transfer.h" +#include "model_tester.h" +#include "data_provider.h" + +/************************************************************************ +* State +************************************************************************/ + +enum State +{ + IDLE_DISCONNECTED, // Arduino was just turned on + IDLE_CONNECTED, // BLE was connected + FILE_TRANSFER, // File transfer mode + INFERENCE, // Inference is happening and published + IMU_DATA_PROVIDER, // Send IMU data over BLE for IMU Trainer + ERROR_STATE, // Something went wrong, + CALIBRATION, // Calibrate Magnetometer position + INFERENCE_AND_DATA_PROVIDER // both inference and IMU Data +}; + +State currentState = IDLE_DISCONNECTED; +State prevState = IDLE_DISCONNECTED; + +enum FileTransferType +{ + MODEL_FILE, + TEST_FILE +}; + +FileTransferType fileTransferType = MODEL_FILE; + +/************************************************************************ +* Globals / General +************************************************************************/ +bool useMagnetometer = false; // Can be toggled with BLE (disableMagnetometerRx) + +Adafruit_NeoPixel neopixels = Adafruit_NeoPixel(NEOPIXEL_NUM, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800); + +/************************************************************************ +* BLE Characteristic / Service UUIDs +************************************************************************/ + +#define LOCAL_NAME "TF4Micro - Motion Kit" + +#define UUID_GEN(val) ("81c30e5c-" val "-4f7d-a886-de3e90749161") + +//BLEService service (UUID_GEN("0000")); +// +//BLECharacteristic dataProviderTxChar (UUID_GEN("1001"), BLERead | BLENotify, 9 * FLOAT_BYTE_SIZE); +//BLECharacteristic dataProviderLabelsTxChar (UUID_GEN("1002"), BLERead, 128); +//BLEUnsignedCharCharacteristic versionTxChar (UUID_GEN("1003"), BLERead); +//BLECharacteristic inferenceTxChar (UUID_GEN("1004"), BLERead | BLENotify, 3); +// +//BLEUnsignedCharCharacteristic numClassesRxChar (UUID_GEN("2001"), BLEWrite); +//BLEIntCharacteristic numSamplesRxChar (UUID_GEN("2002"), BLEWrite); +//BLEIntCharacteristic captureDelayRxChar (UUID_GEN("2003"), BLEWrite); +//BLEFloatCharacteristic thresholdRxChar (UUID_GEN("2004"), BLEWrite); +//BLEBoolCharacteristic disableMagnetometerRx (UUID_GEN("2005"), BLEWrite); +// +//BLEUnsignedCharCharacteristic stateRxChar (UUID_GEN("3001"), BLEWrite); +//BLEUnsignedCharCharacteristic stateTxChar (UUID_GEN("3002"), BLERead | BLENotify); +//BLEUnsignedCharCharacteristic fileTransferTypeRxChar (UUID_GEN("3003"), BLEWrite); +//BLEBoolCharacteristic hasModelTxChar (UUID_GEN("3004"), BLERead | BLENotify); +// +//// Meta is for future-proofing, we can use it to store and read any 64 bytes +//BLECharacteristic metaRxChar (UUID_GEN("4001"), BLEWrite, 64); +//BLECharacteristic metaTxChar (UUID_GEN("4002"), BLERead, 64); + +/************************************************************************ +* Model file transfer +************************************************************************/ + +uint8_t *newModelFileData = nullptr; +int newModelFileLength = 0; + +/************************************************************************ +* LED / State status functions +************************************************************************/ + +void rgbLedOff() +{ +// digitalWrite(LEDR, HIGH); +// digitalWrite(LEDG, HIGH); +// digitalWrite(LEDB, HIGH); +} + +void rgbLedYellow() +{ +// digitalWrite(LEDR, LOW); +// digitalWrite(LEDG, LOW); +// digitalWrite(LEDB, HIGH); +} + +void rgbLedRed() +{ +// digitalWrite(LEDR, LOW); +// digitalWrite(LEDG, HIGH); +// digitalWrite(LEDB, HIGH); +} + +void rgbLedGreen() +{ +// digitalWrite(LEDR, HIGH); +// digitalWrite(LEDG, LOW); +// digitalWrite(LEDB, HIGH); +} + +void rgbLedBlue() +{ +// digitalWrite(LEDR, HIGH); +// digitalWrite(LEDG, HIGH); +// digitalWrite(LEDB, LOW); +} + +void showErrorLed() +{ + // blink red + millis() % 1000 > 500 ? rgbLedOff() : rgbLedRed(); +} + +void updateLed() +{ + switch (currentState) + { + + case FILE_TRANSFER: +#if 0 + if (ble_file_transfer::isTransfering()) +#else + if (0) +#endif + { + // Rapid blink while transfering is in progress + millis() % 100 > 50 ? rgbLedOff() : rgbLedYellow(); + } + else + { + rgbLedYellow(); + } + break; + + case INFERENCE: + rgbLedGreen(); + break; + + case IMU_DATA_PROVIDER: + rgbLedBlue(); + break; + + case INFERENCE_AND_DATA_PROVIDER: + millis() % 800 > 400 ? rgbLedBlue() : rgbLedGreen(); + break; + + case ERROR_STATE: + showErrorLed(); + break; + + case CALIBRATION: + millis() % 100 > 50 ? rgbLedOff() : rgbLedGreen(); + break; + + case IDLE_DISCONNECTED: + case IDLE_CONNECTED: + default: +#if 0 + if (BLE.connected()) +#else + if (1) +#endif + { + rgbLedBlue(); + } + else + { + // Blink yellow at a .5 second interval + const int now = millis(); + if (now % 1000 > 800) + { + rgbLedOff(); + } + else + { + int blinkStep = floor(now % 3000); + switch (blinkStep) + { + case 0: + rgbLedRed(); + break; + case 1000: + rgbLedGreen(); + break; + case 2000: + rgbLedBlue(); + break; + } + } + } + break; + } +} + +void setState(State state) +{ + if (state != prevState && state != currentState) + { + prevState = currentState; + } + currentState = state; +#if 0 + stateTxChar.writeValue((unsigned char)state); +#endif + switch (currentState) + { + case IDLE_DISCONNECTED: + Serial.println("state is now IDLE_DISCONNECTED"); + break; + case IDLE_CONNECTED: + Serial.println("state is now IDLE_CONNECTED"); + break; + case FILE_TRANSFER: + Serial.println("state is now FILE_TRANSFER"); + break; + case IMU_DATA_PROVIDER: + Serial.println("state is now IMU_DATA_PROVIDER"); + break; + case ERROR_STATE: + Serial.println("state is now ERROR_STATE"); + break; + case CALIBRATION: + data_provider::calibrate(); + Serial.println("state is now CALIBRATION"); + break; + case INFERENCE_AND_DATA_PROVIDER: + Serial.println("state is now INFERENCE_AND_DATA_PROVIDER"); + break; + default: + Serial.println("Error: Unknown state"); + } +} + +/************************************************************************ +* BLE Event handlers +************************************************************************/ + +#if 0 +void handleNumSamplesRxWritten(BLEDevice central, BLECharacteristic characteristic) +{ + model_tester::setNumSamples(numSamplesRxChar.value()); + Serial.print("Received numSamples: "); + Serial.println(numSamplesRxChar.value()); +} + +void handleThresholdRxWritten(BLEDevice central, BLECharacteristic characteristic) +{ + model_tester::setThreshold(thresholdRxChar.value()); + Serial.print("Received threshold: "); + Serial.println(thresholdRxChar.value(), 4); +} + +void handleCaptureDelayRxWritten(BLEDevice central, BLECharacteristic characteristic) +{ + model_tester::setCaptureDelay(captureDelayRxChar.value()); + Serial.print("Received delay: "); + Serial.println(captureDelayRxChar.value()); +} + +void handleNumClassesRxWritten(BLEDevice central, BLECharacteristic characteristic) +{ + model_tester::setNumClasses(numClassesRxChar.value()); + Serial.print("Received numClasses: "); + Serial.println(numClassesRxChar.value()); +} + +void handleDisableMagnetometerRxWritten(BLEDevice central, BLECharacteristic characteristic) +{ + bool val = disableMagnetometerRx.value(); + model_tester::setDisableMagnetometer(val); + + useMagnetometer = !val; + + Serial.print("Received disableMagnetometer: "); + Serial.println(disableMagnetometerRx.value()); +} + +void handleStateWritten(BLEDevice central, BLECharacteristic characteristic) +{ + setState((State)stateRxChar.value()); + Serial.print("Received state: "); + Serial.println(stateRxChar.value()); +} + +void handleMetaWritten(BLEDevice central, BLECharacteristic characteristic) +{ + // Meta is just a 64 byte storage for anything, just publish it + byte values[64]; + metaRxChar.readValue(values, 64); + metaTxChar.writeValue(values, 64); +} + +void handleFileTransferTypeWritten(BLEDevice central, BLECharacteristic characteristic) +{ + fileTransferType = (FileTransferType)fileTransferTypeRxChar.value(); + Serial.print("Received fileTransferType: "); + Serial.println(fileTransferType); +} +#endif + +/************************************************************************ +* Callbacks +************************************************************************/ + +// called on inference (gesture detected) +void model_tester_onInference(unsigned char classIndex, unsigned char score, unsigned char velocity) +{ + const byte buffer[]{classIndex, score, velocity}; +#if 0 + inferenceTxChar.setValue(buffer, 3); +#endif + Serial.print("Inference - class: "); + Serial.print(classIndex); + Serial.print(" score: "); + Serial.println(score); +} + +// called when calibration completes +void data_provider_calibrationComplete(){ + setState(prevState); +} + +// called on file transfer complete +void onBLEFileReceived(uint8_t *file_data, int file_length) +{ + switch (fileTransferType) + { + case MODEL_FILE: + // Queue up the model swap + newModelFileData = file_data; + newModelFileLength = file_length; + break; + case TEST_FILE: + { + int floatLength = file_length / 4; + float buffer[floatLength]; + for (int i = 0; i < file_length; i += 4) + { + union u_tag + { + byte b[4]; + float fval; + } u; + + u.b[0] = file_data[i + 0]; + u.b[1] = file_data[i + 1]; + u.b[2] = file_data[i + 2]; + u.b[3] = file_data[i + 3]; + + buffer[i / 4] = u.fval; + } + // set state to inference so we can capture result + setState(INFERENCE); + model_tester::runTest(buffer, floatLength); + } + break; + default: + Serial.println("Error: unkown file type"); + setState(ERROR_STATE); + while (0) updateLed(); + } +} + +/************************************************************************ +* Main / Lifecycle +************************************************************************/ + +void setup() +{ + + Serial.begin(9600); + const int startTime = millis(); + + // Give serial port 2 second to connect. + while (!Serial && millis() - startTime < 2000) + yield(); + + // Prepare LED pins. + pinMode(LED_BUILTIN, OUTPUT); + neopixels.begin(); + + // Start IMU / Data provider. + if (!data_provider::setup()) + { + Serial.println("Failed to initialize IMU!"); + while (1) showErrorLed(); + } +#if 0 + service.addCharacteristic(versionTxChar); + service.addCharacteristic(dataProviderTxChar); + service.addCharacteristic(dataProviderLabelsTxChar); + service.addCharacteristic(inferenceTxChar); + + service.addCharacteristic(numClassesRxChar); + service.addCharacteristic(numSamplesRxChar); + service.addCharacteristic(captureDelayRxChar); + service.addCharacteristic(thresholdRxChar); + service.addCharacteristic(disableMagnetometerRx); + + service.addCharacteristic(stateRxChar); + service.addCharacteristic(stateTxChar); + service.addCharacteristic(fileTransferTypeRxChar); + service.addCharacteristic(hasModelTxChar); + + service.addCharacteristic(metaRxChar); + service.addCharacteristic(metaTxChar); + + // Event driven reads. + numClassesRxChar.setEventHandler(BLEWritten, handleNumClassesRxWritten); + numSamplesRxChar.setEventHandler(BLEWritten, handleNumSamplesRxWritten); + thresholdRxChar.setEventHandler(BLEWritten, handleThresholdRxWritten); + captureDelayRxChar.setEventHandler(BLEWritten, handleCaptureDelayRxWritten); + stateRxChar.setEventHandler(BLEWritten, handleStateWritten); + fileTransferTypeRxChar.setEventHandler(BLEWritten, handleFileTransferTypeWritten); + metaRxChar.setEventHandler(BLEWritten, handleMetaWritten); + disableMagnetometerRx.setEventHandler(BLEWritten, handleDisableMagnetometerRxWritten); + + // Start the core BLE engine. + if (!BLE.begin()) + { + Serial.println("Failed to initialized BLE!"); + setState(ERROR_STATE); + while (1) showErrorLed(); + } +#endif + +#if 0 + String address = BLE.address(); + + // Output BLE settings over Serial. + Serial.print("address = "); + Serial.println(address); + + address.toUpperCase(); + + static String deviceName = LOCAL_NAME; + deviceName += " - "; + deviceName += address[address.length() - 5]; + deviceName += address[address.length() - 4]; + deviceName += address[address.length() - 2]; + deviceName += address[address.length() - 1]; + + Serial.print("deviceName = "); + Serial.println(deviceName); + + Serial.print("localName = "); + Serial.println(deviceName); + + // Set up properties for the whole service. + BLE.setLocalName(deviceName.c_str()); + BLE.setDeviceName(deviceName.c_str()); + BLE.setAdvertisedService(service); + + ble_file_transfer::setupBLEFileTransfer(service); + + // Print out full UUID and MAC address. + Serial.println("Peripheral advertising info: "); + Serial.print("Name: "); + Serial.println(LOCAL_NAME); + Serial.print("MAC: "); + Serial.println(BLE.address()); + Serial.print("Service UUID: "); + Serial.println(service.uuid()); + + // Start up the service itself. + BLE.addService(service); + BLE.advertise(); + + Serial.println("Bluetooth device active, waiting for connections..."); + + // Broadcast sketch version + versionTxChar.writeValue(VERSION); + + // Used for Tiny Motion Trainer to label / filter values + dataProviderLabelsTxChar.writeValue("acc.x, acc.y, acc.z, gyro.x, gyro.y, gyro.z, mag.x, mag.y, max.zl"); +#endif +} + +inline void updateIMU() +{ + const char bufferSize = useMagnetometer ? 9 : 6; + float buffer[bufferSize]; + while(data_provider::dataAvailable()){ + + // Collect the IMU data + data_provider::update(buffer, useMagnetometer); + + if(currentState == INFERENCE || currentState == INFERENCE_AND_DATA_PROVIDER){ + // if we have a model, do inference + if(model_tester::isModelLoaded){ + model_tester::update(buffer); + } + } +#if 0 + if(currentState == IMU_DATA_PROVIDER || currentState == INFERENCE_AND_DATA_PROVIDER){ + // provide data to IMU trainer + dataProviderTxChar.writeValue(buffer, bufferSize * FLOAT_BYTE_SIZE); + } +#endif + } +} + +inline void updateFileTransfer() +{ +#if 0 + // Update file transfer state + ble_file_transfer::updateBLEFileTransfer(); + + // Check if we should load a new model + if (newModelFileData != nullptr) + { + Serial.println("reloading model"); + model_tester::loadModel(newModelFileData); + Serial.println("done reloading model"); + newModelFileData = nullptr; + + hasModelTxChar.writeValue(true); + + // We have a new model, always enter INFERENCE mode + setState(INFERENCE); + } +#endif +} + +void loop() +{ +#if 0 + // Make sure we're connected and not busy file-transfering + if (BLE.connected()) + { + switch (currentState) + { + case FILE_TRANSFER: + updateFileTransfer(); + break; + + case CALIBRATION: + case IMU_DATA_PROVIDER: + case INFERENCE_AND_DATA_PROVIDER: + case INFERENCE: + if(!ble_file_transfer::isTransfering()){ + updateIMU(); + } + break; + + default: + break; + } + } else if(currentState != IDLE_DISCONNECTED){ + setState(IDLE_DISCONNECTED); + } +#endif + + // Update led based on state + updateLed(); +} diff --git a/platform.txt b/platform.txt index 76e75032..2087a3b5 100644 --- a/platform.txt +++ b/platform.txt @@ -71,10 +71,10 @@ compiler.libraries.ldflags= compiler.elf2bin.extra_flags= compiler.elf2hex.extra_flags= -compiler.arm.cmsis.c.flags="-I{runtime.tools.CMSIS-5.4.0.path}/CMSIS/Core/Include/" "-I{runtime.tools.CMSIS-5.4.0.path}/CMSIS/DSP/Include/" +compiler.arm.cmsis.c.flags="-I{runtime.tools.CMSIS-5.7.0.path}/CMSIS/Core/Include/" "-I{runtime.tools.CMSIS-5.7.0.path}/CMSIS/DSP/Include/" # TODO enable linking with libmath later on -compiler.arm.cmsis.ldflags="-L{runtime.tools.CMSIS-5.4.0.path}/CMSIS/Lib/GCC/" -larm_cortexM4lf_math +compiler.arm.cmsis.ldflags="-L{runtime.tools.CMSIS-5.7.0.path}/CMSIS/DSP/Lib/GCC/" -larm_cortexM4lf_math # common compiler for nrf rtos.path={build.core.path}/freertos @@ -100,7 +100,7 @@ recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU= recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}" ## Combine gc-sections, archives, and objects -recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-L{build.core.path}/linker" "-T{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} -Wl,--start-group -lm "{build.path}/{archive_file}" {compiler.libraries.ldflags} -Wl,--end-group +recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" "-L{build.path}" {compiler.c.elf.flags} {compiler.c.elf.extra_flags} "-L{build.core.path}/linker" "-T{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.ldflags} {compiler.arm.cmsis.ldflags} -o "{build.path}/{build.project_name}.elf" {object_files} -Wl,--start-group -lm "{build.path}/{archive_file}" {compiler.libraries.ldflags} -Wl,--end-group ## Create output (bin file) #recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2bin.cmd}" {compiler.elf2bin.flags} {compiler.elf2bin.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"