C
Add files via upload
Jobit Josephc888cb62b2c2
diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/app_channel.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/app_channel.cnew file mode 100644index 0000000..2914a95--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/app_channel.c@@ -0,0 +1,105 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * LPS node firmware.+ *+ * Copyright 2020, Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Lesser General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * Foobar is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with Foobar. If not, see <http://www.gnu.org/licenses/>.+ */+/* app_channel.c: App realtime communication channel with the ground */++#include "app_channel.h"++#include <string.h>++#include "FreeRTOS.h"+#include "semphr.h"+#include "queue.h"++#include "crtp.h"+#include "platformservice.h"+#include "stm32_legacy.h"++static SemaphoreHandle_t sendMutex;++static xQueueHandle rxQueue;++static bool overflow;++void appchannelSendPacket(void* data, size_t length)+{+ static CRTPPacket packet;++ xSemaphoreTake(sendMutex, portMAX_DELAY);++ packet.size = (length > APPCHANNEL_MTU)?APPCHANNEL_MTU:length;+ memcpy(packet.data, data, packet.size);++ // CRTP channel and ports are set in platformservice+ platformserviceSendAppchannelPacket(&packet);++ xSemaphoreGive(sendMutex);+}++size_t appchannelReceivePacket(void* buffer, size_t max_length, int timeout_ms) {+ static CRTPPacket packet;+ int tickToWait = 0;++ if (timeout_ms < 0) {+ tickToWait = portMAX_DELAY;+ } else {+ tickToWait = M2T(timeout_ms);+ }++ int result = xQueueReceive(rxQueue, &packet, tickToWait);++ if (result == pdTRUE) {+ int lenghtToCopy = (max_length < packet.size)?max_length:packet.size;+ memcpy(buffer, packet.data, lenghtToCopy);+ return lenghtToCopy;+ } else {+ return 0;+ }+}++bool appchannelHasOverflowOccured()+{+ bool hasOverflowed = overflow;+ overflow = false;++ return hasOverflowed;+}++void appchannelInit()+{+ sendMutex = xSemaphoreCreateMutex();++ rxQueue = xQueueCreate(10, sizeof(CRTPPacket));++ overflow = false;+}++void appchannelIncomingPacket(CRTPPacket *p)+{+ int res = xQueueSend(rxQueue, p, 0);++ if (res != pdTRUE) {+ overflow = true;+ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/app_handler.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/app_handler.cnew file mode 100644index 0000000..69d1c45--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/app_handler.c@@ -0,0 +1,70 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * LPS node firmware.+ *+ * Copyright 2019, Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Lesser General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * Foobar is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with Foobar. If not, see <http://www.gnu.org/licenses/>.+ */+/* app_handler.c: App layer handling function implementation */++#include <stdbool.h>++#include "FreeRTOS.h"+#include "task.h"++#include "system.h"+#include "static_mem.h"++#include "app.h"++#ifndef APP_STACKSIZE+#define APP_STACKSIZE 300+#endif++#ifndef APP_PRIORITY+#define APP_PRIORITY 0+#endif++static bool isInit = false;++STATIC_MEM_TASK_ALLOC(appTask, APP_STACKSIZE);++static void appTask(void *param);++void __attribute__((weak)) appInit()+{+ if (isInit) {+ return;+ }++ STATIC_MEM_TASK_CREATE(appTask, appTask, "app", NULL, APP_PRIORITY);+ isInit = true;+}++static void appTask(void *param)+{+ systemWaitStart();++ appMain();++ while(1) {+ vTaskDelay(portMAX_DELAY);+ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/attitude_pid_controller.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/attitude_pid_controller.cnew file mode 100644index 0000000..b7d707e--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/attitude_pid_controller.c@@ -0,0 +1,211 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * attitude_pid_controller.c: Attitude controler using PID correctors+ */+#include <stdbool.h>++#include "FreeRTOS.h"++#include "attitude_controller.h"+#include "pid.h"+#include "param.h"+#include "log.h"++#define ATTITUDE_LPF_CUTOFF_FREQ 15.0f+#define ATTITUDE_LPF_ENABLE false+#define ATTITUDE_RATE_LPF_CUTOFF_FREQ 30.0f+#define ATTITUDE_RATE_LPF_ENABLE false+++static inline int16_t saturateSignedInt16(float in)+{+ // don't use INT16_MIN, because later we may negate it, which won't work for that value.+ if (in > INT16_MAX)+ return INT16_MAX;+ else if (in < -INT16_MAX)+ return -INT16_MAX;+ else+ return (int16_t)in;+}++PidObject pidRollRate;+PidObject pidPitchRate;+PidObject pidYawRate;+PidObject pidRoll;+PidObject pidPitch;+PidObject pidYaw;++static int16_t rollOutput;+static int16_t pitchOutput;+static int16_t yawOutput;++static bool isInit;++void attitudeControllerInit(const float updateDt)+{+ if(isInit)+ return;++ //TODO: get parameters from configuration manager instead+ pidInit(&pidRollRate, 0, PID_ROLL_RATE_KP, PID_ROLL_RATE_KI, PID_ROLL_RATE_KD,+ updateDt, ATTITUDE_RATE, ATTITUDE_RATE_LPF_CUTOFF_FREQ, ATTITUDE_RATE_LPF_ENABLE);+ pidInit(&pidPitchRate, 0, PID_PITCH_RATE_KP, PID_PITCH_RATE_KI, PID_PITCH_RATE_KD,+ updateDt, ATTITUDE_RATE, ATTITUDE_RATE_LPF_CUTOFF_FREQ, ATTITUDE_RATE_LPF_ENABLE);+ pidInit(&pidYawRate, 0, PID_YAW_RATE_KP, PID_YAW_RATE_KI, PID_YAW_RATE_KD,+ updateDt, ATTITUDE_RATE, ATTITUDE_RATE_LPF_CUTOFF_FREQ, ATTITUDE_RATE_LPF_ENABLE);++ pidSetIntegralLimit(&pidRollRate, PID_ROLL_RATE_INTEGRATION_LIMIT);+ pidSetIntegralLimit(&pidPitchRate, PID_PITCH_RATE_INTEGRATION_LIMIT);+ pidSetIntegralLimit(&pidYawRate, PID_YAW_RATE_INTEGRATION_LIMIT);++ pidInit(&pidRoll, 0, PID_ROLL_KP, PID_ROLL_KI, PID_ROLL_KD, updateDt,+ ATTITUDE_RATE, ATTITUDE_LPF_CUTOFF_FREQ, ATTITUDE_LPF_ENABLE);+ pidInit(&pidPitch, 0, PID_PITCH_KP, PID_PITCH_KI, PID_PITCH_KD, updateDt,+ ATTITUDE_RATE, ATTITUDE_LPF_CUTOFF_FREQ, ATTITUDE_LPF_ENABLE);+ pidInit(&pidYaw, 0, PID_YAW_KP, PID_YAW_KI, PID_YAW_KD, updateDt,+ ATTITUDE_RATE, ATTITUDE_LPF_CUTOFF_FREQ, ATTITUDE_LPF_ENABLE);++ pidSetIntegralLimit(&pidRoll, PID_ROLL_INTEGRATION_LIMIT);+ pidSetIntegralLimit(&pidPitch, PID_PITCH_INTEGRATION_LIMIT);+ pidSetIntegralLimit(&pidYaw, PID_YAW_INTEGRATION_LIMIT);++ isInit = true;+}++bool attitudeControllerTest()+{+ return isInit;+}++void attitudeControllerCorrectRatePID(+ float rollRateActual, float pitchRateActual, float yawRateActual,+ float rollRateDesired, float pitchRateDesired, float yawRateDesired)+{+ pidSetDesired(&pidRollRate, rollRateDesired);+ rollOutput = saturateSignedInt16(pidUpdate(&pidRollRate, rollRateActual, true));++ pidSetDesired(&pidPitchRate, pitchRateDesired);+ pitchOutput = saturateSignedInt16(pidUpdate(&pidPitchRate, pitchRateActual, true));++ pidSetDesired(&pidYawRate, yawRateDesired);+ yawOutput = saturateSignedInt16(pidUpdate(&pidYawRate, yawRateActual, true));+}++void attitudeControllerCorrectAttitudePID(+ float eulerRollActual, float eulerPitchActual, float eulerYawActual,+ float eulerRollDesired, float eulerPitchDesired, float eulerYawDesired,+ float* rollRateDesired, float* pitchRateDesired, float* yawRateDesired)+{+ pidSetDesired(&pidRoll, eulerRollDesired);+ *rollRateDesired = pidUpdate(&pidRoll, eulerRollActual, true);++ // Update PID for pitch axis+ pidSetDesired(&pidPitch, eulerPitchDesired);+ *pitchRateDesired = pidUpdate(&pidPitch, eulerPitchActual, true);++ // Update PID for yaw axis+ float yawError;+ yawError = eulerYawDesired - eulerYawActual;+ if (yawError > 180.0f)+ yawError -= 360.0f;+ else if (yawError < -180.0f)+ yawError += 360.0f;+ pidSetError(&pidYaw, yawError);+ *yawRateDesired = pidUpdate(&pidYaw, eulerYawActual, false);+}++void attitudeControllerResetRollAttitudePID(void)+{+ pidReset(&pidRoll);+}++void attitudeControllerResetPitchAttitudePID(void)+{+ pidReset(&pidPitch);+}++void attitudeControllerResetAllPID(void)+{+ pidReset(&pidRoll);+ pidReset(&pidPitch);+ pidReset(&pidYaw);+ pidReset(&pidRollRate);+ pidReset(&pidPitchRate);+ pidReset(&pidYawRate);+}++void attitudeControllerGetActuatorOutput(int16_t* roll, int16_t* pitch, int16_t* yaw)+{+ *roll = rollOutput;+ *pitch = pitchOutput;+ *yaw = yawOutput;+}++LOG_GROUP_START(pid_attitude)+LOG_ADD(LOG_FLOAT, roll_outP, &pidRoll.outP)+LOG_ADD(LOG_FLOAT, roll_outI, &pidRoll.outI)+LOG_ADD(LOG_FLOAT, roll_outD, &pidRoll.outD)+LOG_ADD(LOG_FLOAT, pitch_outP, &pidPitch.outP)+LOG_ADD(LOG_FLOAT, pitch_outI, &pidPitch.outI)+LOG_ADD(LOG_FLOAT, pitch_outD, &pidPitch.outD)+LOG_ADD(LOG_FLOAT, yaw_outP, &pidYaw.outP)+LOG_ADD(LOG_FLOAT, yaw_outI, &pidYaw.outI)+LOG_ADD(LOG_FLOAT, yaw_outD, &pidYaw.outD)+LOG_GROUP_STOP(pid_attitude)++LOG_GROUP_START(pid_rate)+LOG_ADD(LOG_FLOAT, roll_outP, &pidRollRate.outP)+LOG_ADD(LOG_FLOAT, roll_outI, &pidRollRate.outI)+LOG_ADD(LOG_FLOAT, roll_outD, &pidRollRate.outD)+LOG_ADD(LOG_FLOAT, pitch_outP, &pidPitchRate.outP)+LOG_ADD(LOG_FLOAT, pitch_outI, &pidPitchRate.outI)+LOG_ADD(LOG_FLOAT, pitch_outD, &pidPitchRate.outD)+LOG_ADD(LOG_FLOAT, yaw_outP, &pidYawRate.outP)+LOG_ADD(LOG_FLOAT, yaw_outI, &pidYawRate.outI)+LOG_ADD(LOG_FLOAT, yaw_outD, &pidYawRate.outD)+LOG_GROUP_STOP(pid_rate)++PARAM_GROUP_START(pid_attitude)+PARAM_ADD(PARAM_FLOAT, roll_kp, &pidRoll.kp)+PARAM_ADD(PARAM_FLOAT, roll_ki, &pidRoll.ki)+PARAM_ADD(PARAM_FLOAT, roll_kd, &pidRoll.kd)+PARAM_ADD(PARAM_FLOAT, pitch_kp, &pidPitch.kp)+PARAM_ADD(PARAM_FLOAT, pitch_ki, &pidPitch.ki)+PARAM_ADD(PARAM_FLOAT, pitch_kd, &pidPitch.kd)+PARAM_ADD(PARAM_FLOAT, yaw_kp, &pidYaw.kp)+PARAM_ADD(PARAM_FLOAT, yaw_ki, &pidYaw.ki)+PARAM_ADD(PARAM_FLOAT, yaw_kd, &pidYaw.kd)+PARAM_GROUP_STOP(pid_attitude)++PARAM_GROUP_START(pid_rate)+PARAM_ADD(PARAM_FLOAT, roll_kp, &pidRollRate.kp)+PARAM_ADD(PARAM_FLOAT, roll_ki, &pidRollRate.ki)+PARAM_ADD(PARAM_FLOAT, roll_kd, &pidRollRate.kd)+PARAM_ADD(PARAM_FLOAT, pitch_kp, &pidPitchRate.kp)+PARAM_ADD(PARAM_FLOAT, pitch_ki, &pidPitchRate.ki)+PARAM_ADD(PARAM_FLOAT, pitch_kd, &pidPitchRate.kd)+PARAM_ADD(PARAM_FLOAT, yaw_kp, &pidYawRate.kp)+PARAM_ADD(PARAM_FLOAT, yaw_ki, &pidYawRate.ki)+PARAM_ADD(PARAM_FLOAT, yaw_kd, &pidYawRate.kd)+PARAM_GROUP_STOP(pid_rate)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/collision_avoidance.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/collision_avoidance.cnew file mode 100644index 0000000..d6bf499--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/collision_avoidance.c@@ -0,0 +1,371 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * collision_avoidance.c - Collision avoidance for multiple Crazyflies.+ *+ * Original author: James A. Preiss, University of Southern California, 2020.+ */++#include <float.h>+#include <string.h> // for memset++#include "collision_avoidance.h"+#include "peer_localization.h"+++// See header for API comments.+++// We must convert from stabilizer types to cmath3d types to get the library of+// math operations.+static struct vec vec2svec(struct vec3_s v)+{+ return mkvec(v.x, v.y, v.z);+}+static struct vec3_s svec2vec(struct vec v)+{+ struct vec3_s vv = { .x = v.x, .y = v.y, .z = v.z, };+ return vv;+}++// Computes a new goal position inside our buffered Voronoi cell.+//+// "Sidestep" dentoes a behavior to avoid deadlock when two robots are+// instructed to swap positions. When they approach a head-on collision, both+// will step to their right instead of stopping.+//+// Args:+// params: Algorithm parameters.+// goal: Goal position.+// modifyIfInside: Controls behavior when the goal is within our cell but the+// we are still close to the wall behind the the goal. In a position+// control mode, we should never modify the goal under this condition.+// However, in a velocity control mode, our best guess is that the velocity+// command will not change soon. Therefore, we are likely to hit that wall,+// so we should go ahead and begin the sidestep.+// A: LHS matrix for polytope inequality Ax <= B. Dimension [nRows * 3].+// B: RHS vector for polytope inequality Ax <= B. Dimension [nRows].+// projectionWorkspace: Additional scratch area. Dimension [nRows * 3].+// nRows: Number of rows in our cell polytope inequality.+//+static struct vec sidestepGoal(+ collision_avoidance_params_t const *params,+ struct vec goal,+ bool modifyIfInside,+ float const A[], float const B[], float projectionWorkspace[], int nRows)+{+ float const rayScale = rayintersectpolytope(vzero(), goal, A, B, nRows, NULL);+ if (rayScale >= 1.0f && !modifyIfInside) {+ return goal;+ }+ float const distance = vmag(goal);+ float const distFromWall = rayScale * distance;+ if (distFromWall <= params->sidestepThreshold) {+ struct vec sidestepDir = vcross(goal, mkvec(0.0f, 0.0f, 1.0f));+ float const sidestepAmount = fsqr(1.0f - distFromWall / params->sidestepThreshold);+ goal = vadd(goal, vscl(sidestepAmount, sidestepDir));+ }+ // Otherwise no sidestep, but still project+ return vprojectpolytope(+ goal,+ A, B, projectionWorkspace, nRows,+ params->voronoiProjectionTolerance,+ params->voronoiProjectionMaxIters+ );+}++void collisionAvoidanceUpdateSetpointCore(+ collision_avoidance_params_t const *params,+ collision_avoidance_state_t *collisionState,+ int nOthers,+ float const *otherPositions,+ float *workspace,+ setpoint_t *setpoint, sensorData_t const *sensorData, state_t const *state)+{+ //+ // Part 1: Construct the polytope inequalities in A, b.+ //++ int const nRows = nOthers + 6;+ float *A = workspace;+ float *B = workspace + 3 * nRows;+ float *projectionWorkspace = workspace + 4 * nRows;++ // Compute the cell in a stretched coordinate system for downwash awareness.+ // See header for details.+ struct vec const radiiInv = veltrecip(params->ellipsoidRadii);+ struct vec const ourPos = vec2svec(state->position);++ // We could do some optimizations here to reduce the number of rows, like+ // leave out very far away neighbors. It would help the average case+ // complexity, but not the worst case - so we skip it for now.+ for (int i = 0; i < nOthers; ++i) {+ struct vec peerPos = vloadf(otherPositions + 3 * i);+ struct vec const toPeerStretched = veltmul(vsub(peerPos, ourPos), radiiInv);+ float const dist = vmag(toPeerStretched);+ struct vec const a = vdiv(veltmul(toPeerStretched, radiiInv), dist);+ float const b = dist / 2.0f - 1.0f;+ float scale = 1.0f / vmag(a);+ vstoref(vscl(scale, a), A + 3 * i);+ B[i] = scale * b;+ }++ // Add the bounding box polytope faces. We also use the box faces to enforce+ // max speed in the infinity-norm.+ float const maxDist = params->horizonSecs * params->maxSpeed;++ memset(A + 3 * nOthers, 0, 18 * sizeof(float));++ for (int dim = 0; dim < 3; ++dim) {+ float boxMax = vindex(params->bboxMax, dim) - vindex(ourPos, dim);+ A[3 * (nOthers + dim) + dim] = 1.0f;+ B[nOthers + dim] = fminf(maxDist, boxMax);++ float boxMin = vindex(params->bboxMin, dim) - vindex(ourPos, dim);+ A[3 * (nOthers + dim + 3) + dim] = -1.0f;+ B[nOthers + dim + 3] = -fmaxf(-maxDist, boxMin);+ }++ //+ // Part 2: Use the constructed polytope to modify the setpoint.+ //++ float const inPolytopeTolerance = 10.0f * params->voronoiProjectionTolerance;++ struct vec setPos = vec2svec(setpoint->position);+ struct vec setVel = vec2svec(setpoint->velocity);++ if (setpoint->mode.x == modeVelocity) {+ // Interpret the setpoint to mean "fly with this velocity".++ if (vinpolytope(vzero(), A, B, nRows, inPolytopeTolerance)) {+ // Typical case - our current position is within our cell.+ struct vec pseudoGoal = vscl(params->horizonSecs, setVel);+ pseudoGoal = sidestepGoal(params, pseudoGoal, true, A, B, projectionWorkspace, nRows);+ if (vinpolytope(pseudoGoal, A, B, nRows, inPolytopeTolerance)) {+ setVel = vdiv(pseudoGoal, params->horizonSecs);+ }+ else {+ // Projection failed to converge. Best we can do is stay still.+ setVel = vzero();+ }+ }+ else {+ // Atypical case - our current position is not within our cell. Forget+ // about the original goal velocity and try to move towards our cell.+ struct vec nearestInCell = vprojectpolytope(+ vzero(),+ A, B, projectionWorkspace, nRows,+ params->voronoiProjectionTolerance,+ params->voronoiProjectionMaxIters+ );+ if (vinpolytope(nearestInCell, A, B, nRows, inPolytopeTolerance)) {+ setVel = vclampnorm(nearestInCell, params->maxSpeed);+ }+ else {+ // Projection failed to converge. Best we can do is stay still.+ setVel = vzero();+ }+ }+ collisionState->lastFeasibleSetPosition = ourPos;+ }+ else if (setpoint->mode.x == modeAbs) {++ struct vec const setPosRelative = vsub(setPos, ourPos);+ struct vec const setPosRelativeNew = sidestepGoal(+ params, setPosRelative, false, A, B, projectionWorkspace, nRows);++ if (!vinpolytope(setPosRelativeNew, A, B, nRows, inPolytopeTolerance)) {+ // If the projection algorithm failed to converge, then either+ // 1) The problem is infeasible, or+ // 2) The problem is somehow badly conditioned.+ // Case 2) is still effectively infeasible -- we're in a real-time system+ // with a fixed computation time budget, and we've already spent it.+ //+ // There's not a lot we can do if our buffered cell is empty. It means+ // someone failed to stay within their cell in the past. We choose to stay+ // a fixed position for as long as the cell is empty.+ setVel = vzero();+ if (!visnan(collisionState->lastFeasibleSetPosition)) {+ setPos = collisionState->lastFeasibleSetPosition;+ }+ else {+ // This case should never happen as long as collision avoidance is+ // initialized in a collision-free state, but we do something reasonable+ // just in case.+ setPos = ourPos;+ collisionState->lastFeasibleSetPosition = ourPos;+ }+ }+ else if (veq(setVel, vzero())) {+ // Position, but no velocity. Interpret as waypoint, not trajectory+ // tracking. "Go to this position and stop".+ setPos = vadd(ourPos, setPosRelativeNew);+ }+ else {+ // Position with nonzero velocity. Interpret as trajectory tracking.+ if (vneq(setPosRelative, setPosRelativeNew)) {+ // Set position is not within our cell. The situation has likely diverged+ // from the original plan, and the nonzero velocity is probably pointing+ // further away from our cell. Therefore, degrade to the v == 0 behavior.+ setPos = vadd(ourPos, setPosRelativeNew);+ setVel = vzero();+ }+ else {+ // Set position is within our cell. In case velocity would take us+ // outside the cell within the planning horizon, scale it appropriately.+ // See github issue #567 for more detailed discussion of this behavior.+ float const scale = rayintersectpolytope(setPosRelative, setVel, A, B, nRows, NULL);+ if (scale < 1.0f) {+ setVel = vscl(scale, setVel);+ }+ // leave setPos unchanged.+ }+ }+ collisionState->lastFeasibleSetPosition = setPos;+ }+ else {+ // Unsupported control mode, do nothing.+ }++ setpoint->position = svec2vec(setPos);+ setpoint->velocity = svec2vec(setVel);+}+++//+// Everything below this comment will only be compiled in a firware build made+// with the standard Makefile. Everything depending on FreeRTOS, ARM, params,+// etc. must go here.+//+#ifdef CRAZYFLIE_FW++#include "FreeRTOS.h"+#include "task.h"++#include "param.h"+#include "log.h"+++static uint8_t collisionAvoidanceEnable = 0;++static collision_avoidance_params_t params = {+ .ellipsoidRadii = { .x = 0.3, .y = 0.3, .z = 0.9 },+ .bboxMin = { .x = -FLT_MAX, .y = -FLT_MAX, .z = -FLT_MAX },+ .bboxMax = { .x = FLT_MAX, .y = FLT_MAX, .z = FLT_MAX },+ .horizonSecs = 1.0f,+ .maxSpeed = 0.5f, // Fairly conservative.+ .sidestepThreshold = 0.25f,+ .maxPeerLocAgeMillis = 5000, // Probably longer than desired in most applications.+ .voronoiProjectionTolerance = 1e-5,+ .voronoiProjectionMaxIters = 100,+};++static collision_avoidance_state_t collisionState = {+ .lastFeasibleSetPosition = { .x = NAN, .y = NAN, .z = NAN },+};++void collisionAvoidanceInit()+{+}++bool collisionAvoidanceTest()+{+ return true;+}++// Each face of the Voronoi cell is defined by a linear inequality a^T x <= b.+// The algorithm for projecting a point into a convex polytope requires 3 more+// floats of working space per face. The six extra faces come from the overall+// flight area bounding box.+#define MAX_CELL_ROWS (PEER_LOCALIZATION_MAX_NEIGHBORS + 6)+static float workspace[7 * MAX_CELL_ROWS];++// Latency counter for logging.+static uint32_t latency = 0;++void collisionAvoidanceUpdateSetpoint(+ setpoint_t *setpoint, sensorData_t const *sensorData, state_t const *state, uint32_t tick)+{+ if (!collisionAvoidanceEnable) {+ return;+ }++ TickType_t const time = xTaskGetTickCount();+ bool doAgeFilter = params.maxPeerLocAgeMillis >= 0;++ // Counts the actual number of neighbors after we filter stale measurements.+ int nOthers = 0;++ for (int i = 0; i < PEER_LOCALIZATION_MAX_NEIGHBORS; ++i) {++ peerLocalizationOtherPosition_t const *otherPos = peerLocalizationGetPositionByIdx(i);++ if (otherPos == NULL || otherPos->id == 0) {+ continue;+ }++ if (doAgeFilter && (time - otherPos->pos.timestamp > params.maxPeerLocAgeMillis)) {+ continue;+ }++ workspace[3 * nOthers + 0] = otherPos->pos.x;+ workspace[3 * nOthers + 1] = otherPos->pos.y;+ workspace[3 * nOthers + 2] = otherPos->pos.z;+ ++nOthers;+ }++ collisionAvoidanceUpdateSetpointCore(¶ms, &collisionState, nOthers, workspace, workspace, setpoint, sensorData, state);++ latency = xTaskGetTickCount() - time;+}++LOG_GROUP_START(colAv)+ LOG_ADD(LOG_UINT32, latency, &latency)+LOG_GROUP_STOP(colAv)+++PARAM_GROUP_START(colAv)+ PARAM_ADD(PARAM_UINT8, enable, &collisionAvoidanceEnable)++ PARAM_ADD(PARAM_FLOAT, ellipsoidX, ¶ms.ellipsoidRadii.x)+ PARAM_ADD(PARAM_FLOAT, ellipsoidY, ¶ms.ellipsoidRadii.y)+ PARAM_ADD(PARAM_FLOAT, ellipsoidZ, ¶ms.ellipsoidRadii.z)++ PARAM_ADD(PARAM_FLOAT, bboxMinX, ¶ms.bboxMin.x)+ PARAM_ADD(PARAM_FLOAT, bboxMinY, ¶ms.bboxMin.y)+ PARAM_ADD(PARAM_FLOAT, bboxMinZ, ¶ms.bboxMin.z)++ PARAM_ADD(PARAM_FLOAT, bboxMaxX, ¶ms.bboxMax.x)+ PARAM_ADD(PARAM_FLOAT, bboxMaxY, ¶ms.bboxMax.y)+ PARAM_ADD(PARAM_FLOAT, bboxMaxZ, ¶ms.bboxMax.z)++ PARAM_ADD(PARAM_FLOAT, horizon, ¶ms.horizonSecs)+ PARAM_ADD(PARAM_FLOAT, maxSpeed, ¶ms.maxSpeed)+ PARAM_ADD(PARAM_FLOAT, sidestepThrsh, ¶ms.sidestepThreshold)+ PARAM_ADD(PARAM_INT32, maxPeerLocAge, ¶ms.maxPeerLocAgeMillis)+ PARAM_ADD(PARAM_FLOAT, vorTol, ¶ms.voronoiProjectionTolerance)+ PARAM_ADD(PARAM_INT32, vorIters, ¶ms.voronoiProjectionMaxIters)+PARAM_GROUP_STOP(colAv)++#endif // CRAZYFLIE_FWdiff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/comm.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/comm.cnew file mode 100644index 0000000..6b03521--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/comm.c@@ -0,0 +1,90 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * comm.c - High level communication module+ */++#include <stdbool.h>+#define DEBUG_MODULE "COMM"+#include "comm.h"+#include "config.h"++#include "crtp.h"+#include "console.h"+#include "crtpservice.h"+#include "param.h"+#include "debug_cf.h"+#include "log.h"+#include "wifi_esp32.h"+#include "wifilink.h"+#include "platformservice.h"+#include "crtp_localization_service.h"++static bool isInit;++void commInit(void)+{+ if (isInit) {+ return;}++ /* These functions are moved to be initialized early so+ * that DEBUG_PRINTD can be used early */+ //wifilinkInit();+ //crtpInit();+ //consoleInit();++ crtpSetLink(wifilinkGetLink());+ crtpserviceInit();+ platformserviceInit();+ logInit();+ paramInit();+ //locSrvInit();++ //setup CRTP communication channel+ //TODO: check for USB first and prefer USB over radio+ //if (usbTest())+ // crtpSetLink(usbGetLink);+ //else if(radiolinkTest())+ // crtpSetLink(radiolinkGetLink());+ isInit = true;+}++bool commTest(void)+{+ bool pass = isInit;+ pass &= wifilinkTest();+ DEBUG_PRINTI("wifilinkTest = %d ", pass);+ pass &= crtpTest();+ DEBUG_PRINTI("crtpTest = %d ", pass);+ pass &= crtpserviceTest();+ DEBUG_PRINTI("crtpserviceTest = %d ", pass);+ pass &= platformserviceTest();+ DEBUG_PRINTI("platformserviceTest = %d ", pass);+ pass &= consoleTest();+ DEBUG_PRINTI("consoleTest = %d ", pass);+ pass &= paramTest();+ DEBUG_PRINTI("paramTest = %d ", pass);++ return pass;+}+diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/commander.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/commander.cnew file mode 100644index 0000000..7b008b3--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/commander.c@@ -0,0 +1,158 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */+#include <string.h>++#include "FreeRTOS.h"+#include "task.h"+#include "queue.h"++#include "commander.h"+#include "crtp_commander.h"+#include "crtp_commander_high_level.h"++#include "cf_math.h"+#include "param.h"+#include "stm32_legacy.h"+#include "static_mem.h"++static bool isInit;+const static setpoint_t nullSetpoint;+static setpoint_t tempSetpoint;+static state_t lastState;+const static int priorityDisable = COMMANDER_PRIORITY_DISABLE;++static uint32_t lastUpdate;+static bool enableHighLevel = false;++static QueueHandle_t setpointQueue;+STATIC_MEM_QUEUE_ALLOC(setpointQueue, 1, sizeof(setpoint_t));+static QueueHandle_t priorityQueue;+STATIC_MEM_QUEUE_ALLOC(priorityQueue, 1, sizeof(int));++/* Public functions */+void commanderInit(void)+{+ setpointQueue = STATIC_MEM_QUEUE_CREATE(setpointQueue);+ ASSERT(setpointQueue);+ xQueueSend(setpointQueue, &nullSetpoint, 0);++ priorityQueue = STATIC_MEM_QUEUE_CREATE(priorityQueue);+ ASSERT(priorityQueue);+ xQueueSend(priorityQueue, &priorityDisable, 0);++ crtpCommanderInit();+ crtpCommanderHighLevelInit();+ lastUpdate = xTaskGetTickCount();++ isInit = true;+}++void commanderSetSetpoint(setpoint_t *setpoint, int priority)+{+ int currentPriority;++ const BaseType_t peekResult = xQueuePeek(priorityQueue, ¤tPriority, 0);+ ASSERT(peekResult == pdTRUE);++ if (priority >= currentPriority) {+ setpoint->timestamp = xTaskGetTickCount();+ // This is a potential race but without effect on functionality+ xQueueOverwrite(setpointQueue, setpoint);+ xQueueOverwrite(priorityQueue, &priority);+ // Send the high-level planner to idle so it will forget its current state+ // and start over if we switch from low-level to high-level in the future.+ crtpCommanderHighLevelStop();+ }+}++void commanderNotifySetpointsStop(int remainValidMillisecs)+{+ uint32_t currentTime = xTaskGetTickCount();+ int timeSetback = MIN(+ COMMANDER_WDT_TIMEOUT_SHUTDOWN - M2T(remainValidMillisecs),+ currentTime+ );+ xQueuePeek(setpointQueue, &tempSetpoint, 0);+ tempSetpoint.timestamp = currentTime - timeSetback;+ xQueueOverwrite(setpointQueue, &tempSetpoint);+ crtpCommanderHighLevelTellState(&lastState);+}++void commanderGetSetpoint(setpoint_t *setpoint, const state_t *state)+{+ xQueuePeek(setpointQueue, setpoint, 0);+ lastUpdate = setpoint->timestamp;+ uint32_t currentTime = xTaskGetTickCount();++ if ((currentTime - setpoint->timestamp) > COMMANDER_WDT_TIMEOUT_SHUTDOWN) {+ if (enableHighLevel) {+ crtpCommanderHighLevelGetSetpoint(setpoint, state);+ }+ if (!enableHighLevel || crtpCommanderHighLevelIsStopped()) {+ memcpy(setpoint, &nullSetpoint, sizeof(nullSetpoint));+ }+ } else if ((currentTime - setpoint->timestamp) > COMMANDER_WDT_TIMEOUT_STABILIZE) {+ xQueueOverwrite(priorityQueue, &priorityDisable);+ // Leveling ...+ setpoint->mode.x = modeDisable;+ setpoint->mode.y = modeDisable;+ setpoint->mode.roll = modeAbs;+ setpoint->mode.pitch = modeAbs;+ setpoint->mode.yaw = modeVelocity;+ setpoint->attitude.roll = 0;+ setpoint->attitude.pitch = 0;+ setpoint->attitudeRate.yaw = 0;+ // Keep Z as it is+ }+ // This copying is not strictly necessary because stabilizer.c already keeps+ // a static state_t containing the most recent state estimate. However, it is+ // not accessible by the public interface.+ lastState = *state;+}++bool commanderTest(void)+{+ return isInit;+}++uint32_t commanderGetInactivityTime(void)+{+ return xTaskGetTickCount() - lastUpdate;+}++int commanderGetActivePriority(void)+{+ int priority;++ const BaseType_t peekResult = xQueuePeek(priorityQueue, &priority, 0);+ ASSERT(peekResult == pdTRUE);++ return priority;+}++PARAM_GROUP_START(commander)+PARAM_ADD(PARAM_UINT8, enHighLevel, &enableHighLevel)+PARAM_GROUP_STOP(commander)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/console.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/console.cnew file mode 100644index 0000000..0619a8a--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/console.c@@ -0,0 +1,196 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * console.c - Used to send console data to client+ */++#include <stdbool.h>+#include <string.h>++/*FreeRtos includes*/+#include "FreeRTOS.h"+#include "semphr.h"++#include "crtp.h"++#ifdef STM32F40_41xxx+#include "stm32f4xx.h"+#else+#include "stm32_legacy.h"+#ifndef SCB_ICSR_VECTACTIVE_Msk+#define SCB_ICSR_VECTACTIVE_Msk 0x1FFUL+#endif+#endif++static CRTPPacket messageToPrint;+static bool messageSendingIsPending = false;+static xSemaphoreHandle synch = NULL;++static const char bufferFullMsg[] = "<F>\n";+static bool isInit;++static void addBufferFullMarker();+++/**+ * Send the data to the client+ * returns TRUE if successful otherwise FALSE+ */+static bool consoleSendMessage(void)+{+ if (crtpSendPacket(&messageToPrint) == pdTRUE)+ {+ messageToPrint.size = 0;+ messageSendingIsPending = false;+ }+ else+ {+ return false;+ }++ return true;+}++void consoleInit()+{+ if (isInit)+ return;++ messageToPrint.size = 0;+ messageToPrint.header = CRTP_HEADER(CRTP_PORT_CONSOLE, 0);+ vSemaphoreCreateBinary(synch);+ messageSendingIsPending = false;++ isInit = true;+}++bool consoleTest(void)+{+ return isInit;+}++int consolePutchar(int ch)+{+ bool isInInterrupt = false; //bool isInInterrupt = (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0;++ if (!isInit) {+ return 0;+ }++ if (isInInterrupt) {+ return consolePutcharFromISR(ch);+ }++ if (xSemaphoreTake(synch, portMAX_DELAY) == pdTRUE)+ {+ // Try to send if we already have a pending message+ if (messageSendingIsPending)+ {+ consoleSendMessage();+ }++ if (! messageSendingIsPending)+ {+ if (messageToPrint.size < CRTP_MAX_DATA_SIZE)+ {+ messageToPrint.data[messageToPrint.size] = (unsigned char)ch;+ messageToPrint.size++;+ }++ if (ch == '\n' || messageToPrint.size >= CRTP_MAX_DATA_SIZE)+ {+ if (crtpGetFreeTxQueuePackets() == 1)+ {+ addBufferFullMarker();+ }+ messageSendingIsPending = true;+ consoleSendMessage();+ }+ }+ xSemaphoreGive(synch);+ }++ return (unsigned char)ch;+}++int consolePutcharFromISR(int ch) {+ BaseType_t higherPriorityTaskWoken;++ if (xSemaphoreTakeFromISR(synch, &higherPriorityTaskWoken) == pdTRUE) {+ if (messageToPrint.size < CRTP_MAX_DATA_SIZE)+ {+ messageToPrint.data[messageToPrint.size] = (unsigned char)ch;+ messageToPrint.size++;+ }+ xSemaphoreGiveFromISR(synch, &higherPriorityTaskWoken);+ }++ return ch;+}++int consolePuts(char *str)+{+ int ret = 0;++ while(*str)+ ret |= consolePutchar(*str++);++ return ret;+}++void consoleFlush(void)+{+ if (xSemaphoreTake(synch, portMAX_DELAY) == pdTRUE)+ {+ consoleSendMessage();+ xSemaphoreGive(synch);+ }+}+++static int findMarkerStart()+{+ int start = messageToPrint.size;++ // If last char is new line, rewind one char since the marker contains a new line.+ if (start > 0 && messageToPrint.data[start - 1] == '\n')+ {+ start -= 1;+ }++ return start;+}++static void addBufferFullMarker()+{+ // Try to add the marker after the message if it fits in the buffer, otherwise overwrite the end of the message+ int endMarker = findMarkerStart() + sizeof(bufferFullMsg);+ if (endMarker >= (CRTP_MAX_DATA_SIZE))+ {+ endMarker = CRTP_MAX_DATA_SIZE;+ }++ int startMarker = endMarker - sizeof(bufferFullMsg);+ memcpy(&messageToPrint.data[startMarker], bufferFullMsg, sizeof(bufferFullMsg));+ messageToPrint.size = startMarker + sizeof(bufferFullMsg);+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/controller.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller.cnew file mode 100644index 0000000..f9e48f2--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller.c@@ -0,0 +1,70 @@+#define DEBUG_MODULE "CONTROLLER"+#include "debug_cf.h"++#include "cfassert.h"+#include "controller.h"+#include "controller_pid.h"+#include "controller_mellinger.h"+#include "controller_indi.h"++#define DEFAULT_CONTROLLER ControllerTypePID+static ControllerType currentController = ControllerTypeAny;++static void initController();++typedef struct {+ void (*init)(void);+ bool (*test)(void);+ void (*update)(control_t *control, setpoint_t *setpoint, const sensorData_t *sensors, const state_t *state, const uint32_t tick);+ const char* name;+} ControllerFcns;++static ControllerFcns controllerFunctions[] = {+ {.init = 0, .test = 0, .update = 0, .name = "None"}, // Any+ {.init = controllerPidInit, .test = controllerPidTest, .update = controllerPid, .name = "PID"},+ {.init = controllerMellingerInit, .test = controllerMellingerTest, .update = controllerMellinger, .name = "Mellinger"},+ {.init = controllerINDIInit, .test = controllerINDITest, .update = controllerINDI, .name = "INDI"},+};+++void controllerInit(ControllerType controller) {+ if (controller < 0 || controller >= ControllerType_COUNT) {+ return;+ }++ currentController = controller;++ if (ControllerTypeAny == currentController) {+ currentController = DEFAULT_CONTROLLER;+ }++ ControllerType forcedController = ControllerTypeAny;+ if (forcedController != ControllerTypeAny) {+ DEBUG_PRINTD("Controller type forced\n");+ currentController = forcedController;+ }++ initController();++ DEBUG_PRINTD("Using %s (%d) controller\n", controllerGetName(), currentController);+}++ControllerType getControllerType(void) {+ return currentController;+}++static void initController() {+ controllerFunctions[currentController].init();+}++bool controllerTest(void) {+ return controllerFunctions[currentController].test();+}++void controller(control_t *control, setpoint_t *setpoint, const sensorData_t *sensors, const state_t *state, const uint32_t tick) {+ controllerFunctions[currentController].update(control, setpoint, sensors, state, tick);+}++const char* controllerGetName() {+ return controllerFunctions[currentController].name;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_indi.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_indi.cnew file mode 100644index 0000000..cf87340--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_indi.c@@ -0,0 +1,404 @@+/*+ *+ * Copyright (c) 2019 Ewoud Smeur and Andre Luis Ogando Paraense+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * This control algorithm is the Incremental Nonlinear Dynamic Inversion (INDI)+ * controller.+ *+ * This is an implementation of the publication in the+ * journal of Control Guidance and Dynamics: Adaptive Incremental Nonlinear+ * Dynamic Inversion for Attitude Control of Micro Aerial Vehicles+ * http://arc.aiaa.org/doi/pdf/10.2514/1.G001490+ */++#include "controller_indi.h"+#include "math3d.h"++static float thrust_threshold = 300.0f;+static float bound_control_input = 32000.0f;++static attitude_t attitudeDesired;+static attitude_t rateDesired;+static float actuatorThrust;+static float roll_kp = 5.0f;+static float pitch_kp = 5.0f;+static float yaw_kp = 5.0f;++static float attYawError;++static float r_roll;+static float r_pitch;+static float r_yaw;+static float accelz;++static vector_t refOuterINDI; // Reference values from outer loop INDI+static bool outerLoopActive = false ; // if 1, outer loop INDI is activated++static struct IndiVariables indi = {+ .g1 = {STABILIZATION_INDI_G1_P, STABILIZATION_INDI_G1_Q, STABILIZATION_INDI_G1_R},+ .g2 = STABILIZATION_INDI_G2_R,+ .reference_acceleration = {+ STABILIZATION_INDI_REF_ERR_P,+ STABILIZATION_INDI_REF_ERR_Q,+ STABILIZATION_INDI_REF_ERR_R,+ STABILIZATION_INDI_REF_RATE_P,+ STABILIZATION_INDI_REF_RATE_Q,+ STABILIZATION_INDI_REF_RATE_R+ },+ .act_dyn = {STABILIZATION_INDI_ACT_DYN_P, STABILIZATION_INDI_ACT_DYN_Q, STABILIZATION_INDI_ACT_DYN_R},+ .filt_cutoff = STABILIZATION_INDI_FILT_CUTOFF,+ .filt_cutoff_r = STABILIZATION_INDI_FILT_CUTOFF_R,+};++static inline void float_rates_zero(struct FloatRates *fr) {+ fr->p = 0.0f;+ fr->q = 0.0f;+ fr->r = 0.0f;+}++void indi_init_filters(void)+{+ // tau = 1/(2*pi*Fc)+ float tau = 1.0f / (2.0f * M_PI_F * indi.filt_cutoff);+ float tau_r = 1.0f / (2.0f * M_PI_F * indi.filt_cutoff_r);+ float tau_axis[3] = {tau, tau, tau_r};+ float sample_time = 1.0f / ATTITUDE_RATE;+ // Filtering of gyroscope and actuators+ for (int8_t i = 0; i < 3; i++) {+ init_butterworth_2_low_pass(&indi.u[i], tau_axis[i], sample_time, 0.0f);+ init_butterworth_2_low_pass(&indi.rate[i], tau_axis[i], sample_time, 0.0f);+ }+}++/**+ * @brief Update butterworth filter for p, q and r of a FloatRates struct+ *+ * @param filter The filter array to use+ * @param new_values The new values+ */+static inline void filter_pqr(Butterworth2LowPass *filter, struct FloatRates *new_values)+{+ update_butterworth_2_low_pass(&filter[0], new_values->p);+ update_butterworth_2_low_pass(&filter[1], new_values->q);+ update_butterworth_2_low_pass(&filter[2], new_values->r);+}++/**+ * @brief Caclulate finite difference form a filter array+ * The filter already contains the previous values+ *+ * @param output The output array+ * @param filter The filter array input+ */+static inline void finite_difference_from_filter(float *output, Butterworth2LowPass *filter)+{+ for (int8_t i = 0; i < 3; i++) {+ output[i] = (filter[i].o[0] - filter[i].o[1]) * ATTITUDE_RATE;+ }+}++static float capAngle(float angle) {+ float result = angle;++ while (result > 180.0f) {+ result -= 360.0f;+ }++ while (result < -180.0f) {+ result += 360.0f;+ }++ return result;+}+++void controllerINDIInit(void)+{+ /*+ * TODO+ * Can this also be called during flight, for instance when switching controllers?+ * Then the filters should not be reset to zero but to the current values of sensors and actuators.+ */+ float_rates_zero(&indi.angular_accel_ref);+ float_rates_zero(&indi.u_act_dyn);+ float_rates_zero(&indi.u_in);++ // Re-initialize filters+ indi_init_filters();++ attitudeControllerInit(ATTITUDE_UPDATE_DT);+ positionControllerInit();+ positionControllerINDIInit();+}++bool controllerINDITest(void)+{+ bool pass = true;++ pass &= attitudeControllerTest();++ return pass;+}++void controllerINDI(control_t *control, setpoint_t *setpoint,+ const sensorData_t *sensors,+ const state_t *state,+ const uint32_t tick)+{++ if (RATE_DO_EXECUTE(ATTITUDE_RATE, tick)) {+ // Rate-controled YAW is moving YAW angle setpoint+ if (setpoint->mode.yaw == modeVelocity) {+ attitudeDesired.yaw += setpoint->attitudeRate.yaw * ATTITUDE_UPDATE_DT;+ while (attitudeDesired.yaw > 180.0f)+ attitudeDesired.yaw -= 360.0f;+ while (attitudeDesired.yaw < -180.0f)+ attitudeDesired.yaw += 360.0f;+ } else {+ attitudeDesired.yaw = setpoint->attitude.yaw;+ }+ }++ if (RATE_DO_EXECUTE(POSITION_RATE, tick) && !outerLoopActive) {+ positionController(&actuatorThrust, &attitudeDesired, setpoint, state);+ }++ /*+ * Skipping calls faster than ATTITUDE_RATE+ */+ if (RATE_DO_EXECUTE(ATTITUDE_RATE, tick)) {++ // Call outer loop INDI (position controller)+ if (outerLoopActive) {+ positionControllerINDI(sensors, setpoint, state, &refOuterINDI);+ }++ // Switch between manual and automatic position control+ if (setpoint->mode.z == modeDisable) {+ // INDI position controller not active, INDI attitude controller is main loop+ actuatorThrust = setpoint->thrust;+ } else{+ if (outerLoopActive) {+ // INDI position controller active, INDI attitude controller becomes inner loop+ actuatorThrust = refOuterINDI.z;+ }+ }+ if (setpoint->mode.x == modeDisable) {++ // INDI position controller not active, INDI attitude controller is main loop+ attitudeDesired.roll = setpoint->attitude.roll;++ }else{+ if (outerLoopActive) {+ // INDI position controller active, INDI attitude controller becomes inner loop+ attitudeDesired.roll = refOuterINDI.x;+ }+ }++ if (setpoint->mode.y == modeDisable) {++ // INDI position controller not active, INDI attitude controller is main loop+ attitudeDesired.pitch = setpoint->attitude.pitch;++ }else{+ if (outerLoopActive) {+ // INDI position controller active, INDI attitude controller becomes inner loop+ attitudeDesired.pitch = refOuterINDI.y;+ }+ }+++// attitudeControllerCorrectAttitudePID(state->attitude.roll, state->attitude.pitch, state->attitude.yaw,+// attitudeDesired.roll, attitudeDesired.pitch, attitudeDesired.yaw,+// &rateDesired.roll, &rateDesired.pitch, &rateDesired.yaw);++ rateDesired.roll = roll_kp*(attitudeDesired.roll - state->attitude.roll);+ rateDesired.pitch = pitch_kp*(attitudeDesired.pitch - state->attitude.pitch);+ //rateDesired.yaw = yaw_kp*(attitudeDesired.yaw - state->attitude.yaw);+ attYawError = attitudeDesired.yaw - state->attitude.yaw;+ attYawError = capAngle(attYawError);+ rateDesired.yaw = yaw_kp*attYawError;+++ // For roll and pitch, if velocity mode, overwrite rateDesired with the setpoint+ // value. Also reset the PID to avoid error buildup, which can lead to unstable+ // behavior if level mode is engaged later+ if (setpoint->mode.roll == modeVelocity) {+ rateDesired.roll = setpoint->attitudeRate.roll;+ attitudeControllerResetRollAttitudePID();+ }+ if (setpoint->mode.pitch == modeVelocity) {+ rateDesired.pitch = setpoint->attitudeRate.pitch;+ attitudeControllerResetPitchAttitudePID();+ }++ /*+ * 1 - Update the gyro filter with the new measurements.+ */++ float stateAttitudeRateRoll = radians(sensors->gyro.x);+ float stateAttitudeRatePitch = -radians(sensors->gyro.y); // Account for Crazyflie coordinate system+ float stateAttitudeRateYaw = radians(sensors->gyro.z);++ struct FloatRates body_rates = {+ .p = stateAttitudeRateRoll,+ .q = stateAttitudeRatePitch,+ .r = stateAttitudeRateYaw,+ };+ filter_pqr(indi.rate, &body_rates);+++ /*+ * 2 - Calculate the derivative with finite difference.+ */++ finite_difference_from_filter(indi.rate_d, indi.rate);+++ /*+ * 3 - same filter on the actuators (or control_t values), using the commands from the previous timestep.+ */+ filter_pqr(indi.u, &indi.u_act_dyn);+++ /*+ * 4 - Calculate the desired angular acceleration by:+ * 4.1 - Rate_reference = P * attitude_error, where attitude error can be calculated with your favorite+ * algorithm. You may even use a function that is already there, such as attitudeControllerCorrectAttitudePID(),+ * though this will be inaccurate for large attitude errors, but it will be ok for now.+ * 4.2 Angular_acceleration_reference = D * (rate_reference – rate_measurement)+ */++ float attitude_error_p = radians(rateDesired.roll) - stateAttitudeRateRoll;+ float attitude_error_q = radians(rateDesired.pitch) - stateAttitudeRatePitch;+ float attitude_error_r = radians(rateDesired.yaw) - stateAttitudeRateYaw;++ indi.angular_accel_ref.p = indi.reference_acceleration.err_p * attitude_error_p;++ indi.angular_accel_ref.q = indi.reference_acceleration.err_q * attitude_error_q;++ indi.angular_accel_ref.r = indi.reference_acceleration.err_r * attitude_error_r;++ /*+ * 5. Update the For each axis: delta_command = 1/control_effectiveness * (angular_acceleration_reference – angular_acceleration)+ */++ //Increment in angular acceleration requires increment in control input+ //G1 is the control effectiveness. In the yaw axis, we need something additional: G2.+ //It takes care of the angular acceleration caused by the change in rotation rate of the propellers+ //(they have significant inertia, see the paper mentioned in the header for more explanation)+ indi.du.p = 1.0f / indi.g1.p * (indi.angular_accel_ref.p - indi.rate_d[0]);+ indi.du.q = 1.0f / indi.g1.q * (indi.angular_accel_ref.q - indi.rate_d[1]);+ indi.du.r = 1.0f / (indi.g1.r - indi.g2) * (indi.angular_accel_ref.r - indi.rate_d[2] - indi.g2 * indi.du.r);+++ /*+ * 6. Add delta_commands to commands and bound to allowable values+ */++ indi.u_in.p = indi.u[0].o[0] + indi.du.p;+ indi.u_in.q = indi.u[1].o[0] + indi.du.q;+ indi.u_in.r = indi.u[2].o[0] + indi.du.r;++ //bound the total control input+ indi.u_in.p = clamp(indi.u_in.p, -1.0f*bound_control_input, bound_control_input);+ indi.u_in.q = clamp(indi.u_in.q, -1.0f*bound_control_input, bound_control_input);+ indi.u_in.r = clamp(indi.u_in.r, -1.0f*bound_control_input, bound_control_input);++ //Propagate input filters+ //first order actuator dynamics+ indi.u_act_dyn.p = indi.u_act_dyn.p + indi.act_dyn.p * (indi.u_in.p - indi.u_act_dyn.p);+ indi.u_act_dyn.q = indi.u_act_dyn.q + indi.act_dyn.q * (indi.u_in.q - indi.u_act_dyn.q);+ indi.u_act_dyn.r = indi.u_act_dyn.r + indi.act_dyn.r * (indi.u_in.r - indi.u_act_dyn.r);++ }++ indi.thrust = actuatorThrust;+ r_roll = radians(sensors->gyro.x);+ r_pitch = -radians(sensors->gyro.y);+ r_yaw = radians(sensors->gyro.z);+ accelz = sensors->acc.z;++ //Don't increment if thrust is off+ //TODO: this should be something more elegant, but without this the inputs+ //will increment to the maximum before even getting in the air.+ if(indi.thrust < thrust_threshold) {+ float_rates_zero(&indi.angular_accel_ref);+ float_rates_zero(&indi.u_act_dyn);+ float_rates_zero(&indi.u_in);++ if(indi.thrust == 0){+ attitudeControllerResetAllPID();+ positionControllerResetAllPID();++ // Reset the calculated YAW angle for rate control+ attitudeDesired.yaw = state->attitude.yaw;+ }+ }++ /* INDI feedback */+ control->thrust = indi.thrust;+ control->roll = indi.u_in.p;+ control->pitch = indi.u_in.q;+ control->yaw = indi.u_in.r;++}++PARAM_GROUP_START(ctrlINDI)+PARAM_ADD(PARAM_FLOAT, thrust_threshold, &thrust_threshold)+PARAM_ADD(PARAM_FLOAT, bound_ctrl_input, &bound_control_input)+PARAM_ADD(PARAM_FLOAT, roll_kp, &roll_kp)+PARAM_ADD(PARAM_FLOAT, pitch_kp, &pitch_kp)+PARAM_ADD(PARAM_FLOAT, yaw_kp, &yaw_kp)+PARAM_ADD(PARAM_FLOAT, g1_p, &indi.g1.p)+PARAM_ADD(PARAM_FLOAT, g1_q, &indi.g1.q)+PARAM_ADD(PARAM_FLOAT, g1_r, &indi.g1.r)+PARAM_ADD(PARAM_FLOAT, g2, &indi.g2)+PARAM_ADD(PARAM_FLOAT, ref_err_p, &indi.reference_acceleration.err_p)+PARAM_ADD(PARAM_FLOAT, ref_err_q, &indi.reference_acceleration.err_q)+PARAM_ADD(PARAM_FLOAT, ref_err_r, &indi.reference_acceleration.err_r)+PARAM_ADD(PARAM_FLOAT, ref_rate_p, &indi.reference_acceleration.rate_p)+PARAM_ADD(PARAM_FLOAT, ref_rate_q, &indi.reference_acceleration.rate_q)+PARAM_ADD(PARAM_FLOAT, ref_rate_r, &indi.reference_acceleration.rate_r)+PARAM_ADD(PARAM_FLOAT, act_dyn_p, &indi.act_dyn.p)+PARAM_ADD(PARAM_FLOAT, act_dyn_q, &indi.act_dyn.q)+PARAM_ADD(PARAM_FLOAT, act_dyn_r, &indi.act_dyn.r)+PARAM_ADD(PARAM_FLOAT, filt_cutoff, &indi.filt_cutoff)+PARAM_ADD(PARAM_FLOAT, filt_cutoff_r, &indi.filt_cutoff_r)+PARAM_ADD(PARAM_UINT8, outerLoopActive, &outerLoopActive)+PARAM_GROUP_STOP(ctrlINDI)++LOG_GROUP_START(ctrlINDI)+LOG_ADD(LOG_FLOAT, cmd_thrust, &indi.thrust)+LOG_ADD(LOG_FLOAT, cmd_roll, &indi.u_in.p)+LOG_ADD(LOG_FLOAT, cmd_pitch, &indi.u_in.q)+LOG_ADD(LOG_FLOAT, cmd_yaw, &indi.u_in.r)+LOG_ADD(LOG_FLOAT, r_roll, &r_roll)+LOG_ADD(LOG_FLOAT, r_pitch, &r_pitch)+LOG_ADD(LOG_FLOAT, r_yaw, &r_yaw)+LOG_ADD(LOG_FLOAT, accelz, &accelz)+LOG_ADD(LOG_FLOAT, u_act_dyn.p, &indi.u_act_dyn.p)+LOG_ADD(LOG_FLOAT, u_act_dyn.q, &indi.u_act_dyn.q)+LOG_ADD(LOG_FLOAT, u_act_dyn.r, &indi.u_act_dyn.r)+LOG_ADD(LOG_FLOAT, du.p, &indi.du.p)+LOG_ADD(LOG_FLOAT, du.q, &indi.du.q)+LOG_ADD(LOG_FLOAT, du.r, &indi.du.r)+LOG_ADD(LOG_FLOAT, ang_accel_ref.p, &indi.angular_accel_ref.p)+LOG_ADD(LOG_FLOAT, ang_accel_ref.q, &indi.angular_accel_ref.q)+LOG_ADD(LOG_FLOAT, ang_accel_ref.r, &indi.angular_accel_ref.r)+LOG_ADD(LOG_FLOAT, rate_d[0], &indi.rate_d[0])+LOG_ADD(LOG_FLOAT, rate_d[1], &indi.rate_d[1])+LOG_ADD(LOG_FLOAT, rate_d[2], &indi.rate_d[2])+LOG_GROUP_STOP(ctrlINDI)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_mellinger.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_mellinger.cnew file mode 100644index 0000000..4a2dd25--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_mellinger.c@@ -0,0 +1,361 @@+/*+The MIT License (MIT)++Copyright (c) 2018 Wolfgang Hoenig and James Alan Preiss++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+*/++/*+This controller is based on the following publication:++Daniel Mellinger, Vijay Kumar:+Minimum snap trajectory generation and control for quadrotors.+IEEE International Conference on Robotics and Automation (ICRA), 2011.++We added the following:+ * Integral terms (compensates for: battery voltage drop over time, unbalanced center of mass due to asymmmetries, and uneven wear on propellers and motors)+ * D-term for angular velocity+ * Support to use this controller as an attitude-only controller for manual flight+*/++#include <math.h>++#include "param.h"+#include "log.h"+#include "math3d.h"+#include "position_controller.h"+#include "controller_mellinger.h"+#include "physicalConstants.h"++static float g_vehicleMass = CF_MASS;+static float massThrust = 132000;++// XY Position PID+static float kp_xy = 0.4; // P+static float kd_xy = 0.2; // D+static float ki_xy = 0.05; // I+static float i_range_xy = 2.0;++// Z Position+static float kp_z = 1.25; // P+static float kd_z = 0.4; // D+static float ki_z = 0.05; // I+static float i_range_z = 0.4;++// Attitude+static float kR_xy = 70000; // P+static float kw_xy = 20000; // D+static float ki_m_xy = 0.0; // I+static float i_range_m_xy = 1.0;++// Yaw+static float kR_z = 60000; // P+static float kw_z = 12000; // D+static float ki_m_z = 500; // I+static float i_range_m_z = 1500;++// roll and pitch angular velocity+static float kd_omega_rp = 200; // D+++// Helper variables+static float i_error_x = 0;+static float i_error_y = 0;+static float i_error_z = 0;++static float prev_omega_roll;+static float prev_omega_pitch;+static float prev_setpoint_omega_roll;+static float prev_setpoint_omega_pitch;++static float i_error_m_x = 0;+static float i_error_m_y = 0;+static float i_error_m_z = 0;++// Logging variables+static struct vec z_axis_desired;++static float cmd_thrust;+static float cmd_roll;+static float cmd_pitch;+static float cmd_yaw;+static float r_roll;+static float r_pitch;+static float r_yaw;+static float accelz;++void controllerMellingerReset(void)+{+ i_error_x = 0;+ i_error_y = 0;+ i_error_z = 0;+ i_error_m_x = 0;+ i_error_m_y = 0;+ i_error_m_z = 0;+}++void controllerMellingerInit(void)+{+ controllerMellingerReset();+}++bool controllerMellingerTest(void)+{+ return true;+}++void controllerMellinger(control_t *control, setpoint_t *setpoint,+ const sensorData_t *sensors,+ const state_t *state,+ const uint32_t tick)+{+ struct vec r_error;+ struct vec v_error;+ struct vec target_thrust;+ struct vec z_axis;+ float current_thrust;+ struct vec x_axis_desired;+ struct vec y_axis_desired;+ struct vec x_c_des;+ struct vec eR, ew, M;+ float dt;+ float desiredYaw = 0; //deg++ if (!RATE_DO_EXECUTE(ATTITUDE_RATE, tick)) {+ return;+ }++ dt = (float)(1.0f/ATTITUDE_RATE);+ struct vec setpointPos = mkvec(setpoint->position.x, setpoint->position.y, setpoint->position.z);+ struct vec setpointVel = mkvec(setpoint->velocity.x, setpoint->velocity.y, setpoint->velocity.z);+ struct vec statePos = mkvec(state->position.x, state->position.y, state->position.z);+ struct vec stateVel = mkvec(state->velocity.x, state->velocity.y, state->velocity.z);++ // Position Error (ep)+ r_error = vsub(setpointPos, statePos);++ // Velocity Error (ev)+ v_error = vsub(setpointVel, stateVel);++ // Integral Error+ i_error_z += r_error.z * dt;+ i_error_z = clamp(i_error_z, -i_range_z, i_range_z);++ i_error_x += r_error.x * dt;+ i_error_x = clamp(i_error_x, -i_range_xy, i_range_xy);++ i_error_y += r_error.y * dt;+ i_error_y = clamp(i_error_y, -i_range_xy, i_range_xy);++ // Desired thrust [F_des]+ if (setpoint->mode.x == modeAbs) {+ target_thrust.x = g_vehicleMass * setpoint->acceleration.x + kp_xy * r_error.x + kd_xy * v_error.x + ki_xy * i_error_x;+ target_thrust.y = g_vehicleMass * setpoint->acceleration.y + kp_xy * r_error.y + kd_xy * v_error.y + ki_xy * i_error_y;+ target_thrust.z = g_vehicleMass * (setpoint->acceleration.z + GRAVITY_MAGNITUDE) + kp_z * r_error.z + kd_z * v_error.z + ki_z * i_error_z;+ } else {+ target_thrust.x = -sinf(radians(setpoint->attitude.pitch));+ target_thrust.y = -sinf(radians(setpoint->attitude.roll));+ // In case of a timeout, the commander tries to level, ie. x/y are disabled, but z will use the previous setting+ // In that case we ignore the last feedforward term for acceleration+ if (setpoint->mode.z == modeAbs) {+ target_thrust.z = g_vehicleMass * GRAVITY_MAGNITUDE + kp_z * r_error.z + kd_z * v_error.z + ki_z * i_error_z;+ } else {+ target_thrust.z = 1;+ }+ }++ // Rate-controlled YAW is moving YAW angle setpoint+ if (setpoint->mode.yaw == modeVelocity) {+ desiredYaw = state->attitude.yaw + setpoint->attitudeRate.yaw * dt;+ } else if (setpoint->mode.yaw == modeAbs) {+ desiredYaw = setpoint->attitude.yaw;+ } else if (setpoint->mode.quat == modeAbs) {+ struct quat setpoint_quat = mkquat(setpoint->attitudeQuaternion.x, setpoint->attitudeQuaternion.y, setpoint->attitudeQuaternion.z, setpoint->attitudeQuaternion.w);+ struct vec rpy = quat2rpy(setpoint_quat);+ desiredYaw = degrees(rpy.z);+ }++ // Z-Axis [zB]+ struct quat q = mkquat(state->attitudeQuaternion.x, state->attitudeQuaternion.y, state->attitudeQuaternion.z, state->attitudeQuaternion.w);+ struct mat33 R = quat2rotmat(q);+ z_axis = mcolumn(R, 2);++ // yaw correction (only if position control is not used)+ if (setpoint->mode.x != modeAbs) {+ struct vec x_yaw = mcolumn(R, 0);+ x_yaw.z = 0;+ x_yaw = vnormalize(x_yaw);+ struct vec y_yaw = vcross(mkvec(0, 0, 1), x_yaw);+ struct mat33 R_yaw_only = mcolumns(x_yaw, y_yaw, mkvec(0, 0, 1));+ target_thrust = mvmul(R_yaw_only, target_thrust);+ }++ // Current thrust [F]+ current_thrust = vdot(target_thrust, z_axis);++ // Calculate axis [zB_des]+ z_axis_desired = vnormalize(target_thrust);++ // [xC_des]+ // x_axis_desired = z_axis_desired x [sin(yaw), cos(yaw), 0]^T+ x_c_des.x = cosf(radians(desiredYaw));+ x_c_des.y = sinf(radians(desiredYaw));+ x_c_des.z = 0;+ // [yB_des]+ y_axis_desired = vnormalize(vcross(z_axis_desired, x_c_des));+ // [xB_des]+ x_axis_desired = vcross(y_axis_desired, z_axis_desired);++ // [eR]+ // Slow version+ // struct mat33 Rdes = mcolumns(+ // mkvec(x_axis_desired.x, x_axis_desired.y, x_axis_desired.z),+ // mkvec(y_axis_desired.x, y_axis_desired.y, y_axis_desired.z),+ // mkvec(z_axis_desired.x, z_axis_desired.y, z_axis_desired.z));++ // struct mat33 R_transpose = mtranspose(R);+ // struct mat33 Rdes_transpose = mtranspose(Rdes);++ // struct mat33 eRM = msub(mmult(Rdes_transpose, R), mmult(R_transpose, Rdes));++ // eR.x = eRM.m[2][1];+ // eR.y = -eRM.m[0][2];+ // eR.z = eRM.m[1][0];++ // Fast version (generated using Mathematica)+ float x = q.x;+ float y = q.y;+ float z = q.z;+ float w = q.w;+ eR.x = (-1 + 2*fsqr(x) + 2*fsqr(y))*y_axis_desired.z + z_axis_desired.y - 2*(x*y_axis_desired.x*z + y*y_axis_desired.y*z - x*y*z_axis_desired.x + fsqr(x)*z_axis_desired.y + fsqr(z)*z_axis_desired.y - y*z*z_axis_desired.z) + 2*w*(-(y*y_axis_desired.x) - z*z_axis_desired.x + x*(y_axis_desired.y + z_axis_desired.z));+ eR.y = x_axis_desired.z - z_axis_desired.x - 2*(fsqr(x)*x_axis_desired.z + y*(x_axis_desired.z*y - x_axis_desired.y*z) - (fsqr(y) + fsqr(z))*z_axis_desired.x + x*(-(x_axis_desired.x*z) + y*z_axis_desired.y + z*z_axis_desired.z) + w*(x*x_axis_desired.y + z*z_axis_desired.y - y*(x_axis_desired.x + z_axis_desired.z)));+ eR.z = y_axis_desired.x - 2*(y*(x*x_axis_desired.x + y*y_axis_desired.x - x*y_axis_desired.y) + w*(x*x_axis_desired.z + y*y_axis_desired.z)) + 2*(-(x_axis_desired.z*y) + w*(x_axis_desired.x + y_axis_desired.y) + x*y_axis_desired.z)*z - 2*y_axis_desired.x*fsqr(z) + x_axis_desired.y*(-1 + 2*fsqr(x) + 2*fsqr(z));++ // Account for Crazyflie coordinate system+ eR.y = -eR.y;++ // [ew]+ float err_d_roll = 0;+ float err_d_pitch = 0;++ float stateAttitudeRateRoll = radians(sensors->gyro.x);+ float stateAttitudeRatePitch = -radians(sensors->gyro.y);+ float stateAttitudeRateYaw = radians(sensors->gyro.z);++ ew.x = radians(setpoint->attitudeRate.roll) - stateAttitudeRateRoll;+ ew.y = -radians(setpoint->attitudeRate.pitch) - stateAttitudeRatePitch;+ ew.z = radians(setpoint->attitudeRate.yaw) - stateAttitudeRateYaw;+ if (prev_omega_roll == prev_omega_roll) { /*d part initialized*/+ err_d_roll = ((radians(setpoint->attitudeRate.roll) - prev_setpoint_omega_roll) - (stateAttitudeRateRoll - prev_omega_roll)) / dt;+ err_d_pitch = (-(radians(setpoint->attitudeRate.pitch) - prev_setpoint_omega_pitch) - (stateAttitudeRatePitch - prev_omega_pitch)) / dt;+ }+ prev_omega_roll = stateAttitudeRateRoll;+ prev_omega_pitch = stateAttitudeRatePitch;+ prev_setpoint_omega_roll = radians(setpoint->attitudeRate.roll);+ prev_setpoint_omega_pitch = radians(setpoint->attitudeRate.pitch);++ // Integral Error+ i_error_m_x += (-eR.x) * dt;+ i_error_m_x = clamp(i_error_m_x, -i_range_m_xy, i_range_m_xy);++ i_error_m_y += (-eR.y) * dt;+ i_error_m_y = clamp(i_error_m_y, -i_range_m_xy, i_range_m_xy);++ i_error_m_z += (-eR.z) * dt;+ i_error_m_z = clamp(i_error_m_z, -i_range_m_z, i_range_m_z);++ // Moment:+ M.x = -kR_xy * eR.x + kw_xy * ew.x + ki_m_xy * i_error_m_x + kd_omega_rp * err_d_roll;+ M.y = -kR_xy * eR.y + kw_xy * ew.y + ki_m_xy * i_error_m_y + kd_omega_rp * err_d_pitch;+ M.z = -kR_z * eR.z + kw_z * ew.z + ki_m_z * i_error_m_z;++ // Output+ if (setpoint->mode.z == modeDisable) {+ control->thrust = setpoint->thrust;+ } else {+ control->thrust = massThrust * current_thrust;+ }++ cmd_thrust = control->thrust;+ r_roll = radians(sensors->gyro.x);+ r_pitch = -radians(sensors->gyro.y);+ r_yaw = radians(sensors->gyro.z);+ accelz = sensors->acc.z;++ if (control->thrust > 0) {+ control->roll = clamp(M.x, -32000, 32000);+ control->pitch = clamp(M.y, -32000, 32000);+ control->yaw = clamp(-M.z, -32000, 32000);++ cmd_roll = control->roll;+ cmd_pitch = control->pitch;+ cmd_yaw = control->yaw;++ } else {+ control->roll = 0;+ control->pitch = 0;+ control->yaw = 0;++ cmd_roll = control->roll;+ cmd_pitch = control->pitch;+ cmd_yaw = control->yaw;++ controllerMellingerReset();+ }+}++PARAM_GROUP_START(ctrlMel)+PARAM_ADD(PARAM_FLOAT, kp_xy, &kp_xy)+PARAM_ADD(PARAM_FLOAT, kd_xy, &kd_xy)+PARAM_ADD(PARAM_FLOAT, ki_xy, &ki_xy)+PARAM_ADD(PARAM_FLOAT, i_range_xy, &i_range_xy)+PARAM_ADD(PARAM_FLOAT, kp_z, &kp_z)+PARAM_ADD(PARAM_FLOAT, kd_z, &kd_z)+PARAM_ADD(PARAM_FLOAT, ki_z, &ki_z)+PARAM_ADD(PARAM_FLOAT, i_range_z, &i_range_z)+PARAM_ADD(PARAM_FLOAT, mass, &g_vehicleMass)+PARAM_ADD(PARAM_FLOAT, massThrust, &massThrust)+PARAM_ADD(PARAM_FLOAT, kR_xy, &kR_xy)+PARAM_ADD(PARAM_FLOAT, kR_z, &kR_z)+PARAM_ADD(PARAM_FLOAT, kw_xy, &kw_xy)+PARAM_ADD(PARAM_FLOAT, kw_z, &kw_z)+PARAM_ADD(PARAM_FLOAT, ki_m_xy, &ki_m_xy)+PARAM_ADD(PARAM_FLOAT, ki_m_z, &ki_m_z)+PARAM_ADD(PARAM_FLOAT, kd_omega_rp, &kd_omega_rp)+PARAM_ADD(PARAM_FLOAT, i_range_m_xy, &i_range_m_xy)+PARAM_ADD(PARAM_FLOAT, i_range_m_z, &i_range_m_z)+PARAM_GROUP_STOP(ctrlMel)++LOG_GROUP_START(ctrlMel)+LOG_ADD(LOG_FLOAT, cmd_thrust, &cmd_thrust)+LOG_ADD(LOG_FLOAT, cmd_roll, &cmd_roll)+LOG_ADD(LOG_FLOAT, cmd_pitch, &cmd_pitch)+LOG_ADD(LOG_FLOAT, cmd_yaw, &cmd_yaw)+LOG_ADD(LOG_FLOAT, r_roll, &r_roll)+LOG_ADD(LOG_FLOAT, r_pitch, &r_pitch)+LOG_ADD(LOG_FLOAT, r_yaw, &r_yaw)+LOG_ADD(LOG_FLOAT, accelz, &accelz)+LOG_ADD(LOG_FLOAT, zdx, &z_axis_desired.x)+LOG_ADD(LOG_FLOAT, zdy, &z_axis_desired.y)+LOG_ADD(LOG_FLOAT, zdz, &z_axis_desired.z)+LOG_ADD(LOG_FLOAT, i_err_x, &i_error_x)+LOG_ADD(LOG_FLOAT, i_err_y, &i_error_y)+LOG_ADD(LOG_FLOAT, i_err_z, &i_error_z)+LOG_GROUP_STOP(ctrlMel)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_pid.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_pid.cnew file mode 100644index 0000000..e846ab3--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/controller_pid.c@@ -0,0 +1,178 @@++#include "stabilizer.h"+#include "stabilizer_types.h"++#include "attitude_controller.h"+#include "sensfusion6.h"+#include "position_controller.h"+#include "controller_pid.h"++#include "log.h"+#include "debug_cf.h"+#include "param.h"+#include "math3d.h"++#define ATTITUDE_UPDATE_DT (float)(1.0f/ATTITUDE_RATE)++static bool tiltCompensationEnabled = false;++static attitude_t attitudeDesired;+static attitude_t rateDesired;+static float actuatorThrust;++static float cmd_thrust;+static float cmd_roll;+static float cmd_pitch;+static float cmd_yaw;+static float r_roll;+static float r_pitch;+static float r_yaw;+static float accelz;++void controllerPidInit(void)+{+ attitudeControllerInit(ATTITUDE_UPDATE_DT);+ positionControllerInit();+}++bool controllerPidTest(void)+{+ bool pass = true;++ pass &= attitudeControllerTest();+ DEBUG_PRINTD("controller_Pid_Test = %d", pass);++ return pass;+}++static float capAngle(float angle) {+ float result = angle;++ while (result > 180.0f) {+ result -= 360.0f;+ }++ while (result < -180.0f) {+ result += 360.0f;+ }++ return result;+}++void controllerPid(control_t *control, setpoint_t *setpoint,+ const sensorData_t *sensors,+ const state_t *state,+ const uint32_t tick)+{+ if (RATE_DO_EXECUTE(ATTITUDE_RATE, tick)) {+ // Rate-controled YAW is moving YAW angle setpoint+ if (setpoint->mode.yaw == modeVelocity) {+ attitudeDesired.yaw += setpoint->attitudeRate.yaw * ATTITUDE_UPDATE_DT;+ } else {+ attitudeDesired.yaw = setpoint->attitude.yaw;+ }++ attitudeDesired.yaw = capAngle(attitudeDesired.yaw);+ }++ if (RATE_DO_EXECUTE(POSITION_RATE, tick)) {+ positionController(&actuatorThrust, &attitudeDesired, setpoint, state);+ }++ if (RATE_DO_EXECUTE(ATTITUDE_RATE, tick)) {+ // Switch between manual and automatic position control+ if (setpoint->mode.z == modeDisable) {+ actuatorThrust = setpoint->thrust;+ }+ if (setpoint->mode.x == modeDisable || setpoint->mode.y == modeDisable) {+ attitudeDesired.roll = setpoint->attitude.roll;+ attitudeDesired.pitch = setpoint->attitude.pitch;+ }++ attitudeControllerCorrectAttitudePID(state->attitude.roll, state->attitude.pitch, state->attitude.yaw,+ attitudeDesired.roll, attitudeDesired.pitch, attitudeDesired.yaw,+ &rateDesired.roll, &rateDesired.pitch, &rateDesired.yaw);++ // For roll and pitch, if velocity mode, overwrite rateDesired with the setpoint+ // value. Also reset the PID to avoid error buildup, which can lead to unstable+ // behavior if level mode is engaged later+ if (setpoint->mode.roll == modeVelocity) {+ rateDesired.roll = setpoint->attitudeRate.roll;+ attitudeControllerResetRollAttitudePID();+ }+ if (setpoint->mode.pitch == modeVelocity) {+ rateDesired.pitch = setpoint->attitudeRate.pitch;+ attitudeControllerResetPitchAttitudePID();+ }++ // TODO: Investigate possibility to subtract gyro drift.+ attitudeControllerCorrectRatePID(sensors->gyro.x, -sensors->gyro.y, sensors->gyro.z,+ rateDesired.roll, rateDesired.pitch, rateDesired.yaw);++ attitudeControllerGetActuatorOutput(&control->roll,+ &control->pitch,+ &control->yaw);++ control->yaw = -control->yaw;++ cmd_thrust = control->thrust;+ cmd_roll = control->roll;+ cmd_pitch = control->pitch;+ cmd_yaw = control->yaw;+ r_roll = radians(sensors->gyro.x);+ r_pitch = -radians(sensors->gyro.y);+ r_yaw = radians(sensors->gyro.z);+ accelz = sensors->acc.z;+ }++ if (tiltCompensationEnabled)+ {+ control->thrust = actuatorThrust / sensfusion6GetInvThrustCompensationForTilt();+ }+ else+ {+ control->thrust = actuatorThrust;+ }++ if (control->thrust == 0)+ {+ control->thrust = 0;+ control->roll = 0;+ control->pitch = 0;+ control->yaw = 0;++ cmd_thrust = control->thrust;+ cmd_roll = control->roll;+ cmd_pitch = control->pitch;+ cmd_yaw = control->yaw;++ attitudeControllerResetAllPID();+ positionControllerResetAllPID();++ // Reset the calculated YAW angle for rate control+ attitudeDesired.yaw = state->attitude.yaw;+ }+}+++LOG_GROUP_START(controller)+LOG_ADD(LOG_FLOAT, cmd_thrust, &cmd_thrust)+LOG_ADD(LOG_FLOAT, cmd_roll, &cmd_roll)+LOG_ADD(LOG_FLOAT, cmd_pitch, &cmd_pitch)+LOG_ADD(LOG_FLOAT, cmd_yaw, &cmd_yaw)+LOG_ADD(LOG_FLOAT, r_roll, &r_roll)+LOG_ADD(LOG_FLOAT, r_pitch, &r_pitch)+LOG_ADD(LOG_FLOAT, r_yaw, &r_yaw)+LOG_ADD(LOG_FLOAT, accelz, &accelz)+LOG_ADD(LOG_FLOAT, actuatorThrust, &actuatorThrust)+LOG_ADD(LOG_FLOAT, roll, &attitudeDesired.roll)+LOG_ADD(LOG_FLOAT, pitch, &attitudeDesired.pitch)+LOG_ADD(LOG_FLOAT, yaw, &attitudeDesired.yaw)+LOG_ADD(LOG_FLOAT, rollRate, &rateDesired.roll)+LOG_ADD(LOG_FLOAT, pitchRate, &rateDesired.pitch)+LOG_ADD(LOG_FLOAT, yawRate, &rateDesired.yaw)+LOG_GROUP_STOP(controller)++PARAM_GROUP_START(controller)+PARAM_ADD(PARAM_UINT8, tiltComp, &tiltCompensationEnabled)+PARAM_GROUP_STOP(controller)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp.cnew file mode 100644index 0000000..23c7563--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp.c@@ -0,0 +1,291 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * crtp.c - CrazyRealtimeTransferProtocol stack+ */++#include <stdbool.h>+#include <errno.h>++/*FreeRtos includes*/+#include "FreeRTOS.h"+#include "task.h"+#include "semphr.h"+#include "queue.h"++#include "config.h"++#include "crtp.h"+#include "info.h"+#include "cfassert.h"+#include "queuemonitor.h"+#include "static_mem.h"++#include "log.h"++#define DEBUG_MODULE "CRTP"+#include "debug_cf.h"+#include "stm32_legacy.h"+++static bool isInit;++static int nopFunc(void);+static struct crtpLinkOperations nopLink = {+ .setEnable = (void*) nopFunc,+ .sendPacket = (void*) nopFunc,+ .receivePacket = (void*) nopFunc,+};++static struct crtpLinkOperations *link = &nopLink;++#define STATS_INTERVAL 500+static struct {+ uint32_t rxCount;+ uint32_t txCount;++ uint16_t rxRate;+ uint16_t txRate;++ uint32_t nextStatisticsTime;+ uint32_t previousStatisticsTime;+} stats;++static xQueueHandle txQueue;++#define CRTP_NBR_OF_PORTS 16+#define CRTP_TX_QUEUE_SIZE 120+#define CRTP_RX_QUEUE_SIZE 16++static void crtpTxTask(void *param);+static void crtpRxTask(void *param);++static xQueueHandle queues[CRTP_NBR_OF_PORTS];+static volatile CrtpCallback callbacks[CRTP_NBR_OF_PORTS];+static void updateStats();++STATIC_MEM_TASK_ALLOC_STACK_NO_DMA_CCM_SAFE(crtpTxTask, CRTP_TX_TASK_STACKSIZE);+STATIC_MEM_TASK_ALLOC_STACK_NO_DMA_CCM_SAFE(crtpRxTask, CRTP_RX_TASK_STACKSIZE);++void crtpInit(void)+{+ if(isInit)+ return;++ txQueue = xQueueCreate(CRTP_TX_QUEUE_SIZE, sizeof(CRTPPacket));+ DEBUG_QUEUE_MONITOR_REGISTER(txQueue);++ STATIC_MEM_TASK_CREATE(crtpTxTask, crtpTxTask, CRTP_TX_TASK_NAME, NULL, CRTP_TX_TASK_PRI);+ STATIC_MEM_TASK_CREATE(crtpRxTask, crtpRxTask, CRTP_RX_TASK_NAME, NULL, CRTP_RX_TASK_PRI);++ isInit = true;+}++bool crtpTest(void)+{+ return isInit;+}++void crtpInitTaskQueue(CRTPPort portId)+{+ ASSERT(queues[portId] == NULL);++ queues[portId] = xQueueCreate(CRTP_RX_QUEUE_SIZE, sizeof(CRTPPacket));+ DEBUG_QUEUE_MONITOR_REGISTER(queues[portId]);+}++int crtpReceivePacket(CRTPPort portId, CRTPPacket *p)+{+ ASSERT(queues[portId]);+ ASSERT(p);++ return xQueueReceive(queues[portId], p, 0);+}++int crtpReceivePacketBlock(CRTPPort portId, CRTPPacket *p)+{+ ASSERT(queues[portId]);+ ASSERT(p);++ return xQueueReceive(queues[portId], p, portMAX_DELAY);+}+++int crtpReceivePacketWait(CRTPPort portId, CRTPPacket *p, int wait)+{+ ASSERT(queues[portId]);+ ASSERT(p);++ return xQueueReceive(queues[portId], p, M2T(wait));+}++int crtpGetFreeTxQueuePackets(void)+{+ return (CRTP_TX_QUEUE_SIZE - uxQueueMessagesWaiting(txQueue));+}++void crtpTxTask(void *param)+{+ CRTPPacket p;++ while (true)+ {+ if (link != &nopLink)+ {+ if (xQueueReceive(txQueue, &p, portMAX_DELAY) == pdTRUE)+ {+ // Keep testing, if the link changes to USB it will go though+ while (link->sendPacket(&p) == false)+ {+ // Relaxation time+ vTaskDelay(M2T(10));+ }+ stats.txCount++;+ updateStats();+ }+ }+ else+ {+ vTaskDelay(M2T(10));+ }+ }+}++void crtpRxTask(void *param)+{+ CRTPPacket p;++ while (true)+ {+ if (link != &nopLink)+ {+ if (!link->receivePacket(&p))+ {+ if (queues[p.port])+ {+ if (xQueueSend(queues[p.port], &p, 0) == errQUEUE_FULL)+ {+ // We should never drop packet+ ASSERT(0);+ }+ }++ if (callbacks[p.port])+ {+ callbacks[p.port](&p);+ }++ stats.rxCount++;+ updateStats();+ }+ }+ else+ {+ vTaskDelay(M2T(10));+ }+ }+}++void crtpRegisterPortCB(int port, CrtpCallback cb)+{+ if (port>CRTP_NBR_OF_PORTS)+ return;++ callbacks[port] = cb;+}++int crtpSendPacket(CRTPPacket *p)+{+ ASSERT(p);+ ASSERT(p->size <= CRTP_MAX_DATA_SIZE);++ return xQueueSend(txQueue, p, 0);+}++int crtpSendPacketBlock(CRTPPacket *p)+{+ ASSERT(p);+ ASSERT(p->size <= CRTP_MAX_DATA_SIZE);++ return xQueueSend(txQueue, p, portMAX_DELAY);+}++int crtpReset(void)+{+ xQueueReset(txQueue);+ if (link->reset) {+ link->reset();+ }++ return 0;+}++bool crtpIsConnected(void)+{+ if (link->isConnected)+ return link->isConnected();+ return true;+}++void crtpSetLink(struct crtpLinkOperations * lk)+{+ if(link)+ link->setEnable(false);++ if (lk)+ link = lk;+ else+ link = &nopLink;++ link->setEnable(true);+}++static int nopFunc(void)+{+ return ENETDOWN;+}++static void clearStats()+{+ stats.rxCount = 0;+ stats.txCount = 0;+}++static void updateStats()+{+ uint32_t now = xTaskGetTickCount();+ if (now > stats.nextStatisticsTime) {+ float interval = now - stats.previousStatisticsTime;+ stats.rxRate = (uint16_t)(1000.0f * stats.rxCount / interval);+ stats.txRate = (uint16_t)(1000.0f * stats.txCount / interval);++ clearStats();+ stats.previousStatisticsTime = now;+ stats.nextStatisticsTime = now + STATS_INTERVAL;+ }+}++LOG_GROUP_START(crtp)+LOG_ADD(LOG_UINT16, rxRate, &stats.rxRate)+LOG_ADD(LOG_UINT16, txRate, &stats.txRate)+LOG_GROUP_STOP(tdoa)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander.cnew file mode 100644index 0000000..3069a3c--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander.c@@ -0,0 +1,135 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */+#include <stdbool.h>+#include <stddef.h>++#include "crtp_commander.h"++#include "cfassert.h"+#include "commander.h"+#include "crtp.h"+++static bool isInit;++static void commanderCrtpCB(CRTPPacket* pk);++void crtpCommanderInit(void)+{+ if(isInit) {+ return;+ }++ crtpInit();+ crtpRegisterPortCB(CRTP_PORT_SETPOINT, commanderCrtpCB);+ crtpRegisterPortCB(CRTP_PORT_SETPOINT_GENERIC, commanderCrtpCB);+ isInit = true;+}++enum crtpSetpointGenericChannel {+ SET_SETPOINT_CHANNEL = 0,+ META_COMMAND_CHANNEL = 1,+};++/* Channel 1 of the generic commander port is used for "meta-commands"+ * that alter the behavior of the commander itself, e.g. mode switching.+ * Although we use the generic commander port due to increasing pressure on the+ * 4-bit space of ports numbers, meta-commands that are unrelated to+ * streaming generic setpoint control modes are permitted.+ *+ * The packet format for meta-commands is:+ * +------+==========================++ * | TYPE | DATA |+ * +------+==========================++ *+ * TYPE is an 8-bit value. The remainder of the data depends on the command.+ * The maximum data size is 29 bytes.+ */++/* To add a new packet:+ * 1 - Add a new type in the metaCommand_e enum.+ * 2 - Implement a decoder function with good documentation about the data+ * structure and the intent of the packet.+ * 3 - Add the decoder function to the metaCommandDecoders array.+ * 4 - Create a new params group for your handler if necessary+ * 5 - Pull-request your change :-)+ */++/* ---===== 1 - metaCommand_e enum =====--- */+enum metaCommand_e {+ metaNotifySetpointsStop = 0,+ nMetaCommands,+};++typedef void (*metaCommandDecoder_t)(const void *data, size_t datalen);++/* ---===== 2 - Decoding functions =====--- */++/* notifySetpointsStop meta-command. See commander.h function+ * commanderNotifySetpointsStop() for description and motivation.+ */+struct notifySetpointsStopPacket {+ uint32_t remainValidMillisecs;+} __attribute__((packed));+void notifySetpointsStopDecoder(const void *data, size_t datalen)+{+ ASSERT(datalen == sizeof(struct notifySetpointsStopPacket));+ const struct notifySetpointsStopPacket *values = data;+ commanderNotifySetpointsStop(values->remainValidMillisecs);+}++ /* ---===== packetDecoders array =====--- */+const static metaCommandDecoder_t metaCommandDecoders[] = {+ [metaNotifySetpointsStop] = notifySetpointsStopDecoder,+};++/* Decoder switch */+static void commanderCrtpCB(CRTPPacket* pk)+{+ static setpoint_t setpoint;++ if(pk->port == CRTP_PORT_SETPOINT && pk->channel == 0) {+ crtpCommanderRpytDecodeSetpoint(&setpoint, pk);+ commanderSetSetpoint(&setpoint, COMMANDER_PRIORITY_CRTP);+ } else if (pk->port == CRTP_PORT_SETPOINT_GENERIC) {+ switch (pk->channel) {+ case SET_SETPOINT_CHANNEL:+ crtpCommanderGenericDecodeSetpoint(&setpoint, pk);+ commanderSetSetpoint(&setpoint, COMMANDER_PRIORITY_CRTP);+ break;+ case META_COMMAND_CHANNEL: {+ uint8_t metaCmd = pk->data[0];+ if (metaCmd < nMetaCommands && (metaCommandDecoders[metaCmd] != NULL)) {+ metaCommandDecoders[metaCmd](pk->data + 1, pk->size - 1);+ }+ }+ break;+ default:+ /* Do nothing */+ break;+ }+ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_generic.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_generic.cnew file mode 100644index 0000000..e88997e--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_generic.c@@ -0,0 +1,412 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */+#include <stdbool.h>+#include <stdint.h>+#include <string.h>++#include "crtp_commander.h"++#include "commander.h"+#include "param.h"+#include "crtp.h"+#include "num.h"+#include "quatcompress.h"+#include "FreeRTOS.h"+#include "cfassert.h"++/* The generic commander format contains a packet type and data that has to be+ * decoded into a setpoint_t structure. The aim is to make it future-proof+ * by easily allowing the addition of new packets for future use cases.+ *+ * The packet format is:+ * +------+==========================++ * | TYPE | DATA |+ * +------+==========================++ *+ * The type is defined bellow together with a decoder function that should take+ * the data buffer in and fill up a setpoint_t structure.+ * The maximum data size is 29 bytes.+ */++/* To add a new packet:+ * 1 - Add a new type in the packetType_e enum.+ * 2 - Implement a decoder function with good documentation about the data+ * structure and the intent of the packet.+ * 3 - Add the decoder function to the packetDecoders array.+ * 4 - Create a new params group for your handler if necessary+ * 5 - Pull-request your change :-)+ */++typedef void (*packetDecoder_t)(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen);++/* ---===== 1 - packetType_e enum =====--- */+enum packet_type {+ stopType = 0,+ velocityWorldType = 1,+ zDistanceType = 2,+ cppmEmuType = 3,+ altHoldType = 4,+ hoverType = 5,+ fullStateType = 6,+ positionType = 7,+};++/* ---===== 2 - Decoding functions =====--- */+/* The setpoint structure is reinitialized to 0 before being passed to the+ * functions+ */++/* stopDecoder+ * Keeps setpoint to 0: stops the motors and fall+ */+static void stopDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ return;+}++/* velocityDecoder+ * Set the Crazyflie velocity in the world coordinate system+ */+struct velocityPacket_s {+ float vx; // m in the world frame of reference+ float vy; // ...+ float vz; // ...+ float yawrate; // deg/s+} __attribute__((packed));+static void velocityDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ const struct velocityPacket_s *values = data;++ ASSERT(datalen == sizeof(struct velocityPacket_s));++ setpoint->mode.x = modeVelocity;+ setpoint->mode.y = modeVelocity;+ setpoint->mode.z = modeVelocity;++ setpoint->velocity.x = values->vx;+ setpoint->velocity.y = values->vy;+ setpoint->velocity.z = values->vz;++ setpoint->mode.yaw = modeVelocity;++ setpoint->attitudeRate.yaw = -values->yawrate;+}++/* zDistanceDecoder+ * Set the Crazyflie absolute height and roll/pitch angles+ */+struct zDistancePacket_s {+ float roll; // deg+ float pitch; // ...+ float yawrate; // deg/s+ float zDistance; // m in the world frame of reference+} __attribute__((packed));+static void zDistanceDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ const struct zDistancePacket_s *values = data;+++ ASSERT(datalen == sizeof(struct zDistancePacket_s));++ setpoint->mode.z = modeAbs;++ setpoint->position.z = values->zDistance;+++ setpoint->mode.yaw = modeVelocity;++ setpoint->attitudeRate.yaw = -values->yawrate;+++ setpoint->mode.roll = modeAbs;+ setpoint->mode.pitch = modeAbs;++ setpoint->attitude.roll = values->roll;+ setpoint->attitude.pitch = values->pitch;+}++/* cppmEmuDecoder+ * CRTP packet containing an emulation of CPPM channels+ * Channels have a range of 1000-2000 with a midpoint of 1500+ * Supports the ordinary RPYT channels plus up to MAX_AUX_RC_CHANNELS auxiliary channels.+ * Auxiliary channels are optional and transmitters do not have to transmit all the data+ * unless a given channel is actually in use (numAuxChannels must be set accordingly)+ *+ * Current aux channel assignments:+ * - AuxChannel0: set high to enable self-leveling, low to disable+ */+#define MAX_AUX_RC_CHANNELS 10++static float s_CppmEmuRollMaxRateDps = 720.0f; // For rate mode+static float s_CppmEmuPitchMaxRateDps = 720.0f; // For rate mode+static float s_CppmEmuRollMaxAngleDeg = 50.0f; // For level mode+static float s_CppmEmuPitchMaxAngleDeg = 50.0f; // For level mode+static float s_CppmEmuYawMaxRateDps = 400.0f; // Used regardless of flight mode++struct cppmEmuPacket_s {+ struct {+ uint8_t numAuxChannels : 4; // Set to 0 through MAX_AUX_RC_CHANNELS+ uint8_t reserved : 4;+ } hdr;+ uint16_t channelRoll;+ uint16_t channelPitch;+ uint16_t channelYaw;+ uint16_t channelThrust;+ uint16_t channelAux[MAX_AUX_RC_CHANNELS];+} __attribute__((packed));++static inline float getChannelUnitMultiplier(uint16_t channelValue, uint16_t channelMidpoint, uint16_t channelRange)+{+ // Compute a float from -1 to 1 based on the RC channel value, midpoint, and total range magnitude+ return ((float)channelValue - (float)channelMidpoint) / (float)channelRange;+}++static void cppmEmuDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ bool isSelfLevelEnabled = true;++ ASSERT(datalen >= 9); // minimum 9 bytes expected - 1byte header + four 2byte channels+ const struct cppmEmuPacket_s *values = data;+ ASSERT(datalen == 9 + (2*values->hdr.numAuxChannels)); // Total size is 9 + number of active aux channels++ // Aux channel 0 is reserved for enabling/disabling self-leveling+ // If it's in use, check and see if it's set and enable self-leveling.+ // If aux channel 0 is not in use, default to self-leveling enabled.+ isSelfLevelEnabled = !(values->hdr.numAuxChannels >= 1 && values->channelAux[0] < 1500);++ // Set the modes++ // Position is disabled+ setpoint->mode.x = modeDisable;+ setpoint->mode.y = modeDisable;+ setpoint->mode.z = modeDisable;++ // Yaw is always velocity+ setpoint->mode.yaw = modeVelocity;++ // Roll/Pitch mode is either velocity or abs based on isSelfLevelEnabled+ setpoint->mode.roll = isSelfLevelEnabled ? modeAbs : modeVelocity;+ setpoint->mode.pitch = isSelfLevelEnabled ? modeAbs : modeVelocity;++ // Rescale the CPPM values into angles to build the setpoint packet+ if(isSelfLevelEnabled)+ {+ setpoint->attitude.roll = -1 * getChannelUnitMultiplier(values->channelRoll, 1500, 500) * s_CppmEmuRollMaxAngleDeg; // roll inverted+ setpoint->attitude.pitch = -1 * getChannelUnitMultiplier(values->channelPitch, 1500, 500) * s_CppmEmuPitchMaxAngleDeg; // pitch inverted+ }+ else+ {+ setpoint->attitudeRate.roll = -1 * getChannelUnitMultiplier(values->channelRoll, 1500, 500) * s_CppmEmuRollMaxRateDps; // roll inverted+ setpoint->attitudeRate.pitch = -1 * getChannelUnitMultiplier(values->channelPitch, 1500, 500) * s_CppmEmuPitchMaxRateDps; // pitch inverted+ }++ setpoint->attitudeRate.yaw = -1 * getChannelUnitMultiplier(values->channelYaw, 1500, 500) * s_CppmEmuYawMaxRateDps; // yaw inverted+ setpoint->thrust = getChannelUnitMultiplier(values->channelThrust, 1000, 1000) * (float)UINT16_MAX; // Thrust is positive only - uses the full 1000-2000 range++ // Make sure thrust isn't negative+ if(setpoint->thrust < 0)+ {+ setpoint->thrust = 0;+ }+}++/* altHoldDecoder+ * Set the Crazyflie vertical velocity and roll/pitch angle+ */+struct altHoldPacket_s {+ float roll; // rad+ float pitch; // ...+ float yawrate; // deg/s+ float zVelocity; // m/s in the world frame of reference+} __attribute__((packed));+static void altHoldDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ const struct altHoldPacket_s *values = data;++ ASSERT(datalen == sizeof(struct altHoldPacket_s));+++ setpoint->mode.z = modeVelocity;++ setpoint->velocity.z = values->zVelocity;+++ setpoint->mode.yaw = modeVelocity;++ setpoint->attitudeRate.yaw = -values->yawrate;+++ setpoint->mode.roll = modeAbs;+ setpoint->mode.pitch = modeAbs;++ setpoint->attitude.roll = values->roll;+ setpoint->attitude.pitch = values->pitch;+}++/* hoverDecoder+ * Set the Crazyflie absolute height and velocity in the body coordinate system+ */+struct hoverPacket_s {+ float vx; // m/s in the body frame of reference+ float vy; // ...+ float yawrate; // deg/s+ float zDistance; // m in the world frame of reference+} __attribute__((packed));+static void hoverDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ const struct hoverPacket_s *values = data;++ ASSERT(datalen == sizeof(struct hoverPacket_s));++ setpoint->mode.z = modeAbs;+ setpoint->position.z = values->zDistance;+++ setpoint->mode.yaw = modeVelocity;+ setpoint->attitudeRate.yaw = -values->yawrate;+++ setpoint->mode.x = modeVelocity;+ setpoint->mode.y = modeVelocity;+ setpoint->velocity.x = values->vx;+ setpoint->velocity.y = values->vy;++ setpoint->velocity_body = true;+}++struct fullStatePacket_s {+ int16_t x; // position - mm+ int16_t y;+ int16_t z;+ int16_t vx; // velocity - mm / sec+ int16_t vy;+ int16_t vz;+ int16_t ax; // acceleration - mm / sec^2+ int16_t ay;+ int16_t az;+ int32_t quat; // compressed quaternion, see quatcompress.h+ int16_t rateRoll; // angular velocity - milliradians / sec+ int16_t ratePitch; // (NOTE: limits to about 5 full circles per sec.+ int16_t rateYaw; // may not be enough for extremely aggressive flight.)+} __attribute__((packed));+static void fullStateDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ const struct fullStatePacket_s *values = data;++ ASSERT(datalen == sizeof(struct fullStatePacket_s));++ #define UNPACK(x) \+ setpoint->mode.x = modeAbs; \+ setpoint->position.x = values->x / 1000.0f; \+ setpoint->velocity.x = (values->v ## x) / 1000.0f; \+ setpoint->acceleration.x = (values->a ## x) / 1000.0f; \++ UNPACK(x)+ UNPACK(y)+ UNPACK(z)+ #undef UNPACK++ float const millirad2deg = 180.0f / ((float)M_PI * 1000.0f);+ setpoint->attitudeRate.roll = millirad2deg * values->rateRoll;+ setpoint->attitudeRate.pitch = millirad2deg * values->ratePitch;+ setpoint->attitudeRate.yaw = millirad2deg * values->rateYaw;++ quatdecompress(values->quat, (float *)&setpoint->attitudeQuaternion.q0);+ setpoint->mode.quat = modeAbs;+ setpoint->mode.roll = modeDisable;+ setpoint->mode.pitch = modeDisable;+ setpoint->mode.yaw = modeDisable;+}++/* positionDecoder+ * Set the absolute postition and orientation+ */+ struct positionPacket_s {+ float x; // Position in m+ float y;+ float z;+ float yaw; // Orientation in degree+ } __attribute__((packed));+static void positionDecoder(setpoint_t *setpoint, uint8_t type, const void *data, size_t datalen)+{+ const struct positionPacket_s *values = data;++ setpoint->mode.x = modeAbs;+ setpoint->mode.y = modeAbs;+ setpoint->mode.z = modeAbs;++ setpoint->position.x = values->x;+ setpoint->position.y = values->y;+ setpoint->position.z = values->z;+++ setpoint->mode.yaw = modeAbs;++ setpoint->attitude.yaw = values->yaw;+}++ /* ---===== 3 - packetDecoders array =====--- */+const static packetDecoder_t packetDecoders[] = {+ [stopType] = stopDecoder,+ [velocityWorldType] = velocityDecoder,+ [zDistanceType] = zDistanceDecoder,+ [cppmEmuType] = cppmEmuDecoder,+ [altHoldType] = altHoldDecoder,+ [hoverType] = hoverDecoder,+ [fullStateType] = fullStateDecoder,+ [positionType] = positionDecoder,+};++/* Decoder switch */+void crtpCommanderGenericDecodeSetpoint(setpoint_t *setpoint, CRTPPacket *pk)+{+ static int nTypes = -1;++ ASSERT(pk->size > 0);++ if (nTypes<0) {+ nTypes = sizeof(packetDecoders)/sizeof(packetDecoders[0]);+ }++ uint8_t type = pk->data[0];++ memset(setpoint, 0, sizeof(setpoint_t));++ if (type<nTypes && (packetDecoders[type] != NULL)) {+ packetDecoders[type](setpoint, type, ((char*)pk->data)+1, pk->size-1);+ }+}++// Params for generic CRTP handlers++// CPPM Emulation commander+PARAM_GROUP_START(cmdrCPPM)+PARAM_ADD(PARAM_FLOAT, rateRoll, &s_CppmEmuRollMaxRateDps)+PARAM_ADD(PARAM_FLOAT, ratePitch, &s_CppmEmuPitchMaxRateDps)+PARAM_ADD(PARAM_FLOAT, rateYaw, &s_CppmEmuYawMaxRateDps)+PARAM_ADD(PARAM_FLOAT, angRoll, &s_CppmEmuRollMaxAngleDeg)+PARAM_ADD(PARAM_FLOAT, angPitch, &s_CppmEmuPitchMaxAngleDeg)+PARAM_GROUP_STOP(cmdrCPPM)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_high_level.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_high_level.cnew file mode 100644index 0000000..18e1a8e--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_high_level.c@@ -0,0 +1,827 @@+/*+ * ______+ * / ____/________ _____ __ ________ ______ __________ ___+ * / / / ___/ __ `/_ / / / / / ___/ | /| / / __ `/ ___/ __ `__ \+ * / /___/ / / /_/ / / /_/ /_/ (__ )| |/ |/ / /_/ / / / / / / / /+ * \____/_/ \__,_/ /___/\__, /____/ |__/|__/\__,_/_/ /_/ /_/ /_/+ * /____/+ *+ * Crazyswarm advanced control firmware for Crazyflie+ *++The MIT License (MIT)++Copyright (c) 2018 Wolfgang Hoenig and James Alan Preiss++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+*/+++/*+High-level commander: computes smooth setpoints based on high-level inputs+such as: take-off, landing, polynomial trajectories.+*/++#include <string.h>+#include <errno.h>+#include <math.h>++/* FreeRtos includes */+#include "FreeRTOS.h"+#include "task.h"+#include "semphr.h"++// Crazyswarm includes+#include "crtp.h"+#include "crtp_commander_high_level.h"+#include "planner.h"+#include "log.h"+#include "param.h"+#include "stm32_legacy.h"+#include "static_mem.h"++#define DEBUG_MODULE "CTRL_HL"+#include "debug_cf.h"+#include "mem.h"++// Local types+enum TrajectoryLocation_e {+ TRAJECTORY_LOCATION_INVALID = 0,+ TRAJECTORY_LOCATION_MEM = 1, // for trajectories that are uploaded dynamically+ // Future features might include trajectories on flash or uSD card+};++struct trajectoryDescription+{+ uint8_t trajectoryLocation; // one of TrajectoryLocation_e+ uint8_t trajectoryType; // one of TrajectoryType_e+ union+ {+ struct {+ uint32_t offset; // offset in uploaded memory+ uint8_t n_pieces;+ } __attribute__((packed)) mem; // if trajectoryLocation is TRAJECTORY_LOCATION_MEM+ } trajectoryIdentifier;+} __attribute__((packed));++// allocate memory to store trajectories+// 4k allows us to store 31 poly4d pieces+// other (compressed) formats might be added in the future+#define TRAJECTORY_MEMORY_SIZE 4096+extern uint8_t trajectories_memory[TRAJECTORY_MEMORY_SIZE];++#define ALL_GROUPS 0++// Global variables+uint8_t trajectories_memory[TRAJECTORY_MEMORY_SIZE];+static struct trajectoryDescription trajectory_descriptions[NUM_TRAJECTORY_DEFINITIONS];++static bool isInit = false;+static struct planner planner;+static uint8_t group_mask;+static struct vec pos; // last known setpoint (position [m])+static struct vec vel; // last known setpoint (velocity [m/s])+static float yaw; // last known setpoint yaw (yaw [rad])+static struct piecewise_traj trajectory;+static struct piecewise_traj_compressed compressed_trajectory;++// makes sure that we don't evaluate the trajectory while it is being changed+static xSemaphoreHandle lockTraj;+static StaticSemaphore_t lockTrajBuffer;++// safe default settings for takeoff and landing velocity+static float defaultTakeoffVelocity = 0.5f;+static float defaultLandingVelocity = 0.5f;++// TODO+// Trajectory memory handling from the memory module+// static uint32_t handleMemGetSize(void) { return crtpCommanderHighLevelTrajectoryMemSize(); }+// static bool handleMemRead(const uint32_t memAddr, const uint8_t readLen, uint8_t* buffer);+// static bool handleMemWrite(const uint32_t memAddr, const uint8_t writeLen, const uint8_t* buffer);+// static const MemoryHandlerDef_t memDef = {+// .type = MEM_TYPE_TRAJ,+// .getSize = handleMemGetSize,+// .read = handleMemRead,+// .write = handleMemWrite,+// };++STATIC_MEM_TASK_ALLOC(crtpCommanderHighLevelTask, CMD_HIGH_LEVEL_TASK_STACKSIZE);++// CRTP Packet definitions++// trajectory command (first byte of crtp packet)+enum TrajectoryCommand_e {+ COMMAND_SET_GROUP_MASK = 0,+ COMMAND_TAKEOFF = 1, // Deprecated, use COMMAND_TAKEOFF_2+ COMMAND_LAND = 2, // Deprecated, use COMMAND_LAND_2+ COMMAND_STOP = 3,+ COMMAND_GO_TO = 4,+ COMMAND_START_TRAJECTORY = 5,+ COMMAND_DEFINE_TRAJECTORY = 6,+ COMMAND_TAKEOFF_2 = 7,+ COMMAND_LAND_2 = 8,+ COMMAND_TAKEOFF_WITH_VELOCITY = 9,+ COMMAND_LAND_WITH_VELOCITY = 10,+};++struct data_set_group_mask {+ uint8_t groupMask; // mask for which groups this CF belongs to+} __attribute__((packed));++// vertical takeoff from current x-y position to given height+// Deprecated+struct data_takeoff {+ uint8_t groupMask; // mask for which CFs this should apply to+ float height; // m (absolute)+ float duration; // s (time it should take until target height is reached)+} __attribute__((packed));++// vertical takeoff from current x-y position to given height+struct data_takeoff_2 {+ uint8_t groupMask; // mask for which CFs this should apply to+ float height; // m (absolute)+ float yaw; // rad+ bool useCurrentYaw; // If true, use the current yaw (ignore the yaw parameter)+ float duration; // s (time it should take until target height is reached)+} __attribute__((packed));++// vertical takeoff from current x-y position to given height, with prescribed+// velocity+struct data_takeoff_with_velocity {+ uint8_t groupMask; // mask for which CFs this should apply to+ float height; // m (absolute or relative)+ bool heightIsRelative; // If true, height is relative to the current height (positive pointing up)+ float yaw; // rad+ bool useCurrentYaw; // If true, use the current yaw (ignore the yaw parameter)+ float velocity; // m/sec (average velocity during takeoff)+} __attribute__((packed));++// vertical land from current x-y position to given height+// Deprecated+struct data_land {+ uint8_t groupMask; // mask for which CFs this should apply to+ float height; // m (absolute)+ float duration; // s (time it should take until target height is reached)+} __attribute__((packed));++// vertical land from current x-y position to given height+struct data_land_2 {+ uint8_t groupMask; // mask for which CFs this should apply to+ float height; // m (absolute)+ float yaw; // rad+ bool useCurrentYaw; // If true, use the current yaw (ignore the yaw parameter)+ float duration; // s (time it should take until target height is reached)+} __attribute__((packed));++// vertical land from current x-y position to given height, with prescribed+// velocity+struct data_land_with_velocity {+ uint8_t groupMask; // mask for which CFs this should apply to+ float height; // m (absolute or relative)+ bool heightIsRelative; // If true, height is relative to the current height (positive pointing down)+ float yaw; // rad+ bool useCurrentYaw; // If true, use the current yaw (ignore the yaw parameter)+ float velocity; // m/s (average velocity during landing)+} __attribute__((packed));++// stops the current trajectory (turns off the motors)+struct data_stop {+ uint8_t groupMask; // mask for which CFs this should apply to+} __attribute__((packed));++// "take this much time to go here, then hover"+struct data_go_to {+ uint8_t groupMask; // mask for which CFs this should apply to+ uint8_t relative; // set to true, if position/yaw are relative to current setpoint+ float x; // m+ float y; // m+ float z; // m+ float yaw; // rad+ float duration; // sec+} __attribute__((packed));++// starts executing a specified trajectory+struct data_start_trajectory {+ uint8_t groupMask; // mask for which CFs this should apply to+ uint8_t relative; // set to true, if trajectory should be shifted to current setpoint+ uint8_t reversed; // set to true, if trajectory should be executed in reverse+ uint8_t trajectoryId; // id of the trajectory (previously defined by COMMAND_DEFINE_TRAJECTORY)+ float timescale; // time factor; 1 = original speed; >1: slower; <1: faster+} __attribute__((packed));++// starts executing a specified trajectory+struct data_define_trajectory {+ uint8_t trajectoryId;+ struct trajectoryDescription description;+} __attribute__((packed));++// Private functions+static void crtpCommanderHighLevelTask(void * prm);++static int set_group_mask(const struct data_set_group_mask* data);+static int takeoff(const struct data_takeoff* data);+static int land(const struct data_land* data);+static int takeoff2(const struct data_takeoff_2* data);+static int land2(const struct data_land_2* data);+static int takeoff_with_velocity(const struct data_takeoff_with_velocity* data);+static int land_with_velocity(const struct data_land_with_velocity* data);+static int stop(const struct data_stop* data);+static int go_to(const struct data_go_to* data);+static int start_trajectory(const struct data_start_trajectory* data);+static int define_trajectory(const struct data_define_trajectory* data);++// Helper functions+static struct vec state2vec(struct vec3_s v)+{+ return mkvec(v.x, v.y, v.z);+}++bool isInGroup(uint8_t g) {+ return g == ALL_GROUPS || (g & group_mask) != 0;+}++void crtpCommanderHighLevelInit(void)+{+ if (isInit) {+ return;+ }++ //memoryRegisterHandler(&memDef);+ plan_init(&planner);++ //Start the trajectory task+ STATIC_MEM_TASK_CREATE(crtpCommanderHighLevelTask, crtpCommanderHighLevelTask, CMD_HIGH_LEVEL_TASK_NAME, NULL, CMD_HIGH_LEVEL_TASK_PRI);++ lockTraj = xSemaphoreCreateMutexStatic(&lockTrajBuffer);++ pos = vzero();+ vel = vzero();+ yaw = 0;++ isInit = true;+}++bool crtpCommanderHighLevelIsStopped()+{+ return plan_is_stopped(&planner);+}++void crtpCommanderHighLevelTellState(const state_t *state)+{+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ pos = state2vec(state->position);+ vel = state2vec(state->velocity);+ yaw = radians(state->attitude.yaw);+ xSemaphoreGive(lockTraj);+}++void crtpCommanderHighLevelGetSetpoint(setpoint_t* setpoint, const state_t *state)+{+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;+ struct traj_eval ev = plan_current_goal(&planner, t);+ if (!is_traj_eval_valid(&ev)) {+ // programming error+ plan_stop(&planner);+ }+ xSemaphoreGive(lockTraj);++ // if we are on the ground, update the last setpoint with the current state estimate+ if (plan_is_stopped(&planner)) {+ pos = state2vec(state->position);+ vel = state2vec(state->velocity);+ yaw = radians(state->attitude.yaw);+ }++ if (is_traj_eval_valid(&ev)) {+ setpoint->position.x = ev.pos.x;+ setpoint->position.y = ev.pos.y;+ setpoint->position.z = ev.pos.z;+ setpoint->velocity.x = ev.vel.x;+ setpoint->velocity.y = ev.vel.y;+ setpoint->velocity.z = ev.vel.z;+ setpoint->attitude.yaw = degrees(ev.yaw);+ setpoint->attitudeRate.roll = degrees(ev.omega.x);+ setpoint->attitudeRate.pitch = degrees(ev.omega.y);+ setpoint->attitudeRate.yaw = degrees(ev.omega.z);+ setpoint->mode.x = modeAbs;+ setpoint->mode.y = modeAbs;+ setpoint->mode.z = modeAbs;+ setpoint->mode.roll = modeDisable;+ setpoint->mode.pitch = modeDisable;+ setpoint->mode.yaw = modeAbs;+ setpoint->mode.quat = modeDisable;+ setpoint->acceleration.x = ev.acc.x;+ setpoint->acceleration.y = ev.acc.y;+ setpoint->acceleration.z = ev.acc.z;++ // store the last setpoint+ pos = ev.pos;+ vel = ev.vel;+ yaw = ev.yaw;+ }+}++static int handleCommand(const enum TrajectoryCommand_e command, const uint8_t* data)+{+ int ret = 0;++ switch(command)+ {+ case COMMAND_SET_GROUP_MASK:+ ret = set_group_mask((const struct data_set_group_mask*)data);+ break;+ case COMMAND_TAKEOFF:+ ret = takeoff((const struct data_takeoff*)data);+ break;+ case COMMAND_LAND:+ ret = land((const struct data_land*)data);+ break;+ case COMMAND_TAKEOFF_2:+ ret = takeoff2((const struct data_takeoff_2*)data);+ break;+ case COMMAND_LAND_2:+ ret = land2((const struct data_land_2*)data);+ break;+ case COMMAND_TAKEOFF_WITH_VELOCITY:+ ret = takeoff_with_velocity((const struct data_takeoff_with_velocity*)data);+ break;+ case COMMAND_LAND_WITH_VELOCITY:+ ret = land_with_velocity((const struct data_land_with_velocity*)data);+ break;+ case COMMAND_STOP:+ ret = stop((const struct data_stop*)data);+ break;+ case COMMAND_GO_TO:+ ret = go_to((const struct data_go_to*)data);+ break;+ case COMMAND_START_TRAJECTORY:+ ret = start_trajectory((const struct data_start_trajectory*)data);+ break;+ case COMMAND_DEFINE_TRAJECTORY:+ ret = define_trajectory((const struct data_define_trajectory*)data);+ break;+ default:+ ret = ENOEXEC;+ break;+ }++ return ret;+}++void crtpCommanderHighLevelTask(void * prm)+{+ CRTPPacket p;+ crtpInitTaskQueue(CRTP_PORT_SETPOINT_HL);++ while(1) {+ crtpReceivePacketBlock(CRTP_PORT_SETPOINT_HL, &p);++ int ret = handleCommand(p.data[0], &p.data[1]);++ //answer+ p.data[3] = ret;+ p.size = 4;+ crtpSendPacket(&p);+ }+}++int set_group_mask(const struct data_set_group_mask* data)+{+ group_mask = data->groupMask;++ return 0;+}++int takeoff(const struct data_takeoff* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ DEBUG_PRINTD("take off !!!!!");+ float t = usecTimestamp() / 1e6;+ result = plan_takeoff(&planner, pos, yaw, data->height, 0.0f, data->duration, t);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int takeoff2(const struct data_takeoff_2* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;++ float hover_yaw = data->yaw;+ if (data->useCurrentYaw) {+ hover_yaw = yaw;+ }++ result = plan_takeoff(&planner, pos, yaw, data->height, hover_yaw, data->duration, t);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int takeoff_with_velocity(const struct data_takeoff_with_velocity* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;++ float hover_yaw = data->yaw;+ if (data->useCurrentYaw) {+ hover_yaw = yaw;+ }++ float height = data->height;+ if (data->heightIsRelative) {+ height += pos.z;+ }++ float velocity = data->velocity > 0 ? data->velocity : defaultTakeoffVelocity;+ float duration = fabsf(height - pos.z) / velocity;+ result = plan_takeoff(&planner, pos, yaw, height, hover_yaw, duration, t);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int land(const struct data_land* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;+ result = plan_land(&planner, pos, yaw, data->height, 0.0f, data->duration, t);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int land2(const struct data_land_2* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;++ float hover_yaw = data->yaw;+ if (data->useCurrentYaw) {+ hover_yaw = yaw;+ }++ result = plan_land(&planner, pos, yaw, data->height, hover_yaw, data->duration, t);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int land_with_velocity(const struct data_land_with_velocity* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;++ float hover_yaw = data->yaw;+ if (data->useCurrentYaw) {+ hover_yaw = yaw;+ }++ float height = data->height;+ if (data->heightIsRelative) {+ height = pos.z - height;+ }++ float velocity = data->velocity > 0 ? data->velocity : defaultLandingVelocity;+ float duration = fabsf(height - pos.z) / velocity;+ result = plan_land(&planner, pos, yaw, height, hover_yaw, duration, t);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int stop(const struct data_stop* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ plan_stop(&planner);+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int go_to(const struct data_go_to* data)+{+ static struct traj_eval ev = {+ // pos, vel, yaw will be filled before using+ .acc = {0.0f, 0.0f, 0.0f},+ .omega = {0.0f, 0.0f, 0.0f},+ };++ int result = 0;+ if (isInGroup(data->groupMask)) {+ struct vec hover_pos = mkvec(data->x, data->y, data->z);+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;+ if (plan_is_stopped(&planner)) {+ ev.pos = pos;+ ev.vel = vel;+ ev.yaw = yaw;+ result = plan_go_to_from(&planner, &ev, data->relative, hover_pos, data->yaw, data->duration, t);+ }+ else {+ result = plan_go_to(&planner, data->relative, hover_pos, data->yaw, data->duration, t);+ }+ xSemaphoreGive(lockTraj);+ }+ return result;+}++int start_trajectory(const struct data_start_trajectory* data)+{+ int result = 0;+ if (isInGroup(data->groupMask)) {+ if (data->trajectoryId < NUM_TRAJECTORY_DEFINITIONS) {+ struct trajectoryDescription* trajDesc = &trajectory_descriptions[data->trajectoryId];+ if ( trajDesc->trajectoryLocation == TRAJECTORY_LOCATION_MEM+ && trajDesc->trajectoryType == CRTP_CHL_TRAJECTORY_TYPE_POLY4D) {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;+ trajectory.t_begin = t;+ trajectory.timescale = data->timescale;+ trajectory.n_pieces = trajDesc->trajectoryIdentifier.mem.n_pieces;+ trajectory.pieces = (struct poly4d*)&trajectories_memory[trajDesc->trajectoryIdentifier.mem.offset];+ if (data->relative) {+ trajectory.shift = vzero();+ struct traj_eval traj_init;+ if (data->reversed) {+ traj_init = piecewise_eval_reversed(&trajectory, trajectory.t_begin);+ }+ else {+ traj_init = piecewise_eval(&trajectory, trajectory.t_begin);+ }+ struct vec shift_pos = vsub(pos, traj_init.pos);+ trajectory.shift = shift_pos;+ } else {+ trajectory.shift = vzero();+ }+ result = plan_start_trajectory(&planner, &trajectory, data->reversed);+ xSemaphoreGive(lockTraj);+ } else if (trajDesc->trajectoryLocation == TRAJECTORY_LOCATION_MEM+ && trajDesc->trajectoryType == CRTP_CHL_TRAJECTORY_TYPE_POLY4D_COMPRESSED) {++ if (data->timescale != 1 || data->reversed) {+ result = ENOEXEC;+ } else {+ xSemaphoreTake(lockTraj, portMAX_DELAY);+ float t = usecTimestamp() / 1e6;+ piecewise_compressed_load(+ &compressed_trajectory,+ &trajectories_memory[trajDesc->trajectoryIdentifier.mem.offset]+ );+ compressed_trajectory.t_begin = t;+ if (data->relative) {+ struct traj_eval traj_init = piecewise_compressed_eval(+ &compressed_trajectory, compressed_trajectory.t_begin+ );+ struct vec shift_pos = vsub(pos, traj_init.pos);+ compressed_trajectory.shift = shift_pos;+ } else {+ compressed_trajectory.shift = vzero();+ }+ result = plan_start_compressed_trajectory(&planner, &compressed_trajectory);+ xSemaphoreGive(lockTraj);+ }++ }+ }+ }+ return result;+}++int define_trajectory(const struct data_define_trajectory* data)+{+ if (data->trajectoryId >= NUM_TRAJECTORY_DEFINITIONS) {+ return ENOEXEC;+ }+ trajectory_descriptions[data->trajectoryId] = data->description;+ return 0;+}++// static bool handleMemRead(const uint32_t memAddr, const uint8_t readLen, uint8_t* buffer) {+// return crtpCommanderHighLevelReadTrajectory(memAddr, readLen, buffer);+// }++// static bool handleMemWrite(const uint32_t memAddr, const uint8_t writeLen, const uint8_t* buffer) {+// return crtpCommanderHighLevelWriteTrajectory(memAddr, writeLen, buffer);+// }++uint8_t* initCrtpPacket(CRTPPacket* packet, const enum TrajectoryCommand_e command)+{+ packet->port = CRTP_PORT_SETPOINT_HL;+ packet->data[0] = command;+ return &packet->data[1];+}++int crtpCommanderHighLevelTakeoff(const float absoluteHeight_m, const float duration_s)+{+ struct data_takeoff_2 data =+ {+ .height = absoluteHeight_m,+ .duration = duration_s,+ .useCurrentYaw = true,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_TAKEOFF_2, (const uint8_t*)&data);+}++int crtpCommanderHighLevelTakeoffYaw(const float absoluteHeight_m, const float duration_s, const float yaw)+{+ struct data_takeoff_2 data =+ {+ .height = absoluteHeight_m,+ .duration = duration_s,+ .useCurrentYaw = false,+ .yaw = yaw,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_TAKEOFF_2, (const uint8_t*)&data);+}++int crtpCommanderHighLevelTakeoffWithVelocity(const float height_m, const float velocity_m_s, bool relative)+{+ struct data_takeoff_with_velocity data =+ {+ .height = height_m,+ .heightIsRelative = relative,+ .velocity = velocity_m_s,+ .useCurrentYaw = true,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_TAKEOFF_WITH_VELOCITY, (const uint8_t*)&data);+}++int crtpCommanderHighLevelLand(const float absoluteHeight_m, const float duration_s)+{+ struct data_land_2 data =+ {+ .height = absoluteHeight_m,+ .duration = duration_s,+ .useCurrentYaw = true,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_LAND_2, (const uint8_t*)&data);+}++int crtpCommanderHighLevelLandWithVelocity(const float height_m, const float velocity_m_s, bool relative)+{+ struct data_land_with_velocity data =+ {+ .height = height_m,+ .heightIsRelative = relative,+ .velocity = velocity_m_s,+ .useCurrentYaw = true,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_LAND_WITH_VELOCITY, (const uint8_t*)&data);+}++int crtpCommanderHighLevelLandYaw(const float absoluteHeight_m, const float duration_s, const float yaw)+{+ struct data_land_2 data =+ {+ .height = absoluteHeight_m,+ .duration = duration_s,+ .useCurrentYaw = false,+ .yaw = yaw,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_LAND_2, (const uint8_t*)&data);+}++int crtpCommanderHighLevelStop()+{+ struct data_stop data =+ {+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_STOP, (const uint8_t*)&data);+}++int crtpCommanderHighLevelGoTo(const float x, const float y, const float z, const float yaw, const float duration_s, const bool relative)+{+ struct data_go_to data =+ {+ .x = x,+ .y = y,+ .z = z,+ .yaw = yaw,+ .duration = duration_s,+ .relative = relative,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_GO_TO, (const uint8_t*)&data);+}++bool crtpCommanderHighLevelIsTrajectoryDefined(uint8_t trajectoryId)+{+ return (+ trajectoryId < NUM_TRAJECTORY_DEFINITIONS &&+ trajectory_descriptions[trajectoryId].trajectoryLocation != TRAJECTORY_LOCATION_INVALID+ );+}++int crtpCommanderHighLevelStartTrajectory(const uint8_t trajectoryId, const float timeScale, const bool relative, const bool reversed)+{+ struct data_start_trajectory data =+ {+ .trajectoryId = trajectoryId,+ .timescale = timeScale,+ .relative = relative,+ .reversed = reversed,+ .groupMask = ALL_GROUPS,+ };++ return handleCommand(COMMAND_START_TRAJECTORY, (const uint8_t*)&data);+}++int crtpCommanderHighLevelDefineTrajectory(const uint8_t trajectoryId, const crtpCommanderTrajectoryType_t type, const uint32_t offset, const uint8_t nPieces)+{+ struct data_define_trajectory data =+ {+ .trajectoryId = trajectoryId,+ .description.trajectoryLocation = TRAJECTORY_LOCATION_MEM,+ .description.trajectoryType = type,+ .description.trajectoryIdentifier.mem.offset = offset,+ .description.trajectoryIdentifier.mem.n_pieces = nPieces,+ };++ return handleCommand(COMMAND_DEFINE_TRAJECTORY, (const uint8_t*)&data);+}++uint32_t crtpCommanderHighLevelTrajectoryMemSize()+{+ return sizeof(trajectories_memory);+}++bool crtpCommanderHighLevelWriteTrajectory(const uint32_t offset, const uint32_t length, const uint8_t* data)+{+ bool result = false;++ if ((offset + length) <= sizeof(trajectories_memory)) {+ memcpy(&(trajectories_memory[offset]), data, length);+ result = true;+ }++ return result;+}++bool crtpCommanderHighLevelReadTrajectory(const uint32_t offset, const uint32_t length, uint8_t* destination)+{+ bool result = false;++ if (offset + length <= sizeof(trajectories_memory) && memcpy(destination, &(trajectories_memory[offset]), length)) {+ result = true;+ }++ return result;+}++bool crtpCommanderHighLevelIsTrajectoryFinished() {+ float t = usecTimestamp() / 1e6;+ return plan_is_finished(&planner, t);+}++PARAM_GROUP_START(hlCommander)+PARAM_ADD(PARAM_FLOAT, vtoff, &defaultTakeoffVelocity)+PARAM_ADD(PARAM_FLOAT, vland, &defaultLandingVelocity)+PARAM_GROUP_STOP(hlCommander)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_rpyt.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_rpyt.cnew file mode 100644index 0000000..17c9e60--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_commander_rpyt.c@@ -0,0 +1,272 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2017 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */+#include <math.h>+#include <stdbool.h>++#include "crtp_commander.h"+#include "commander.h"+#include "estimator.h"+#include "crtp.h"+#include "param.h"+#include "FreeRTOS.h"+#include "num.h"+#include "stm32_legacy.h"+#define DEBUG_MODULE "MODE"+#include "debug_cf.h"++#define MIN_THRUST 1000+#define MAX_THRUST 60000++/**+ * CRTP commander rpyt packet format+ */+struct CommanderCrtpLegacyValues+{+ float roll; // deg+ float pitch; // deg+ float yaw; // deg+ uint16_t thrust;+} __attribute__((packed));++/**+ * Stabilization modes for Roll, Pitch, Yaw.+ */+typedef enum+{+ RATE = 0,+ ANGLE = 1,+} RPYType;++/**+ * Yaw flight Modes+ */+typedef enum+{+ CAREFREE = 0, // Yaw is locked to world coordinates thus heading stays the same when yaw rotates+ PLUSMODE = 1, // Plus-mode. Motor M1 is defined as front+ XMODE = 2, // X-mode. M1 & M4 are defined as front+} YawModeType;++static RPYType stabilizationModeRoll = ANGLE; // Current stabilization type of roll (rate or angle)+static RPYType stabilizationModePitch = ANGLE; // Current stabilization type of pitch (rate or angle)+static RPYType stabilizationModeYaw = RATE; // Current stabilization type of yaw (rate or angle)++static YawModeType yawMode = DEFAULT_YAW_MODE; // Yaw mode configuration+static bool carefreeResetFront; // Reset what is front in carefree mode++static bool thrustLocked = true;+static bool altHoldMode = false;+static bool posHoldMode = false;+static bool posSetMode = false;++/**+ * Set flight mode deponds on the present sensors+ *+ * @param mode flight mode num+ */+void setCommandermode(FlightMode mode){+#ifdef CONFIG_ENABLE_COMMAND_MODE_SET+ switch (mode) {+ case ALTHOLD_MODE:+ altHoldMode = true;+ posHoldMode = false;+ posSetMode = false;+ registerRequiredEstimator(complementaryEstimator);+ break;+ case POSHOLD_MODE:+ altHoldMode = true;+ posHoldMode = true;+ posSetMode = false;+ registerRequiredEstimator(kalmanEstimator);+ break;+ case POSSET_MODE:+ altHoldMode = false;+ posHoldMode = false;+ posSetMode = true;+ registerRequiredEstimator(kalmanEstimator);+ break;+ default:+ altHoldMode = false;+ posHoldMode = false;+ posSetMode = false;+ registerRequiredEstimator(complementaryEstimator);+ break;+ }+ DEBUG_PRINTI("FlightMode = %d",mode);+#else+ DEBUG_PRINTI("set FlightMode disable");+#endif+}++/**+ * Rotate Yaw so that the Crazyflie will change what is considered front.+ *+ * @param yawRad Amount of radians to rotate yaw.+ */+static void rotateYaw(setpoint_t *setpoint, float yawRad)+{+ float cosy = cosf(yawRad);+ float siny = sinf(yawRad);+ float originalRoll = setpoint->attitude.roll;+ float originalPitch = setpoint->attitude.pitch;++ setpoint->attitude.roll = originalRoll * cosy - originalPitch * siny;+ setpoint->attitude.pitch = originalPitch * cosy + originalRoll * siny;+}++/**+ * Update Yaw according to current setting+ */+static void yawModeUpdate(setpoint_t *setpoint)+{+ switch (yawMode)+ {+ case CAREFREE:+ // TODO: Add frame of reference to setpoint+ ASSERT(false);+ break;+ case PLUSMODE:+ rotateYaw(setpoint, 45 * M_PI / 180);+ break;+ case XMODE: // Fall through+ default:+ // Default in x-mode. Do nothing+ break;+ }+}++void crtpCommanderRpytDecodeSetpoint(setpoint_t *setpoint, CRTPPacket *pk)+{+ struct CommanderCrtpLegacyValues *values = (struct CommanderCrtpLegacyValues*)pk->data;++ if (commanderGetActivePriority() == COMMANDER_PRIORITY_DISABLE) {+ thrustLocked = true;+ }+ if (values->thrust == 0) {+ thrustLocked = false;+ }++ // Thrust+ uint16_t rawThrust = values->thrust;++ if (thrustLocked || (rawThrust < MIN_THRUST)) {+ setpoint->thrust = 0;+ } else {+ setpoint->thrust = fminf(rawThrust, MAX_THRUST);+ }++ if (altHoldMode) {+ setpoint->thrust = 0;+ setpoint->mode.z = modeVelocity;++ setpoint->velocity.z = ((float) rawThrust - 32767.f) / 32767.f;+ } else {+ setpoint->mode.z = modeDisable;+ }++ // roll/pitch+ if (posHoldMode) {+ setpoint->mode.x = modeVelocity;+ setpoint->mode.y = modeVelocity;+ setpoint->mode.roll = modeDisable;+ setpoint->mode.pitch = modeDisable;+ setpoint->velocity_body = true;++ setpoint->velocity.x = -values->pitch/30.0f;+ setpoint->velocity.y = -values->roll/30.0f;+ setpoint->attitude.roll = 0;+ setpoint->attitude.pitch = 0;+ } else if (posSetMode && values->thrust != 0) {+ setpoint->mode.x = modeAbs;+ setpoint->mode.y = modeAbs;+ setpoint->mode.z = modeAbs;+ setpoint->mode.roll = modeDisable;+ setpoint->mode.pitch = modeDisable;+ setpoint->mode.yaw = modeAbs;++ setpoint->position.x = -values->pitch;+ setpoint->position.y = values->roll;+ setpoint->position.z = values->thrust/1000.0f;++ setpoint->attitude.roll = 0;+ setpoint->attitude.pitch = 0;+ setpoint->attitude.yaw = values->yaw;+ setpoint->thrust = 0;+ } else {+ setpoint->mode.x = modeDisable;+ setpoint->mode.y = modeDisable;++ if (stabilizationModeRoll == RATE) {+ setpoint->mode.roll = modeVelocity;+ setpoint->attitudeRate.roll = values->roll;+ setpoint->attitude.roll = 0;+ } else {+ setpoint->mode.roll = modeAbs;+ setpoint->attitudeRate.roll = 0;+ setpoint->attitude.roll = values->roll;+ }++ if (stabilizationModePitch == RATE) {+ setpoint->mode.pitch = modeVelocity;+ setpoint->attitudeRate.pitch = values->pitch;+ setpoint->attitude.pitch = 0;+ } else {+ setpoint->mode.pitch = modeAbs;+ setpoint->attitudeRate.pitch = 0;+ setpoint->attitude.pitch = values->pitch;+ }++ setpoint->velocity.x = 0;+ setpoint->velocity.y = 0;+ }++ // Yaw+ if (!posSetMode) {+ if (stabilizationModeYaw == RATE) {+ // legacy rate input is inverted+ setpoint->attitudeRate.yaw = -values->yaw;+ yawModeUpdate(setpoint);+ setpoint->mode.yaw = modeVelocity;+ } else {+ setpoint->mode.yaw = modeAbs;+ setpoint->attitudeRate.yaw = 0;+ setpoint->attitude.yaw = values->yaw;+ }+ }+}++// Params for flight modes+PARAM_GROUP_START(flightmode)+PARAM_ADD(PARAM_UINT8, althold, &altHoldMode)+PARAM_ADD(PARAM_UINT8, poshold, &posHoldMode)+PARAM_ADD(PARAM_UINT8, posSet, &posSetMode)+PARAM_ADD(PARAM_UINT8, yawMode, &yawMode)+PARAM_ADD(PARAM_UINT8, yawRst, &carefreeResetFront)+PARAM_ADD(PARAM_UINT8, stabModeRoll, &stabilizationModeRoll)+PARAM_ADD(PARAM_UINT8, stabModePitch, &stabilizationModePitch)+PARAM_ADD(PARAM_UINT8, stabModeYaw, &stabilizationModeYaw)+PARAM_GROUP_STOP(flightmode)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_localization_service.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_localization_service.cnew file mode 100644index 0000000..c4affd8--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtp_localization_service.c@@ -0,0 +1,379 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */+#include <string.h>+#include <stdint.h>++#include "FreeRTOS.h"+#include "task.h"++#include "crtp.h"+#include "crtp_localization_service.h"+#include "log.h"+#include "param.h"++#include "stabilizer_types.h"+#include "stabilizer.h"+#include "configblock.h"+//#include "worker.h"+//#include "lighthouse_core.h"++//#include "locodeck.h"++#include "estimator.h"+#include "quatcompress.h"++#include "peer_localization.h"++#include "num.h"++#define NBR_OF_RANGES_IN_PACKET 5+#define NBR_OF_SWEEPS_IN_PACKET 2+#define NBR_OF_SENSOR_DIFFS_IN_PACKET 3+#define NBR_OF_BASESTATIONS 2+#define NBR_OF_+#define DEFAULT_EMERGENCY_STOP_TIMEOUT (1 * RATE_MAIN_LOOP)++typedef enum+{+ EXT_POSITION = 0,+ GENERIC_TYPE = 1,+ EXT_POSITION_PACKED = 2,+} locsrvChannels_t;++typedef struct+{+ uint8_t type;+ struct+ {+ uint8_t id;+ float range;+ } __attribute__((packed)) ranges[NBR_OF_RANGES_IN_PACKET];+} __attribute__((packed)) rangePacket;++typedef struct {+ uint8_t type;+ uint8_t basestation;+ struct {+ float sweep;+ struct {+ uint16_t angleDiff;+ } __attribute__((packed)) angleDiffs [NBR_OF_SENSOR_DIFFS_IN_PACKET];+ } __attribute__((packed)) sweeps [NBR_OF_SWEEPS_IN_PACKET];+} __attribute__((packed)) anglePacket;++// up to 4 items per CRTP packet+typedef struct {+ uint8_t id; // last 8 bit of the Crazyflie address+ int16_t x; // mm+ int16_t y; // mm+ int16_t z; // mm+} __attribute__((packed)) extPositionPackedItem;++// up to 2 items per CRTP packet+typedef struct {+ uint8_t id; // last 8 bit of the Crazyflie address+ int16_t x; // mm+ int16_t y; // mm+ int16_t z; // mm+ uint32_t quat; // compressed quaternion, see quatcompress.h+} __attribute__((packed)) extPosePackedItem;++// Struct for logging position information+static positionMeasurement_t ext_pos;+// Struct for logging pose information+static poseMeasurement_t ext_pose;++static CRTPPacket pkRange;+static uint8_t rangeIndex;+static bool enableRangeStreamFloat = false;++static CRTPPacket LhAngle;+static bool enableLighthouseAngleStream = false;+static float extPosStdDev = 0.01;+static float extQuatStdDev = 4.5e-3;+static bool isInit = false;+static uint8_t my_id;+static uint16_t tickOfLastPacket; // tick when last packet was received++static void locSrvCrtpCB(CRTPPacket* pk);+static void extPositionHandler(CRTPPacket* pk);+static void genericLocHandle(CRTPPacket* pk);+static void extPositionPackedHandler(CRTPPacket* pk);++void locSrvInit()+{+ if (isInit) {+ return;+ }++ uint64_t address = configblockGetRadioAddress();+ my_id = address & 0xFF;++ crtpRegisterPortCB(CRTP_PORT_LOCALIZATION, locSrvCrtpCB);+ isInit = true;+}++static void locSrvCrtpCB(CRTPPacket* pk)+{+ switch (pk->channel)+ {+ case EXT_POSITION:+ extPositionHandler(pk);+ break;+ case GENERIC_TYPE:+ genericLocHandle(pk);+ break;+ case EXT_POSITION_PACKED:+ extPositionPackedHandler(pk);+ break;+ default:+ break;+ }+}++static void extPositionHandler(CRTPPacket* pk) {+ const struct CrtpExtPosition* data = (const struct CrtpExtPosition*)pk->data;++ ext_pos.x = data->x;+ ext_pos.y = data->y;+ ext_pos.z = data->z;+ ext_pos.stdDev = extPosStdDev;++ estimatorEnqueuePosition(&ext_pos);+ tickOfLastPacket = xTaskGetTickCount();+}++static void extPoseHandler(const CRTPPacket* pk) {+ const struct CrtpExtPose* data = (const struct CrtpExtPose*)&pk->data[1];++ ext_pose.x = data->x;+ ext_pose.y = data->y;+ ext_pose.z = data->z;+ ext_pose.quat.x = data->qx;+ ext_pose.quat.y = data->qy;+ ext_pose.quat.z = data->qz;+ ext_pose.quat.w = data->qw;+ ext_pose.stdDevPos = extPosStdDev;+ ext_pose.stdDevQuat = extQuatStdDev;++ estimatorEnqueuePose(&ext_pose);+ tickOfLastPacket = xTaskGetTickCount();+}++static void extPosePackedHandler(const CRTPPacket* pk) {+ uint8_t numItems = (pk->size - 1) / sizeof(extPosePackedItem);+ for (uint8_t i = 0; i < numItems; ++i) {+ const extPosePackedItem* item = (const extPosePackedItem*)&pk->data[1 + i * sizeof(extPosePackedItem)];+ if (item->id == my_id) {+ ext_pose.x = item->x / 1000.0f;+ ext_pose.y = item->y / 1000.0f;+ ext_pose.z = item->z / 1000.0f;+ quatdecompress(item->quat, (float *)&ext_pose.quat.q0);+ ext_pose.stdDevPos = extPosStdDev;+ ext_pose.stdDevQuat = extQuatStdDev;+ estimatorEnqueuePose(&ext_pose);+ tickOfLastPacket = xTaskGetTickCount();+ } else {+ ext_pos.x = item->x / 1000.0f;+ ext_pos.y = item->y / 1000.0f;+ ext_pos.z = item->z / 1000.0f;+ ext_pos.stdDev = extPosStdDev;+ peerLocalizationTellPosition(item->id, &ext_pos);+ }+ }+}++static void lpsShortLppPacketHandler(CRTPPacket* pk) {+ if (pk->size >= 2) {+ bool success = lpsSendLppShort(pk->data[1], &pk->data[2], pk->size-2);++ pk->port = CRTP_PORT_LOCALIZATION;+ pk->channel = GENERIC_TYPE;+ pk->size = 3;+ pk->data[0] = LPS_SHORT_LPP_PACKET;+ pk->data[2] = success?1:0;+ crtpSendPacket(pk);+ }+}++typedef union {+ struct {+ // A bit field indicating for which base stations to store geometry data+ uint16_t geoDataBsField;+ // A bit field indicating for which base stations to store calibration data+ uint16_t calibrationDataBsField;+ } __attribute__((packed));+ uint32_t combinedField;+} __attribute__((packed)) LhPersistArgs_t;++static void lhPersistDataWorker(void* arg) {+ LhPersistArgs_t* args = (LhPersistArgs_t*) &arg;++ bool result = true;++ for (int baseStation = 0; baseStation < PULSE_PROCESSOR_N_BASE_STATIONS; baseStation++) {+ uint16_t mask = 1 << baseStation;+ bool storeGeo = (args->geoDataBsField & mask) != 0;+ bool storeCalibration = (args->calibrationDataBsField & mask) != 0;+ if (! lighthouseCorePersistData(baseStation, storeGeo, storeCalibration)) {+ result = false;+ break;+ }+ }++ CRTPPacket response = {+ .port = CRTP_PORT_LOCALIZATION,+ .channel = GENERIC_TYPE,+ .size = 2,+ .data = {LH_PERSIST_DATA, result}+ };++ crtpSendPacket(&response);+}++static void lhPersistDataHandler(CRTPPacket* pk) {+ if (pk->size >= (1 + sizeof(LhPersistArgs_t))) {+ LhPersistArgs_t* args = (LhPersistArgs_t*) &pk->data[1];+ workerSchedule(lhPersistDataWorker, (void*)args->combinedField);+ }+}++static void genericLocHandle(CRTPPacket* pk)+{+ const uint8_t type = pk->data[0];+ if (pk->size < 1) return;++ switch (type) {+ case LPS_SHORT_LPP_PACKET:+ lpsShortLppPacketHandler(pk);+ break;+ case EMERGENCY_STOP:+ stabilizerSetEmergencyStop();+ break;+ case EMERGENCY_STOP_WATCHDOG:+ stabilizerSetEmergencyStopTimeout(DEFAULT_EMERGENCY_STOP_TIMEOUT);+ break;+ case EXT_POSE:+ extPoseHandler(pk);+ break;+ case EXT_POSE_PACKED:+ extPosePackedHandler(pk);+ break;+ case LH_PERSIST_DATA:+ lhPersistDataHandler(pk);+ break;+ default:+ // Nothing here+ break;+ }+}++static void extPositionPackedHandler(CRTPPacket* pk)+{+ uint8_t numItems = pk->size / sizeof(extPositionPackedItem);+ for (uint8_t i = 0; i < numItems; ++i) {+ const extPositionPackedItem* item = (const extPositionPackedItem*)&pk->data[i * sizeof(extPositionPackedItem)];+ ext_pos.x = item->x / 1000.0f;+ ext_pos.y = item->y / 1000.0f;+ ext_pos.z = item->z / 1000.0f;+ ext_pos.stdDev = extPosStdDev;+ if (item->id == my_id) {+ estimatorEnqueuePosition(&ext_pos);+ tickOfLastPacket = xTaskGetTickCount();+ }+ else {+ peerLocalizationTellPosition(item->id, &ext_pos);+ }+ }+}++void locSrvSendRangeFloat(uint8_t id, float range)+{+ rangePacket *rp = (rangePacket *)pkRange.data;++ ASSERT(rangeIndex <= NBR_OF_RANGES_IN_PACKET);++ if (enableRangeStreamFloat)+ {+ rp->ranges[rangeIndex].id = id;+ rp->ranges[rangeIndex].range = range;+ rangeIndex++;++ if (rangeIndex >= 5)+ {+ rp->type = RANGE_STREAM_FLOAT;+ pkRange.port = CRTP_PORT_LOCALIZATION;+ pkRange.channel = GENERIC_TYPE;+ pkRange.size = sizeof(rangePacket);+ crtpSendPacket(&pkRange);+ rangeIndex = 0;+ }+ }+}++void locSrvSendLighthouseAngle(int basestation, pulseProcessorResult_t* angles)+{+ anglePacket *ap = (anglePacket *)LhAngle.data;++ if (enableLighthouseAngleStream) {+ ap->basestation = basestation;++ for(uint8_t its = 0; its < NBR_OF_SWEEPS_IN_PACKET; its++) {+ float angle_first_sensor = angles->sensorMeasurementsLh1[0].baseStatonMeasurements[basestation].correctedAngles[its];+ ap->sweeps[its].sweep = angle_first_sensor;++ for(uint8_t itd = 0; itd < NBR_OF_SENSOR_DIFFS_IN_PACKET; itd++) {+ float angle_other_sensor = angles->sensorMeasurementsLh1[itd + 1].baseStatonMeasurements[basestation].correctedAngles[its];+ uint16_t angle_diff = single2half(angle_first_sensor - angle_other_sensor);+ ap->sweeps[its].angleDiffs[itd].angleDiff = angle_diff;+ }+ }++ ap->type = LH_ANGLE_STREAM;+ LhAngle.port = CRTP_PORT_LOCALIZATION;+ LhAngle.channel = GENERIC_TYPE;+ LhAngle.size = sizeof(anglePacket);+ crtpSendPacket(&LhAngle);+ }+}+++LOG_GROUP_START(ext_pos)+ LOG_ADD(LOG_FLOAT, X, &ext_pos.x)+ LOG_ADD(LOG_FLOAT, Y, &ext_pos.y)+ LOG_ADD(LOG_FLOAT, Z, &ext_pos.z)+LOG_GROUP_STOP(ext_pos)++LOG_GROUP_START(locSrvZ)+ LOG_ADD(LOG_UINT16, tick, &tickOfLastPacket) // time when data was received last (ms/ticks)+LOG_GROUP_STOP(locSrvZ)++PARAM_GROUP_START(locSrv)+ PARAM_ADD(PARAM_UINT8, enRangeStreamFP32, &enableRangeStreamFloat)+ PARAM_ADD(PARAM_UINT8, enLhAngleStream, &enableLighthouseAngleStream)+ PARAM_ADD(PARAM_FLOAT, extPosStdDev, &extPosStdDev)+ PARAM_ADD(PARAM_FLOAT, extQuatStdDev, &extQuatStdDev)+PARAM_GROUP_STOP(locSrv)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/crtpservice.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtpservice.cnew file mode 100644index 0000000..0b0b8f5--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/crtpservice.c@@ -0,0 +1,81 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * crtpservice.c - Implements low level services for CRTP+ */++#include <stdbool.h>+#include <string.h>++/* FreeRtos includes */+#include "FreeRTOS.h"++#include "crtp.h"+#include "crtpservice.h"++static bool isInit=false;++typedef enum {+ linkEcho = 0x00,+ linkSource = 0x01,+ linkSink = 0x02,+} LinkNbr;++void crtpserviceHandler(CRTPPacket *p);++void crtpserviceInit(void)+{+ if (isInit)+ return;++ // Register a callback to service the Link port+ crtpRegisterPortCB(CRTP_PORT_LINK, crtpserviceHandler);++ isInit = true;+}++bool crtpserviceTest(void)+{+ return isInit;+}++void crtpserviceHandler(CRTPPacket *p)+{+ switch (p->channel)+ {+ case linkEcho:+ crtpSendPacket(p);+ break;+ case linkSource:+ p->size = CRTP_MAX_DATA_SIZE;+ bzero(p->data, CRTP_MAX_DATA_SIZE);+ strcpy((char*)p->data, "Bitcraze Crazyflie");+ crtpSendPacket(p);+ break;+ case linkSink:+ /* Ignore packet */+ break;+ default:+ break;+ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator.cnew file mode 100644index 0000000..f16034f--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator.c@@ -0,0 +1,238 @@+#define DEBUG_MODULE "ESTIMATOR"+#include "debug_cf.h"+#include "cfassert.h"+#include "estimator.h"+#include "estimator_complementary.h"+#include "estimator_kalman.h"+#include "debug_cf.h"+#define ESTIMATOR_NAME anyEstimator+#define DEFAULT_ESTIMATOR complementaryEstimator+static StateEstimatorType currentEstimator = anyEstimator;+static StateEstimatorType requiredEstimator = anyEstimator;++static void initEstimator(const StateEstimatorType estimator);+static void deinitEstimator(const StateEstimatorType estimator);++typedef struct {+ void (*init)(void);+ void (*deinit)(void);+ bool (*test)(void);+ void (*update)(state_t *state, sensorData_t *sensors, control_t *control, const uint32_t tick);+ const char* name;+ bool (*estimatorEnqueueTDOA)(const tdoaMeasurement_t *uwb);+ bool (*estimatorEnqueuePosition)(const positionMeasurement_t *pos);+ bool (*estimatorEnqueuePose)(const poseMeasurement_t *pose);+ bool (*estimatorEnqueueDistance)(const distanceMeasurement_t *dist);+ bool (*estimatorEnqueueTOF)(const tofMeasurement_t *tof);+ bool (*estimatorEnqueueAbsoluteHeight)(const heightMeasurement_t *height);+ bool (*estimatorEnqueueFlow)(const flowMeasurement_t *flow);+ bool (*estimatorEnqueueYawError)(const yawErrorMeasurement_t *error);+ //bool (*estimatorEnqueueSweepAngles)(const sweepAngleMeasurement_t *angles);+} EstimatorFcns;++#define NOT_IMPLEMENTED ((void*)0)++static EstimatorFcns estimatorFunctions[] = {+ {+ .init = NOT_IMPLEMENTED,+ .deinit = NOT_IMPLEMENTED,+ .test = NOT_IMPLEMENTED,+ .update = NOT_IMPLEMENTED,+ .name = "None",+ .estimatorEnqueueTDOA = NOT_IMPLEMENTED,+ .estimatorEnqueuePosition = NOT_IMPLEMENTED,+ .estimatorEnqueuePose = NOT_IMPLEMENTED,+ .estimatorEnqueueDistance = NOT_IMPLEMENTED,+ .estimatorEnqueueTOF = NOT_IMPLEMENTED,+ .estimatorEnqueueAbsoluteHeight = NOT_IMPLEMENTED,+ .estimatorEnqueueFlow = NOT_IMPLEMENTED,+ .estimatorEnqueueYawError = NOT_IMPLEMENTED,+ //.estimatorEnqueueSweepAngles = NOT_IMPLEMENTED,+ }, // Any estimator+ {+ .init = estimatorComplementaryInit,+ .deinit = NOT_IMPLEMENTED,+ .test = estimatorComplementaryTest,+ .update = estimatorComplementary,+ .name = "Complementary",+ .estimatorEnqueueTDOA = NOT_IMPLEMENTED,+ .estimatorEnqueuePosition = NOT_IMPLEMENTED,+ .estimatorEnqueuePose = NOT_IMPLEMENTED,+ .estimatorEnqueueDistance = NOT_IMPLEMENTED,+ .estimatorEnqueueTOF = estimatorComplementaryEnqueueTOF,+ .estimatorEnqueueAbsoluteHeight = NOT_IMPLEMENTED,+ .estimatorEnqueueFlow = NOT_IMPLEMENTED,+ .estimatorEnqueueYawError = NOT_IMPLEMENTED,+ //.estimatorEnqueueSweepAngles = NOT_IMPLEMENTED,+ },+ {+ .init = estimatorKalmanInit,+ .deinit = NOT_IMPLEMENTED,+ .test = estimatorKalmanTest,+ .update = estimatorKalman,+ .name = "Kalman",+ .estimatorEnqueueTDOA = estimatorKalmanEnqueueTDOA,+ .estimatorEnqueuePosition = estimatorKalmanEnqueuePosition,+ .estimatorEnqueuePose = estimatorKalmanEnqueuePose,+ .estimatorEnqueueDistance = estimatorKalmanEnqueueDistance,+ .estimatorEnqueueTOF = estimatorKalmanEnqueueTOF,+ .estimatorEnqueueAbsoluteHeight = estimatorKalmanEnqueueAbsoluteHeight,+ .estimatorEnqueueFlow = estimatorKalmanEnqueueFlow,+ .estimatorEnqueueYawError = estimatorKalmanEnqueueYawError,+ //.estimatorEnqueueSweepAngles = estimatorKalmanEnqueueSweepAngles,+ },+};++bool registerRequiredEstimator(StateEstimatorType estimator)+{+ bool isError = false;++ if (anyEstimator != estimator) {+ if (anyEstimator == requiredEstimator) {+ requiredEstimator = estimator;+ }+ else {+ if (requiredEstimator != estimator) {+ isError = true;+ DEBUG_PRINTW("WARNING: Two decks require different estimators\n");+ }+ }+ }++ return isError;+}++StateEstimatorType deckGetRequiredEstimator()+{+ return requiredEstimator;+}++void stateEstimatorInit(StateEstimatorType estimator) {+ stateEstimatorSwitchTo(estimator);+}++void stateEstimatorSwitchTo(StateEstimatorType estimator) {+ if (estimator < 0 || estimator >= StateEstimatorTypeCount) {+ return;+ }++ StateEstimatorType newEstimator = estimator;++ if (anyEstimator == newEstimator) {+ newEstimator = DEFAULT_ESTIMATOR;+ }++ StateEstimatorType forcedEstimator = ESTIMATOR_NAME;+ if (forcedEstimator != anyEstimator) {+ DEBUG_PRINTI("Estimator type forced\n");+ newEstimator = forcedEstimator;+ }++ initEstimator(newEstimator);+ StateEstimatorType previousEstimator = currentEstimator;+ currentEstimator = newEstimator;+ deinitEstimator(previousEstimator);++ DEBUG_PRINTI("Using %s (%d) estimator\n", stateEstimatorGetName(), currentEstimator);+}++StateEstimatorType getStateEstimator(void) {+ return currentEstimator;+}++static void initEstimator(const StateEstimatorType estimator) {+ if (estimatorFunctions[estimator].init) {+ estimatorFunctions[estimator].init();+ }+}++static void deinitEstimator(const StateEstimatorType estimator) {+ if (estimatorFunctions[estimator].deinit) {+ estimatorFunctions[estimator].deinit();+ }+}++bool stateEstimatorTest(void) {+ return estimatorFunctions[currentEstimator].test();+}++void stateEstimator(state_t *state, sensorData_t *sensors, control_t *control, const uint32_t tick) {+ estimatorFunctions[currentEstimator].update(state, sensors, control, tick);+}++const char* stateEstimatorGetName() {+ return estimatorFunctions[currentEstimator].name;+}+++bool estimatorEnqueueTDOA(const tdoaMeasurement_t *uwb) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueueTDOA) {+ return estimatorFunctions[currentEstimator].estimatorEnqueueTDOA(uwb);+ }++ return false;+}++bool estimatorEnqueueYawError(const yawErrorMeasurement_t* error) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueueYawError) {+ return estimatorFunctions[currentEstimator].estimatorEnqueueYawError(error);+ }++ return false;+}++bool estimatorEnqueuePosition(const positionMeasurement_t *pos) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueuePosition) {+ return estimatorFunctions[currentEstimator].estimatorEnqueuePosition(pos);+ }++ return false;+}++bool estimatorEnqueuePose(const poseMeasurement_t *pose) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueuePose) {+ return estimatorFunctions[currentEstimator].estimatorEnqueuePose(pose);+ }++ return false;+}++bool estimatorEnqueueDistance(const distanceMeasurement_t *dist) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueueDistance) {+ return estimatorFunctions[currentEstimator].estimatorEnqueueDistance(dist);+ }++ return false;+}++bool estimatorEnqueueTOF(const tofMeasurement_t *tof) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueueTOF) {+ return estimatorFunctions[currentEstimator].estimatorEnqueueTOF(tof);+ }++ return false;+}++bool estimatorEnqueueAbsoluteHeight(const heightMeasurement_t *height) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueueAbsoluteHeight) {+ return estimatorFunctions[currentEstimator].estimatorEnqueueAbsoluteHeight(height);+ }++ return false;+}++bool estimatorEnqueueFlow(const flowMeasurement_t *flow) {+ if (estimatorFunctions[currentEstimator].estimatorEnqueueFlow) {+ return estimatorFunctions[currentEstimator].estimatorEnqueueFlow(flow);+ }++ return false;+}++// bool estimatorEnqueueSweepAngles(const sweepAngleMeasurement_t *angles) {+// if (estimatorFunctions[currentEstimator].estimatorEnqueueSweepAngles) {+// return estimatorFunctions[currentEstimator].estimatorEnqueueSweepAngles(angles);+// }++// return false;+// }diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator_complementary.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator_complementary.cnew file mode 100644index 0000000..3e9f348--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator_complementary.c@@ -0,0 +1,131 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * estimator_complementary.c - a complementary estimator+ */++++#include "FreeRTOS.h"+#include "queue.h"+#include "stabilizer.h"+#include "estimator_complementary.h"+#include "sensfusion6.h"+#include "position_estimator.h"+#include "sensors.h"+#include "stabilizer_types.h"+#include "static_mem.h"++#define ATTITUDE_UPDATE_RATE RATE_250_HZ+#define ATTITUDE_UPDATE_DT 1.0/ATTITUDE_UPDATE_RATE++#define POS_UPDATE_RATE RATE_100_HZ+#define POS_UPDATE_DT 1.0/POS_UPDATE_RATE++static bool latestTofMeasurement(tofMeasurement_t* tofMeasurement);++// Measurements of TOF from laser sensor+#define TOF_QUEUE_LENGTH (1)+static xQueueHandle tofDataQueue;+STATIC_MEM_QUEUE_ALLOC(tofDataQueue, TOF_QUEUE_LENGTH, sizeof(tofMeasurement_t));+++void estimatorComplementaryInit(void)+{+ tofDataQueue = STATIC_MEM_QUEUE_CREATE(tofDataQueue);++ sensfusion6Init();+}++bool estimatorComplementaryTest(void)+{+ bool pass = true;++ pass &= sensfusion6Test();++ return pass;+}++void estimatorComplementary(state_t *state, sensorData_t *sensorData, control_t *control, const uint32_t tick)+{+ sensorsAcquire(sensorData, tick); // Read sensors at full rate (1000Hz)+ if (RATE_DO_EXECUTE(ATTITUDE_UPDATE_RATE, tick)) {+ sensfusion6UpdateQ(sensorData->gyro.x, sensorData->gyro.y, sensorData->gyro.z,+ sensorData->acc.x, sensorData->acc.y, sensorData->acc.z,+ ATTITUDE_UPDATE_DT);++ // Save attitude, adjusted for the legacy CF2 body coordinate system+ sensfusion6GetEulerRPY(&state->attitude.roll, &state->attitude.pitch, &state->attitude.yaw);++ // Save quaternion, hopefully one day this could be used in a better controller.+ // Note that this is not adjusted for the legacy coordinate system+ sensfusion6GetQuaternion(+ &state->attitudeQuaternion.x,+ &state->attitudeQuaternion.y,+ &state->attitudeQuaternion.z,+ &state->attitudeQuaternion.w);++ state->acc.z = sensfusion6GetAccZWithoutGravity(sensorData->acc.x,+ sensorData->acc.y,+ sensorData->acc.z);++ positionUpdateVelocity(state->acc.z, ATTITUDE_UPDATE_DT);+ }++ if (RATE_DO_EXECUTE(POS_UPDATE_RATE, tick)) {+ tofMeasurement_t tofMeasurement;++ latestTofMeasurement(&tofMeasurement);+ positionEstimate(state, sensorData, &tofMeasurement, POS_UPDATE_DT, tick);+ }+}++static bool latestTofMeasurement(tofMeasurement_t* tofMeasurement) {+ return xQueuePeek(tofDataQueue, tofMeasurement, 0) == pdTRUE;+}++static bool overwriteMeasurement(xQueueHandle queue, void *measurement)+{+ portBASE_TYPE result;+ bool isInInterrupt = false;//(SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0;++ if (isInInterrupt) {+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;+ result = xQueueOverwriteFromISR(queue, measurement, &xHigherPriorityTaskWoken);+ if(xHigherPriorityTaskWoken == pdTRUE)+ {+ portYIELD();+ }+ } else {+ result = xQueueOverwrite(queue, measurement);+ }+ return (result==pdTRUE);+}+++bool estimatorComplementaryEnqueueTOF(const tofMeasurement_t *tof)+{+ // A distance (distance) [m] to the ground along the z_B axis.+ return overwriteMeasurement(tofDataQueue, (void *)tof);+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator_kalman.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator_kalman.cnew file mode 100644index 0000000..9abf5ce--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/estimator_kalman.c@@ -0,0 +1,753 @@+/**+ * Authored by Michael Hamer (http://www.mikehamer.info), June 2016+ * Thank you to Mark Mueller (www.mwm.im) for advice during implementation,+ * and for derivation of the original filter in the below-cited paper.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ============================================================================+ *+ * The Kalman filter implemented in this file is based on the papers:+ *+ * "Fusing ultra-wideband range measurements with accelerometers and rate gyroscopes for quadrocopter state estimation"+ * http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=7139421+ *+ * and+ *+ * "Covariance Correction Step for Kalman Filtering with an Attitude"+ * http://arc.aiaa.org/doi/abs/10.2514/1.G000848+ *+ * Academic citation would be appreciated.+ *+ * BIBTEX ENTRIES:+ @INPROCEEDINGS{MuellerHamerUWB2015,+ author = {Mueller, Mark W and Hamer, Michael and D’Andrea, Raffaello},+ title = {Fusing ultra-wideband range measurements with accelerometers and rate gyroscopes for quadrocopter state estimation},+ booktitle = {2015 IEEE International Conference on Robotics and Automation (ICRA)},+ year = {2015},+ month = {May},+ pages = {1730-1736},+ doi = {10.1109/ICRA.2015.7139421},+ ISSN = {1050-4729}}++ @ARTICLE{MuellerCovariance2016,+ author={Mueller, Mark W and Hehn, Markus and D’Andrea, Raffaello},+ title={Covariance Correction Step for Kalman Filtering with an Attitude},+ journal={Journal of Guidance, Control, and Dynamics},+ pages={1--7},+ year={2016},+ publisher={American Institute of Aeronautics and Astronautics}}+ *+ * ============================================================================+ *+ * MAJOR CHANGELOG:+ * 2016.06.28, Mike Hamer: Initial version+ * 2019.04.12, Kristoffer Richardsson: Refactored, separated kalman implementation from OS related functionality+ *+ */+#include <inttypes.h>+#include "kalman_core.h"+#include "estimator_kalman.h"+#include "kalman_supervisor.h"+++#include "stm32_legacy.h"++#include "FreeRTOS.h"+#include "queue.h"+#include "task.h"+#include "semphr.h"+#include "sensors.h"+#include "static_mem.h"++#include "system.h"+#include "log.h"+#include "param.h"+#include "physicalConstants.h"++#include "statsCnt.h"+#include "rateSupervisor.h"+#include "config.h"++#define DEBUG_MODULE "ESTKALMAN"+#include "debug_cf.h"+++// #define KALMAN_USE_BARO_UPDATE+++/**+ * Additionally, the filter supports the incorporation of additional sensors into the state estimate+ *+ * This is done via the external functions:+ * - bool estimatorKalmanEnqueueUWBPacket(uwbPacket_t *uwb)+ * - bool estimatorKalmanEnqueuePosition(positionMeasurement_t *pos)+ * - bool estimatorKalmanEnqueueDistance(distanceMeasurement_t *dist)+ *+ * As well as by the following internal functions and datatypes+ */++// Distance-to-point measurements+static xQueueHandle distDataQueue;+STATIC_MEM_QUEUE_ALLOC(distDataQueue, 10, sizeof(distanceMeasurement_t));++static inline bool stateEstimatorHasDistanceMeasurement(distanceMeasurement_t *dist) {+ return (pdTRUE == xQueueReceive(distDataQueue, dist, 0));+}++// Direct measurements of Crazyflie position+static xQueueHandle posDataQueue;+STATIC_MEM_QUEUE_ALLOC(posDataQueue, 10, sizeof(positionMeasurement_t));++static inline bool stateEstimatorHasPositionMeasurement(positionMeasurement_t *pos) {+ return (pdTRUE == xQueueReceive(posDataQueue, pos, 0));+}++// Direct measurements of Crazyflie pose+static xQueueHandle poseDataQueue;+STATIC_MEM_QUEUE_ALLOC(poseDataQueue, 10, sizeof(poseMeasurement_t));++static inline bool stateEstimatorHasPoseMeasurement(poseMeasurement_t *pose) {+ return (pdTRUE == xQueueReceive(poseDataQueue, pose, 0));+}++// Measurements of a UWB Tx/Rx+static xQueueHandle tdoaDataQueue;+STATIC_MEM_QUEUE_ALLOC(tdoaDataQueue, 10, sizeof(tdoaMeasurement_t));++static inline bool stateEstimatorHasTDOAPacket(tdoaMeasurement_t *uwb) {+ return (pdTRUE == xQueueReceive(tdoaDataQueue, uwb, 0));+}++// Measurements of flow (dnx, dny)+static xQueueHandle flowDataQueue;+STATIC_MEM_QUEUE_ALLOC(flowDataQueue, 10, sizeof(flowMeasurement_t));++static inline bool stateEstimatorHasFlowPacket(flowMeasurement_t *flow) {+ return (pdTRUE == xQueueReceive(flowDataQueue, flow, 0));+}++// Measurements of TOF from laser sensor+static xQueueHandle tofDataQueue;+STATIC_MEM_QUEUE_ALLOC(tofDataQueue, 10, sizeof(tofMeasurement_t));++static inline bool stateEstimatorHasTOFPacket(tofMeasurement_t *tof) {+ return (pdTRUE == xQueueReceive(tofDataQueue, tof, 0));+}++// Absolute height measurement along the room Z+static xQueueHandle heightDataQueue;+STATIC_MEM_QUEUE_ALLOC(heightDataQueue, 10, sizeof(heightMeasurement_t));++static inline bool stateEstimatorHasHeightPacket(heightMeasurement_t *height) {+ return (pdTRUE == xQueueReceive(heightDataQueue, height, 0));+}+++static xQueueHandle yawErrorDataQueue;+STATIC_MEM_QUEUE_ALLOC(yawErrorDataQueue, 10, sizeof(yawErrorMeasurement_t));++static inline bool stateEstimatorHasYawErrorPacket(yawErrorMeasurement_t *error)+{+ return (pdTRUE == xQueueReceive(yawErrorDataQueue, error, 0));+}++// static xQueueHandle sweepAnglesDataQueue;+// STATIC_MEM_QUEUE_ALLOC(sweepAnglesDataQueue, 10, sizeof(sweepAngleMeasurement_t));++// static inline bool stateEstimatorHasSweepAnglesPacket(sweepAngleMeasurement_t *angles)+// {+// return (pdTRUE == xQueueReceive(sweepAnglesDataQueue, angles, 0));+// }++// Semaphore to signal that we got data from the stabilzer loop to process+static SemaphoreHandle_t runTaskSemaphore;++// Mutex to protect data that is shared between the task and+// functions called by the stabilizer loop+static SemaphoreHandle_t dataMutex;+static StaticSemaphore_t dataMutexBuffer;+++/**+ * Constants used in the estimator+ */++//thrust is thrust mapped for 65536 <==> 60 GRAMS!+#define CONTROL_TO_ACC (GRAVITY_MAGNITUDE*60.0f/(CF_MASS*1000.0f)/65536.0f)+++/**+ * Tuning parameters+ */+#define PREDICT_RATE RATE_100_HZ // this is slower than the IMU update rate of 500Hz+#define BARO_RATE RATE_25_HZ++// the point at which the dynamics change from stationary to flying+#define IN_FLIGHT_THRUST_THRESHOLD (GRAVITY_MAGNITUDE*0.1f)+#define IN_FLIGHT_TIME_THRESHOLD (500)++// The bounds on the covariance, these shouldn't be hit, but sometimes are... why?+#define MAX_COVARIANCE (100)+#define MIN_COVARIANCE (1e-6f)++++/**+ * Quadrocopter State+ *+ * The internally-estimated state is:+ * - X, Y, Z: the quad's position in the global frame+ * - PX, PY, PZ: the quad's velocity in its body frame+ * - D0, D1, D2: attitude error+ *+ * For more information, refer to the paper+ */++NO_DMA_CCM_SAFE_ZERO_INIT static kalmanCoreData_t coreData;++/**+ * Internal variables. Note that static declaration results in default initialization (to 0)+ */++static bool isInit = false;++static Axis3f accAccumulator;+static float thrustAccumulator;+static Axis3f gyroAccumulator;+static float baroAslAccumulator;+static uint32_t accAccumulatorCount;+static uint32_t thrustAccumulatorCount;+static uint32_t gyroAccumulatorCount;+static uint32_t baroAccumulatorCount;+static bool quadIsFlying = false;+static uint32_t lastFlightCmd;+static uint32_t takeoffTime;++// Data used to enable the task and stabilizer loop to run with minimal locking+static state_t taskEstimatorState; // The estimator state produced by the task, copied to the stabilzer when needed.+static Axis3f gyroSnapshot; // A snpashot of the latest gyro data, used by the task+static Axis3f accSnapshot; // A snpashot of the latest acc data, used by the task++// Statistics+#define ONE_SECOND 1000+static STATS_CNT_RATE_DEFINE(updateCounter, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(predictionCounter, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(baroUpdateCounter, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(finalizeCounter, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(measurementAppendedCounter, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(measurementNotAppendedCounter, ONE_SECOND);++static rateSupervisor_t rateSupervisorContext;++#define WARNING_HOLD_BACK_TIME M2T(2000)+static uint32_t warningBlockTime = 0;++#ifdef KALMAN_USE_BARO_UPDATE+static const bool useBaroUpdate = true;+#else+static const bool useBaroUpdate = false;+#endif++static void kalmanTask(void* parameters);+static bool predictStateForward(uint32_t osTick, float dt);+static bool updateQueuedMeasurments(const Axis3f *gyro, const uint32_t tick);++STATIC_MEM_TASK_ALLOC_STACK_NO_DMA_CCM_SAFE(kalmanTask, 3 * configMINIMAL_STACK_SIZE);++// --------------------------------------------------++// Called one time during system startup+void estimatorKalmanTaskInit() {+ distDataQueue = STATIC_MEM_QUEUE_CREATE(distDataQueue);+ posDataQueue = STATIC_MEM_QUEUE_CREATE(posDataQueue);+ poseDataQueue = STATIC_MEM_QUEUE_CREATE(poseDataQueue);+ tdoaDataQueue = STATIC_MEM_QUEUE_CREATE(tdoaDataQueue);+ flowDataQueue = STATIC_MEM_QUEUE_CREATE(flowDataQueue);+ tofDataQueue = STATIC_MEM_QUEUE_CREATE(tofDataQueue);+ heightDataQueue = STATIC_MEM_QUEUE_CREATE(heightDataQueue);+ yawErrorDataQueue = STATIC_MEM_QUEUE_CREATE(yawErrorDataQueue);+ //sweepAnglesDataQueue = STATIC_MEM_QUEUE_CREATE(sweepAnglesDataQueue);++ vSemaphoreCreateBinary(runTaskSemaphore);++ dataMutex = xSemaphoreCreateMutexStatic(&dataMutexBuffer);++ STATIC_MEM_TASK_CREATE(kalmanTask, kalmanTask, KALMAN_TASK_NAME, NULL, KALMAN_TASK_PRI);++ isInit = true;+}++bool estimatorKalmanTaskTest() {+ return isInit;+}++static void kalmanTask(void* parameters) {+ systemWaitStart();++ uint32_t lastPrediction = xTaskGetTickCount();+ uint32_t nextPrediction = xTaskGetTickCount();+ uint32_t lastPNUpdate = xTaskGetTickCount();+ uint32_t nextBaroUpdate = xTaskGetTickCount();++ rateSupervisorInit(&rateSupervisorContext, xTaskGetTickCount(), M2T(1000), 99, 101, 1);++ while (true) {+ xSemaphoreTake(runTaskSemaphore, portMAX_DELAY);++ // If the client triggers an estimator reset via parameter update+ if (coreData.resetEstimation) {+ estimatorKalmanInit();+ paramSetInt(paramGetVarId("kalman", "resetEstimation"), 0);+ }++ // Tracks whether an update to the state has been made, and the state therefore requires finalization+ bool doneUpdate = false;++ uint32_t osTick = xTaskGetTickCount(); // would be nice if this had a precision higher than 1ms...++ #ifdef KALMAN_DECOUPLE_XY+ kalmanCoreDecoupleXY(&coreData);+ #endif++ // Run the system dynamics to predict the state forward.+ if (osTick >= nextPrediction) { // update at the PREDICT_RATE+ float dt = T2S(osTick - lastPrediction);+ if (predictStateForward(osTick, dt)) {+ lastPrediction = osTick;+ doneUpdate = true;+ STATS_CNT_RATE_EVENT(&predictionCounter);+ }++ nextPrediction = osTick + S2T(1.0f / PREDICT_RATE);++ if (!rateSupervisorValidate(&rateSupervisorContext, T2M(osTick))) {+ DEBUG_PRINT("WARNING: Kalman prediction rate low (%"PRIu32")\n", rateSupervisorLatestCount(&rateSupervisorContext));+ }+ }++ /**+ * Add process noise every loop, rather than every prediction+ */+ {+ float dt = T2S(osTick - lastPNUpdate);+ if (dt > 0.0f) {+ kalmanCoreAddProcessNoise(&coreData, dt);+ lastPNUpdate = osTick;+ }+ }++ /**+ * Update the state estimate with the barometer measurements+ */+ // Accumulate the barometer measurements+ if (useBaroUpdate) {+ if (osTick > nextBaroUpdate // update at BARO_RATE+ && baroAccumulatorCount > 0)+ {+ xSemaphoreTake(dataMutex, portMAX_DELAY);+ float baroAslAverage = baroAslAccumulator / baroAccumulatorCount;+ baroAslAccumulator = 0;+ baroAccumulatorCount = 0;+ xSemaphoreGive(dataMutex);++ kalmanCoreUpdateWithBaro(&coreData, baroAslAverage, quadIsFlying);++ nextBaroUpdate = osTick + S2T(1.0f / BARO_RATE);+ doneUpdate = true;++ STATS_CNT_RATE_EVENT(&baroUpdateCounter);+ }+ }++ {+ Axis3f gyro;+ xSemaphoreTake(dataMutex, portMAX_DELAY);+ memcpy(&gyro, &gyroSnapshot, sizeof(gyro));+ xSemaphoreGive(dataMutex);++ if(updateQueuedMeasurments(&gyro, osTick)) {+ doneUpdate = true;+ }+ }++ /**+ * If an update has been made, the state is finalized:+ * - the attitude error is moved into the body attitude quaternion,+ * - the body attitude is converted into a rotation matrix for the next prediction, and+ * - correctness of the covariance matrix is ensured+ */++ if (doneUpdate)+ {+ kalmanCoreFinalize(&coreData, osTick);+ STATS_CNT_RATE_EVENT(&finalizeCounter);+ if (! kalmanSupervisorIsStateWithinBounds(&coreData)) {+ coreData.resetEstimation = true;++ if (osTick > warningBlockTime) {+ warningBlockTime = osTick + WARNING_HOLD_BACK_TIME;+ DEBUG_PRINT("State out of bounds, resetting\n");+ }+ }+ }++ /**+ * Finally, the internal state is externalized.+ * This is done every round, since the external state includes some sensor data+ */+ xSemaphoreTake(dataMutex, portMAX_DELAY);+ kalmanCoreExternalizeState(&coreData, &taskEstimatorState, &accSnapshot, osTick);+ xSemaphoreGive(dataMutex);++ STATS_CNT_RATE_EVENT(&updateCounter);+ }+}++void estimatorKalman(state_t *state, sensorData_t *sensors, control_t *control, const uint32_t tick)+{+ // This function is called from the stabilizer loop. It is important that this call returns+ // as quickly as possible. The dataMutex must only be locked short periods by the task.+ xSemaphoreTake(dataMutex, portMAX_DELAY);++ // Average the last IMU measurements. We do this because the prediction loop is+ // slower than the IMU loop, but the IMU information is required externally at+ // a higher rate (for body rate control).+ if (sensorsReadAcc(&sensors->acc)) {+ accAccumulator.x += sensors->acc.x;+ accAccumulator.y += sensors->acc.y;+ accAccumulator.z += sensors->acc.z;+ accAccumulatorCount++;+ }++ if (sensorsReadGyro(&sensors->gyro)) {+ gyroAccumulator.x += sensors->gyro.x;+ gyroAccumulator.y += sensors->gyro.y;+ gyroAccumulator.z += sensors->gyro.z;+ gyroAccumulatorCount++;+ }++ // Average the thrust command from the last time steps, generated externally by the controller+ thrustAccumulator += control->thrust;+ thrustAccumulatorCount++;++ // Average barometer data+ if (useBaroUpdate) {+ if (sensorsReadBaro(&sensors->baro)) {+ baroAslAccumulator += sensors->baro.asl;+ baroAccumulatorCount++;+ }+ }++ // Make a copy of sensor data to be used by the task+ memcpy(&gyroSnapshot, &sensors->gyro, sizeof(gyroSnapshot));+ memcpy(&accSnapshot, &sensors->acc, sizeof(accSnapshot));++ // Copy the latest state, calculated by the task+ memcpy(state, &taskEstimatorState, sizeof(state_t));+ xSemaphoreGive(dataMutex);++ xSemaphoreGive(runTaskSemaphore);+}++static bool predictStateForward(uint32_t osTick, float dt) {+ if (gyroAccumulatorCount == 0+ || accAccumulatorCount == 0+ || thrustAccumulatorCount == 0)+ {+ return false;+ }++ xSemaphoreTake(dataMutex, portMAX_DELAY);++ // gyro is in deg/sec but the estimator requires rad/sec+ Axis3f gyroAverage;+ gyroAverage.x = gyroAccumulator.x * DEG_TO_RAD / gyroAccumulatorCount;+ gyroAverage.y = gyroAccumulator.y * DEG_TO_RAD / gyroAccumulatorCount;+ gyroAverage.z = gyroAccumulator.z * DEG_TO_RAD / gyroAccumulatorCount;++ // accelerometer is in Gs but the estimator requires ms^-2+ Axis3f accAverage;+ accAverage.x = accAccumulator.x * GRAVITY_MAGNITUDE / accAccumulatorCount;+ accAverage.y = accAccumulator.y * GRAVITY_MAGNITUDE / accAccumulatorCount;+ accAverage.z = accAccumulator.z * GRAVITY_MAGNITUDE / accAccumulatorCount;++ // thrust is in grams, we need ms^-2+ float thrustAverage = thrustAccumulator * CONTROL_TO_ACC / thrustAccumulatorCount;++ accAccumulator = (Axis3f){.axis={0}};+ accAccumulatorCount = 0;+ gyroAccumulator = (Axis3f){.axis={0}};+ gyroAccumulatorCount = 0;+ thrustAccumulator = 0;+ thrustAccumulatorCount = 0;++ xSemaphoreGive(dataMutex);++ // TODO: Find a better check for whether the quad is flying+ // Assume that the flight begins when the thrust is large enough and for now we never stop "flying".+ if (thrustAverage > IN_FLIGHT_THRUST_THRESHOLD) {+ lastFlightCmd = osTick;+ if (!quadIsFlying) {+ takeoffTime = lastFlightCmd;+ }+ }+ quadIsFlying = (osTick-lastFlightCmd) < IN_FLIGHT_TIME_THRESHOLD;++ kalmanCorePredict(&coreData, thrustAverage, &accAverage, &gyroAverage, dt, quadIsFlying);++ return true;+}+++static bool updateQueuedMeasurments(const Axis3f *gyro, const uint32_t tick) {+ bool doneUpdate = false;+ /**+ * Sensor measurements can come in sporadically and faster than the stabilizer loop frequency,+ * we therefore consume all measurements since the last loop, rather than accumulating+ */++ tofMeasurement_t tof;+ while (stateEstimatorHasTOFPacket(&tof))+ {+ kalmanCoreUpdateWithTof(&coreData, &tof);+ doneUpdate = true;+ }++ yawErrorMeasurement_t yawError;+ while (stateEstimatorHasYawErrorPacket(&yawError))+ {+ kalmanCoreUpdateWithYawError(&coreData, &yawError);+ doneUpdate = true;+ }++ heightMeasurement_t height;+ while (stateEstimatorHasHeightPacket(&height))+ {+ kalmanCoreUpdateWithAbsoluteHeight(&coreData, &height);+ doneUpdate = true;+ }++ distanceMeasurement_t dist;+ while (stateEstimatorHasDistanceMeasurement(&dist))+ {+ kalmanCoreUpdateWithDistance(&coreData, &dist);+ doneUpdate = true;+ }++ positionMeasurement_t pos;+ while (stateEstimatorHasPositionMeasurement(&pos))+ {+ kalmanCoreUpdateWithPosition(&coreData, &pos);+ doneUpdate = true;+ }++ poseMeasurement_t pose;+ while (stateEstimatorHasPoseMeasurement(&pose))+ {+ kalmanCoreUpdateWithPose(&coreData, &pose);+ doneUpdate = true;+ }++ tdoaMeasurement_t tdoa;+ while (stateEstimatorHasTDOAPacket(&tdoa))+ {+ kalmanCoreUpdateWithTDOA(&coreData, &tdoa);+ doneUpdate = true;+ }++ flowMeasurement_t flow;+ while (stateEstimatorHasFlowPacket(&flow))+ {+ kalmanCoreUpdateWithFlow(&coreData, &flow, gyro);+ doneUpdate = true;+ }++ // sweepAngleMeasurement_t angles;+ // while (stateEstimatorHasSweepAnglesPacket(&angles))+ // {+ // kalmanCoreUpdateWithSweepAngles(&coreData, &angles, tick);+ // doneUpdate = true;+ // }++ return doneUpdate;+}++// Called when this estimator is activated+void estimatorKalmanInit(void) {+ xQueueReset(distDataQueue);+ xQueueReset(posDataQueue);+ xQueueReset(poseDataQueue);+ xQueueReset(tdoaDataQueue);+ xQueueReset(flowDataQueue);+ xQueueReset(tofDataQueue);++ xSemaphoreTake(dataMutex, portMAX_DELAY);+ accAccumulator = (Axis3f){.axis={0}};+ gyroAccumulator = (Axis3f){.axis={0}};+ thrustAccumulator = 0;+ baroAslAccumulator = 0;++ accAccumulatorCount = 0;+ gyroAccumulatorCount = 0;+ thrustAccumulatorCount = 0;+ baroAccumulatorCount = 0;+ xSemaphoreGive(dataMutex);++ kalmanCoreInit(&coreData);+}++static bool appendMeasurement(xQueueHandle queue, void *measurement)+{+ portBASE_TYPE result;+ bool isInInterrupt = 0; //TODO:= (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) != 0;++ if (isInInterrupt) {+ portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE;+ result = xQueueSendFromISR(queue, measurement, &xHigherPriorityTaskWoken);+ if(xHigherPriorityTaskWoken == pdTRUE)+ {+ portYIELD();+ }+ } else {+ result = xQueueSend(queue, measurement, 0);+ }++ if (result == pdTRUE) {+ STATS_CNT_RATE_EVENT(&measurementAppendedCounter);+ return true;+ } else {+ STATS_CNT_RATE_EVENT(&measurementNotAppendedCounter);+ return true;+ }+}++bool estimatorKalmanEnqueueTDOA(const tdoaMeasurement_t *uwb)+{+ ASSERT(isInit);+ return appendMeasurement(tdoaDataQueue, (void *)uwb);+}++bool estimatorKalmanEnqueuePosition(const positionMeasurement_t *pos)+{+ ASSERT(isInit);+ return appendMeasurement(posDataQueue, (void *)pos);+}++bool estimatorKalmanEnqueuePose(const poseMeasurement_t *pose)+{+ ASSERT(isInit);+ return appendMeasurement(poseDataQueue, (void *)pose);+}++bool estimatorKalmanEnqueueDistance(const distanceMeasurement_t *dist)+{+ ASSERT(isInit);+ return appendMeasurement(distDataQueue, (void *)dist);+}++bool estimatorKalmanEnqueueFlow(const flowMeasurement_t *flow)+{+ // A flow measurement (dnx, dny) [accumulated pixels]+ ASSERT(isInit);+ return appendMeasurement(flowDataQueue, (void *)flow);+}++bool estimatorKalmanEnqueueTOF(const tofMeasurement_t *tof)+{+ // A distance (distance) [m] to the ground along the z_B axis.+ ASSERT(isInit);+ return appendMeasurement(tofDataQueue, (void *)tof);+}++bool estimatorKalmanEnqueueAbsoluteHeight(const heightMeasurement_t *height)+{+ // A distance (height) [m] to the ground along the z axis.+ ASSERT(isInit);+ return appendMeasurement(heightDataQueue, (void *)height);+}++bool estimatorKalmanEnqueueYawError(const yawErrorMeasurement_t* error)+{+ ASSERT(isInit);+ return appendMeasurement(yawErrorDataQueue, (void *)error);+}++// bool estimatorKalmanEnqueueSweepAngles(const sweepAngleMeasurement_t *angles)+// {+// ASSERT(isInit);+// return appendMeasurement(sweepAnglesDataQueue, (void *)angles);+// }++bool estimatorKalmanTest(void)+{+ return isInit;+}++void estimatorKalmanGetEstimatedPos(point_t* pos) {+ pos->x = coreData.S[KC_STATE_X];+ pos->y = coreData.S[KC_STATE_Y];+ pos->z = coreData.S[KC_STATE_Z];+}++void estimatorKalmanGetEstimatedRot(float * rotationMatrix) {+ memcpy(rotationMatrix, coreData.R, 9*sizeof(float));+}++// Temporary development groups+LOG_GROUP_START(kalman_states)+ LOG_ADD(LOG_FLOAT, ox, &coreData.S[KC_STATE_X])+ LOG_ADD(LOG_FLOAT, oy, &coreData.S[KC_STATE_Y])+ LOG_ADD(LOG_FLOAT, vx, &coreData.S[KC_STATE_PX])+ LOG_ADD(LOG_FLOAT, vy, &coreData.S[KC_STATE_PY])+LOG_GROUP_STOP(kalman_states)+++// Stock log groups+LOG_GROUP_START(kalman)+ LOG_ADD(LOG_UINT8, inFlight, &quadIsFlying)+ LOG_ADD(LOG_FLOAT, stateX, &coreData.S[KC_STATE_X])+ LOG_ADD(LOG_FLOAT, stateY, &coreData.S[KC_STATE_Y])+ LOG_ADD(LOG_FLOAT, stateZ, &coreData.S[KC_STATE_Z])+ LOG_ADD(LOG_FLOAT, statePX, &coreData.S[KC_STATE_PX])+ LOG_ADD(LOG_FLOAT, statePY, &coreData.S[KC_STATE_PY])+ LOG_ADD(LOG_FLOAT, statePZ, &coreData.S[KC_STATE_PZ])+ LOG_ADD(LOG_FLOAT, stateD0, &coreData.S[KC_STATE_D0])+ LOG_ADD(LOG_FLOAT, stateD1, &coreData.S[KC_STATE_D1])+ LOG_ADD(LOG_FLOAT, stateD2, &coreData.S[KC_STATE_D2])+ LOG_ADD(LOG_FLOAT, varX, &coreData.P[KC_STATE_X][KC_STATE_X])+ LOG_ADD(LOG_FLOAT, varY, &coreData.P[KC_STATE_Y][KC_STATE_Y])+ LOG_ADD(LOG_FLOAT, varZ, &coreData.P[KC_STATE_Z][KC_STATE_Z])+ LOG_ADD(LOG_FLOAT, varPX, &coreData.P[KC_STATE_PX][KC_STATE_PX])+ LOG_ADD(LOG_FLOAT, varPY, &coreData.P[KC_STATE_PY][KC_STATE_PY])+ LOG_ADD(LOG_FLOAT, varPZ, &coreData.P[KC_STATE_PZ][KC_STATE_PZ])+ LOG_ADD(LOG_FLOAT, varD0, &coreData.P[KC_STATE_D0][KC_STATE_D0])+ LOG_ADD(LOG_FLOAT, varD1, &coreData.P[KC_STATE_D1][KC_STATE_D1])+ LOG_ADD(LOG_FLOAT, varD2, &coreData.P[KC_STATE_D2][KC_STATE_D2])+ LOG_ADD(LOG_FLOAT, q0, &coreData.q[0])+ LOG_ADD(LOG_FLOAT, q1, &coreData.q[1])+ LOG_ADD(LOG_FLOAT, q2, &coreData.q[2])+ LOG_ADD(LOG_FLOAT, q3, &coreData.q[3])++ STATS_CNT_RATE_LOG_ADD(rtUpdate, &updateCounter)+ STATS_CNT_RATE_LOG_ADD(rtPred, &predictionCounter)+ STATS_CNT_RATE_LOG_ADD(rtBaro, &baroUpdateCounter)+ STATS_CNT_RATE_LOG_ADD(rtFinal, &finalizeCounter)+ STATS_CNT_RATE_LOG_ADD(rtApnd, &measurementAppendedCounter)+ STATS_CNT_RATE_LOG_ADD(rtRej, &measurementNotAppendedCounter)+LOG_GROUP_STOP(kalman)++PARAM_GROUP_START(kalman)+ PARAM_ADD(PARAM_UINT8, resetEstimation, &coreData.resetEstimation)+ PARAM_ADD(PARAM_UINT8, quadIsFlying, &quadIsFlying)+PARAM_GROUP_STOP(kalman)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/extrx.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/extrx.cnew file mode 100644index 0000000..515afb6--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/extrx.c@@ -0,0 +1,191 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2013 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * extrx.c - Module to handle external receiver inputs+ */++/* FreeRtos includes */+#include "FreeRTOS.h"+#include "task.h"+#include "queue.h"+++#include "stm32_legacy.h"+#include "config.h"+#include "system.h"+#include "nvicconf.h"+#include "commander.h"+#include "uart1.h"+#include "cppm.h"++#define DEBUG_MODULE "EXTRX"+#include "debug_cf.h"+#include "log.h"+#include "static_mem.h"++//#define ENABLE_CPPM+#define ENABLE_EXTRX_LOG+++#define EXTRX_NR_CHANNELS 8++#define EXTRX_CH_TRUST 2+#define EXTRX_CH_ROLL 0+#define EXTRX_CH_PITCH 1+#define EXTRX_CH_YAW 3++#define EXTRX_SIGN_ROLL (-1)+#define EXTRX_SIGN_PITCH (-1)+#define EXTRX_SIGN_YAW (-1)++#define EXTRX_SCALE_ROLL (40.0f)+#define EXTRX_SCALE_PITCH (40.0f)+#define EXTRX_SCALE_YAW (400.0f)++static setpoint_t extrxSetpoint;+static uint16_t ch[EXTRX_NR_CHANNELS];++static void extRxTask(void *param);+static void extRxDecodeCppm(void);+static void extRxDecodeChannels(void);++STATIC_MEM_TASK_ALLOC(extRxTask, EXTRX_TASK_STACKSIZE);++void extRxInit(void)+{++ extrxSetpoint.mode.roll = modeAbs;+ extrxSetpoint.mode.pitch = modeAbs;+ extrxSetpoint.mode.yaw = modeVelocity;++#ifdef ENABLE_CPPM+ cppmInit();+#endif++#ifdef ENABLE_SPEKTRUM+ uart1Init();+#endif++ STATIC_MEM_TASK_CREATE(extRxTask, extRxTask, EXTRX_TASK_NAME, NULL, EXTRX_TASK_PRI);+}++static void extRxTask(void *param)+{++ //Wait for the system to be fully started+ systemWaitStart();++ while (true)+ {+ extRxDecodeCppm();+ }+}++static void extRxDecodeChannels(void)+{+ extrxSetpoint.thrust = cppmConvert2uint16(ch[EXTRX_CH_TRUST]);+ extrxSetpoint.attitude.roll = EXTRX_SIGN_ROLL * cppmConvert2Float(ch[EXTRX_CH_ROLL], -EXTRX_SCALE_ROLL, EXTRX_SCALE_ROLL);+ extrxSetpoint.attitude.pitch = EXTRX_SIGN_PITCH * cppmConvert2Float(ch[EXTRX_CH_PITCH], -EXTRX_SCALE_PITCH, EXTRX_SCALE_PITCH);+ extrxSetpoint.attitude.yaw = EXTRX_SIGN_YAW * cppmConvert2Float(ch[EXTRX_CH_YAW], -EXTRX_SCALE_YAW, EXTRX_SCALE_YAW);+ commanderSetSetpoint(&extrxSetpoint, COMMANDER_PRIORITY_EXTRX);+}++static void extRxDecodeCppm(void)+{+ uint16_t ppm;+ static uint8_t currChannel = 0;++ if (cppmGetTimestamp(&ppm) == pdTRUE)+ {+ if (cppmIsAvailible() && ppm < 2100)+ {+ if (currChannel < EXTRX_NR_CHANNELS)+ {+ ch[currChannel] = ppm;+ }+ currChannel++;+ }+ else+ {+ extRxDecodeChannels();+ currChannel = 0;+ }+ }+}++#if 0+static void extRxDecodeSpektrum(void)+{+ while (SerialAvailable(SPEK_SERIAL_PORT) > SPEK_FRAME_SIZE)+ { // More than a frame? More bytes implies we weren't called for multiple frame times. We do not want to process 'old' frames in the buffer.+ for (uint8_t i = 0; i < SPEK_FRAME_SIZE; i++)+ {+ SerialRead(SPEK_SERIAL_PORT);+ } //Toss one full frame of bytes.+ }+ if (spekFrameFlags == 0x01)+ { //The interrupt handler saw at least one valid frame start since we were last here.+ if (SerialAvailable(SPEK_SERIAL_PORT) == SPEK_FRAME_SIZE)+ { //A complete frame? If not, we'll catch it next time we are called.+ SerialRead(SPEK_SERIAL_PORT);+ SerialRead(SPEK_SERIAL_PORT); //Eat the header bytes+ for (uint8_t b = 2; b < SPEK_FRAME_SIZE; b += 2)+ {+ uint8_t bh = SerialRead(SPEK_SERIAL_PORT);+ uint8_t bl = SerialRead(SPEK_SERIAL_PORT);+ uint8_t spekChannel = 0x0F & (bh >> SPEK_CHAN_SHIFT);+ if (spekChannel < RC_CHANS) rcValue[spekChannel] = 988 + ((((uint16_t)(bh & SPEK_CHAN_MASK) << 8) + bl) SPEK_DATA_SHIFT);+ }+ spekFrameFlags = 0x00;+ spekFrameData = 0x01;+#if defined(FAILSAFE)+ if(failsafeCnt > 20) failsafeCnt -= 20;+ else failsafeCnt = 0; // Valid frame, clear FailSafe counter+#endif+ }+ else+ { //Start flag is on, but not enough bytes means there is an incomplete frame in buffer. This could be OK, if we happened to be called in the middle of a frame. Or not, if it has been a while since the start flag was set.+ uint32_t spekInterval = (timer0_overflow_count << 8)+ * (64 / clockCyclesPerMicrosecond()) - spekTimeLast;+ if (spekInterval > 2500)+ {+ spekFrameFlags = 0;+ } //If it has been a while, make the interrupt handler start over.+ }+}+#endif++/* Loggable variables */+#ifdef ENABLE_EXTRX_LOG+LOG_GROUP_START(extrx)+LOG_ADD(LOG_UINT16, ch0, &ch[0])+LOG_ADD(LOG_UINT16, ch1, &ch[1])+LOG_ADD(LOG_UINT16, ch2, &ch[2])+LOG_ADD(LOG_UINT16, ch3, &ch[3])+LOG_ADD(LOG_UINT16, thrust, &extrxSetpoint.thrust)+LOG_ADD(LOG_FLOAT, roll, &extrxSetpoint.attitude.roll)+LOG_ADD(LOG_FLOAT, pitch, &extrxSetpoint.attitude.pitch)+LOG_ADD(LOG_FLOAT, yaw, &extrxSetpoint.attitude.yaw)+LOG_GROUP_STOP(extrx)+#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/info.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/info.cnew file mode 100644index 0000000..ce61943--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/info.c@@ -0,0 +1,177 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * info.c - Receive information requests and send them back to the client+ */++#include <string.h>+#include <math.h>++/*FreeRtos includes*/+#include "FreeRTOS.h"+#include "task.h"++#include "crtp.h"+#include "info.h"+#include "version.h"+#include "pm_esplane.h"+#include "stm32_legacy.h"+#include "static_mem.h"++//CPUID access+static const unsigned int * CpuId = (unsigned int*)0x1FFFF7E8;++typedef enum {+ infoCopterNr = 0x00,+ infoBatteryNr = 0x01,+ infoWarningNr = 0x03+} InfoNbr;++typedef enum {+ infoName = 0x00,+ infoVersion = 0x01,+ infoCpuId = 0x02+} infoId;++typedef enum {+ batteryVoltage = 0x00,+ batteryMin = 0x01,+ batteryMax = 0x02+} batteryId;++typedef enum {+ warningBattery = 0x00+} warningId;++STATIC_MEM_TASK_ALLOC(infoTask, INFO_TASK_STACKSIZE);++void infoTask(void *param);++void infoInit()+{+ STATIC_MEM_TASK_CREATE(infoTask, infoTask, INFO_TASK_NAME, NULL, INFO_TASK_PRI);+ crtpInitTaskQueue(crtpInfo);+}++void infoTask(void *param)+{+ CRTPPacket p;+ int i;+ static int ctr=0;++ while (TRUE)+ {+ if (crtpReceivePacketWait(crtpInfo, &p, 1000) == pdTRUE)+ {+ InfoNbr infoNbr = CRTP_GET_NBR(p.port);++ switch (infoNbr)+ {+ case infoCopterNr:+ if (p.data[0] == infoName)+ {+ p.data[1] = 0x90;+ p.data[2] = 0x00; //Version 0.9.0 (Crazyflie)+ strcpy((char*)&p.data[3], "CrazyFlie");++ p.size = 3+strlen("CrazyFlie");+ crtpSendPacket(&p);+ } else if (p.data[0] == infoVersion) {+ i=1;++ strncpy((char*)&p.data[i], V_SLOCAL_REVISION, 31-i);+ i += strlen(V_SLOCAL_REVISION);++ if (i<31) p.data[i++] = ',';++ strncpy((char*)&p.data[i], V_SREVISION, 31-i);+ i += strlen(V_SREVISION);++ if (i<31) p.data[i++] = ',';++ strncpy((char*)&p.data[i], V_STAG, 31-i);+ i += strlen(V_STAG);++ if (i<31) p.data[i++] = ',';+ if (i<31) p.data[i++] = V_MODIFIED?'M':'C';++ p.size = (i<31)?i:31;+ crtpSendPacket(&p);+ } else if (p.data[0] == infoCpuId) {+ memcpy((char*)&p.data[1], (char*)CpuId, 12);++ p.size = 13;+ crtpSendPacket(&p);+ }++ break;+ case infoBatteryNr:+ if (p.data[0] == batteryVoltage)+ {+ float value = pmGetBatteryVoltage();++ memcpy(&p.data[1], (char*)&value, 4);++ p.size = 5;+ crtpSendPacket(&p);+ } else if (p.data[0] == batteryMax) {+ float value = pmGetBatteryVoltageMax();++ memcpy(&p.data[1], (char*)&value, 4);++ p.size = 5;+ crtpSendPacket(&p);+ } else if (p.data[0] == batteryMin) {+ float value = pmGetBatteryVoltageMin();++ memcpy(&p.data[1], (char*)&value, 4);++ p.size = 5;+ crtpSendPacket(&p);+ }+ break;+ default:+ break;+ }+ }++ // Send a warning message if the battery voltage drops under 3.3V+ // This is sent every 5 info transaction or every 5 seconds+ if (ctr++>5) {+ ctr=0;++ if (pmGetBatteryVoltageMin() < INFO_BAT_WARNING)+ {+ float value = pmGetBatteryVoltage();++ p.port = CRTP_PORT(0,8,3);+ p.data[0] = 0;+ memcpy(&p.data[1], (char*)&value, 4);++ p.size = 5;+ crtpSendPacket(&p);+ }+ }++ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/kalman_core.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/kalman_core.cnew file mode 100644index 0000000..e6021a0--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/kalman_core.c@@ -0,0 +1,1123 @@+/**+ * Authored by Michael Hamer (http://www.mikehamer.info), June 2016+ * Thank you to Mark Mueller (www.mwm.im) for advice during implementation,+ * and for derivation of the original filter in the below-cited paper.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ============================================================================+ *+ * The Kalman filter implemented in this file is based on the papers:+ *+ * "Fusing ultra-wideband range measurements with accelerometers and rate gyroscopes for quadrocopter state estimation"+ * http://ieeexplore.ieee.org/xpl/articleDetails.jsp?arnumber=7139421+ *+ * and+ *+ * "Covariance Correction Step for Kalman Filtering with an Attitude"+ * http://arc.aiaa.org/doi/abs/10.2514/1.G000848+ *+ * Academic citation would be appreciated.+ *+ * BIBTEX ENTRIES:+ @INPROCEEDINGS{MuellerHamerUWB2015,+ author = {Mueller, Mark W and Hamer, Michael and D’Andrea, Raffaello},+ title = {Fusing ultra-wideband range measurements with accelerometers and rate gyroscopes for quadrocopter state estimation},+ booktitle = {2015 IEEE International Conference on Robotics and Automation (ICRA)},+ year = {2015},+ month = {May},+ pages = {1730-1736},+ doi = {10.1109/ICRA.2015.7139421},+ ISSN = {1050-4729}}++ @ARTICLE{MuellerCovariance2016,+ author={Mueller, Mark W and Hehn, Markus and D’Andrea, Raffaello},+ title={Covariance Correction Step for Kalman Filtering with an Attitude},+ journal={Journal of Guidance, Control, and Dynamics},+ pages={1--7},+ year={2016},+ publisher={American Institute of Aeronautics and Astronautics}}+ *+ * ============================================================================+ *+ * MAJOR CHANGELOG:+ * 2016.06.28, Mike Hamer: Initial version+ * 2019.04.12, Kristoffer Richardsson: Refactored, separated kalman implementation from OS related functionality+ */++#include "kalman_core.h"+#include "cfassert.h"++#include "outlierFilter.h"+#include "physicalConstants.h"++#include "log.h"+#include "debug_cf.h"+#include "param.h"+#include "math3d.h"+#include "xtensa_math.h"+#include "static_mem.h"++//#include "lighthouse_calibration.h"++// #define DEBUG_STATE_CHECK++// the reversion of pitch and roll to zero+#ifdef LPS_2D_POSITION_HEIGHT+#define ROLLPITCH_ZERO_REVERSION (0.0f)+#else+#define ROLLPITCH_ZERO_REVERSION (0.001f)+#endif+++/**+ * Supporting and utility functions+ */++#ifdef DEBUG_STATE_CHECK+static void assertStateNotNaN(const kalmanCoreData_t* this) {+ if ((isnan(this->S[KC_STATE_X])) ||+ (isnan(this->S[KC_STATE_Y])) ||+ (isnan(this->S[KC_STATE_Z])) ||+ (isnan(this->S[KC_STATE_PX])) ||+ (isnan(this->S[KC_STATE_PY])) ||+ (isnan(this->S[KC_STATE_PZ])) ||+ (isnan(this->S[KC_STATE_D0])) ||+ (isnan(this->S[KC_STATE_D1])) ||+ (isnan(this->S[KC_STATE_D2])) ||+ (isnan(this->q[0])) ||+ (isnan(this->q[1])) ||+ (isnan(this->q[2])) ||+ (isnan(this->q[3])))+ {+ ASSERT(false);+ }++ for(int i=0; i<KC_STATE_DIM; i++) {+ for(int j=0; j<KC_STATE_DIM; j++)+ {+ if (isnan(this->P[i][j]))+ {+ ASSERT(false);+ }+ }+ }+}+#else+static void assertStateNotNaN(const kalmanCoreData_t* this)+{+ return;+}+#endif+++// The bounds on the covariance, these shouldn't be hit, but sometimes are... why?+#define MAX_COVARIANCE (100)+#define MIN_COVARIANCE (1e-6f)++// Initial variances, uncertain of position, but know we're stationary and roughly flat+static const float stdDevInitialPosition_xy = 100;+static const float stdDevInitialPosition_z = 1;+static const float stdDevInitialVelocity = 0.01;+static const float stdDevInitialAttitude_rollpitch = 0.01;+static const float stdDevInitialAttitude_yaw = 0.01;++static float procNoiseAcc_xy = 0.5f;+static float procNoiseAcc_z = 1.0f;+static float procNoiseVel = 0;+static float procNoisePos = 0;+static float procNoiseAtt = 0;+static float measNoiseBaro = 2.0f; // meters+static float measNoiseGyro_rollpitch = 0.1f; // radians per second+static float measNoiseGyro_yaw = 0.1f; // radians per second++static float initialX = 0.0;+static float initialY = 0.0;+static float initialZ = 0.0;++// Initial yaw of the Crazyflie in radians.+// 0 --- facing positive X+// PI / 2 --- facing positive Y+// PI --- facing negative X+// 3 * PI / 2 --- facing negative Y+static float initialYaw = 0.0;++// Quaternion used for initial yaw+static float initialQuaternion[4] = {0.0, 0.0, 0.0, 0.0};++static uint32_t tdoaCount;++static OutlierFilterLhState_t sweepOutlierFilterState;+++void kalmanCoreInit(kalmanCoreData_t* this) {+ tdoaCount = 0;++ // Reset all data to 0 (like upon system reset)+ memset(this, 0, sizeof(kalmanCoreData_t));++ this->S[KC_STATE_X] = initialX;+ this->S[KC_STATE_Y] = initialY;+ this->S[KC_STATE_Z] = initialZ;+// this->S[KC_STATE_PX] = 0;+// this->S[KC_STATE_PY] = 0;+// this->S[KC_STATE_PZ] = 0;+// this->S[KC_STATE_D0] = 0;+// this->S[KC_STATE_D1] = 0;+// this->S[KC_STATE_D2] = 0;++ // reset the attitude quaternion+ initialQuaternion[0] = xtensa_cos_f32(initialYaw / 2);+ initialQuaternion[1] = 0.0;+ initialQuaternion[2] = 0.0;+ initialQuaternion[3] = xtensa_sin_f32(initialYaw / 2);+ for (int i = 0; i < 4; i++) { this->q[i] = initialQuaternion[i]; }++ // then set the initial rotation matrix to the identity. This only affects+ // the first prediction step, since in the finalization, after shifting+ // attitude errors into the attitude state, the rotation matrix is updated.+ for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { this->R[i][j] = i==j ? 1 : 0; }}++ for (int i=0; i< KC_STATE_DIM; i++) {+ for (int j=0; j < KC_STATE_DIM; j++) {+ this->P[i][j] = 0; // set covariances to zero (diagonals will be changed from zero in the next section)+ }+ }++ // initialize state variances+ this->P[KC_STATE_X][KC_STATE_X] = powf(stdDevInitialPosition_xy, 2);+ this->P[KC_STATE_Y][KC_STATE_Y] = powf(stdDevInitialPosition_xy, 2);+ this->P[KC_STATE_Z][KC_STATE_Z] = powf(stdDevInitialPosition_z, 2);++ this->P[KC_STATE_PX][KC_STATE_PX] = powf(stdDevInitialVelocity, 2);+ this->P[KC_STATE_PY][KC_STATE_PY] = powf(stdDevInitialVelocity, 2);+ this->P[KC_STATE_PZ][KC_STATE_PZ] = powf(stdDevInitialVelocity, 2);++ this->P[KC_STATE_D0][KC_STATE_D0] = powf(stdDevInitialAttitude_rollpitch, 2);+ this->P[KC_STATE_D1][KC_STATE_D1] = powf(stdDevInitialAttitude_rollpitch, 2);+ this->P[KC_STATE_D2][KC_STATE_D2] = powf(stdDevInitialAttitude_yaw, 2);++ this->Pm.numRows = KC_STATE_DIM;+ this->Pm.numCols = KC_STATE_DIM;+ this->Pm.pData = (float*)this->P;++ this->baroReferenceHeight = 0.0;++ outlierFilterReset(&sweepOutlierFilterState, 0);+}++static void scalarUpdate(kalmanCoreData_t* this, xtensa_matrix_instance_f32 *Hm, float error, float stdMeasNoise)+{+ // The Kalman gain as a column vector+ NO_DMA_CCM_SAFE_ZERO_INIT static float K[KC_STATE_DIM];+ static xtensa_matrix_instance_f32 Km = {KC_STATE_DIM, 1, (float *)K};++ // Temporary matrices for the covariance updates+ NO_DMA_CCM_SAFE_ZERO_INIT __attribute__((aligned(4))) static float tmpNN1d[KC_STATE_DIM * KC_STATE_DIM];+ static xtensa_matrix_instance_f32 tmpNN1m = {KC_STATE_DIM, KC_STATE_DIM, tmpNN1d};++ NO_DMA_CCM_SAFE_ZERO_INIT __attribute__((aligned(4))) static float tmpNN2d[KC_STATE_DIM * KC_STATE_DIM];+ static xtensa_matrix_instance_f32 tmpNN2m = {KC_STATE_DIM, KC_STATE_DIM, tmpNN2d};++ NO_DMA_CCM_SAFE_ZERO_INIT __attribute__((aligned(4))) static float tmpNN3d[KC_STATE_DIM * KC_STATE_DIM];+ static xtensa_matrix_instance_f32 tmpNN3m = {KC_STATE_DIM, KC_STATE_DIM, tmpNN3d};++ NO_DMA_CCM_SAFE_ZERO_INIT __attribute__((aligned(4))) static float HTd[KC_STATE_DIM * 1];+ static xtensa_matrix_instance_f32 HTm = {KC_STATE_DIM, 1, HTd};++ NO_DMA_CCM_SAFE_ZERO_INIT __attribute__((aligned(4))) static float PHTd[KC_STATE_DIM * 1];+ static xtensa_matrix_instance_f32 PHTm = {KC_STATE_DIM, 1, PHTd};++ ASSERT(Hm->numRows == 1);+ ASSERT(Hm->numCols == KC_STATE_DIM);++ // ====== INNOVATION COVARIANCE ======++ mat_trans(Hm, &HTm);+ mat_mult(&this->Pm, &HTm, &PHTm); // PH'+ float R = stdMeasNoise*stdMeasNoise;+ float HPHR = R; // HPH' + R+ for (int i=0; i<KC_STATE_DIM; i++) { // Add the element of HPH' to the above+ HPHR += Hm->pData[i]*PHTd[i]; // this obviously only works if the update is scalar (as in this function)+ }+ ASSERT(!isnan(HPHR));++ // ====== MEASUREMENT UPDATE ======+ // Calculate the Kalman gain and perform the state update+ for (int i=0; i<KC_STATE_DIM; i++) {+ K[i] = PHTd[i]/HPHR; // kalman gain = (PH' (HPH' + R )^-1)+ this->S[i] = this->S[i] + K[i] * error; // state update+ }+ assertStateNotNaN(this);++ // ====== COVARIANCE UPDATE ======+ mat_mult(&Km, Hm, &tmpNN1m); // KH+ for (int i=0; i<KC_STATE_DIM; i++) { tmpNN1d[KC_STATE_DIM*i+i] -= 1; } // KH - I+ mat_trans(&tmpNN1m, &tmpNN2m); // (KH - I)'+ mat_mult(&tmpNN1m, &this->Pm, &tmpNN3m); // (KH - I)*P+ mat_mult(&tmpNN3m, &tmpNN2m, &this->Pm); // (KH - I)*P*(KH - I)'+ assertStateNotNaN(this);+ // add the measurement variance and ensure boundedness and symmetry+ // TODO: Why would it hit these bounds? Needs to be investigated.+ for (int i=0; i<KC_STATE_DIM; i++) {+ for (int j=i; j<KC_STATE_DIM; j++) {+ float v = K[i] * R * K[j];+ float p = 0.5f*this->P[i][j] + 0.5f*this->P[j][i] + v; // add measurement noise+ if (isnan(p) || p > MAX_COVARIANCE) {+ this->P[i][j] = this->P[j][i] = MAX_COVARIANCE;+ } else if ( i==j && p < MIN_COVARIANCE ) {+ this->P[i][j] = this->P[j][i] = MIN_COVARIANCE;+ } else {+ this->P[i][j] = this->P[j][i] = p;+ }+ }+ }++ assertStateNotNaN(this);+}+++void kalmanCoreUpdateWithBaro(kalmanCoreData_t* this, float baroAsl, bool quadIsFlying)+{+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};++ h[KC_STATE_Z] = 1;++ if (!quadIsFlying || this->baroReferenceHeight < 1) {+ //TODO: maybe we could track the zero height as a state. Would be especially useful if UWB anchors had barometers.+ this->baroReferenceHeight = baroAsl;+ }++ float meas = (baroAsl - this->baroReferenceHeight);+ scalarUpdate(this, &H, meas - this->S[KC_STATE_Z], measNoiseBaro);+}++void kalmanCoreUpdateWithAbsoluteHeight(kalmanCoreData_t* this, heightMeasurement_t* height) {+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};+ h[KC_STATE_Z] = 1;+ scalarUpdate(this, &H, height->height - this->S[KC_STATE_Z], height->stdDev);+}++void kalmanCoreUpdateWithPosition(kalmanCoreData_t* this, positionMeasurement_t *xyz)+{+ // a direct measurement of states x, y, and z+ // do a scalar update for each state, since this should be faster than updating all together+ for (int i=0; i<3; i++) {+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};+ h[KC_STATE_X+i] = 1;+ scalarUpdate(this, &H, xyz->pos[i] - this->S[KC_STATE_X+i], xyz->stdDev);+ }+}++void kalmanCoreUpdateWithPose(kalmanCoreData_t* this, poseMeasurement_t *pose)+{+ // a direct measurement of states x, y, and z, and orientation+ // do a scalar update for each state, since this should be faster than updating all together+ for (int i=0; i<3; i++) {+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};+ h[KC_STATE_X+i] = 1;+ scalarUpdate(this, &H, pose->pos[i] - this->S[KC_STATE_X+i], pose->stdDevPos);+ }++ // compute orientation error+ struct quat const q_ekf = mkquat(this->q[1], this->q[2], this->q[3], this->q[0]);+ struct quat const q_measured = mkquat(pose->quat.x, pose->quat.y, pose->quat.z, pose->quat.w);+ struct quat const q_residual = qqmul(qinv(q_ekf), q_measured);+ // small angle approximation, see eq. 141 in http://mars.cs.umn.edu/tr/reports/Trawny05b.pdf+ struct vec const err_quat = vscl(2.0f / q_residual.w, quatimagpart(q_residual));++ // do a scalar update for each state+ {+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};+ h[KC_STATE_D0] = 1;+ scalarUpdate(this, &H, err_quat.x, pose->stdDevQuat);+ h[KC_STATE_D0] = 0;++ h[KC_STATE_D1] = 1;+ scalarUpdate(this, &H, err_quat.y, pose->stdDevQuat);+ h[KC_STATE_D1] = 0;++ h[KC_STATE_D2] = 1;+ scalarUpdate(this, &H, err_quat.z, pose->stdDevQuat);+ }+}++void kalmanCoreUpdateWithDistance(kalmanCoreData_t* this, distanceMeasurement_t *d)+{+ // a measurement of distance to point (x, y, z)+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};++ float dx = this->S[KC_STATE_X] - d->x;+ float dy = this->S[KC_STATE_Y] - d->y;+ float dz = this->S[KC_STATE_Z] - d->z;++ float measuredDistance = d->distance;++ float predictedDistance = xtensa_sqrt(powf(dx, 2) + powf(dy, 2) + powf(dz, 2));+ if (predictedDistance != 0.0f)+ {+ // The measurement is: z = sqrt(dx^2 + dy^2 + dz^2). The derivative dz/dX gives h.+ h[KC_STATE_X] = dx/predictedDistance;+ h[KC_STATE_Y] = dy/predictedDistance;+ h[KC_STATE_Z] = dz/predictedDistance;+ }+ else+ {+ // Avoid divide by zero+ h[KC_STATE_X] = 1.0f;+ h[KC_STATE_Y] = 0.0f;+ h[KC_STATE_Z] = 0.0f;+ }++ scalarUpdate(this, &H, measuredDistance-predictedDistance, d->stdDev);+}+++void kalmanCoreUpdateWithTDOA(kalmanCoreData_t* this, tdoaMeasurement_t *tdoa)+{+ if (tdoaCount >= 100)+ {+ /**+ * Measurement equation:+ * dR = dT + d1 - d0+ */++ float measurement = tdoa->distanceDiff;++ // predict based on current state+ float x = this->S[KC_STATE_X];+ float y = this->S[KC_STATE_Y];+ float z = this->S[KC_STATE_Z];++ float x1 = tdoa->anchorPosition[1].x, y1 = tdoa->anchorPosition[1].y, z1 = tdoa->anchorPosition[1].z;+ float x0 = tdoa->anchorPosition[0].x, y0 = tdoa->anchorPosition[0].y, z0 = tdoa->anchorPosition[0].z;++ float dx1 = x - x1;+ float dy1 = y - y1;+ float dz1 = z - z1;++ float dy0 = y - y0;+ float dx0 = x - x0;+ float dz0 = z - z0;++ float d1 = sqrtf(powf(dx1, 2) + powf(dy1, 2) + powf(dz1, 2));+ float d0 = sqrtf(powf(dx0, 2) + powf(dy0, 2) + powf(dz0, 2));++ float predicted = d1 - d0;+ float error = measurement - predicted;++ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};++ if ((d0 != 0.0f) && (d1 != 0.0f)) {+ h[KC_STATE_X] = (dx1 / d1 - dx0 / d0);+ h[KC_STATE_Y] = (dy1 / d1 - dy0 / d0);+ h[KC_STATE_Z] = (dz1 / d1 - dz0 / d0);++ vector_t jacobian = {+ .x = h[KC_STATE_X],+ .y = h[KC_STATE_Y],+ .z = h[KC_STATE_Z],+ };++ point_t estimatedPosition = {+ .x = this->S[KC_STATE_X],+ .y = this->S[KC_STATE_Y],+ .z = this->S[KC_STATE_Z],+ };++ bool sampleIsGood = outlierFilterValidateTdoaSteps(tdoa, error, &jacobian, &estimatedPosition);+ if (sampleIsGood) {+ scalarUpdate(this, &H, error, tdoa->stdDev);+ }+ }+ }++ tdoaCount++;+}++++// TODO remove the temporary test variables (used for logging)+static float predictedNX;+static float predictedNY;+static float measuredNX;+static float measuredNY;++void kalmanCoreUpdateWithFlow(kalmanCoreData_t* this, const flowMeasurement_t *flow, const Axis3f *gyro)+{+ // Inclusion of flow measurements in the EKF done by two scalar updates++ // ~~~ Camera constants ~~~+ // The angle of aperture is guessed from the raw data register and thankfully look to be symmetric+ float Npix = 30.0; // [pixels] (same in x and y)+ //float thetapix = DEG_TO_RAD * 4.0f; // [rad] (same in x and y)+ float thetapix = DEG_TO_RAD * 4.2f;+ //~~~ Body rates ~~~+ // TODO check if this is feasible or if some filtering has to be done+ float omegax_b = gyro->x * DEG_TO_RAD;+ float omegay_b = gyro->y * DEG_TO_RAD;++ // ~~~ Moves the body velocity into the global coordinate system ~~~+ // [bar{x},bar{y},bar{z}]_G = R*[bar{x},bar{y},bar{z}]_B+ //+ // \dot{x}_G = (R^T*[dot{x}_B,dot{y}_B,dot{z}_B])\dot \hat{x}_G+ // \dot{x}_G = (R^T*[dot{x}_B,dot{y}_B,dot{z}_B])\dot \hat{x}_G+ //+ // where \hat{} denotes a basis vector, \dot{} denotes a derivative and+ // _G and _B refer to the global/body coordinate systems.++ // Modification 1+ //dx_g = R[0][0] * S[KC_STATE_PX] + R[0][1] * S[KC_STATE_PY] + R[0][2] * S[KC_STATE_PZ];+ //dy_g = R[1][0] * S[KC_STATE_PX] + R[1][1] * S[KC_STATE_PY] + R[1][2] * S[KC_STATE_PZ];+++ float dx_g = this->S[KC_STATE_PX];+ float dy_g = this->S[KC_STATE_PY];+ float z_g = 0.0;+ // Saturate elevation in prediction and correction to avoid singularities+ if ( this->S[KC_STATE_Z] < 0.1f ) {+ z_g = 0.1;+ } else {+ z_g = this->S[KC_STATE_Z];+ }++ // ~~~ X velocity prediction and update ~~~+ // predics the number of accumulated pixels in the x-direction+ float omegaFactor = 1.25f;+ float hx[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 Hx = {1, KC_STATE_DIM, hx};+ predictedNX = (flow->dt * Npix / thetapix ) * ((dx_g * this->R[2][2] / z_g) - omegaFactor * omegay_b);+ measuredNX = flow->dpixelx;++ // derive measurement equation with respect to dx (and z?)+ hx[KC_STATE_Z] = (Npix * flow->dt / thetapix) * ((this->R[2][2] * dx_g) / (-z_g * z_g));+ hx[KC_STATE_PX] = (Npix * flow->dt / thetapix) * (this->R[2][2] / z_g);++ //First update+ scalarUpdate(this, &Hx, measuredNX-predictedNX, flow->stdDevX);++ // ~~~ Y velocity prediction and update ~~~+ float hy[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 Hy = {1, KC_STATE_DIM, hy};+ predictedNY = (flow->dt * Npix / thetapix ) * ((dy_g * this->R[2][2] / z_g) + omegaFactor * omegax_b);+ measuredNY = flow->dpixely;++ // derive measurement equation with respect to dy (and z?)+ hy[KC_STATE_Z] = (Npix * flow->dt / thetapix) * ((this->R[2][2] * dy_g) / (-z_g * z_g));+ hy[KC_STATE_PY] = (Npix * flow->dt / thetapix) * (this->R[2][2] / z_g);++ // Second update+ scalarUpdate(this, &Hy, measuredNY-predictedNY, flow->stdDevY);+}+++void kalmanCoreUpdateWithTof(kalmanCoreData_t* this, tofMeasurement_t *tof)+{+ // Updates the filter with a measured distance in the zb direction using the+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};++ // Only update the filter if the measurement is reliable (\hat{h} -> infty when R[2][2] -> 0)+ if (fabs(this->R[2][2]) > 0.1 && this->R[2][2] > 0){+ float angle = fabsf(acosf(this->R[2][2])) - DEG_TO_RAD * (15.0f / 2.0f);+ if (angle < 0.0f) {+ angle = 0.0f;+ }+ //float predictedDistance = S[KC_STATE_Z] / cosf(angle);+ float predictedDistance = this->S[KC_STATE_Z] / this->R[2][2];+ float measuredDistance = tof->distance; // [m]++ //Measurement equation+ //+ // h = z/((R*z_b)\dot z_b) = z/cos(alpha)+ h[KC_STATE_Z] = 1 / this->R[2][2];+ //h[KC_STATE_Z] = 1 / cosf(angle);++ // Scalar update+ scalarUpdate(this, &H, measuredDistance-predictedDistance, tof->stdDev);+ }+}++void kalmanCoreUpdateWithYawError(kalmanCoreData_t *this, yawErrorMeasurement_t *error)+{+ float h[KC_STATE_DIM] = {0};+ xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};++ h[KC_STATE_D2] = 1;+ scalarUpdate(this, &H, this->S[KC_STATE_D2] - error->yawError, error->stdDev);+}++//void kalmanCoreUpdateWithSweepAngles(kalmanCoreData_t *this, sweepAngleMeasurement_t *sweepInfo, const uint32_t tick) {+ // Rotate the sensor position from CF reference frame to global reference frame,+ // using the CF roatation matrix+ // vec3d s;+ // xtensa_matrix_instance_f32 Rcf_ = {3, 3, (float32_t *)this->R};+ // xtensa_matrix_instance_f32 scf_ = {3, 1, (float32_t *)*sweepInfo->sensorPos};+ // xtensa_matrix_instance_f32 s_ = {3, 1, s};+ // mat_mult(&Rcf_, &scf_, &s_);++ // // Get the current state values of the position of the crazyflie (global reference frame) and add the relative sensor pos+ // vec3d pcf = {this->S[KC_STATE_X] + s[0], this->S[KC_STATE_Y] + s[1], this->S[KC_STATE_Z] + s[2]};++ // // Calculate the difference between the rotor and the sensor on the CF (global reference frame)+ // const vec3d* pr = sweepInfo->rotorPos;+ // vec3d stmp = {pcf[0] - (*pr)[0], pcf[1] - (*pr)[1], pcf[2] - (*pr)[2]};+ // xtensa_matrix_instance_f32 stmp_ = {3, 1, stmp};++ // // Rotate the difference in position to the rotor reference frame,+ // // using the rotor inverse rotation matrix+ // vec3d sr;+ // xtensa_matrix_instance_f32 Rr_inv_ = {3, 3, (float32_t *)(*sweepInfo->rotorRotInv)};+ // xtensa_matrix_instance_f32 sr_ = {3, 1, sr};+ // mat_mult(&Rr_inv_, &stmp_, &sr_);++ // // The following computations are in the rotor refernece frame+ // const float x = sr[0];+ // const float y = sr[1];+ // const float z = sr[2];+ // const float t = sweepInfo->t;+ // const float tan_t = tanf(t);++ // const float r2 = x * x + y * y;+ // const float r = xtensa_sqrt(r2);++ // const float predictedSweepAngle = sweepInfo->calibrationMeasurementModel(x, y, z, t, sweepInfo->calib);+ // const float measuredSweepAngle = sweepInfo->measuredSweepAngle;+ // const float error = measuredSweepAngle - predictedSweepAngle;++ // if (outlierFilterValidateLighthouseSweep(&sweepOutlierFilterState, r, error, tick)) {+ // // Calculate H vector (in the rotor reference frame)+ // const float z_tan_t = z * tan_t;+ // const float qNum = r2 - z_tan_t * z_tan_t;+ // // Avoid singularity+ // if (qNum > 0.0001f) {+ // const float q = tan_t / xtensa_sqrt(qNum);+ // vec3d gr = {(-y - x * z * q) / r2, (x - y * z * q) / r2 , q};++ // // gr is in the rotor reference frame, rotate back to the global+ // // reference frame using the rotor rotation matrix+ // vec3d g;+ // xtensa_matrix_instance_f32 gr_ = {3, 1, gr};+ // xtensa_matrix_instance_f32 Rr_ = {3, 3, (float32_t *)(*sweepInfo->rotorRot)};+ // xtensa_matrix_instance_f32 g_ = {3, 1, g};+ // mat_mult(&Rr_, &gr_, &g_);++ // float h[KC_STATE_DIM] = {0};+ // h[KC_STATE_X] = g[0];+ // h[KC_STATE_Y] = g[1];+ // h[KC_STATE_Z] = g[2];++ // xtensa_matrix_instance_f32 H = {1, KC_STATE_DIM, h};+ // scalarUpdate(this, &H, error, sweepInfo->stdDev);+ // }+ // }+//}++void kalmanCorePredict(kalmanCoreData_t* this, float cmdThrust, Axis3f *acc, Axis3f *gyro, float dt, bool quadIsFlying)+{+ /* Here we discretize (euler forward) and linearise the quadrocopter dynamics in order+ * to push the covariance forward.+ *+ * QUADROCOPTER DYNAMICS (see paper):+ *+ * \dot{x} = R(I + [[d]])p+ * \dot{p} = f/m * e3 - [[\omega]]p - g(I - [[d]])R^-1 e3 //drag negligible+ * \dot{d} = \omega+ *+ * where [[.]] is the cross-product matrix of .+ * \omega are the gyro measurements+ * e3 is the column vector [0 0 1]'+ * I is the identity+ * R is the current attitude as a rotation matrix+ * f/m is the mass-normalized motor force (acceleration in the body's z direction)+ * g is gravity+ * x, p, d are the quad's states+ * note that d (attitude error) is zero at the beginning of each iteration,+ * since error information is incorporated into R after each Kalman update.+ */++ // The linearized update matrix+ NO_DMA_CCM_SAFE_ZERO_INIT static float A[KC_STATE_DIM][KC_STATE_DIM];+ static __attribute__((aligned(4))) xtensa_matrix_instance_f32 Am = { KC_STATE_DIM, KC_STATE_DIM, (float *)A}; // linearized dynamics for covariance update;++ // Temporary matrices for the covariance updates+ NO_DMA_CCM_SAFE_ZERO_INIT static float tmpNN1d[KC_STATE_DIM * KC_STATE_DIM];+ static __attribute__((aligned(4))) xtensa_matrix_instance_f32 tmpNN1m = { KC_STATE_DIM, KC_STATE_DIM, tmpNN1d};++ NO_DMA_CCM_SAFE_ZERO_INIT static float tmpNN2d[KC_STATE_DIM * KC_STATE_DIM];+ static __attribute__((aligned(4))) xtensa_matrix_instance_f32 tmpNN2m = { KC_STATE_DIM, KC_STATE_DIM, tmpNN2d};++ float dt2 = dt*dt;++ // ====== DYNAMICS LINEARIZATION ======+ // Initialize as the identity+ A[KC_STATE_X][KC_STATE_X] = 1;+ A[KC_STATE_Y][KC_STATE_Y] = 1;+ A[KC_STATE_Z][KC_STATE_Z] = 1;++ A[KC_STATE_PX][KC_STATE_PX] = 1;+ A[KC_STATE_PY][KC_STATE_PY] = 1;+ A[KC_STATE_PZ][KC_STATE_PZ] = 1;++ A[KC_STATE_D0][KC_STATE_D0] = 1;+ A[KC_STATE_D1][KC_STATE_D1] = 1;+ A[KC_STATE_D2][KC_STATE_D2] = 1;++ // position from body-frame velocity+ A[KC_STATE_X][KC_STATE_PX] = this->R[0][0]*dt;+ A[KC_STATE_Y][KC_STATE_PX] = this->R[1][0]*dt;+ A[KC_STATE_Z][KC_STATE_PX] = this->R[2][0]*dt;++ A[KC_STATE_X][KC_STATE_PY] = this->R[0][1]*dt;+ A[KC_STATE_Y][KC_STATE_PY] = this->R[1][1]*dt;+ A[KC_STATE_Z][KC_STATE_PY] = this->R[2][1]*dt;++ A[KC_STATE_X][KC_STATE_PZ] = this->R[0][2]*dt;+ A[KC_STATE_Y][KC_STATE_PZ] = this->R[1][2]*dt;+ A[KC_STATE_Z][KC_STATE_PZ] = this->R[2][2]*dt;++ // position from attitude error+ A[KC_STATE_X][KC_STATE_D0] = (this->S[KC_STATE_PY]*this->R[0][2] - this->S[KC_STATE_PZ]*this->R[0][1])*dt;+ A[KC_STATE_Y][KC_STATE_D0] = (this->S[KC_STATE_PY]*this->R[1][2] - this->S[KC_STATE_PZ]*this->R[1][1])*dt;+ A[KC_STATE_Z][KC_STATE_D0] = (this->S[KC_STATE_PY]*this->R[2][2] - this->S[KC_STATE_PZ]*this->R[2][1])*dt;++ A[KC_STATE_X][KC_STATE_D1] = (- this->S[KC_STATE_PX]*this->R[0][2] + this->S[KC_STATE_PZ]*this->R[0][0])*dt;+ A[KC_STATE_Y][KC_STATE_D1] = (- this->S[KC_STATE_PX]*this->R[1][2] + this->S[KC_STATE_PZ]*this->R[1][0])*dt;+ A[KC_STATE_Z][KC_STATE_D1] = (- this->S[KC_STATE_PX]*this->R[2][2] + this->S[KC_STATE_PZ]*this->R[2][0])*dt;++ A[KC_STATE_X][KC_STATE_D2] = (this->S[KC_STATE_PX]*this->R[0][1] - this->S[KC_STATE_PY]*this->R[0][0])*dt;+ A[KC_STATE_Y][KC_STATE_D2] = (this->S[KC_STATE_PX]*this->R[1][1] - this->S[KC_STATE_PY]*this->R[1][0])*dt;+ A[KC_STATE_Z][KC_STATE_D2] = (this->S[KC_STATE_PX]*this->R[2][1] - this->S[KC_STATE_PY]*this->R[2][0])*dt;++ // body-frame velocity from body-frame velocity+ A[KC_STATE_PX][KC_STATE_PX] = 1; //drag negligible+ A[KC_STATE_PY][KC_STATE_PX] =-gyro->z*dt;+ A[KC_STATE_PZ][KC_STATE_PX] = gyro->y*dt;++ A[KC_STATE_PX][KC_STATE_PY] = gyro->z*dt;+ A[KC_STATE_PY][KC_STATE_PY] = 1; //drag negligible+ A[KC_STATE_PZ][KC_STATE_PY] =-gyro->x*dt;++ A[KC_STATE_PX][KC_STATE_PZ] =-gyro->y*dt;+ A[KC_STATE_PY][KC_STATE_PZ] = gyro->x*dt;+ A[KC_STATE_PZ][KC_STATE_PZ] = 1; //drag negligible++ // body-frame velocity from attitude error+ A[KC_STATE_PX][KC_STATE_D0] = 0;+ A[KC_STATE_PY][KC_STATE_D0] = -GRAVITY_MAGNITUDE*this->R[2][2]*dt;+ A[KC_STATE_PZ][KC_STATE_D0] = GRAVITY_MAGNITUDE*this->R[2][1]*dt;++ A[KC_STATE_PX][KC_STATE_D1] = GRAVITY_MAGNITUDE*this->R[2][2]*dt;+ A[KC_STATE_PY][KC_STATE_D1] = 0;+ A[KC_STATE_PZ][KC_STATE_D1] = -GRAVITY_MAGNITUDE*this->R[2][0]*dt;++ A[KC_STATE_PX][KC_STATE_D2] = -GRAVITY_MAGNITUDE*this->R[2][1]*dt;+ A[KC_STATE_PY][KC_STATE_D2] = GRAVITY_MAGNITUDE*this->R[2][0]*dt;+ A[KC_STATE_PZ][KC_STATE_D2] = 0;++ // attitude error from attitude error+ /**+ * At first glance, it may not be clear where the next values come from, since they do not appear directly in the+ * dynamics. In this prediction step, we skip the step of first updating attitude-error, and then incorporating the+ * new error into the current attitude (which requires a rotation of the attitude-error covariance). Instead, we+ * directly update the body attitude, however still need to rotate the covariance, which is what you see below.+ *+ * This comes from a second order approximation to:+ * Sigma_post = exps(-d) Sigma_pre exps(-d)'+ * ~ (I + [[-d]] + [[-d]]^2 / 2) Sigma_pre (I + [[-d]] + [[-d]]^2 / 2)'+ * where d is the attitude error expressed as Rodriges parameters, ie. d0 = 1/2*gyro.x*dt under the assumption that+ * d = [0,0,0] at the beginning of each prediction step and that gyro.x is constant over the sampling period+ *+ * As derived in "Covariance Correction Step for Kalman Filtering with an Attitude"+ * http://arc.aiaa.org/doi/abs/10.2514/1.G000848+ */+ float d0 = gyro->x*dt/2;+ float d1 = gyro->y*dt/2;+ float d2 = gyro->z*dt/2;++ A[KC_STATE_D0][KC_STATE_D0] = 1 - d1*d1/2 - d2*d2/2;+ A[KC_STATE_D0][KC_STATE_D1] = d2 + d0*d1/2;+ A[KC_STATE_D0][KC_STATE_D2] = -d1 + d0*d2/2;++ A[KC_STATE_D1][KC_STATE_D0] = -d2 + d0*d1/2;+ A[KC_STATE_D1][KC_STATE_D1] = 1 - d0*d0/2 - d2*d2/2;+ A[KC_STATE_D1][KC_STATE_D2] = d0 + d1*d2/2;++ A[KC_STATE_D2][KC_STATE_D0] = d1 + d0*d2/2;+ A[KC_STATE_D2][KC_STATE_D1] = -d0 + d1*d2/2;+ A[KC_STATE_D2][KC_STATE_D2] = 1 - d0*d0/2 - d1*d1/2;+++ // ====== COVARIANCE UPDATE ======+ mat_mult(&Am, &this->Pm, &tmpNN1m); // A P+ mat_trans(&Am, &tmpNN2m); // A'+ mat_mult(&tmpNN1m, &tmpNN2m, &this->Pm); // A P A'+ // Process noise is added after the return from the prediction step++ // ====== PREDICTION STEP ======+ // The prediction depends on whether we're on the ground, or in flight.+ // When flying, the accelerometer directly measures thrust (hence is useless to estimate body angle while flying)++ float dx, dy, dz;+ float tmpSPX, tmpSPY, tmpSPZ;+ float zacc;++ if (quadIsFlying) // only acceleration in z direction+ {+ // TODO: In the next lines, can either use cmdThrust/mass, or acc->z. Need to test which is more reliable.+ // cmdThrust's error comes from poorly calibrated mass, and inexact cmdThrust -> thrust map+ // acc->z's error comes from measurement noise and accelerometer scaling+ // float zacc = cmdThrust;+ zacc = acc->z;++ // position updates in the body frame (will be rotated to inertial frame)+ dx = this->S[KC_STATE_PX] * dt;+ dy = this->S[KC_STATE_PY] * dt;+ dz = this->S[KC_STATE_PZ] * dt + zacc * dt2 / 2.0f; // thrust can only be produced in the body's Z direction++ // position update+ this->S[KC_STATE_X] += this->R[0][0] * dx + this->R[0][1] * dy + this->R[0][2] * dz;+ this->S[KC_STATE_Y] += this->R[1][0] * dx + this->R[1][1] * dy + this->R[1][2] * dz;+ this->S[KC_STATE_Z] += this->R[2][0] * dx + this->R[2][1] * dy + this->R[2][2] * dz - GRAVITY_MAGNITUDE * dt2 / 2.0f;++ // keep previous time step's state for the update+ tmpSPX = this->S[KC_STATE_PX];+ tmpSPY = this->S[KC_STATE_PY];+ tmpSPZ = this->S[KC_STATE_PZ];++ // body-velocity update: accelerometers - gyros cross velocity - gravity in body frame+ this->S[KC_STATE_PX] += dt * (gyro->z * tmpSPY - gyro->y * tmpSPZ - GRAVITY_MAGNITUDE * this->R[2][0]);+ this->S[KC_STATE_PY] += dt * (-gyro->z * tmpSPX + gyro->x * tmpSPZ - GRAVITY_MAGNITUDE * this->R[2][1]);+ this->S[KC_STATE_PZ] += dt * (zacc + gyro->y * tmpSPX - gyro->x * tmpSPY - GRAVITY_MAGNITUDE * this->R[2][2]);+ }+ else // Acceleration can be in any direction, as measured by the accelerometer. This occurs, eg. in freefall or while being carried.+ {+ // position updates in the body frame (will be rotated to inertial frame)+ dx = this->S[KC_STATE_PX] * dt + acc->x * dt2 / 2.0f;+ dy = this->S[KC_STATE_PY] * dt + acc->y * dt2 / 2.0f;+ dz = this->S[KC_STATE_PZ] * dt + acc->z * dt2 / 2.0f; // thrust can only be produced in the body's Z direction++ // position update+ this->S[KC_STATE_X] += this->R[0][0] * dx + this->R[0][1] * dy + this->R[0][2] * dz;+ this->S[KC_STATE_Y] += this->R[1][0] * dx + this->R[1][1] * dy + this->R[1][2] * dz;+ this->S[KC_STATE_Z] += this->R[2][0] * dx + this->R[2][1] * dy + this->R[2][2] * dz - GRAVITY_MAGNITUDE * dt2 / 2.0f;++ // keep previous time step's state for the update+ tmpSPX = this->S[KC_STATE_PX];+ tmpSPY = this->S[KC_STATE_PY];+ tmpSPZ = this->S[KC_STATE_PZ];++ // body-velocity update: accelerometers - gyros cross velocity - gravity in body frame+ this->S[KC_STATE_PX] += dt * (acc->x + gyro->z * tmpSPY - gyro->y * tmpSPZ - GRAVITY_MAGNITUDE * this->R[2][0]);+ this->S[KC_STATE_PY] += dt * (acc->y - gyro->z * tmpSPX + gyro->x * tmpSPZ - GRAVITY_MAGNITUDE * this->R[2][1]);+ this->S[KC_STATE_PZ] += dt * (acc->z + gyro->y * tmpSPX - gyro->x * tmpSPY - GRAVITY_MAGNITUDE * this->R[2][2]);+ }++ // attitude update (rotate by gyroscope), we do this in quaternions+ // this is the gyroscope angular velocity integrated over the sample period+ float dtwx = dt*gyro->x;+ float dtwy = dt*gyro->y;+ float dtwz = dt*gyro->z;++ // compute the quaternion values in [w,x,y,z] order+ float angle = xtensa_sqrt(dtwx*dtwx + dtwy*dtwy + dtwz*dtwz);+ float ca = xtensa_cos_f32(angle/2.0f);+ float sa = xtensa_sin_f32(angle/2.0f);+ float dq[4] = {ca , sa*dtwx/angle , sa*dtwy/angle , sa*dtwz/angle};++ float tmpq0;+ float tmpq1;+ float tmpq2;+ float tmpq3;++ // rotate the quad's attitude by the delta quaternion vector computed above+ tmpq0 = dq[0]*this->q[0] - dq[1]*this->q[1] - dq[2]*this->q[2] - dq[3]*this->q[3];+ tmpq1 = dq[1]*this->q[0] + dq[0]*this->q[1] + dq[3]*this->q[2] - dq[2]*this->q[3];+ tmpq2 = dq[2]*this->q[0] - dq[3]*this->q[1] + dq[0]*this->q[2] + dq[1]*this->q[3];+ tmpq3 = dq[3]*this->q[0] + dq[2]*this->q[1] - dq[1]*this->q[2] + dq[0]*this->q[3];++ if (! quadIsFlying) {+ float keep = 1.0f - ROLLPITCH_ZERO_REVERSION;++ tmpq0 = keep * tmpq0 + ROLLPITCH_ZERO_REVERSION * initialQuaternion[0];+ tmpq1 = keep * tmpq1 + ROLLPITCH_ZERO_REVERSION * initialQuaternion[1];+ tmpq2 = keep * tmpq2 + ROLLPITCH_ZERO_REVERSION * initialQuaternion[2];+ tmpq3 = keep * tmpq3 + ROLLPITCH_ZERO_REVERSION * initialQuaternion[3];+ }++ // normalize and store the result+ float norm = xtensa_sqrt(tmpq0*tmpq0 + tmpq1*tmpq1 + tmpq2*tmpq2 + tmpq3*tmpq3);+ this->q[0] = tmpq0/norm; this->q[1] = tmpq1/norm; this->q[2] = tmpq2/norm; this->q[3] = tmpq3/norm;+ assertStateNotNaN(this);+}+++void kalmanCoreAddProcessNoise(kalmanCoreData_t* this, float dt)+{+ if (dt>0)+ {+ this->P[KC_STATE_X][KC_STATE_X] += powf(procNoiseAcc_xy*dt*dt + procNoiseVel*dt + procNoisePos, 2); // add process noise on position+ this->P[KC_STATE_Y][KC_STATE_Y] += powf(procNoiseAcc_xy*dt*dt + procNoiseVel*dt + procNoisePos, 2); // add process noise on position+ this->P[KC_STATE_Z][KC_STATE_Z] += powf(procNoiseAcc_z*dt*dt + procNoiseVel*dt + procNoisePos, 2); // add process noise on position++ this->P[KC_STATE_PX][KC_STATE_PX] += powf(procNoiseAcc_xy*dt + procNoiseVel, 2); // add process noise on velocity+ this->P[KC_STATE_PY][KC_STATE_PY] += powf(procNoiseAcc_xy*dt + procNoiseVel, 2); // add process noise on velocity+ this->P[KC_STATE_PZ][KC_STATE_PZ] += powf(procNoiseAcc_z*dt + procNoiseVel, 2); // add process noise on velocity++ this->P[KC_STATE_D0][KC_STATE_D0] += powf(measNoiseGyro_rollpitch * dt + procNoiseAtt, 2);+ this->P[KC_STATE_D1][KC_STATE_D1] += powf(measNoiseGyro_rollpitch * dt + procNoiseAtt, 2);+ this->P[KC_STATE_D2][KC_STATE_D2] += powf(measNoiseGyro_yaw * dt + procNoiseAtt, 2);+ }++ for (int i=0; i<KC_STATE_DIM; i++) {+ for (int j=i; j<KC_STATE_DIM; j++) {+ float p = 0.5f*this->P[i][j] + 0.5f*this->P[j][i];+ if (isnan(p) || p > MAX_COVARIANCE) {+ this->P[i][j] = this->P[j][i] = MAX_COVARIANCE;+ } else if ( i==j && p < MIN_COVARIANCE ) {+ this->P[i][j] = this->P[j][i] = MIN_COVARIANCE;+ } else {+ this->P[i][j] = this->P[j][i] = p;+ }+ }+ }++ assertStateNotNaN(this);+}++++void kalmanCoreFinalize(kalmanCoreData_t* this, uint32_t tick)+{+ // Matrix to rotate the attitude covariances once updated+ NO_DMA_CCM_SAFE_ZERO_INIT static float A[KC_STATE_DIM][KC_STATE_DIM];+ static xtensa_matrix_instance_f32 Am = {KC_STATE_DIM, KC_STATE_DIM, (float *)A};++ // Temporary matrices for the covariance updates+ NO_DMA_CCM_SAFE_ZERO_INIT static float tmpNN1d[KC_STATE_DIM * KC_STATE_DIM];+ static xtensa_matrix_instance_f32 tmpNN1m = {KC_STATE_DIM, KC_STATE_DIM, tmpNN1d};++ NO_DMA_CCM_SAFE_ZERO_INIT static float tmpNN2d[KC_STATE_DIM * KC_STATE_DIM];+ static xtensa_matrix_instance_f32 tmpNN2m = {KC_STATE_DIM, KC_STATE_DIM, tmpNN2d};++ // Incorporate the attitude error (Kalman filter state) with the attitude+ float v0 = this->S[KC_STATE_D0];+ float v1 = this->S[KC_STATE_D1];+ float v2 = this->S[KC_STATE_D2];++ // Move attitude error into attitude if any of the angle errors are large enough+ if ((fabsf(v0) > 0.1e-3f || fabsf(v1) > 0.1e-3f || fabsf(v2) > 0.1e-3f) && (fabsf(v0) < 10 && fabsf(v1) < 10 && fabsf(v2) < 10))+ {+ float angle = xtensa_sqrt(v0*v0 + v1*v1 + v2*v2);+ float ca = xtensa_cos_f32(angle / 2.0f);+ float sa = xtensa_sin_f32(angle / 2.0f);+ float dq[4] = {ca, sa * v0 / angle, sa * v1 / angle, sa * v2 / angle};++ // rotate the quad's attitude by the delta quaternion vector computed above+ float tmpq0 = dq[0] * this->q[0] - dq[1] * this->q[1] - dq[2] * this->q[2] - dq[3] * this->q[3];+ float tmpq1 = dq[1] * this->q[0] + dq[0] * this->q[1] + dq[3] * this->q[2] - dq[2] * this->q[3];+ float tmpq2 = dq[2] * this->q[0] - dq[3] * this->q[1] + dq[0] * this->q[2] + dq[1] * this->q[3];+ float tmpq3 = dq[3] * this->q[0] + dq[2] * this->q[1] - dq[1] * this->q[2] + dq[0] * this->q[3];++ // normalize and store the result+ float norm = xtensa_sqrt(tmpq0 * tmpq0 + tmpq1 * tmpq1 + tmpq2 * tmpq2 + tmpq3 * tmpq3);+ this->q[0] = tmpq0 / norm;+ this->q[1] = tmpq1 / norm;+ this->q[2] = tmpq2 / norm;+ this->q[3] = tmpq3 / norm;++ /** Rotate the covariance, since we've rotated the body+ *+ * This comes from a second order approximation to:+ * Sigma_post = exps(-d) Sigma_pre exps(-d)'+ * ~ (I + [[-d]] + [[-d]]^2 / 2) Sigma_pre (I + [[-d]] + [[-d]]^2 / 2)'+ * where d is the attitude error expressed as Rodriges parameters, ie. d = tan(|v|/2)*v/|v|+ *+ * As derived in "Covariance Correction Step for Kalman Filtering with an Attitude"+ * http://arc.aiaa.org/doi/abs/10.2514/1.G000848+ */++ float d0 = v0/2; // the attitude error vector (v0,v1,v2) is small,+ float d1 = v1/2; // so we use a first order approximation to d0 = tan(|v0|/2)*v0/|v0|+ float d2 = v2/2;++ A[KC_STATE_X][KC_STATE_X] = 1;+ A[KC_STATE_Y][KC_STATE_Y] = 1;+ A[KC_STATE_Z][KC_STATE_Z] = 1;++ A[KC_STATE_PX][KC_STATE_PX] = 1;+ A[KC_STATE_PY][KC_STATE_PY] = 1;+ A[KC_STATE_PZ][KC_STATE_PZ] = 1;++ A[KC_STATE_D0][KC_STATE_D0] = 1 - d1*d1/2 - d2*d2/2;+ A[KC_STATE_D0][KC_STATE_D1] = d2 + d0*d1/2;+ A[KC_STATE_D0][KC_STATE_D2] = -d1 + d0*d2/2;++ A[KC_STATE_D1][KC_STATE_D0] = -d2 + d0*d1/2;+ A[KC_STATE_D1][KC_STATE_D1] = 1 - d0*d0/2 - d2*d2/2;+ A[KC_STATE_D1][KC_STATE_D2] = d0 + d1*d2/2;++ A[KC_STATE_D2][KC_STATE_D0] = d1 + d0*d2/2;+ A[KC_STATE_D2][KC_STATE_D1] = -d0 + d1*d2/2;+ A[KC_STATE_D2][KC_STATE_D2] = 1 - d0*d0/2 - d1*d1/2;++ mat_trans(&Am, &tmpNN1m); // A'+ mat_mult(&Am, &this->Pm, &tmpNN2m); // AP+ mat_mult(&tmpNN2m, &tmpNN1m, &this->Pm); //APA'+ }++ // convert the new attitude to a rotation matrix, such that we can rotate body-frame velocity and acc+ this->R[0][0] = this->q[0] * this->q[0] + this->q[1] * this->q[1] - this->q[2] * this->q[2] - this->q[3] * this->q[3];+ this->R[0][1] = 2 * this->q[1] * this->q[2] - 2 * this->q[0] * this->q[3];+ this->R[0][2] = 2 * this->q[1] * this->q[3] + 2 * this->q[0] * this->q[2];++ this->R[1][0] = 2 * this->q[1] * this->q[2] + 2 * this->q[0] * this->q[3];+ this->R[1][1] = this->q[0] * this->q[0] - this->q[1] * this->q[1] + this->q[2] * this->q[2] - this->q[3] * this->q[3];+ this->R[1][2] = 2 * this->q[2] * this->q[3] - 2 * this->q[0] * this->q[1];++ this->R[2][0] = 2 * this->q[1] * this->q[3] - 2 * this->q[0] * this->q[2];+ this->R[2][1] = 2 * this->q[2] * this->q[3] + 2 * this->q[0] * this->q[1];+ this->R[2][2] = this->q[0] * this->q[0] - this->q[1] * this->q[1] - this->q[2] * this->q[2] + this->q[3] * this->q[3];++ // reset the attitude error+ this->S[KC_STATE_D0] = 0;+ this->S[KC_STATE_D1] = 0;+ this->S[KC_STATE_D2] = 0;++ // enforce symmetry of the covariance matrix, and ensure the values stay bounded+ for (int i=0; i<KC_STATE_DIM; i++) {+ for (int j=i; j<KC_STATE_DIM; j++) {+ float p = 0.5f*this->P[i][j] + 0.5f*this->P[j][i];+ if (isnan(p) || p > MAX_COVARIANCE) {+ this->P[i][j] = this->P[j][i] = MAX_COVARIANCE;+ } else if ( i==j && p < MIN_COVARIANCE ) {+ this->P[i][j] = this->P[j][i] = MIN_COVARIANCE;+ } else {+ this->P[i][j] = this->P[j][i] = p;+ }+ }+ }++ assertStateNotNaN(this);+}++void kalmanCoreExternalizeState(const kalmanCoreData_t* this, state_t *state, const Axis3f *acc, uint32_t tick)+{+ // position state is already in world frame+ state->position = (point_t){+ .timestamp = tick,+ .x = this->S[KC_STATE_X],+ .y = this->S[KC_STATE_Y],+ .z = this->S[KC_STATE_Z]+ };++ // velocity is in body frame and needs to be rotated to world frame+ state->velocity = (velocity_t){+ .timestamp = tick,+ .x = this->R[0][0]*this->S[KC_STATE_PX] + this->R[0][1]*this->S[KC_STATE_PY] + this->R[0][2]*this->S[KC_STATE_PZ],+ .y = this->R[1][0]*this->S[KC_STATE_PX] + this->R[1][1]*this->S[KC_STATE_PY] + this->R[1][2]*this->S[KC_STATE_PZ],+ .z = this->R[2][0]*this->S[KC_STATE_PX] + this->R[2][1]*this->S[KC_STATE_PY] + this->R[2][2]*this->S[KC_STATE_PZ]+ };++ // Accelerometer measurements are in the body frame and need to be rotated to world frame.+ // Furthermore, the legacy code requires acc.z to be acceleration without gravity.+ // Finally, note that these accelerations are in Gs, and not in m/s^2, hence - 1 for removing gravity+ state->acc = (acc_t){+ .timestamp = tick,+ .x = this->R[0][0]*acc->x + this->R[0][1]*acc->y + this->R[0][2]*acc->z,+ .y = this->R[1][0]*acc->x + this->R[1][1]*acc->y + this->R[1][2]*acc->z,+ .z = this->R[2][0]*acc->x + this->R[2][1]*acc->y + this->R[2][2]*acc->z - 1+ };++ // convert the new attitude into Euler YPR+ float yaw = atan2f(2*(this->q[1]*this->q[2]+this->q[0]*this->q[3]) , this->q[0]*this->q[0] + this->q[1]*this->q[1] - this->q[2]*this->q[2] - this->q[3]*this->q[3]);+ float pitch = asinf(-2*(this->q[1]*this->q[3] - this->q[0]*this->q[2]));+ float roll = atan2f(2*(this->q[2]*this->q[3]+this->q[0]*this->q[1]) , this->q[0]*this->q[0] - this->q[1]*this->q[1] - this->q[2]*this->q[2] + this->q[3]*this->q[3]);++ // Save attitude, adjusted for the legacy CF2 body coordinate system+ state->attitude = (attitude_t){+ .timestamp = tick,+ .roll = roll*RAD_TO_DEG,+ .pitch = -pitch*RAD_TO_DEG,+ .yaw = yaw*RAD_TO_DEG+ };++ // Save quaternion, hopefully one day this could be used in a better controller.+ // Note that this is not adjusted for the legacy coordinate system+ state->attitudeQuaternion = (quaternion_t){+ .timestamp = tick,+ .w = this->q[0],+ .x = this->q[1],+ .y = this->q[2],+ .z = this->q[3]+ };++ assertStateNotNaN(this);+}++// Reset a state to 0 with max covariance+// If called often, this decouples the state to the rest of the filter+static void decoupleState(kalmanCoreData_t* this, kalmanCoreStateIdx_t state)+{+ // Set all covariance to 0+ for(int i=0; i<KC_STATE_DIM; i++) {+ this->P[state][i] = 0;+ this->P[i][state] = 0;+ }+ // Set state variance to maximum+ this->P[state][state] = MAX_COVARIANCE;+ // set state to zero+ this->S[state] = 0;+}++void kalmanCoreDecoupleXY(kalmanCoreData_t* this)+{+ decoupleState(this, KC_STATE_X);+ decoupleState(this, KC_STATE_PX);+ decoupleState(this, KC_STATE_Y);+ decoupleState(this, KC_STATE_PY);+}++// Stock log groups+LOG_GROUP_START(kalman_pred)+ LOG_ADD(LOG_FLOAT, predNX, &predictedNX)+ LOG_ADD(LOG_FLOAT, predNY, &predictedNY)+ LOG_ADD(LOG_FLOAT, measNX, &measuredNX)+ LOG_ADD(LOG_FLOAT, measNY, &measuredNY)+LOG_GROUP_STOP(kalman_pred)++LOG_GROUP_START(outlierf)+ LOG_ADD(LOG_INT32, lhWin, &sweepOutlierFilterState.openingWindow)+LOG_GROUP_STOP(outlierf)++PARAM_GROUP_START(kalman)+ PARAM_ADD(PARAM_FLOAT, pNAcc_xy, &procNoiseAcc_xy)+ PARAM_ADD(PARAM_FLOAT, pNAcc_z, &procNoiseAcc_z)+ PARAM_ADD(PARAM_FLOAT, pNVel, &procNoiseVel)+ PARAM_ADD(PARAM_FLOAT, pNPos, &procNoisePos)+ PARAM_ADD(PARAM_FLOAT, pNAtt, &procNoiseAtt)+ PARAM_ADD(PARAM_FLOAT, mNBaro, &measNoiseBaro)+ PARAM_ADD(PARAM_FLOAT, mNGyro_rollpitch, &measNoiseGyro_rollpitch)+ PARAM_ADD(PARAM_FLOAT, mNGyro_yaw, &measNoiseGyro_yaw)+ PARAM_ADD(PARAM_FLOAT, initialX, &initialX)+ PARAM_ADD(PARAM_FLOAT, initialY, &initialY)+ PARAM_ADD(PARAM_FLOAT, initialZ, &initialZ)+ PARAM_ADD(PARAM_FLOAT, initialYaw, &initialYaw)+PARAM_GROUP_STOP(kalman)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/kalman_supervisor.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/kalman_supervisor.cnew file mode 100644index 0000000..c152dca--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/kalman_supervisor.c@@ -0,0 +1,62 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * kalman_supervisor.c - Supervises the kalman estimator and makes sure it+ * stays within bounds.+ */++#include "kalman_supervisor.h"++#include "param.h"++// The bounds on states, these shouldn't be hit...+float maxPosition = 100; //meters+float maxVelocity = 10; //meters per second++bool kalmanSupervisorIsStateWithinBounds(const kalmanCoreData_t* this) {+ for (int i = 0; i < 3; i++) {+ if (maxPosition > 0.0f) {+ if (this->S[KC_STATE_X + i] > maxPosition) {+ return false;+ } else if (this->S[KC_STATE_X + i] < -maxPosition) {+ return false;+ }+ }++ if (maxVelocity > 0.0f) {+ if (this->S[KC_STATE_PX + i] > maxVelocity) {+ return false;+ } else if (this->S[KC_STATE_PX + i] < -maxVelocity) {+ return false;+ }+ }+ }++ return true;+}++PARAM_GROUP_START(kalman)+ PARAM_ADD(PARAM_FLOAT, maxPos, &maxPosition)+ PARAM_ADD(PARAM_FLOAT, maxVel, &maxVelocity)+PARAM_GROUP_STOP(kalman)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_core.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_core.cnew file mode 100644index 0000000..cdaa3e0--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_core.c@@ -0,0 +1,531 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 - 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * lighthouse_core.c - central part of the lighthouse positioning system+ */++#include "stm32fxxx.h"+#include "FreeRTOS.h"+#include "task.h"++#include <math.h>+#include <stdbool.h>+#include <stdint.h>++#include "system.h"+#include "log.h"+#include "param.h"+#include "statsCnt.h"++#define DEBUG_MODULE "LH"+#include "debug.h"+#include "uart1.h"+#include "crtp_localization_service.h"++#include "pulse_processor.h"+#include "pulse_processor_v1.h"+#include "pulse_processor_v2.h"++#include "lighthouse_deck_flasher.h"+#include "lighthouse_position_est.h"+#include "lighthouse_core.h"++#include "storage.h"++#include "test_support.h"+#include "static_mem.h"++static const uint32_t MAX_WAIT_TIME_FOR_HEALTH_MS = 4000;++static pulseProcessorResult_t angles;+static lighthouseUartFrame_t frame;+static lighthouseBsIdentificationData_t bsIdentificationData;++// Stats+static bool uartSynchronized = false;++#define ONE_SECOND 1000+#define HALF_SECOND 500+static STATS_CNT_RATE_DEFINE(serialFrameRate, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(frameRate, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(cycleRate, ONE_SECOND);++static STATS_CNT_RATE_DEFINE(bs0Rate, HALF_SECOND);+static STATS_CNT_RATE_DEFINE(bs1Rate, HALF_SECOND);+static statsCntRateLogger_t* bsRates[PULSE_PROCESSOR_N_BASE_STATIONS] = {&bs0Rate, &bs1Rate};++static uint16_t pulseWidth[PULSE_PROCESSOR_N_SENSORS];+pulseProcessor_t lighthouseCoreState = {+ // .bsGeometry = {+ // Arena LH1+ // {.valid = true, .origin = {-1.958483, 0.542299, 3.152727, }, .mat = {{0.79721498, -0.004274, 0.60368103, }, {0.0, 0.99997503, 0.00708, }, {-0.60369599, -0.005645, 0.79719502, }, }},+ // {.valid = true, .origin = {1.062398, -2.563488, 3.112367, }, .mat = {{0.018067, -0.999336, 0.031647, }, {0.76125097, 0.034269, 0.64755201, }, {-0.648206, 0.012392, 0.76136398, }, }},++ // Arena LH2+ // {.valid = true, .origin = {-2.057947, 0.398319, 3.109704, }, .mat = {{0.807210, 0.002766, 0.590258, }, {0.067095, 0.993078, -0.096409, }, {-0.586439, 0.117426, 0.801437, }, }},+ // {.valid = true, .origin = {0.866244, -2.566829, 3.132632, }, .mat = {{-0.043296, -0.997675, -0.052627, }, {0.766284, -0.066962, 0.639003, }, {-0.641042, -0.012661, 0.767401, }, }},+ // },++ // .bsCalibration = {+ // // Arena LH2+ // { // Base station 0+ // .valid = true,+ // .sweep = {+ // {.tilt = -0.047058, .phase = 0.0, .curve = 0.052215, .gibphase = 2.087890, .gibmag = -0.003913, .ogeephase = 0.433105, .ogeemag = -0.049285},+ // {.tilt = 0.048065, .phase = -0.005336, .curve = 0.122375, .gibphase = 2.097656, .gibmag = -0.003883, .ogeephase = 0.631835, .ogeemag = -0.034851},+ // },+ // },+ // { // Base station 1+ // .valid = true,+ // .sweep = {+ // {.tilt = -0.051208, .phase = 0.0, .curve = 0.011756, .gibphase = 2.136718, .gibmag = -0.006057, .ogeephase = 2.705078,},+ // {.tilt = 0.045623, .phase = -0.004142, .curve = 0.104736, .gibphase = 2.349609, .gibmag = -0.003332, .ogeephase = 0.380859, .ogeemag = -0.240112,},+ // },+ // },+ // }+};++#if LIGHTHOUSE_FORCE_TYPE == 1+pulseProcessorProcessPulse_t pulseProcessorProcessPulse = pulseProcessorV1ProcessPulse;+#elif LIGHTHOUSE_FORCE_TYPE == 2+pulseProcessorProcessPulse_t pulseProcessorProcessPulse = pulseProcessorV2ProcessPulse;+#else+pulseProcessorProcessPulse_t pulseProcessorProcessPulse = (void*)0;+#endif++#define UART_FRAME_LENGTH 12+++// Persistent storage+#define STORAGE_VERSION_KEY "lh/ver"+#define CURRENT_STORAGE_VERSION "1"+#define STORAGE_KEY_GEO "lh/sys/0/geo/"+#define STORAGE_KEY_CALIB "lh/sys/0/cal/"+#define KEY_LEN 20++static void verifySetStorageVersion();+static baseStationGeometry_t geoBuffer;+TESTABLE_STATIC void initializeGeoDataFromStorage();+static lighthouseCalibration_t calibBuffer;+TESTABLE_STATIC void initializeCalibDataFromStorage();+++void lighthouseCoreInit() {+ lighthousePositionEstInit();+}++TESTABLE_STATIC bool getUartFrameRaw(lighthouseUartFrame_t *frame) {+ static char data[UART_FRAME_LENGTH];+ int syncCounter = 0;++ for(int i = 0; i < UART_FRAME_LENGTH; i++) {+ uart1Getchar(&data[i]);+ if ((unsigned char)data[i] == 0xff) {+ syncCounter += 1;+ }+ }++ memset(frame, 0, sizeof(*frame));++ frame->isSyncFrame = (syncCounter == UART_FRAME_LENGTH);++ frame->data.sensor = data[0] & 0x03;+ frame->data.channelFound = (data[0] & 0x80) == 0;+ frame->data.channel = (data[0] >> 3) & 0x0f;+ frame->data.slowbit = (data[0] >> 2) & 0x01;+ memcpy(&frame->data.width, &data[1], 2);+ memcpy(&frame->data.offset, &data[3], 3);+ memcpy(&frame->data.beamData, &data[6], 3);+ memcpy(&frame->data.timestamp, &data[9], 3);++ // Offset is expressed in a 6 MHz clock, convert to the 24 MHz that is used for timestamps+ frame->data.offset *= 4;++ bool isPaddingZero = (((data[5] | data[8]) & 0xfe) == 0);+ bool isFrameValid = (isPaddingZero || frame->isSyncFrame);++ STATS_CNT_RATE_EVENT(&serialFrameRate);++ return isFrameValid;+}++TESTABLE_STATIC void waitForUartSynchFrame() {+ char c;+ int syncCounter = 0;+ bool synchronized = false;++ while (!synchronized) {+ uart1Getchar(&c);+ if ((unsigned char)c == 0xff) {+ syncCounter += 1;+ } else {+ syncCounter = 0;+ }+ synchronized = (syncCounter == UART_FRAME_LENGTH);+ }+}+++// Method used to estimate position+// 0 = Position calculated outside the estimator using intersection point of beams.+// Yaw error calculated outside the estimator. Position and yaw error is pushed to the+// estimator as pre-calculated.+// 1 = Sweep angles pushed into the estimator. Yaw error calculated outside the estimator+// and pushed to the estimator as a pre-calculated value.+static uint8_t estimationMethod = 1;+++static void usePulseResultCrossingBeams(pulseProcessor_t *appState, pulseProcessorResult_t* angles, int basestation) {+ pulseProcessorClearOutdated(appState, angles, basestation);++ if (basestation == 1) {+ STATS_CNT_RATE_EVENT(&cycleRate);++ lighthousePositionEstimatePoseCrossingBeams(appState, angles, 1);++ pulseProcessorProcessed(angles, 0);+ pulseProcessorProcessed(angles, 1);+ }+}+++static void usePulseResultSweeps(pulseProcessor_t *appState, pulseProcessorResult_t* angles, int basestation) {+ STATS_CNT_RATE_EVENT(&cycleRate);++ pulseProcessorClearOutdated(appState, angles, basestation);++ lighthousePositionEstimatePoseSweeps(appState, angles, basestation);++ pulseProcessorProcessed(angles, basestation);+}++static void convertV2AnglesToV1Angles(pulseProcessorResult_t* angles) {+ for (int sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ for (int bs = 0; bs < PULSE_PROCESSOR_N_BASE_STATIONS; bs++) {+ pulseProcessorBaseStationMeasuremnt_t* from = &angles->sensorMeasurementsLh2[sensor].baseStatonMeasurements[bs];+ pulseProcessorBaseStationMeasuremnt_t* to = &angles->sensorMeasurementsLh1[sensor].baseStatonMeasurements[bs];++ if (2 == from->validCount) {+ pulseProcessorV2ConvertToV1Angles(from->correctedAngles[0], from->correctedAngles[1], to->correctedAngles);+ to->validCount = from->validCount;+ } else {+ to->validCount = 0;+ }+ }+ }+}++static void usePulseResult(pulseProcessor_t *appState, pulseProcessorResult_t* angles, int basestation, int sweepId) {+ if (sweepId == sweepIdSecond) {+ pulseProcessorApplyCalibration(appState, angles, basestation);+ if (lighthouseBsTypeV2 == angles->measurementType) {+ // Emulate V1 base stations for now, convert to V1 angles+ convertV2AnglesToV1Angles(angles);+ }++ // Send measurement to the ground+ locSrvSendLighthouseAngle(basestation, angles);++ switch(estimationMethod) {+ case 0:+ usePulseResultCrossingBeams(appState, angles, basestation);+ break;+ case 1:+ usePulseResultSweeps(appState, angles, basestation);+ break;+ default:+ break;+ }+ }+}++/**+ * @brief Identify the type of base stations used in the system.+ * There is not member of the UART frame data we can use to directly identify the type, but we can use statistical methods.+ * The beamWord will vary for V2 base stations, while it will have the value 0x1ffff fairly offen for V1 base stations.+ *+ * @param frame+ * @param state+ * @return TESTABLE_STATIC identifyBaseStationType+ */+TESTABLE_STATIC lighthouseBaseStationType_t identifyBaseStationType(const lighthouseUartFrame_t* frame, lighthouseBsIdentificationData_t* state) {+ const uint32_t v1Indicator = 0x1ffff;+ const int requiredIndicatorsForV1 = 6;+ const int requiredSamplesForV2 = 20;+ state->sampleCount++;+ if (frame->data.beamData == v1Indicator) {+ state->hitCount++;+ }++ if (state->hitCount >= requiredIndicatorsForV1) {+ return lighthouseBsTypeV1;+ }++ if (state->sampleCount >= requiredSamplesForV2) {+ return lighthouseBsTypeV2;+ }++ return lighthouseBsTypeUnknown;+}++static pulseProcessorProcessPulse_t identifySystem(const lighthouseUartFrame_t* frame, lighthouseBsIdentificationData_t* bsIdentificationData) {+ pulseProcessorProcessPulse_t result = (void*)0;++ switch (identifyBaseStationType(frame, bsIdentificationData)) {+ case lighthouseBsTypeV1:+ DEBUG_PRINT("Locking to V1 system\n");+ result = pulseProcessorV1ProcessPulse;+ break;+ case lighthouseBsTypeV2:+ DEBUG_PRINT("Locking to V2 system\n");+ result = pulseProcessorV2ProcessPulse;+ break;+ default:+ // Nothing here+ break;+ }++ return result;+}++static void processFrame(pulseProcessor_t *appState, pulseProcessorResult_t* angles, const lighthouseUartFrame_t* frame) {+ int basestation;+ int sweepId;++ pulseWidth[frame->data.sensor] = frame->data.width;++ if (pulseProcessorProcessPulse(appState, &frame->data, angles, &basestation, &sweepId)) {+ STATS_CNT_RATE_EVENT(bsRates[basestation]);+ usePulseResult(appState, angles, basestation, sweepId);+ }+}++static void deckHealthCheck(pulseProcessor_t *appState, const lighthouseUartFrame_t* frame) {+ if (!appState->healthDetermined) {+ const uint32_t now = xTaskGetTickCount();+ if (0 == appState->healthFirstSensorTs) {+ appState->healthFirstSensorTs = now;+ }++ if (0x0f == appState->healthSensorBitField) {+ appState->healthDetermined = true;+ // DEBUG_PRINT("All sensors good\n");+ } else {+ appState->healthSensorBitField |= (0x01 << frame->data.sensor);++ if ((now - appState->healthFirstSensorTs) > MAX_WAIT_TIME_FOR_HEALTH_MS) {+ appState->healthDetermined = true;+ DEBUG_PRINT("Warning: not getting data from all sensors\n");+ for (int i = 0; i < PULSE_PROCESSOR_N_SENSORS; i++) {+ if (appState->healthSensorBitField & (0x1 << i)) {+ DEBUG_PRINT(" %d - OK\n", i);+ } else {+ DEBUG_PRINT(" %d - error\n", i);+ }+ }+ }+ }+ }+}++void lighthouseCoreTask(void *param) {+ bool isUartFrameValid = false;++ uart1Init(230400);+ systemWaitStart();++ verifySetStorageVersion();+ initializeGeoDataFromStorage();+ initializeCalibDataFromStorage();++ lighthouseDeckFlasherCheckVersionAndBoot();++ memset(&bsIdentificationData, 0, sizeof(bsIdentificationData));++ while(1) {+ memset(pulseWidth, 0, sizeof(pulseWidth[0]) * PULSE_PROCESSOR_N_SENSORS);+ waitForUartSynchFrame();+ uartSynchronized = true;++ bool previousWasSyncFrame = false;++ while((isUartFrameValid = getUartFrameRaw(&frame))) {+ // If a sync frame is getting through, we are only receiving sync frames. So nothing else. Reset state+ if(frame.isSyncFrame && previousWasSyncFrame) {+ pulseProcessorAllClear(&angles);+ }+ // Now we are receiving items+ else if(!frame.isSyncFrame) {+ STATS_CNT_RATE_EVENT(&frameRate);++ deckHealthCheck(&lighthouseCoreState, &frame);+ if (pulseProcessorProcessPulse) {+ processFrame(&lighthouseCoreState, &angles, &frame);+ } else {+ pulseProcessorProcessPulse = identifySystem(&frame, &bsIdentificationData);+ }+ }++ previousWasSyncFrame = frame.isSyncFrame;+ }++ uartSynchronized = false;+ }+}++void lighthouseCoreSetCalibrationData(const uint8_t baseStation, const lighthouseCalibration_t* calibration) {+ if (baseStation < PULSE_PROCESSOR_N_BASE_STATIONS) {+ lighthouseCoreState.bsCalibration[baseStation] = *calibration;+ }+}++static void generateStorageKey(char* buf, const char* base, const uint8_t baseStation) {+ // TOOD make an implementation that supports baseStations with 2 digits+ ASSERT(baseStation <= 9);++ const int baseLen = strlen(base);+ memcpy(buf, base, baseLen);+ buf[baseLen] = '0' + baseStation;+ buf[baseLen + 1] = '\0';+}++bool lighthouseCorePersistData(const uint8_t baseStation, const bool geoData, const bool calibData) {+ bool result = true;+ char key[KEY_LEN];++ if (baseStation < PULSE_PROCESSOR_N_BASE_STATIONS) {+ if (geoData) {+ generateStorageKey(key, STORAGE_KEY_GEO, baseStation);+ result = result && storageStore(key, &lighthouseCoreState.bsGeometry[baseStation], sizeof(lighthouseCoreState.bsGeometry[baseStation]));+ }+ if (calibData) {+ generateStorageKey(key, STORAGE_KEY_CALIB, baseStation);+ result = result && storageStore(key, &lighthouseCoreState.bsCalibration[baseStation], sizeof(lighthouseCoreState.bsCalibration[baseStation]));+ }+ }++ return result;+}++static void verifySetStorageVersion() {+ const int bufLen = 5;+ char buffer[bufLen];++ const size_t fetched = storageFetch(STORAGE_VERSION_KEY, buffer, bufLen);+ if (fetched == 0) {+ storageStore(STORAGE_VERSION_KEY, CURRENT_STORAGE_VERSION, strlen(CURRENT_STORAGE_VERSION) + 1);+ } else {+ if (strcmp(buffer, CURRENT_STORAGE_VERSION) != 0) {+ // The storage format version is wrong! What to do?+ // No need to handle until we bump the storage version, assert for now.+ ASSERT_FAILED();+ }+ }+}++TESTABLE_STATIC void initializeGeoDataFromStorage() {+ char key[KEY_LEN];++ for (int baseStation = 0; baseStation < PULSE_PROCESSOR_N_BASE_STATIONS; baseStation++) {+ if (!lighthouseCoreState.bsGeometry[baseStation].valid) {+ generateStorageKey(key, STORAGE_KEY_GEO, baseStation);+ const size_t geoSize = sizeof(geoBuffer);+ const size_t fetched = storageFetch(key, (void*)&geoBuffer, geoSize);+ if (fetched == geoSize) {+ lighthousePositionSetGeometryData(baseStation, &geoBuffer);+ }+ }+ }+}++TESTABLE_STATIC void initializeCalibDataFromStorage() {+ char key[KEY_LEN];++ for (int baseStation = 0; baseStation < PULSE_PROCESSOR_N_BASE_STATIONS; baseStation++) {+ if (!lighthouseCoreState.bsCalibration[baseStation].valid) {+ generateStorageKey(key, STORAGE_KEY_CALIB, baseStation);+ const size_t calibSize = sizeof(calibBuffer);+ const size_t fetched = storageFetch(key, (void*)&calibBuffer, calibSize);+ if (fetched == calibSize) {+ lighthouseCoreSetCalibrationData(baseStation, &calibBuffer);+ }+ }+ }+}++LOG_GROUP_START(lighthouse)+LOG_ADD_BY_FUNCTION(LOG_UINT8, validAngles, &pulseProcessorAnglesQuality)++LOG_ADD(LOG_FLOAT, rawAngle0x, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[0].angles[0])+LOG_ADD(LOG_FLOAT, rawAngle0y, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[0].angles[1])+LOG_ADD(LOG_FLOAT, rawAngle1x, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[1].angles[0])+LOG_ADD(LOG_FLOAT, rawAngle1y, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[1].angles[1])+LOG_ADD(LOG_FLOAT, angle0x, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[0].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle0y, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[0].correctedAngles[1])+LOG_ADD(LOG_FLOAT, angle1x, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[1].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle1y, &angles.sensorMeasurementsLh1[0].baseStatonMeasurements[1].correctedAngles[1])++LOG_ADD(LOG_FLOAT, angle0x_1, &angles.sensorMeasurementsLh1[1].baseStatonMeasurements[0].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle0y_1, &angles.sensorMeasurementsLh1[1].baseStatonMeasurements[0].correctedAngles[1])+LOG_ADD(LOG_FLOAT, angle1x_1, &angles.sensorMeasurementsLh1[1].baseStatonMeasurements[1].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle1y_1, &angles.sensorMeasurementsLh1[1].baseStatonMeasurements[1].correctedAngles[1])++LOG_ADD(LOG_FLOAT, angle0x_2, &angles.sensorMeasurementsLh1[2].baseStatonMeasurements[0].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle0y_2, &angles.sensorMeasurementsLh1[2].baseStatonMeasurements[0].correctedAngles[1])+LOG_ADD(LOG_FLOAT, angle1x_2, &angles.sensorMeasurementsLh1[2].baseStatonMeasurements[1].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle1y_2, &angles.sensorMeasurementsLh1[2].baseStatonMeasurements[1].correctedAngles[1])++LOG_ADD(LOG_FLOAT, angle0x_3, &angles.sensorMeasurementsLh1[3].baseStatonMeasurements[0].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle0y_3, &angles.sensorMeasurementsLh1[3].baseStatonMeasurements[0].correctedAngles[1])+LOG_ADD(LOG_FLOAT, angle1x_3, &angles.sensorMeasurementsLh1[3].baseStatonMeasurements[1].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle1y_3, &angles.sensorMeasurementsLh1[3].baseStatonMeasurements[1].correctedAngles[1])++LOG_ADD(LOG_FLOAT, rawAngle0xlh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[0].angles[0])+LOG_ADD(LOG_FLOAT, rawAngle0ylh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[0].angles[1])+LOG_ADD(LOG_FLOAT, rawAngle1xlh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[1].angles[0])+LOG_ADD(LOG_FLOAT, rawAngle1ylh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[1].angles[1])++LOG_ADD(LOG_FLOAT, angle0x_0lh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[0].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle0y_0lh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[0].correctedAngles[1])+LOG_ADD(LOG_FLOAT, angle1x_0lh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[1].correctedAngles[0])+LOG_ADD(LOG_FLOAT, angle1y_0lh2, &angles.sensorMeasurementsLh2[0].baseStatonMeasurements[1].correctedAngles[1])++STATS_CNT_RATE_LOG_ADD(serRt, &serialFrameRate)+STATS_CNT_RATE_LOG_ADD(frmRt, &frameRate)+STATS_CNT_RATE_LOG_ADD(cycleRt, &cycleRate)++STATS_CNT_RATE_LOG_ADD(bs0Rt, &bs0Rate)+STATS_CNT_RATE_LOG_ADD(bs1Rt, &bs1Rate)++LOG_ADD(LOG_UINT16, width0, &pulseWidth[0])+LOG_ADD(LOG_UINT16, width1, &pulseWidth[1])+LOG_ADD(LOG_UINT16, width2, &pulseWidth[2])+LOG_ADD(LOG_UINT16, width3, &pulseWidth[3])++LOG_ADD(LOG_UINT8, comSync, &uartSynchronized)+LOG_GROUP_STOP(lighthouse)++PARAM_GROUP_START(lighthouse)+PARAM_ADD(PARAM_UINT8, method, &estimationMethod)+PARAM_GROUP_STOP(lighthouse)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_deck_flasher.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_deck_flasher.cnew file mode 100644index 0000000..e534c68--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_deck_flasher.c@@ -0,0 +1,144 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * lighthouse_deck_flasher.h - handles flashing of FPGA binaries on the+ * Lighthouse deck+ */++#include <string.h>+#include <stdlib.h>++#define DEBUG_MODULE "LHFL"+#include "debug.h"+#include "lh_bootloader.h"+#include "lighthouse_deck_flasher.h"++#ifdef LH_FLASH_BOOTLOADER+#include "lh_flasher.h"+#endif+++// Uncomment if you want to force the Crazyflie to reflash the FPGA binary to the deck at each startup+// #define FORCE_FLASH_FPGA true++#ifndef FORCE_FLASH_FPGA+#define FORCE_FLASH_FPGA false+#endif+++#ifndef DISABLE_LIGHTHOUSE_DRIVER+ #define DISABLE_LIGHTHOUSE_DRIVER 1+#endif+++#if DISABLE_LIGHTHOUSE_DRIVER == 1+void lighthouseDeckFlasherCheckVersionAndBoot() {+ DEBUG_PRINT("No Lighthouse support in FW, deck not initialized\n");+}+#else++#define STR2(x) #x+#define STR(x) STR2(x)++#define INCBIN(name, file) \+ __asm__(".section .rodata\n" \+ ".global incbin_" STR(name) "_start\n" \+ ".align 4\n" \+ "incbin_" STR(name) "_start:\n" \+ ".incbin \"" file "\"\n" \+ \+ ".global incbin_" STR(name) "_end\n" \+ ".align 1\n" \+ "incbin_" STR(name) "_end:\n" \+ ".byte 0\n" \+ ".align 4\n" \+ STR(name) "Size:\n" \+ ".int incbin_" STR(name) "_end - incbin_" STR(name) "_start\n" \+ ); \+ extern const __attribute__((aligned(4))) void* incbin_ ## name ## _start; \+ extern const void* incbin_ ## name ## _end; \+ extern const int name ## Size; \+ static const __attribute__((used)) unsigned char* name = (unsigned char*) & incbin_ ## name ## _start; \++INCBIN(bitstream, BLOBS_LOC"lighthouse.bin");+++void lighthouseDeckFlasherCheckVersionAndBoot() {+ lhblInit(I2C1_DEV);++ #ifdef LH_FLASH_BOOTLOADER+ // Flash deck bootloader using SPI (factory and recovery flashing)+ lhflashInit();+ lhflashFlashBootloader();+ #endif++ uint8_t bootloaderVersion = 0;+ lhblGetVersion(&bootloaderVersion);+ DEBUG_PRINT("Lighthouse bootloader version: %d\n", bootloaderVersion);++ // Wakeup mem+ lhblFlashWakeup();+ vTaskDelay(M2T(1));++ // Checking the bitstreams are identical+ // Also decoding bitstream version for console+ static char deckBitstream[65];+ lhblFlashRead(LH_FW_ADDR, 64, (uint8_t*)deckBitstream);+ deckBitstream[64] = 0;+ int deckVersion = strtol(&deckBitstream[2], NULL, 10);+ int embeddedVersion = strtol((char*)&bitstream[2], NULL, 10);++ bool identical = true;+ for (int i=0; i<=bitstreamSize; i+=64) {+ int length = ((i+64)<bitstreamSize)?64:bitstreamSize-i;+ lhblFlashRead(LH_FW_ADDR + i, length, (uint8_t*)deckBitstream);+ if (memcmp(deckBitstream, &bitstream[i], length)) {+ DEBUG_PRINT("Fail comparing firmware\n");+ identical = false;+ break;+ }+ }++ if (identical == false || FORCE_FLASH_FPGA) {+ DEBUG_PRINT("Deck has version %d and we embeed version %d\n", deckVersion, embeddedVersion);+ DEBUG_PRINT("Updating deck with embedded version!\n");++ // Erase LH deck FW+ lhblFlashEraseFirmware();++ // Flash LH deck FW+ if (lhblFlashWriteFW((uint8_t*)bitstream, bitstreamSize)) {+ DEBUG_PRINT("FW updated [OK]\n");+ deckVersion = embeddedVersion;+ } else {+ DEBUG_PRINT("FW updated [FAILED]\n");+ }+ }++ // Launch LH deck FW+ DEBUG_PRINT("Firmware version %d verified, booting deck!\n", deckVersion);+ lhblBootToFW();+}++#endifdiff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_position_est.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_position_est.cnew file mode 100644index 0000000..e006ed3--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_position_est.c@@ -0,0 +1,422 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 - 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * lighthouse_position_est.c - position estimaton for the lighthouse system+ */++#include "stabilizer_types.h"+#include "estimator.h"+#include "estimator_kalman.h"+#include "math.h"+#include "cf_math.h"++#include "log.h"+#include "param.h"+#include "statsCnt.h"+#include "mem.h"++#include "lighthouse_position_est.h"+#include "lighthouse_geometry.h"+#include "lighthouse_state.h"++// lighthouseBaseStationsGeometry has been moved to lighthouse_core.c++#define ONE_SECOND 1000+#define HALF_SECOND 500+static STATS_CNT_RATE_DEFINE(positionRate, ONE_SECOND);+static STATS_CNT_RATE_DEFINE(estBs0Rate, HALF_SECOND);+static STATS_CNT_RATE_DEFINE(estBs1Rate, HALF_SECOND);+static statsCntRateLogger_t* bsEstRates[PULSE_PROCESSOR_N_BASE_STATIONS] = {&estBs0Rate, &estBs1Rate};++// The light planes in LH2 are tilted +- 30 degrees+static const float t30 = M_PI / 6;++static void lighthousePositionGeometryDataUpdated(const int baseStation);+static void preProcessGeometryData(mat3d bsRot, mat3d bsRotInverted, mat3d lh1Rotor2Rot, mat3d lh1Rotor2RotInverted);++// Geometry memory handling for the memory module+static const uint32_t calibStartAddr = 0x1000;+static const uint32_t pageSize = 0x100;+static uint32_t handleMemGetSize(void) { return calibStartAddr + sizeof(lighthouseCoreState.bsCalibration); }+static bool handleMemRead(const uint32_t memAddr, const uint8_t readLen, uint8_t* buffer);+static bool handleMemWrite(const uint32_t memAddr, const uint8_t writeLen, const uint8_t* buffer);+static const MemoryHandlerDef_t memDef = {+ .type = MEM_TYPE_LH,+ .getSize = handleMemGetSize,+ .read = handleMemRead,+ .write = handleMemWrite,+};++void lighthousePositionEstInit() {+ for (int i = 0; i < PULSE_PROCESSOR_N_BASE_STATIONS; i++) {+ lighthousePositionGeometryDataUpdated(i);+ }+ memoryRegisterHandler(&memDef);+}++static bool handleMemRead(const uint32_t memAddr, const uint8_t readLen, uint8_t* buffer) {+ bool result = false;++ if (memAddr < calibStartAddr) {+ uint32_t index = memAddr / pageSize;+ uint32_t inPageAddr = memAddr % pageSize;+ if (index < PULSE_PROCESSOR_N_BASE_STATIONS) {+ if (inPageAddr + readLen <= sizeof(baseStationGeometry_t)) {+ uint8_t* start = (uint8_t*)&lighthouseCoreState.bsGeometry[index];+ memcpy(buffer, start + inPageAddr, readLen);++ result = true;+ }+ }+ } else {+ uint32_t calibOffsetAddr = memAddr - calibStartAddr;+ uint32_t index = calibOffsetAddr / pageSize;+ uint32_t inPageAddr = calibOffsetAddr % pageSize;+ if (index < PULSE_PROCESSOR_N_BASE_STATIONS) {+ if (inPageAddr + readLen <= sizeof(lighthouseCalibration_t)) {+ uint8_t* start = (uint8_t*)&lighthouseCoreState.bsCalibration[index];+ memcpy(buffer, start + inPageAddr, readLen);++ result = true;+ }+ }+ }++ return result;+}++static bool handleMemWrite(const uint32_t memAddr, const uint8_t writeLen, const uint8_t* buffer) {+ bool result = false;++ if (memAddr < calibStartAddr) {+ uint32_t index = memAddr / pageSize;+ uint32_t inPageAddr = memAddr % pageSize;+ if (index < PULSE_PROCESSOR_N_BASE_STATIONS) {+ if (inPageAddr + writeLen <= sizeof(baseStationGeometry_t)) {+ // Mark the geometry as invalid since this write probably only will update part of it+ // If this is the last write in this block, the valid flag will be part of the data and set appropriately+ // This is based on the assumption that the writes are done in oder with increasing addresses+ lighthouseCoreState.bsGeometry[index].valid = false;++ uint8_t* start = (uint8_t*)&lighthouseCoreState.bsGeometry[index];+ memcpy(start + inPageAddr, buffer, writeLen);++ lighthousePositionGeometryDataUpdated(index);++ result = true;+ }+ }+ } else {+ uint32_t calibOffsetAddr = memAddr - calibStartAddr;+ uint32_t index = calibOffsetAddr / pageSize;+ uint32_t inPageAddr = calibOffsetAddr % pageSize;+ if (index < PULSE_PROCESSOR_N_BASE_STATIONS) {+ if (inPageAddr + writeLen <= sizeof(lighthouseCalibration_t)) {+ uint8_t* start = (uint8_t*)&lighthouseCoreState.bsCalibration[index];+ memcpy(start + inPageAddr, buffer, writeLen);++ result = true;+ }+ }+ }++ return result;+}++static void lighthousePositionGeometryDataUpdated(const int baseStation) {+ if (lighthouseCoreState.bsGeometry[baseStation].valid) {+ baseStationGeometryCache_t* cache = &lighthouseCoreState.bsGeoCache[baseStation];+ preProcessGeometryData(lighthouseCoreState.bsGeometry[baseStation].mat, cache->baseStationInvertedRotationMatrixes, cache->lh1Rotor2RotationMatrixes, cache->lh1Rotor2InvertedRotationMatrixes);+ }+}++void lighthousePositionSetGeometryData(const uint8_t baseStation, const baseStationGeometry_t* geometry) {+ if (baseStation < PULSE_PROCESSOR_N_BASE_STATIONS) {+ lighthouseCoreState.bsGeometry[baseStation] = *geometry;+ lighthousePositionGeometryDataUpdated(baseStation);+ }+}++static void preProcessGeometryData(mat3d bsRot, mat3d bsRotInverted, mat3d lh1Rotor2Rot, mat3d lh1Rotor2RotInverted) {+ // For a rotation matrix inverse and transpose is equal. Use transpose instead+ arm_matrix_instance_f32 bsRot_ = {3, 3, (float32_t *)bsRot};+ arm_matrix_instance_f32 bsRotInverted_ = {3, 3, (float32_t *)bsRotInverted};+ mat_trans(&bsRot_, &bsRotInverted_);++ // In a LH1 system, the axis of rotation of the second rotor is perpendicular to the first rotor+ mat3d secondRotorInvertedR = {+ {1, 0, 0},+ {0, 0, -1},+ {0, 1, 0}+ };+ arm_matrix_instance_f32 secondRotorInvertedR_ = {3, 3, (float32_t *)secondRotorInvertedR};+ arm_matrix_instance_f32 lh1Rotor2Rot_ = {3, 3, (float32_t *)lh1Rotor2Rot};+ mat_mult(&bsRot_, &secondRotorInvertedR_, &lh1Rotor2Rot_);++ arm_matrix_instance_f32 lh1Rotor2RotInverted_ = {3, 3, (float32_t *)lh1Rotor2RotInverted};+ mat_trans(&lh1Rotor2Rot_, &lh1Rotor2RotInverted_);+}+++// Sensor positions on the deck+#define SENSOR_POS_W (0.015f / 2.0f)+#define SENSOR_POS_L (0.030f / 2.0f)+static vec3d sensorDeckPositions[4] = {+ {-SENSOR_POS_L, SENSOR_POS_W, 0.0},+ {-SENSOR_POS_L, -SENSOR_POS_W, 0.0},+ {SENSOR_POS_L, SENSOR_POS_W, 0.0},+ {SENSOR_POS_L, -SENSOR_POS_W, 0.0},+};+++static positionMeasurement_t ext_pos;+static float sweepStd = 0.0004;+static float sweepStdLh2 = 0.001;++static vec3d position;+static float deltaLog;++static void estimatePositionCrossingBeams(const pulseProcessor_t *state, pulseProcessorResult_t* angles, int baseStation) {+ memset(&ext_pos, 0, sizeof(ext_pos));+ int sensorsUsed = 0;+ float delta;++ // Average over all sensors with valid data+ for (size_t sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ pulseProcessorBaseStationMeasuremnt_t* bs0Measurement = &angles->sensorMeasurementsLh1[sensor].baseStatonMeasurements[0];+ pulseProcessorBaseStationMeasuremnt_t* bs1Measurement = &angles->sensorMeasurementsLh1[sensor].baseStatonMeasurements[1];++ if (bs0Measurement->validCount == PULSE_PROCESSOR_N_SWEEPS && bs1Measurement->validCount == PULSE_PROCESSOR_N_SWEEPS) {+ lighthouseGeometryGetPositionFromRayIntersection(state->bsGeometry, bs0Measurement->correctedAngles, bs1Measurement->correctedAngles, position, &delta);++ deltaLog = delta;++ ext_pos.x += position[0];+ ext_pos.y += position[1];+ ext_pos.z += position[2];+ sensorsUsed++;++ STATS_CNT_RATE_EVENT(&positionRate);+ }+ }++ ext_pos.x /= sensorsUsed;+ ext_pos.y /= sensorsUsed;+ ext_pos.z /= sensorsUsed;++ // Make sure we feed sane data into the estimator+ if (isfinite(ext_pos.pos[0]) && isfinite(ext_pos.pos[1]) && isfinite(ext_pos.pos[2])) {+ ext_pos.stdDev = 0.01;+ estimatorEnqueuePosition(&ext_pos);+ }+}++static void estimatePositionSweepsLh1(const pulseProcessor_t* appState, pulseProcessorResult_t* angles, int baseStation) {+ const lighthouseCalibration_t* bsCalib = &appState->bsCalibration[baseStation];+ sweepAngleMeasurement_t sweepInfo;+ sweepInfo.stdDev = sweepStd;+ sweepInfo.rotorPos = &appState->bsGeometry[baseStation].origin;+ sweepInfo.t = 0;+ sweepInfo.calibrationMeasurementModel = lighthouseCalibrationMeasurementModelLh1;++ for (size_t sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ pulseProcessorBaseStationMeasuremnt_t* bsMeasurement = &angles->sensorMeasurementsLh1[sensor].baseStatonMeasurements[baseStation];+ if (bsMeasurement->validCount == PULSE_PROCESSOR_N_SWEEPS) {+ sweepInfo.sensorPos = &sensorDeckPositions[sensor];++ sweepInfo.measuredSweepAngle = bsMeasurement->angles[0];+ if (sweepInfo.measuredSweepAngle != 0) {+ sweepInfo.rotorRot = &appState->bsGeometry[baseStation].mat;+ sweepInfo.rotorRotInv = &appState->bsGeoCache[baseStation].baseStationInvertedRotationMatrixes;+ sweepInfo.calib = &bsCalib->sweep[0];++ estimatorEnqueueSweepAngles(&sweepInfo);+ STATS_CNT_RATE_EVENT(bsEstRates[baseStation]);+ STATS_CNT_RATE_EVENT(&positionRate);+ }++ sweepInfo.measuredSweepAngle = bsMeasurement->angles[1];+ if (sweepInfo.measuredSweepAngle != 0) {+ sweepInfo.rotorRot = &appState->bsGeoCache[baseStation].lh1Rotor2RotationMatrixes;+ sweepInfo.rotorRotInv = &appState->bsGeoCache[baseStation].lh1Rotor2InvertedRotationMatrixes;+ sweepInfo.calib = &bsCalib->sweep[1];++ estimatorEnqueueSweepAngles(&sweepInfo);+ STATS_CNT_RATE_EVENT(bsEstRates[baseStation]);+ STATS_CNT_RATE_EVENT(&positionRate);+ }+ }+ }+}++static void estimatePositionSweepsLh2(const pulseProcessor_t* appState, pulseProcessorResult_t* angles, int baseStation) {+ const lighthouseCalibration_t* bsCalib = &appState->bsCalibration[baseStation];+ sweepAngleMeasurement_t sweepInfo;+ sweepInfo.stdDev = sweepStdLh2;+ sweepInfo.rotorPos = &appState->bsGeometry[baseStation].origin;+ sweepInfo.rotorRot = &appState->bsGeometry[baseStation].mat;+ sweepInfo.rotorRotInv = &appState->bsGeoCache[baseStation].baseStationInvertedRotationMatrixes;+ sweepInfo.calibrationMeasurementModel = lighthouseCalibrationMeasurementModelLh2;++ for (size_t sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ pulseProcessorBaseStationMeasuremnt_t* bsMeasurement = &angles->sensorMeasurementsLh2[sensor].baseStatonMeasurements[baseStation];+ if (bsMeasurement->validCount == PULSE_PROCESSOR_N_SWEEPS) {+ sweepInfo.sensorPos = &sensorDeckPositions[sensor];++ sweepInfo.measuredSweepAngle = bsMeasurement->angles[0];+ if (sweepInfo.measuredSweepAngle != 0) {+ sweepInfo.t = -t30;+ sweepInfo.calib = &bsCalib->sweep[0];+ estimatorEnqueueSweepAngles(&sweepInfo);+ STATS_CNT_RATE_EVENT(bsEstRates[baseStation]);+ STATS_CNT_RATE_EVENT(&positionRate);+ }++ sweepInfo.measuredSweepAngle = bsMeasurement->angles[1];+ if (sweepInfo.measuredSweepAngle != 0) {+ sweepInfo.t = t30;+ sweepInfo.calib = &bsCalib->sweep[1];+ estimatorEnqueueSweepAngles(&sweepInfo);+ STATS_CNT_RATE_EVENT(bsEstRates[baseStation]);+ STATS_CNT_RATE_EVENT(&positionRate);+ }+ }+ }+}++static void estimatePositionSweeps(const pulseProcessor_t* appState, pulseProcessorResult_t* angles, int baseStation) {+ switch(angles->measurementType) {+ case lighthouseBsTypeV1:+ estimatePositionSweepsLh1(appState, angles, baseStation);+ break;+ case lighthouseBsTypeV2:+ estimatePositionSweepsLh2(appState, angles, baseStation);+ break;+ default:+ // Do nothing+ break;+ }+}++static bool estimateYawDeltaOneBaseStation(const int bs, const pulseProcessorResult_t* angles, const baseStationGeometry_t baseStationGeometries[], const float cfPos[3], const float n[3], const arm_matrix_instance_f32 *RR, float *yawDelta) {+ const baseStationGeometry_t* baseStationGeometry = &baseStationGeometries[bs];++ vec3d baseStationPos;+ lighthouseGeometryGetBaseStationPosition(baseStationGeometry, baseStationPos);++ vec3d rays[PULSE_PROCESSOR_N_SENSORS];+ for (int sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ const pulseProcessorBaseStationMeasuremnt_t* bsMeasurement = &angles->sensorMeasurementsLh1[sensor].baseStatonMeasurements[bs];+ lighthouseGeometryGetRay(baseStationGeometry, bsMeasurement->correctedAngles[0], bsMeasurement->correctedAngles[1], rays[sensor]);+ }++ // Intersection points of rays and the deck+ vec3d intersectionPoints[PULSE_PROCESSOR_N_SENSORS];+ for (int sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ bool exists = lighthouseGeometryIntersectionPlaneVector(baseStationPos, rays[sensor], cfPos, n, intersectionPoints[sensor]);+ if (! exists) {+ return false;+ }+ }++ // Calculate positions of sensors. Rotate relative postiions using the rotation matrix and add current position+ vec3d sensorPoints[PULSE_PROCESSOR_N_SENSORS];+ for (int sensor = 0; sensor < PULSE_PROCESSOR_N_SENSORS; sensor++) {+ lighthouseGeometryGetSensorPosition(cfPos, RR, sensorDeckPositions[sensor], sensorPoints[sensor]);+ }++ // Calculate diagonals (sensors 0 - 3 and 1 - 2) for intersection and sensor points+ vec3d ipv1 = {intersectionPoints[3][0] - intersectionPoints[0][0], intersectionPoints[3][1] - intersectionPoints[0][1], intersectionPoints[3][2] - intersectionPoints[0][2]};+ vec3d ipv2 = {intersectionPoints[2][0] - intersectionPoints[1][0], intersectionPoints[2][1] - intersectionPoints[1][1], intersectionPoints[2][2] - intersectionPoints[1][2]};+ vec3d spv1 = {sensorPoints[3][0] - sensorPoints[0][0], sensorPoints[3][1] - sensorPoints[0][1], sensorPoints[3][2] - sensorPoints[0][2]};+ vec3d spv2 = {sensorPoints[2][0] - sensorPoints[1][0], sensorPoints[2][1] - sensorPoints[1][1], sensorPoints[2][2] - sensorPoints[1][2]};++ // Calculate yaw delta for the two diagonals and average+ float yawDelta1, yawDelta2;+ if (lighthouseGeometryYawDelta(ipv1, spv1, n, &yawDelta1) && lighthouseGeometryYawDelta(ipv2, spv2, n, &yawDelta2)) {+ *yawDelta = (yawDelta1 + yawDelta2) / 2.0f;+ return true;+ } else {+ *yawDelta = 0.0f;+ return false;+ }+}++static void estimateYaw(const pulseProcessor_t *state, pulseProcessorResult_t* angles, int baseStation) {+ // TODO Most of these calculations should be moved into the estimator instead. It is a+ // bit dirty to get the state from the kalman filer here and calculate the yaw error outside+ // the estimator, but it will do for now.++ // Get data from the current estimated state+ point_t cfPosP;+ estimatorKalmanGetEstimatedPos(&cfPosP);+ vec3d cfPos = {cfPosP.x, cfPosP.y, cfPosP.z};++ // Rotation matrix+ float R[3][3];+ estimatorKalmanGetEstimatedRot((float*)R);+ arm_matrix_instance_f32 RR = {3, 3, (float*)R};++ // Normal to the deck: (0, 0, 1), rotated using the rotation matrix+ const vec3d n = {R[0][2], R[1][2], R[2][2]};++ // Calculate yaw delta using only one base station for now+ float yawDelta;+ if (estimateYawDeltaOneBaseStation(baseStation, angles, state->bsGeometry, cfPos, n, &RR, &yawDelta)) {+ yawErrorMeasurement_t yawDeltaMeasurement = {.yawError = yawDelta, .stdDev = 0.01};+ estimatorEnqueueYawError(&yawDeltaMeasurement);+ }+}++void lighthousePositionEstimatePoseCrossingBeams(const pulseProcessor_t *state, pulseProcessorResult_t* angles, int baseStation) {+ if (state->bsGeometry[0].valid && state->bsGeometry[1].valid) {+ estimatePositionCrossingBeams(state, angles, baseStation);+ estimateYaw(state, angles, baseStation);+ }+}++void lighthousePositionEstimatePoseSweeps(const pulseProcessor_t *state, pulseProcessorResult_t* angles, int baseStation) {+ if (state->bsGeometry[baseStation].valid) {+ estimatePositionSweeps(state, angles, baseStation);+ estimateYaw(state, angles, baseStation);+ }+}+++LOG_GROUP_START(lighthouse)+STATS_CNT_RATE_LOG_ADD(posRt, &positionRate)+STATS_CNT_RATE_LOG_ADD(estBs0Rt, &estBs0Rate)+STATS_CNT_RATE_LOG_ADD(estBs1Rt, &estBs1Rate)++LOG_ADD(LOG_FLOAT, x, &position[0])+LOG_ADD(LOG_FLOAT, y, &position[1])+LOG_ADD(LOG_FLOAT, z, &position[2])++LOG_ADD(LOG_FLOAT, delta, &deltaLog)+LOG_GROUP_STOP(lighthouse)++PARAM_GROUP_START(lighthouse)+PARAM_ADD(PARAM_FLOAT, sweepStd, &sweepStd)+PARAM_ADD(PARAM_FLOAT, sweepStd2, &sweepStdLh2)+PARAM_GROUP_STOP(lighthouse)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_state.h b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_state.hnew file mode 100644index 0000000..2f9a69b--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/lighthouse/lighthouse_state.h@@ -0,0 +1,32 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2019 - 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * lighthouse_state.h - storage for basestation state struct+ */++#pragma once++#include "pulse_processor.h"++extern pulseProcessor_t lighthouseCoreState;diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/log.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/log.cnew file mode 100644index 0000000..cf6b258--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/log.c@@ -0,0 +1,1078 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012-2019 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * log.c: Dynamic log system+ */++/* The TOC logic is mainly based on param.c+ * FIXME: See if we can factorise the TOC code */++#include <string.h>+#include <errno.h>+#include <stdint.h>+#include <stdbool.h>++/* FreeRtos includes */+#include "FreeRTOS.h"+#include "task.h"+#include "timers.h"+#include "semphr.h"++#include "config.h"+#include "crtp.h"+#include "log.h"+#include "crc.h"+#include "worker.h"+#include "num.h"++#include "console.h"+#include "cfassert.h"+#define DEBUG_MODULE "LOG"+#include "debug_cf.h"+#include "stm32_legacy.h"+#include "static_mem.h"++#if 0+#define LOG_DEBUG(fmt, ...) DEBUG_PRINTD("D/log " fmt, ## __VA_ARGS__)+#define LOG_ERROR(fmt, ...) DEBUG_PRINTD("E/log " fmt, ## __VA_ARGS__)+#else+#define LOG_DEBUG(...)+#define LOG_ERROR(...)+#endif+++static const uint8_t typeLength[] = {+ [LOG_UINT8] = 1,+ [LOG_UINT16] = 2,+ [LOG_UINT32] = 4,+ [LOG_INT8] = 1,+ [LOG_INT16] = 2,+ [LOG_INT32] = 4,+ [LOG_FLOAT] = 4,+ [LOG_FP16] = 2,+};++#define TYPE_MASK (0x0f)++typedef enum {+ acqType_memory = 0,+ acqType_function = 1,+} acquisitionType_t;++// Maximum log payload length (4 bytes are used for block id and timestamp)+#define LOG_MAX_LEN 26++/* Log packet parameters storage */+#define LOG_MAX_OPS 128+#define LOG_MAX_BLOCKS 16+struct log_ops {+ struct log_ops * next;+ uint8_t storageType : 4;+ uint8_t logType : 4;+ void * variable;+ acquisitionType_t acquisitionType;+};++struct log_block {+ int id;+ xTimerHandle timer;+ StaticTimer_t timerBuffer;+ struct log_ops * ops;+};++NO_DMA_CCM_SAFE_ZERO_INIT static struct log_ops logOps[LOG_MAX_OPS];+NO_DMA_CCM_SAFE_ZERO_INIT static struct log_block logBlocks[LOG_MAX_BLOCKS];+static xSemaphoreHandle logLock;+static StaticSemaphore_t logLockBuffer;++struct ops_setting {+ uint8_t logType;+ uint8_t id;+} __attribute__((packed));++struct ops_setting_v2 {+ uint8_t logType;+ uint16_t id;+} __attribute__((packed));+++#define TOC_CH 0+#define CONTROL_CH 1+#define LOG_CH 2++#define CMD_GET_ITEM 0 // original version: up to 255 entries+#define CMD_GET_INFO 1 // original version: up to 255 entries+#define CMD_GET_ITEM_V2 2 // version 2: up to 16k entries+#define CMD_GET_INFO_V2 3 // version 2: up to 16k entries++#define CONTROL_CREATE_BLOCK 0+#define CONTROL_APPEND_BLOCK 1+#define CONTROL_DELETE_BLOCK 2+#define CONTROL_START_BLOCK 3+#define CONTROL_STOP_BLOCK 4+#define CONTROL_RESET 5+#define CONTROL_CREATE_BLOCK_V2 6+#define CONTROL_APPEND_BLOCK_V2 7++#define BLOCK_ID_FREE -1++//Private functions+static void logTask(void * prm);+static void logTOCProcess(int command);+static void logControlProcess(void);++void logRunBlock(void * arg);+void logBlockTimed(xTimerHandle timer);++//These are set by the Linker+extern struct log_s _log_start;+extern struct log_s _log_end;++//Pointer to the logeters list and length of it+static struct log_s * logs;+static int logsLen;+static uint32_t logsCrc;+static uint16_t logsCount = 0;++static CRTPPacket p;++static bool isInit = false;++/* Log management functions */+static int logAppendBlock(int id, struct ops_setting * settings, int len);+static int logAppendBlockV2(int id, struct ops_setting_v2 * settings, int len);+static int logCreateBlock(unsigned char id, struct ops_setting * settings, int len);+static int logCreateBlockV2(unsigned char id, struct ops_setting_v2 * settings, int len);+static int logDeleteBlock(int id);+static int logStartBlock(int id, unsigned int period);+static int logStopBlock(int id);+static void logReset();+static acquisitionType_t acquisitionTypeFromLogType(uint8_t logType);++STATIC_MEM_TASK_ALLOC_STACK_NO_DMA_CCM_SAFE(logTask, LOG_TASK_STACKSIZE);++void logInit(void)+{+ int i;+ const char* group = NULL;+ int groupLength = 0;++ if(isInit)+ return;++ logs = &_log_start;+ logsLen = &_log_end - &_log_start;++ // Calculate a hash of the toc by chaining description of each elements+ // Using the CRTP packet as temporary buffer+ logsCrc = 0;+ for (int i=0; i<logsLen; i++)+ {+ int len = 5;+ memcpy(&p.data[0], &logsCrc, 4);+ p.data[4] = logs[i].type;+ if (logs[i].type & LOG_GROUP) {+ if (logs[i].type & LOG_START) {+ group = logs[i].name;+ groupLength = strlen(group);+ }+ } else {+ // CMD_GET_ITEM_V2 result's size is: 3 + strlen(logs[i].name) + groupLength + 2+ if (strlen(logs[i].name) + groupLength + 2 > 26) {+ LOG_ERROR("'%s.%s' too long\n", group, logs[i].name);+ ASSERT_FAILED();+ }+ }+ if (logs[i].name) {+ memcpy(&p.data[5], logs[i].name, strlen(logs[i].name));+ len += strlen(logs[i].name);+ }+ logsCrc = crcSlow(p.data, len);+ }++ // Big lock that protects the log datastructures+ logLock = xSemaphoreCreateMutexStatic(&logLockBuffer);++ for (i=0; i<logsLen; i++)+ {+ if(!(logs[i].type & LOG_GROUP))+ logsCount++;+ }++ //Manually free all log blocks+ for(i=0; i<LOG_MAX_BLOCKS; i++)+ logBlocks[i].id = BLOCK_ID_FREE;++ //Init data structures and set the log subsystem in a known state+ logReset();++ //Start the log task+ STATIC_MEM_TASK_CREATE(logTask, logTask, LOG_TASK_NAME, NULL, LOG_TASK_PRI);++ isInit = true;+}++bool logTest(void)+{+ return isInit;+}++void logTask(void * prm)+{+ crtpInitTaskQueue(CRTP_PORT_LOG);++ while(1) {+ crtpReceivePacketBlock(CRTP_PORT_LOG, &p);++ xSemaphoreTake(logLock, portMAX_DELAY);+ if (p.channel==TOC_CH)+ logTOCProcess(p.data[0]);+ if (p.channel==CONTROL_CH)+ logControlProcess();+ xSemaphoreGive(logLock);+ }+}++void logTOCProcess(int command)+{+ int ptr = 0;+ char * group = "plop";+ uint16_t n=0;+ uint16_t logId=0;++ switch (command)+ {+ case CMD_GET_INFO: //Get info packet about the log implementation+ DEBUG_PRINT("Client uses old logging API!\n");+ LOG_DEBUG("Packet is TOC_GET_INFO\n");+ ptr = 0;+ group = "";+ p.header=CRTP_HEADER(CRTP_PORT_LOG, TOC_CH);+ p.size=8;+ p.data[0]=CMD_GET_INFO;+ if (logsCount < 255) {+ p.data[1]=logsCount;+ } else {+ p.data[1]=255;+ }+ memcpy(&p.data[2], &logsCrc, 4);+ p.data[6]=LOG_MAX_BLOCKS;+ p.data[7]=LOG_MAX_OPS;+ crtpSendPacket(&p);+ break;+ case CMD_GET_ITEM: //Get log variable+ LOG_DEBUG("Packet is TOC_GET_ITEM Id: %d\n", p.data[1]);+ for (ptr=0; ptr<logsLen; ptr++) //Ptr points a group+ {+ if (logs[ptr].type & LOG_GROUP)+ {+ if (logs[ptr].type & LOG_START)+ group = logs[ptr].name;+ else+ group = "";+ }+ else //Ptr points a variable+ {+ if (n==p.data[1])+ break;+ n++;+ }+ }++ if (ptr<logsLen)+ {+ LOG_DEBUG(" Item is \"%s\":\"%s\"\n", group, logs[ptr].name);+ p.header=CRTP_HEADER(CRTP_PORT_LOG, TOC_CH);+ p.data[0]=CMD_GET_ITEM;+ p.data[1]=n;+ p.data[2]=logs[ptr].type & TYPE_MASK;+ p.size=3+2+strlen(group)+strlen(logs[ptr].name);+ ASSERT(p.size <= CRTP_MAX_DATA_SIZE); // Too long! The name of the group or the parameter may be too long.+ memcpy(p.data+3, group, strlen(group)+1);+ memcpy(p.data+3+strlen(group)+1, logs[ptr].name, strlen(logs[ptr].name)+1);+ crtpSendPacket(&p);+ } else {+ LOG_DEBUG(" Index out of range!");+ p.header=CRTP_HEADER(CRTP_PORT_LOG, TOC_CH);+ p.data[0]=CMD_GET_ITEM;+ p.size=1;+ crtpSendPacket(&p);+ }+ break;+ case CMD_GET_INFO_V2: //Get info packet about the log implementation+ LOG_DEBUG("Packet is TOC_GET_INFO\n");+ ptr = 0;+ group = "";+ p.header=CRTP_HEADER(CRTP_PORT_LOG, TOC_CH);+ p.size=9;+ p.data[0]=CMD_GET_INFO_V2;+ memcpy(&p.data[1], &logsCount, 2);+ memcpy(&p.data[3], &logsCrc, 4);+ p.data[7]=LOG_MAX_BLOCKS;+ p.data[8]=LOG_MAX_OPS;+ crtpSendPacket(&p);+ break;+ case CMD_GET_ITEM_V2: //Get log variable+ memcpy(&logId, &p.data[1], 2);+ LOG_DEBUG("Packet is TOC_GET_ITEM Id: %d\n", logId);+ for (ptr=0; ptr<logsLen; ptr++) //Ptr points a group+ {+ if (logs[ptr].type & LOG_GROUP)+ {+ if (logs[ptr].type & LOG_START)+ group = logs[ptr].name;+ else+ group = "";+ }+ else //Ptr points a variable+ {+ if (n==logId)+ break;+ n++;+ }+ }++ if (ptr<logsLen)+ {+ LOG_DEBUG(" Item is \"%s\":\"%s\"\n", group, logs[ptr].name);+ p.header=CRTP_HEADER(CRTP_PORT_LOG, TOC_CH);+ p.data[0]=CMD_GET_ITEM_V2;+ memcpy(&p.data[1], &logId, 2);+ p.data[3]=logs[ptr].type & TYPE_MASK;+ p.size=4+2+strlen(group)+strlen(logs[ptr].name);+ ASSERT(p.size <= CRTP_MAX_DATA_SIZE); // Too long! The name of the group or the parameter may be too long.+ memcpy(p.data+4, group, strlen(group)+1);+ memcpy(p.data+4+strlen(group)+1, logs[ptr].name, strlen(logs[ptr].name)+1);+ crtpSendPacket(&p);+ } else {+ LOG_DEBUG(" Index out of range!");+ p.header=CRTP_HEADER(CRTP_PORT_LOG, TOC_CH);+ p.data[0]=CMD_GET_ITEM_V2;+ p.size=1;+ crtpSendPacket(&p);+ }+ break;+ }+}++void logControlProcess()+{+ int ret = ENOEXEC;++ switch(p.data[0])+ {+ case CONTROL_CREATE_BLOCK:+ ret = logCreateBlock( p.data[1],+ (struct ops_setting*)&p.data[2],+ (p.size-2)/sizeof(struct ops_setting) );+ break;+ case CONTROL_APPEND_BLOCK:+ ret = logAppendBlock( p.data[1],+ (struct ops_setting*)&p.data[2],+ (p.size-2)/sizeof(struct ops_setting) );+ break;+ case CONTROL_DELETE_BLOCK:+ ret = logDeleteBlock( p.data[1] );+ break;+ case CONTROL_START_BLOCK:+ ret = logStartBlock( p.data[1], p.data[2]*10);+ break;+ case CONTROL_STOP_BLOCK:+ ret = logStopBlock( p.data[1] );+ break;+ case CONTROL_RESET:+ logReset();+ ret = 0;+ break;+ case CONTROL_CREATE_BLOCK_V2:+ ret = logCreateBlockV2( p.data[1],+ (struct ops_setting_v2*)&p.data[2],+ (p.size-2)/sizeof(struct ops_setting_v2) );+ break;+ case CONTROL_APPEND_BLOCK_V2:+ ret = logAppendBlockV2( p.data[1],+ (struct ops_setting_v2*)&p.data[2],+ (p.size-2)/sizeof(struct ops_setting_v2) );+ break;+ }++ //Commands answer+ p.data[2] = ret;+ p.size = 3;+ crtpSendPacket(&p);+}++static int logCreateBlock(unsigned char id, struct ops_setting * settings, int len)+{+ int i;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (id == logBlocks[i].id) return EEXIST;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == BLOCK_ID_FREE) break;++ if (i == LOG_MAX_BLOCKS)+ return ENOMEM;++ logBlocks[i].id = id;+ logBlocks[i].timer = xTimerCreateStatic("logTimer", M2T(1000), pdTRUE,+ &logBlocks[i], logBlockTimed, &logBlocks[i].timerBuffer);+ logBlocks[i].ops = NULL;++ if (logBlocks[i].timer == NULL)+ {+ logBlocks[i].id = BLOCK_ID_FREE;+ return ENOMEM;+ }++ LOG_DEBUG("Added block ID %d\n", id);++ return logAppendBlock(id, settings, len);+}++static int logCreateBlockV2(unsigned char id, struct ops_setting_v2 * settings, int len)+{+ int i;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (id == logBlocks[i].id) return EEXIST;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == BLOCK_ID_FREE) break;++ if (i == LOG_MAX_BLOCKS)+ return ENOMEM;++ logBlocks[i].id = id;+ logBlocks[i].timer = xTimerCreateStatic("logTimer", M2T(1000), pdTRUE,+ &logBlocks[i], logBlockTimed, &logBlocks[i].timerBuffer);+ logBlocks[i].ops = NULL;++ if (logBlocks[i].timer == NULL)+ {+ logBlocks[i].id = BLOCK_ID_FREE;+ return ENOMEM;+ }++ LOG_DEBUG("Added block ID %d\n", id);++ return logAppendBlockV2(id, settings, len);+}++static int blockCalcLength(struct log_block * block);+static struct log_ops * opsMalloc();+static void opsFree(struct log_ops * ops);+static void blockAppendOps(struct log_block * block, struct log_ops * ops);+static int variableGetIndex(int id);++static int logAppendBlock(int id, struct ops_setting * settings, int len)+{+ int i;+ struct log_block * block;++ LOG_DEBUG("Appending %d variable to block %d\n", len, id);++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == id) break;++ if (i >= LOG_MAX_BLOCKS) {+ LOG_ERROR("Trying to append block id %d that doesn't exist.", id);+ return ENOENT;+ }++ block = &logBlocks[i];++ for (i=0; i<len; i++)+ {+ int currentLength = blockCalcLength(block);+ struct log_ops * ops;+ int varId;++ if ((currentLength + typeLength[settings[i].logType & TYPE_MASK])>LOG_MAX_LEN) {+ LOG_ERROR("Trying to append a full block. Block id %d.\n", id);+ return E2BIG;+ }++ ops = opsMalloc();++ if(!ops) {+ LOG_ERROR("No more ops memory free!\n");+ return ENOMEM;+ }++ if (settings[i].id != 255) //TOC variable+ {+ varId = variableGetIndex(settings[i].id);++ if (varId<0) {+ LOG_ERROR("Trying to add variable Id %d that does not exists.", settings[i].id);+ return ENOENT;+ }++ ops->variable = logs[varId].address;+ ops->storageType = logs[varId].type & TYPE_MASK;+ ops->logType = settings[i].logType & TYPE_MASK;+ ops->acquisitionType = acquisitionTypeFromLogType(logs[varId].type);++ LOG_DEBUG("Appended variable %d to block %d\n", settings[i].id, id);+ } else { //Memory variable+ //TODO: Check that the address is in ram+ ops->variable = (void*)(&settings[i]+1);+ ops->storageType = (settings[i].logType>>4) & TYPE_MASK;+ ops->logType = settings[i].logType & TYPE_MASK;+ ops->acquisitionType = acqType_memory;+ i += 2;++ LOG_DEBUG("Appended var addr 0x%x to block %d\n", (int)ops->variable, id);+ }+ blockAppendOps(block, ops);++ LOG_DEBUG(" Now lenght %d\n", blockCalcLength(block));+ }++ return 0;+}++static int logAppendBlockV2(int id, struct ops_setting_v2 * settings, int len)+{+ int i;+ struct log_block * block;++ LOG_DEBUG("Appending %d variable to block %d\n", len, id);++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == id) break;++ if (i >= LOG_MAX_BLOCKS) {+ LOG_ERROR("Trying to append block id %d that doesn't exist.", id);+ return ENOENT;+ }++ block = &logBlocks[i];++ for (i=0; i<len; i++)+ {+ int currentLength = blockCalcLength(block);+ struct log_ops * ops;+ int varId;++ if ((currentLength + typeLength[settings[i].logType & TYPE_MASK])>LOG_MAX_LEN) {+ LOG_ERROR("Trying to append a full block. Block id %d.\n", id);+ return E2BIG;+ }++ ops = opsMalloc();++ if(!ops) {+ LOG_ERROR("No more ops memory free!\n");+ return ENOMEM;+ }++ if (settings[i].id != 0xFFFFul) //TOC variable+ {+ varId = variableGetIndex(settings[i].id);++ if (varId<0) {+ LOG_ERROR("Trying to add variable Id %d that does not exists.", settings[i].id);+ return ENOENT;+ }++ ops->variable = logs[varId].address;+ ops->storageType = logs[varId].type & TYPE_MASK;+ ops->logType = settings[i].logType & TYPE_MASK;+ ops->acquisitionType = acquisitionTypeFromLogType(logs[varId].type);++ LOG_DEBUG("Appended variable %d to block %d\n", settings[i].id, id);+ } else { //Memory variable+ //TODO: Check that the address is in ram+ ops->variable = (void*)(&settings[i]+1);+ ops->storageType = (settings[i].logType>>4) & TYPE_MASK;+ ops->logType = settings[i].logType & TYPE_MASK;+ ops->acquisitionType = acqType_memory;+ i += 2;++ LOG_DEBUG("Appended var addr 0x%x to block %d\n", (int)ops->variable, id);+ }+ blockAppendOps(block, ops);++ LOG_DEBUG(" Now lenght %d\n", blockCalcLength(block));+ }++ return 0;+}++static int logDeleteBlock(int id)+{+ int i;+ struct log_ops * ops;+ struct log_ops * opsNext;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == id) break;++ if (i >= LOG_MAX_BLOCKS) {+ LOG_ERROR("trying to delete block id %d that doesn't exist.", id);+ return ENOENT;+ }++ ops = logBlocks[i].ops;+ while (ops)+ {+ opsNext = ops->next;+ opsFree(ops);+ ops = opsNext;+ }++ if (logBlocks[i].timer != 0) {+ xTimerStop(logBlocks[i].timer, portMAX_DELAY);+ xTimerDelete(logBlocks[i].timer, portMAX_DELAY);+ logBlocks[i].timer = 0;+ }++ logBlocks[i].id = BLOCK_ID_FREE;+ return 0;+}++static int logStartBlock(int id, unsigned int period)+{+ int i;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == id) break;++ if (i >= LOG_MAX_BLOCKS) {+ LOG_ERROR("Trying to start block id %d that doesn't exist.", id);+ return ENOENT;+ }++ LOG_DEBUG("Starting block %d with period %dms\n", id, period);++ if (period>0)+ {+ xTimerChangePeriod(logBlocks[i].timer, M2T(period), 100);+ xTimerStart(logBlocks[i].timer, 100);+ } else {+ // single-shoot run+ workerSchedule(logRunBlock, &logBlocks[i]);+ }++ return 0;+}++static int logStopBlock(int id)+{+ int i;++ for (i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id == id) break;++ if (i >= LOG_MAX_BLOCKS) {+ LOG_ERROR("Trying to stop block id %d that doesn't exist.\n", id);+ return ENOENT;+ }++ xTimerStop(logBlocks[i].timer, portMAX_DELAY);++ return 0;+}++/* This function is called by the timer subsystem */+void logBlockTimed(xTimerHandle timer)+{+ workerSchedule(logRunBlock, pvTimerGetTimerID(timer));+}++/* Appends data to a packet if space is available; returns false on failure. */+static bool appendToPacket(CRTPPacket * pk, const void * data, size_t n) {+ if (pk->size <= CRTP_MAX_DATA_SIZE - n)+ {+ memcpy(&pk->data[pk->size], data, n);+ pk->size += n;+ return true;+ }+ else return false;+}++/* This function is usually called by the worker subsystem */+void logRunBlock(void * arg)+{+ struct log_block *blk = arg;+ struct log_ops *ops = blk->ops;+ static CRTPPacket pk;+ unsigned int timestamp;++ xSemaphoreTake(logLock, portMAX_DELAY);++ timestamp = ((long long)xTaskGetTickCount())/portTICK_RATE_MS;++ pk.header = CRTP_HEADER(CRTP_PORT_LOG, LOG_CH);+ pk.size = 4;+ pk.data[0] = blk->id;+ pk.data[1] = timestamp&0x0ff;+ pk.data[2] = (timestamp>>8)&0x0ff;+ pk.data[3] = (timestamp>>16)&0x0ff;++ while (ops)+ {+ int valuei = 0;+ float valuef = 0;++ // FPU instructions must run on aligned data.+ // We first copy the data to an (aligned) local variable, before assigning it+ switch(ops->storageType)+ {+ case LOG_UINT8:+ {+ uint8_t v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->acquireUInt8(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(v));+ }+ valuei = v;+ break;+ }+ case LOG_INT8:+ {+ int8_t v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->acquireInt8(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(v));+ }+ valuei = v;+ break;+ }+ case LOG_UINT16:+ {+ uint16_t v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->acquireUInt16(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(v));+ }+ valuei = v;+ break;+ }+ case LOG_INT16:+ {+ int16_t v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->acquireInt16(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(v));+ }+ valuei = v;+ break;+ }+ case LOG_UINT32:+ {+ uint32_t v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->acquireUInt32(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(v));+ }+ valuei = v;+ break;+ }+ case LOG_INT32:+ {+ int32_t v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->acquireInt32(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(v));+ }+ valuei = v;+ break;+ }+ case LOG_FLOAT:+ {+ float v;+ if (ops->acquisitionType == acqType_function) {+ logByFunction_t* logByFunction = (logByFunction_t*)ops->variable;+ v = logByFunction->aquireFloat(timestamp, logByFunction->data);+ } else {+ memcpy(&v, ops->variable, sizeof(valuef));+ }+ valuei = v;+ valuef = v;+ break;+ }+ }++ if (ops->logType == LOG_FLOAT || ops->logType == LOG_FP16)+ {+ if (ops->storageType != LOG_FLOAT)+ {+ valuef = valuei;+ }++ // Try to append the next item to the packet. If we run out of space,+ // drop this and subsequent items.+ if (ops->logType == LOG_FLOAT)+ {+ if (!appendToPacket(&pk, &valuef, 4)) break;+ }+ else+ {+ valuei = single2half(valuef);+ if (!appendToPacket(&pk, &valuei, 2)) break;+ }+ }+ else //logType is an integer+ {+ if (!appendToPacket(&pk, &valuei, typeLength[ops->logType])) break;+ }++ ops = ops->next;+ }++ xSemaphoreGive(logLock);++ // Check if the connection is still up, oherwise disable+ // all the logging and flush all the CRTP queues.+ if (!crtpIsConnected())+ {+ logReset();+ crtpReset();+ }+ else+ {+ crtpSendPacket(&pk);+ }+}++static int variableGetIndex(int id)+{+ int i;+ int n=0;++ for (i=0; i<logsLen; i++)+ {+ if(!(logs[i].type & LOG_GROUP))+ {+ if(n==id)+ break;+ n++;+ }+ }++ if (i>=logsLen)+ return -1;++ return i;+}++static struct log_ops * opsMalloc()+{+ int i;++ for (i=0;i<LOG_MAX_OPS; i++)+ if (logOps[i].variable == NULL) break;++ if (i >= LOG_MAX_OPS)+ return NULL;++ return &logOps[i];+}++static void opsFree(struct log_ops * ops)+{+ ops->variable = NULL;+}++static int blockCalcLength(struct log_block * block)+{+ struct log_ops * ops;+ int len = 0;++ for (ops = block->ops; ops; ops = ops->next)+ len += typeLength[ops->logType];++ return len;+}++void blockAppendOps(struct log_block * block, struct log_ops * ops)+{+ struct log_ops * o;++ ops->next = NULL;++ if (block->ops == NULL)+ block->ops = ops;+ else+ {+ for (o = block->ops; o->next; o = o->next);++ o->next = ops;+ }+}++static void logReset(void)+{+ int i;++ if (isInit)+ {+ //Stop and delete all started log blocks+ for(i=0; i<LOG_MAX_BLOCKS; i++)+ if (logBlocks[i].id != -1)+ {+ logStopBlock(logBlocks[i].id);+ logDeleteBlock(logBlocks[i].id);+ }+ }++ //Force free all the log block objects+ for(i=0; i<LOG_MAX_BLOCKS; i++)+ logBlocks[i].id = BLOCK_ID_FREE;++ //Force free the log ops+ for (i=0; i<LOG_MAX_OPS; i++)+ logOps[i].variable = NULL;+}++/* Public API to access log TOC from within the copter */+static logVarId_t invalidVarId = 0xffffu;++logVarId_t logGetVarId(char* group, char* name)+{+ int i;+ logVarId_t varId = invalidVarId;+ char * currgroup = "";++ for(i=0; i<logsLen; i++)+ {+ if (logs[i].type & LOG_GROUP) {+ if (logs[i].type & LOG_START)+ currgroup = logs[i].name;+ } if ((!strcmp(group, currgroup)) && (!strcmp(name, logs[i].name))) {+ varId = (logVarId_t)i;+ return varId;+ }+ }++ return invalidVarId;+}++int logGetType(logVarId_t varid)+{+ return logs[varid].type;+}++void logGetGroupAndName(logVarId_t varid, char** group, char** name)+{+ char * currgroup = "";+ *group = 0;+ *name = 0;++ for(int i=0; i<logsLen; i++) {+ if (logs[i].type & LOG_GROUP) {+ if (logs[i].type & LOG_START) {+ currgroup = logs[i].name;+ }+ }++ if (i == varid) {+ *group = currgroup;+ *name = logs[i].name;+ break;+ }+ }+}++void* logGetAddress(logVarId_t varid)+{+ return logs[varid].address;+}++uint8_t logVarSize(int type)+{+ return typeLength[type];+}++int logGetInt(logVarId_t varid)+{+ int valuei = 0;++ ASSERT(LOG_VARID_IS_VALID(varid));++ switch(logs[varid].type)+ {+ case LOG_UINT8:+ valuei = *(uint8_t *)logs[varid].address;+ break;+ case LOG_INT8:+ valuei = *(int8_t *)logs[varid].address;+ break;+ case LOG_UINT16:+ valuei = *(uint16_t *)logs[varid].address;+ break;+ case LOG_INT16:+ valuei = *(int16_t *)logs[varid].address;+ break;+ case LOG_UINT32:+ valuei = *(uint32_t *)logs[varid].address;+ break;+ case LOG_INT32:+ valuei = *(int32_t *)logs[varid].address;+ break;+ case LOG_FLOAT:+ valuei = *(float *)logs[varid].address;+ break;+ }++ return valuei;+}++float logGetFloat(logVarId_t varid)+{+ ASSERT(LOG_VARID_IS_VALID(varid));++ if (logs[varid].type == LOG_FLOAT)+ return *(float *)logs[varid].address;++ return logGetInt(varid);+}++unsigned int logGetUint(logVarId_t varid)+{+ return (unsigned int)logGetInt(varid);+}++static acquisitionType_t acquisitionTypeFromLogType(uint8_t logType) {+ if (logType & LOG_BY_FUNCTION) {+ return acqType_function;+ }++ return acqType_memory;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/mem.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/mem.cnew file mode 100644index 0000000..79f0be0--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/mem.c@@ -0,0 +1,361 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012-2019 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * mem.c: Memory module. Handles one-wire, eeprom and other memory mapping memory functions over crtp link.+ */++#include <errno.h>+#include <stdint.h>+#include <stdbool.h>+#include <string.h>+#include <inttypes.h>+/* FreeRtos includes */+#include "FreeRTOS.h"+#include "task.h"+#include "semphr.h"++#include "mem.h"+#include "crtp.h"+#include "system.h"++#include "console.h"+#include "assert.h"+#define DEBUG_MODULE "MEM_CF2"+#include "debug_cf.h"++#include "log.h"+#include "param.h"+#include "static_mem.h"++#if 0+#define MEM_DEBUG(fmt, ...) DEBUG_PRINT("D/log " fmt, ## __VA_ARGS__)+#define MEM_ERROR(fmt, ...) DEBUG_PRINT("E/log " fmt, ## __VA_ARGS__)+#else+#define MEM_DEBUG(...)+#define MEM_ERROR(...)+#endif+++// Maximum payload length+#define MEM_MAX_LEN 30++#define MEM_SETTINGS_CH 0+#define MEM_READ_CH 1+#define MEM_WRITE_CH 2++#define MEM_CMD_GET_NBR 1+#define MEM_CMD_GET_INFO 2++#define STATUS_OK 0++#define MEM_TESTER_SIZE 0x1000++//Private functions+static void memTask(void * prm);+static void memSettingsProcess(CRTPPacket* p);+static void memWriteProcess(CRTPPacket* p);+static void memReadProcess(CRTPPacket* p);+static void createNbrResponse(CRTPPacket* p);+static void createInfoResponse(CRTPPacket* p, uint8_t memId);+static void createInfoResponseBody(CRTPPacket* p, uint8_t type, uint32_t memSize, const uint8_t data[8]);++static uint32_t handleMemTesterGetSize(void) { return MEM_TESTER_SIZE; }+static bool handleMemTesterRead(const uint32_t memAddr, const uint8_t readLen, uint8_t* buffer);+static bool handleMemTesterWrite(const uint32_t memAddr, const uint8_t writeLen, const uint8_t* startOfData);+static uint32_t memTesterWriteErrorCount = 0;+static uint8_t memTesterWriteReset = 0;+static const MemoryHandlerDef_t memTesterDef = {+ .type = MEM_TYPE_TESTER,+ .getSize = handleMemTesterGetSize,+ .read = handleMemTesterRead,+ .write = handleMemTesterWrite,+};++static bool isInit = false;+static bool registrationEnabled = true;++static uint8_t nbrOwMems = 0;+static const uint8_t NoSerialNr[MEMORY_SERIAL_LENGTH] = {0, 0, 0, 0, 0, 0, 0, 0};+static CRTPPacket packet;++#define MAX_NR_HANDLERS 20+static const MemoryHandlerDef_t* handlers[MAX_NR_HANDLERS];+static uint8_t nrOfHandlers = 0;+static const MemoryOwHandlerDef_t* owMemHandler = 0;++STATIC_MEM_TASK_ALLOC(memTask, MEM_TASK_STACKSIZE);++void memInit(void)+{+ if(isInit) {+ return;+ }++ memoryRegisterHandler(&memTesterDef);++ //Start the mem task+ STATIC_MEM_TASK_CREATE(memTask, memTask, MEM_TASK_NAME, NULL, MEM_TASK_PRI);++ isInit = true;+}++bool memTest(void) {+ if (!isInit) {+ return false;+ }++ if (owMemHandler == 0) {+ return false;+ }++ return true;+}++void memoryRegisterHandler(const MemoryHandlerDef_t* handlerDef){+ for (int i = 0; i < nrOfHandlers; i++) {+ ASSERT(handlerDef->type != handlers[i]->type);+ }+ ASSERT(nrOfHandlers < MAX_NR_HANDLERS);+ ASSERT(registrationEnabled);+ handlers[nrOfHandlers] = handlerDef;+ nrOfHandlers++;+}++void memoryRegisterOwHandler(const MemoryOwHandlerDef_t* handlerDef){+ ASSERT(owMemHandler == 0);+ owMemHandler = handlerDef;++ nbrOwMems = handlerDef->nrOfMems;+}++static void memTask(void* param) {+ crtpInitTaskQueue(CRTP_PORT_MEM);++ systemWaitStart();++ // Do not allow registration of new handlers after this point as clients now can start+ // to query for available memories+ registrationEnabled = false;++ while(1) {+ crtpReceivePacketBlock(CRTP_PORT_MEM, &packet);++ switch (packet.channel) {+ case MEM_SETTINGS_CH:+ memSettingsProcess(&packet);+ break;+ case MEM_READ_CH:+ memReadProcess(&packet);+ break;+ case MEM_WRITE_CH:+ memWriteProcess(&packet);+ break;+ default:+ // Do nothing+ break;+ }+ }+}++static void memSettingsProcess(CRTPPacket* p) {+ switch (p->data[0]) {+ case MEM_CMD_GET_NBR:+ createNbrResponse(p);+ crtpSendPacket(p);+ break;++ case MEM_CMD_GET_INFO:+ {+ uint8_t memId = p->data[1];+ createInfoResponse(p, memId);+ crtpSendPacket(p);+ }+ break;++ default:+ // Do nothing+ break;+ }+}++static void createNbrResponse(CRTPPacket* p) {+ p->header = CRTP_HEADER(CRTP_PORT_MEM, MEM_SETTINGS_CH);+ p->size = 2;+ p->data[0] = MEM_CMD_GET_NBR;+ p->data[1] = 0;//nbrOwMems + OW_FIRST_ID;+}++static void createInfoResponse(CRTPPacket* p, uint8_t memId) {+ p->header = CRTP_HEADER(CRTP_PORT_MEM, MEM_SETTINGS_CH);+ p->size = 2;+ p->data[0] = MEM_CMD_GET_INFO;+ p->data[1] = memId;++ if (memId < nrOfHandlers) {+ createInfoResponseBody(p, handlers[memId]->type, handlers[memId]->getSize(), NoSerialNr);+ } else {+ const uint8_t selectedMem = memId - nrOfHandlers;+ uint8_t serialNr[MEMORY_SERIAL_LENGTH];++ // No error code if we fail, just send an empty packet back+ if (owMemHandler->getSerialNr(selectedMem, serialNr)) {+ createInfoResponseBody(p, MEM_TYPE_OW, owMemHandler->size, serialNr);+ }+ }+}++static void createInfoResponseBody(CRTPPacket* p, uint8_t type, uint32_t memSize, const uint8_t data[8]) {+ p->data[2] = type;+ p->size += 1;++ memcpy(&p->data[3], &memSize, 4);+ p->size += 4;++ memcpy(&p->data[7], data, 8);+ p->size += 8;+}+++static void memReadProcess(CRTPPacket* p) {+ uint32_t memAddr;+ bool result = false;++ MEM_DEBUG("Packet is MEM READ\n");+ p->header = CRTP_HEADER(CRTP_PORT_MEM, MEM_READ_CH);++ uint8_t memId = p->data[0];+ memcpy(&memAddr, &p->data[1], 4);+ uint8_t readLen = p->data[5];+ uint8_t* startOfData = &p->data[6];++ if (memId < nrOfHandlers) {+ if (handlers[memId]->read) {+ result = handlers[memId]->read(memAddr, readLen, startOfData);+ }+ } else {+ uint8_t selectedMem = memId - nrOfHandlers;+ result = owMemHandler->read(selectedMem, memAddr, readLen, startOfData);+ }++ p->data[5] = result ? STATUS_OK : EIO;+ if (result) {+ p->size = 6 + readLen;+ } else {+ p->size = 6;+ }++ crtpSendPacket(p);+}++static void memWriteProcess(CRTPPacket* p) {+ uint32_t memAddr;+ bool result = false;++ uint8_t memId = p->data[0];+ memcpy(&memAddr, &p->data[1], 4);+ uint8_t* startOfData = &p->data[5];++ uint8_t writeLen = p->size - 5;++ MEM_DEBUG("Packet is MEM WRITE\n");+ p->header = CRTP_HEADER(CRTP_PORT_MEM, MEM_WRITE_CH);+ // Dont' touch the first 5 bytes, they will be the same.++ if (memId < nrOfHandlers) {+ if (handlers[memId]->write) {+ result = handlers[memId]->write(memAddr, writeLen, startOfData);+ }+ } else {+ uint8_t selectedMem = memId - nrOfHandlers;+ result = owMemHandler->write(selectedMem, memAddr, writeLen, startOfData);+ }++ p->data[5] = result ? STATUS_OK : EIO;+ p->size = 6;++ crtpSendPacket(p);+}++/**+ * @brief The memory tester is used to verify the functionality of the memory sub system.+ * It supports "virtual" read and writes that are used by a test script to+ * check that a client (for instance the python lib) is working as expected.+ *+ * When reading data from the tester, it simply fills up a buffer with known data so that the+ * client can examine the data and verify that buffers have been correctly assembled.+ *+ * @param memAddr - the virtual address to read from+ * @param readLen - nr of bytes to read+ * @param startOfData - address to write result to+ * @return Always returns true+ */+static bool handleMemTesterRead(const uint32_t memAddr, const uint8_t readLen, uint8_t* startOfData) {+ for (int i = 0; i < readLen; i++) {+ uint32_t addr = memAddr + i;+ uint8_t data = addr & 0xff;+ startOfData[i] = data;+ }++ return true;+}++/**+ * @brief When writing data to the tester, the tester verifies that the received data+ * contains the expected values.+ *+ * @param memAddr - the virtual address to write to+ * @param writeLen - nr of bytes to write+ * @param startOfData - pointer to the data in the packet that is provided by the client+ * @return Always returns true+ */+static bool handleMemTesterWrite(const uint32_t memAddr, const uint8_t writeLen, const uint8_t* startOfData) {+ if (memTesterWriteReset) {+ memTesterWriteReset = 0;+ memTesterWriteErrorCount = 0;+ }++ for (int i = 0; i < writeLen; i++) {+ uint32_t addr = memAddr + i;+ uint8_t expectedData = addr & 0xff;+ uint8_t actualData = startOfData[i];+ if (actualData != expectedData) {+ // Log first error+ if (memTesterWriteErrorCount == 0) {+ DEBUG_PRINT("Verification failed: expected: %d, actual: %d, addr: %"PRIu32"\n", expectedData, actualData, addr);+ }++ memTesterWriteErrorCount++;+ break;+ }+ }++ return true;+}++PARAM_GROUP_START(memTst)+ PARAM_ADD(PARAM_UINT8, resetW, &memTesterWriteReset)+PARAM_GROUP_STOP(memTst)++LOG_GROUP_START(memTst)+ LOG_ADD(LOG_UINT32, errCntW, &memTesterWriteErrorCount)+LOG_GROUP_STOP(memTst)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/msp.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/msp.cnew file mode 100644index 0000000..7abc365--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/msp.c@@ -0,0 +1,383 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2012 BitCraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * msp.c: Implementation of the MultiWii Serial Protocol+ *+ * The MultiWii Serial Protocol is a commonly used protocol for OSDs,+ * data logging, and communication with a ground telemetry station.+ * For more details, see the official MSP documentation and support thread:+ * - http://www.multiwii.com/wiki/index.php?title=Multiwii_Serial_Protocol+ * - http://www.multiwii.com/forum/viewtopic.php?f=8&t=1516+ */++#include "msp.h"+#include "sensfusion6.h"+#include "commander.h"+#define DEBUG_MODULE "MSP"+#include "debug_cf.h"++// MSP command IDs+#define MSP_STATUS 101+#define MSP_RC 105+#define MSP_ATTITUDE 108+#define MSP_BOXIDS 119++// Misc MSP header defines+#define MSP_PREAMBLE_0 '$'+#define MSP_PREAMBLE_1 'M'+#define MSP_DIRECTION_IN '<'+#define MSP_DIRECTION_OUT '>'++// Sensor flag defines+#define BARO_PRESENT (0x01)+#define MAG_PRESENT (0x02)+#define GPS_PRESENT (0x04)+#define SONAR_PRESENT (0x08)++typedef enum+{+ MSP_REQUEST_STATE_WAIT_FOR_START,+ MSP_REQUEST_STATE_PREAMBLE,+ MSP_REQUEST_STATE_DIRECTION,+ MSP_REQUEST_STATE_SIZE,+ MSP_REQUEST_STATE_COMMAND,+ MSP_REQUEST_STATE_CRC+} MSP_REQUEST_STATE;++/**+ * Structures describing data payloads for MSP responses+ * All data must be serialized (LSB first) and the cflie+ * is using a little-endian processor, so no byte swapping+ * required+ */+typedef struct _MspStatus+{+ uint16_t cycleTime; // Rate of main stabilizer loop+ uint16_t i2cErrors; // Number of I2C bus errors encountered+ uint16_t sensors; // Bitmask of supported sensors (see sensor flag bitmasks)+ uint32_t flags; // Bitmask of flags/boxes+ uint8_t currentSet; // ID of current active settings/config+}__attribute__((packed)) MspStatus;++typedef struct _MspAttitude+{+ int16_t angX; // Range [-1800,1800], Units: 1/10th degrees+ int16_t angY; // Range [-1800,1800], Units: 1/10th degrees+ int16_t heading; // Range [-180, 180], Units: degrees+}__attribute__((packed)) MspAttitude;++typedef struct _MspRc+{+ uint16_t roll; // Range [1000,2000]+ uint16_t pitch; // Range [1000,2000]+ uint16_t yaw; // Range [1000,2000]+ uint16_t throttle; // Range [1000,2000]+}__attribute__((packed)) MspRc;++// Helpers+static uint8_t mspComputeCrc(uint8_t* pBuffer, uint32_t bufferLen);+static bool mspIsRequestValid(MspObject* pMspObject);+static void mspProcessRequest(MspObject* pMspObject);++// Request handlers+static void mspHandleRequestMspStatus(MspObject* pMspObject);+static void mspHandleRequestMspRc(MspObject* pMspObject);+static void mspHandleRequestMspAttitude(MspObject* pMspObject);+static void mspHandleRequestMspBoxIds(MspObject* pMspObject);++void mspInit(MspObject* pMspObject, const MspResponseCallback callback)+{+ pMspObject->requestState = MSP_REQUEST_STATE_WAIT_FOR_START;+ pMspObject->responseCallback = callback;+}++void mspProcessByte(MspObject* pMspObject, const uint8_t data)+{+ // If the start token is received at any time,+ // immediately transition back to the first state+ if(data == MSP_PREAMBLE_0)+ {+ pMspObject->requestState = MSP_REQUEST_STATE_PREAMBLE;+ pMspObject->requestHeader.preamble[0] = data;+ return;+ }++ switch(pMspObject->requestState)+ {+ case MSP_REQUEST_STATE_WAIT_FOR_START:+ // Do nothing until the start token comes+ break;++ case MSP_REQUEST_STATE_PREAMBLE:+ pMspObject->requestHeader.preamble[1] = data;+ pMspObject->requestState = MSP_REQUEST_STATE_DIRECTION;+ break;++ case MSP_REQUEST_STATE_DIRECTION:+ pMspObject->requestHeader.direction = data;+ pMspObject->requestState = MSP_REQUEST_STATE_SIZE;+ break;++ case MSP_REQUEST_STATE_SIZE:+ pMspObject->requestHeader.size = data;+ pMspObject->requestState = MSP_REQUEST_STATE_COMMAND;+ break;++ case MSP_REQUEST_STATE_COMMAND:+ pMspObject->requestHeader.command = data;+ pMspObject->requestState = MSP_REQUEST_STATE_CRC;+ break;++ case MSP_REQUEST_STATE_CRC:+ pMspObject->requestCrc = data;++ // Have a completed request+ mspProcessRequest(pMspObject);++ pMspObject->requestState = MSP_REQUEST_STATE_WAIT_FOR_START;+ break;+ }+}++uint8_t mspComputeCrc(uint8_t* pBuffer, uint32_t bufferLen)+{+ uint8_t crc = 0;++ // Make sure the buffer is at least the size of a header+ if(bufferLen >= sizeof(MspHeader))+ {+ MspHeader* pHeader = (MspHeader*)pBuffer;++ // Make sure the buffer is at least the size of the buffer and data+ if(bufferLen >= sizeof(MspHeader) + pHeader->size)+ {+ // The MSP CRC is defined as the XOR of size, command, and all+ // data bytes into a zeroed sum.++ crc ^= pHeader->size;+ crc ^= pHeader->command;++ for(uint16_t i = 0; i < pHeader->size; i++)+ {+ crc ^= pBuffer[sizeof(MspHeader) + i];+ }+ }+ }++ return crc;+}++bool mspIsRequestValid(MspObject* pMspObject)+{+ if(pMspObject->requestHeader.preamble[0] != MSP_PREAMBLE_0 ||+ pMspObject->requestHeader.preamble[1] != MSP_PREAMBLE_1)+ {+ // Invalid preamble+ DEBUG_PRINTD("MSP Request has invalid preamble %d %d\n", pMspObject->requestHeader.preamble[0], pMspObject->requestHeader.preamble[1]);+ return false;+ }++ if(pMspObject->requestHeader.direction != MSP_DIRECTION_IN)+ {+ // Requests should be inputs+ DEBUG_PRINTD("MSP Request has invalid direction %d\n", pMspObject->requestHeader.direction);+ return false;+ }++ if(pMspObject->requestHeader.size != 0)+ {+ // Requests should not have a payload+ DEBUG_PRINTD("MSP Request has invalid size %d\n", pMspObject->requestHeader.size);+ return false;+ }++ if(pMspObject->requestCrc !=+ mspComputeCrc((uint8_t*)&pMspObject->requestHeader, sizeof(pMspObject->requestHeader)))+ {+ // CRC does not match+ DEBUG_PRINTD("MSP Request has invalid crc (%d != %d)\n", pMspObject->requestCrc, mspComputeCrc((uint8_t*)&pMspObject->requestHeader, sizeof(pMspObject->requestHeader)));+ return false;+ }++ return true;+}++void mspProcessRequest(MspObject* pMspObject)+{+ if(!mspIsRequestValid(pMspObject))+ {+ DEBUG_PRINT("Received invalid or improperly formatted MSP request\n");+ return;+ }++ switch(pMspObject->requestHeader.command)+ {+ case MSP_STATUS:+ mspHandleRequestMspStatus(pMspObject);++ if(pMspObject->responseCallback)+ {+ pMspObject->responseCallback(pMspObject->mspResponse, pMspObject->mspResponseSize);+ }+ break;++ case MSP_RC:+ mspHandleRequestMspRc(pMspObject);++ if(pMspObject->responseCallback)+ {+ pMspObject->responseCallback(pMspObject->mspResponse, pMspObject->mspResponseSize);+ }+ break;++ case MSP_ATTITUDE:+ mspHandleRequestMspAttitude(pMspObject);++ if(pMspObject->responseCallback)+ {+ pMspObject->responseCallback(pMspObject->mspResponse, pMspObject->mspResponseSize);+ }+ break;++ case MSP_BOXIDS:+ mspHandleRequestMspBoxIds(pMspObject);++ if(pMspObject->responseCallback)+ {+ pMspObject->responseCallback(pMspObject->mspResponse, pMspObject->mspResponseSize);+ }+ break;++ default:+ DEBUG_PRINT("Received unsupported MSP request: %d\n", pMspObject->requestHeader.command);+ break;+ }+}++void mspHandleRequestMspStatus(MspObject* pMspObject)+{+ MspHeader* pHeader = (MspHeader*)pMspObject->mspResponse;+ MspStatus* pData = (MspStatus*)(pMspObject->mspResponse + sizeof(MspHeader));+ uint8_t* pCrc = (uint8_t*)(pMspObject->mspResponse + sizeof(MspHeader) + sizeof(*pData));++ // Header+ pHeader->preamble[0] = MSP_PREAMBLE_0;+ pHeader->preamble[1] = MSP_PREAMBLE_1;+ pHeader->direction = MSP_DIRECTION_OUT;+ pHeader->size = sizeof(*pData);+ pHeader->command = MSP_STATUS;++ // Data+ pData->cycleTime = 1000; // TODO: API to query this?+ pData->i2cErrors = 0; // unused+ pData->sensors = 0x0001; // no sensors supported yet, but need to report at least one to get the level bars to show+ pData->flags = 0x00000001; // always report armed (bit zero)+ pData->currentSet = 0x00;++ // CRC+ *pCrc = mspComputeCrc(pMspObject->mspResponse, sizeof(pMspObject->mspResponse));++ // Update total response size+ pMspObject->mspResponseSize = sizeof(MspHeader) + sizeof(*pData) + 1;+}++void mspHandleRequestMspRc(MspObject* pMspObject)+{+ MspHeader* pHeader = (MspHeader*)pMspObject->mspResponse;+ MspRc* pData = (MspRc*)(pMspObject->mspResponse + sizeof(MspHeader));+ uint8_t* pCrc = (uint8_t*)(pMspObject->mspResponse + sizeof(MspHeader) + sizeof(*pData));++ // Header+ pHeader->preamble[0] = MSP_PREAMBLE_0;+ pHeader->preamble[1] = MSP_PREAMBLE_1;+ pHeader->direction = MSP_DIRECTION_OUT;+ pHeader->size = sizeof(*pData);+ pHeader->command = MSP_RC;++ // TODO: get actual data - for now hardcode the midpoint+ pData->roll = 1500;+ pData->pitch = 1500;+ pData->yaw = 1500;+ pData->throttle = 1500;++ // CRC+ *pCrc = mspComputeCrc(pMspObject->mspResponse, sizeof(pMspObject->mspResponse));++ // Update total response size+ pMspObject->mspResponseSize = sizeof(MspHeader) + sizeof(*pData) + 1;+}++static void mspHandleRequestMspAttitude(MspObject* pMspObject)+{+ MspHeader* pHeader = (MspHeader*)pMspObject->mspResponse;+ MspAttitude* pData = (MspAttitude*)(pMspObject->mspResponse + sizeof(MspHeader));+ uint8_t* pCrc = (uint8_t*)(pMspObject->mspResponse + sizeof(MspHeader) + sizeof(*pData));++ // Header+ pHeader->preamble[0] = MSP_PREAMBLE_0;+ pHeader->preamble[1] = MSP_PREAMBLE_1;+ pHeader->direction = MSP_DIRECTION_OUT;+ pHeader->size = sizeof(*pData);+ pHeader->command = MSP_ATTITUDE;++ // Data+ float roll;+ float pitch;+ float yaw;+ sensfusion6GetEulerRPY(&roll, &pitch, &yaw); // TODO: handle kalman estimator++ pData->angX = (int16_t)(roll * 10);+ pData->angY = (int16_t)(pitch * 10);+ pData->heading = 0; // TODO: mag support++ // CRC+ *pCrc = mspComputeCrc(pMspObject->mspResponse, sizeof(pMspObject->mspResponse));++ // Update total response size+ pMspObject->mspResponseSize = sizeof(MspHeader) + sizeof(*pData) + 1;+}++static void mspHandleRequestMspBoxIds(MspObject* pMspObject)+{+ MspHeader* pHeader = (MspHeader*)pMspObject->mspResponse;+ uint8_t* pData = (uint8_t*)(pMspObject->mspResponse + sizeof(MspHeader));+ uint8_t* pCrc = (uint8_t*)(pMspObject->mspResponse + sizeof(MspHeader) + sizeof(*pData));++ // Header+ pHeader->preamble[0] = MSP_PREAMBLE_0;+ pHeader->preamble[1] = MSP_PREAMBLE_1;+ pHeader->direction = MSP_DIRECTION_OUT;+ pHeader->size = sizeof(*pData);+ pHeader->command = MSP_BOXIDS;++ // TODO: Data - this needs to be properly implemented+ // For now, we just return byte 0 = 0 which tells+ // the client to use box ID 0 for the ARMED box+ pData[0] = 0x00;++ // CRC+ *pCrc = mspComputeCrc(pMspObject->mspResponse, sizeof(pMspObject->mspResponse));++ // Update total response size+ pMspObject->mspResponseSize = sizeof(MspHeader) + sizeof(*pData) + 1;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/outlierFilter.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/outlierFilter.cnew file mode 100644index 0000000..632a35c--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/outlierFilter.c@@ -0,0 +1,200 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * outlierFilter.c: Outlier rejection filter for the LPS system+ */++#include <math.h>+#include "outlierFilter.h"+#include "stabilizer_types.h"+#include "log.h"+#include "debug_cf.h"++#define BUCKET_ACCEPTANCE_LEVEL 3+#define MAX_BUCKET_FILL 10+#define FILTER_CLOSE_DELAY_COUNT 30++static float acceptanceLevel = 0.0;+static float errorDistance;+static int filterCloseDelayCounter = 0;+static int previousFilterIndex = 0;++typedef struct {+ float acceptanceLevel;+ int bucket;+} filterLevel_t;++#define FILTER_LEVELS 5+#define FILTER_NONE FILTER_LEVELS+filterLevel_t filterLevels[FILTER_LEVELS] = {+ {.acceptanceLevel = 0.4},+ {.acceptanceLevel = 0.8},+ {.acceptanceLevel = 1.2},+ {.acceptanceLevel = 1.6},+ {.acceptanceLevel = 2.0},+};+++static bool isDistanceDiffSmallerThanDistanceBetweenAnchors(const tdoaMeasurement_t* tdoa);+static float distanceSq(const point_t* a, const point_t* b);+static float sq(float a) {return a * a;}+static void addToBucket(filterLevel_t* filter);+static void removeFromBucket(filterLevel_t* filter);+static int updateBuckets(float errorDistance);++++bool outlierFilterValidateTdoaSimple(const tdoaMeasurement_t* tdoa) {+ return isDistanceDiffSmallerThanDistanceBetweenAnchors(tdoa);+}++bool outlierFilterValidateTdoaSteps(const tdoaMeasurement_t* tdoa, const float error, const vector_t* jacobian, const point_t* estPos) {+ bool sampleIsGood = false;++ if (isDistanceDiffSmallerThanDistanceBetweenAnchors(tdoa)) {+ float errorBaseDistance = sqrtf(powf(jacobian->x, 2) + powf(jacobian->y, 2) + powf(jacobian->z, 2));+ errorDistance = fabsf(error / errorBaseDistance);++ int filterIndex = updateBuckets(errorDistance);++ if (filterIndex > previousFilterIndex) {+ filterCloseDelayCounter = FILTER_CLOSE_DELAY_COUNT;+ } else if (filterIndex < previousFilterIndex) {+ if (filterCloseDelayCounter > 0) {+ filterCloseDelayCounter--;+ filterIndex = previousFilterIndex;+ }+ }+ previousFilterIndex = filterIndex;++ if (filterIndex == FILTER_NONE) {+ // Lost tracking, open up to let the kalman filter converge+ acceptanceLevel = 100.0;+ sampleIsGood = true;+ } else {+ acceptanceLevel = filterLevels[filterIndex].acceptanceLevel;+ if (errorDistance < acceptanceLevel) {+ sampleIsGood = true;+ }+ }+ }++ return sampleIsGood;+}+++#define LH_TICKS_PER_FRAME (1000 / 120)+static const int32_t lhMinWindowTime = -2 * LH_TICKS_PER_FRAME;+static const int32_t lhMaxWindowTime = 5 * LH_TICKS_PER_FRAME;+static const int32_t lhBadSampleWindowChange = -LH_TICKS_PER_FRAME;+static const int32_t lhGoodSampleWindowChange = LH_TICKS_PER_FRAME / 2;+static const float lhMaxError = 0.05f;++void outlierFilterReset(OutlierFilterLhState_t* this, const uint32_t now) {+ this->openingTime = now;+ this->openingWindow = lhMinWindowTime;+}+++bool outlierFilterValidateLighthouseSweep(OutlierFilterLhState_t* this, const float distanceToBs, const float angleError, const uint32_t now) {+ // float error = distanceToBs * tan(angleError);+ // We use an approximattion+ float error = distanceToBs * angleError;++ bool isGoodSample = (fabsf(error) < lhMaxError);+ if (isGoodSample) {+ this->openingWindow += lhGoodSampleWindowChange;+ if (this->openingWindow > lhMaxWindowTime) {+ this->openingWindow = lhMaxWindowTime;+ }+ } else {+ this->openingWindow += lhBadSampleWindowChange;+ if (this->openingWindow < lhMinWindowTime) {+ this->openingWindow = lhMinWindowTime;+ }+ }++ bool result = true;+ bool isFilterClosed = (now < this->openingTime);+ if (isFilterClosed) {+ result = isGoodSample;+ }++ this->openingTime = now + this->openingWindow;++ return result;+}+++static bool isDistanceDiffSmallerThanDistanceBetweenAnchors(const tdoaMeasurement_t* tdoa) {+ float anchorDistanceSq = distanceSq(&tdoa->anchorPosition[0], &tdoa->anchorPosition[1]);+ float distanceDiffSq = sq(tdoa->distanceDiff);+ return (distanceDiffSq < anchorDistanceSq);+}++static float distanceSq(const point_t* a, const point_t* b) {+ return sq(a->x - b->x) + sq(a->y - b->y) + sq(a->z - b->z);+}+++static void addToBucket(filterLevel_t* filter) {+ if (filter->bucket < MAX_BUCKET_FILL) {+ filter->bucket++;+ }+}++static void removeFromBucket(filterLevel_t* filter) {+ if (filter->bucket > 0) {+ filter->bucket--;+ }+}++static int updateBuckets(float errorDistance) {+ int filterIndex = FILTER_NONE;++ for (int i = FILTER_LEVELS - 1; i >= 0; i--) {+ filterLevel_t* filter = &filterLevels[i];++ if (errorDistance < filter->acceptanceLevel) {+ removeFromBucket(filter);+ } else {+ addToBucket(filter);+ }++ if (filter->bucket < BUCKET_ACCEPTANCE_LEVEL) {+ filterIndex = i;+ }+ }++ return filterIndex;+}++LOG_GROUP_START(outlierf)+ LOG_ADD(LOG_INT32, bucket0, &filterLevels[0].bucket)+ LOG_ADD(LOG_INT32, bucket1, &filterLevels[1].bucket)+ LOG_ADD(LOG_INT32, bucket2, &filterLevels[2].bucket)+ LOG_ADD(LOG_INT32, bucket3, &filterLevels[3].bucket)+ LOG_ADD(LOG_INT32, bucket4, &filterLevels[4].bucket)+ LOG_ADD(LOG_FLOAT, accLev, &acceptanceLevel)+ LOG_ADD(LOG_FLOAT, errD, &errorDistance)+LOG_GROUP_STOP(outlierf)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/param.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/param.cnew file mode 100644index 0000000..7a784fe--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/param.c@@ -0,0 +1,759 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * param.h - Crazy parameter system source file.+ */+#include <string.h>+#include <errno.h>++/* FreeRtos includes */+#include "FreeRTOS.h"+#include "task.h"++#include "config.h"+#include "crtp.h"+#include "param.h"+#include "crc.h"+#include "console.h"+#define DEBUG_MODULE "PARAM"+#include "debug_cf.h"+#include "stm32_legacy.h"+#include "static_mem.h"++#if 0+#define PARAM_DEBUG(fmt, ...) DEBUG_PRINTD("D/param " fmt, ## __VA_ARGS__)+#define PARAM_ERROR(fmt, ...) DEBUG_PRINTD("E/param " fmt, ## __VA_ARGS__)+#else+#define PARAM_DEBUG(...)+#define PARAM_ERROR(...)+#endif++static const uint8_t typeLength[] = {+ [PARAM_UINT8] = 1,+ [PARAM_UINT16] = 2,+ [PARAM_UINT32] = 4,+ [PARAM_INT8] = 1,+ [PARAM_INT16] = 2,+ [PARAM_INT32] = 4,+ [PARAM_FLOAT] = 4,+};++#define TOC_CH 0+#define READ_CH 1+#define WRITE_CH 2+#define MISC_CH 3++#define CMD_RESET 0+#define CMD_GET_NEXT 1+#define CMD_GET_CRC 2++#define CMD_GET_ITEM 0 // original version: up to 255 entries+#define CMD_GET_INFO 1 // original version: up to 255 entries+#define CMD_GET_ITEM_V2 2 // version 2: up to 16k entries+#define CMD_GET_INFO_V2 3 // version 2: up to 16k entries++#define MISC_SETBYNAME 0+#define MISC_VALUE_UPDATED 1++//Private functions+static void paramTask(void * prm);+void paramTOCProcess(int command);+++//These are set by the Linker+extern struct param_s _param_start;+extern struct param_s _param_end;++//The following two function SHALL NOT be called outside paramTask!+static void paramWriteProcess();+static void paramReadProcess();+static int variableGetIndex(int id);+static char paramWriteByNameProcess(char* group, char* name, int type, void *valptr);++//Pointer to the parameters list and length of it+static struct param_s * params;+static int paramsLen;+static uint32_t paramsCrc;+static uint16_t paramsCount = 0;+// indicates if read/write operation use V2 (i.e., 16-bit index)+// This is set to true, if a client uses TOC_CH in V2+static bool useV2 = false;++static CRTPPacket p;++static bool isInit = false;++STATIC_MEM_TASK_ALLOC_STACK_NO_DMA_CCM_SAFE(paramTask, PARAM_TASK_STACKSIZE);++void paramInit(void)+{+ int i;+ const char* group = NULL;+ int groupLength = 0;++ if(isInit)+ return;++ params = &_param_start;+ paramsLen = &_param_end - &_param_start;++ // Calculate a hash of the toc by chaining description of each elements+ // Using the CRTP packet as temporary buffer+ paramsCrc = 0;+ for (int i=0; i<paramsLen; i++)+ {+ int len = 5;+ memcpy(&p.data[0], ¶msCrc, 4);+ p.data[4] = params[i].type;+ if (params[i].type & PARAM_GROUP) {+ if (params[i].type & PARAM_START) {+ group = params[i].name;+ groupLength = strlen(group);+ }+ } else {+ // CMD_GET_ITEM_V2 result's size is: 4 + strlen(params[i].name) + groupLength + 2+ if (strlen(params[i].name) + groupLength + 2 > 26) {+ PARAM_ERROR("'%s.%s' too long\n", group, params[i].name);+ ASSERT_FAILED();+ }+ }++ if (params[i].name) {+ memcpy(&p.data[5], params[i].name, strlen(params[i].name));+ len += strlen(params[i].name);+ }+ paramsCrc = crcSlow(p.data, len);+ }++ for (i=0; i<paramsLen; i++)+ {+ if(!(params[i].type & PARAM_GROUP))+ paramsCount++;+ }+++ //Start the param task+ STATIC_MEM_TASK_CREATE(paramTask, paramTask, PARAM_TASK_NAME, NULL, PARAM_TASK_PRI);++ //TODO: Handle stored parameters!++ isInit = true;+}++bool paramTest(void)+{+ return isInit;+}++void paramTask(void * prm)+{+ crtpInitTaskQueue(CRTP_PORT_PARAM);++ while(1) {+ crtpReceivePacketBlock(CRTP_PORT_PARAM, &p);++ if (p.channel==TOC_CH)+ paramTOCProcess(p.data[0]);+ else if (p.channel==READ_CH)+ paramReadProcess();+ else if (p.channel==WRITE_CH)+ paramWriteProcess();+ else if (p.channel==MISC_CH) {+ if (p.data[0] == MISC_SETBYNAME) {+ int i, nzero = 0;+ char *group;+ char *name;+ uint8_t type;+ void * valPtr;+ int error;++ // If the packet contains at least 2 zeros in the first 28 bytes+ // The packet decoding algorithm will not crash+ for (i=0; i<CRTP_MAX_DATA_SIZE; i++) {+ if (p.data[i] == '\0') nzero++;+ }++ if (nzero < 2) return;++ group = (char*)&p.data[1];+ name = (char*)&p.data[1+strlen(group)+1];+ type = p.data[1+strlen(group)+1+strlen(name)+1];+ valPtr = &p.data[1+strlen(group)+1+strlen(name)+2];++ error = paramWriteByNameProcess(group, name, type, valPtr);++ p.data[1+strlen(group)+1+strlen(name)+1] = error;+ p.size = 1+strlen(group)+1+strlen(name)+1+1;+ crtpSendPacket(&p);+ }+ }+ }+}++void paramTOCProcess(int command)+{+ int ptr = 0;+ char * group = "";+ uint16_t n=0;+ uint16_t paramId=0;++ switch (command)+ {+ case CMD_GET_INFO: //Get info packet about the param implementation+ DEBUG_PRINT("Client uses old param API!\n");+ ptr = 0;+ group = "";+ p.header=CRTP_HEADER(CRTP_PORT_PARAM, TOC_CH);+ p.size=6;+ p.data[0]=CMD_GET_INFO;+ if (paramsCount < 255) {+ p.data[1]=paramsCount;+ } else {+ p.data[1]=255;+ }+ memcpy(&p.data[2], ¶msCrc, 4);+ crtpSendPacket(&p);+ break;+ case CMD_GET_ITEM: //Get param variable+ for (ptr=0; ptr<paramsLen; ptr++) //Ptr points a group+ {+ if (params[ptr].type & PARAM_GROUP)+ {+ if (params[ptr].type & PARAM_START)+ group = params[ptr].name;+ else+ group = "";+ }+ else //Ptr points a variable+ {+ if (n==p.data[1])+ break;+ n++;+ }+ }++ if (ptr<paramsLen)+ {+ p.header=CRTP_HEADER(CRTP_PORT_PARAM, TOC_CH);+ p.data[0]=CMD_GET_ITEM;+ p.data[1]=n;+ p.data[2]=params[ptr].type;+ p.size=3+2+strlen(group)+strlen(params[ptr].name);+ ASSERT(p.size <= CRTP_MAX_DATA_SIZE); // Too long! The name of the group or the parameter may be too long.+ memcpy(p.data+3, group, strlen(group)+1);+ memcpy(p.data+3+strlen(group)+1, params[ptr].name, strlen(params[ptr].name)+1);+ crtpSendPacket(&p);+ } else {+ p.header=CRTP_HEADER(CRTP_PORT_PARAM, TOC_CH);+ p.data[0]=CMD_GET_ITEM;+ p.size=1;+ crtpSendPacket(&p);+ }+ break;+ case CMD_GET_INFO_V2: //Get info packet about the param implementation+ ptr = 0;+ group = "";+ p.header=CRTP_HEADER(CRTP_PORT_PARAM, TOC_CH);+ p.size=7;+ p.data[0]=CMD_GET_INFO_V2;+ memcpy(&p.data[1], ¶msCount, 2);+ memcpy(&p.data[3], ¶msCrc, 4);+ crtpSendPacket(&p);+ useV2 = true;+ break;+ case CMD_GET_ITEM_V2: //Get param variable+ memcpy(¶mId, &p.data[1], 2);+ for (ptr=0; ptr<paramsLen; ptr++) //Ptr points a group+ {+ if (params[ptr].type & PARAM_GROUP)+ {+ if (params[ptr].type & PARAM_START)+ group = params[ptr].name;+ else+ group = "";+ }+ else //Ptr points a variable+ {+ if (n==paramId)+ break;+ n++;+ }+ }++ if (ptr<paramsLen)+ {+ p.header=CRTP_HEADER(CRTP_PORT_PARAM, TOC_CH);+ p.data[0]=CMD_GET_ITEM_V2;+ memcpy(&p.data[1], ¶mId, 2);+ p.data[3]=params[ptr].type;+ p.size=4+2+strlen(group)+strlen(params[ptr].name);+ ASSERT(p.size <= CRTP_MAX_DATA_SIZE); // Too long! The name of the group or the parameter may be too long.+ memcpy(p.data+4, group, strlen(group)+1);+ memcpy(p.data+4+strlen(group)+1, params[ptr].name, strlen(params[ptr].name)+1);+ crtpSendPacket(&p);+ } else {+ p.header=CRTP_HEADER(CRTP_PORT_PARAM, TOC_CH);+ p.data[0]=CMD_GET_ITEM_V2;+ p.size=1;+ crtpSendPacket(&p);+ }+ break;+ }+}++static void paramWriteProcess()+{+ if (useV2) {+ uint16_t ident;+ memcpy(&ident, &p.data[0], 2);++ void* valptr = &p.data[2];+ int id;++ id = variableGetIndex(ident);++ if (id<0) {+ p.data[2] = ENOENT;+ p.size = 3;++ crtpSendPacket(&p);+ return;+ }++ if (params[id].type & PARAM_RONLY)+ return;++ switch (params[id].type & PARAM_BYTES_MASK)+ {+ case PARAM_1BYTE:+ *(uint8_t*)params[id].address = *(uint8_t*)valptr;+ break;+ case PARAM_2BYTES:+ *(uint16_t*)params[id].address = *(uint16_t*)valptr;+ break;+ case PARAM_4BYTES:+ *(uint32_t*)params[id].address = *(uint32_t*)valptr;+ break;+ case PARAM_8BYTES:+ *(uint64_t*)params[id].address = *(uint64_t*)valptr;+ break;+ }++ crtpSendPacket(&p);+ } else {+ int ident = p.data[0];+ void* valptr = &p.data[1];+ int id;++ id = variableGetIndex(ident);++ if (id<0) {+ p.data[0] = -1;+ p.data[1] = ident;+ p.data[2] = ENOENT;+ p.size = 3;++ crtpSendPacket(&p);+ return;+ }++ if (params[id].type & PARAM_RONLY)+ return;++ switch (params[id].type & PARAM_BYTES_MASK)+ {+ case PARAM_1BYTE:+ *(uint8_t*)params[id].address = *(uint8_t*)valptr;+ break;+ case PARAM_2BYTES:+ *(uint16_t*)params[id].address = *(uint16_t*)valptr;+ break;+ case PARAM_4BYTES:+ *(uint32_t*)params[id].address = *(uint32_t*)valptr;+ break;+ case PARAM_8BYTES:+ *(uint64_t*)params[id].address = *(uint64_t*)valptr;+ break;+ }++ crtpSendPacket(&p);+ }+}++static char paramWriteByNameProcess(char* group, char* name, int type, void *valptr) {+ int ptr;+ char *pgroup = "";++ for (ptr=0; ptr<paramsLen; ptr++) //Ptr points a group+ {+ if (params[ptr].type & PARAM_GROUP)+ {+ if (params[ptr].type & PARAM_START)+ pgroup = params[ptr].name;+ else+ pgroup = "";+ }+ else //Ptr points a variable+ {+ if (!strcmp(params[ptr].name, name) && !strcmp(pgroup, group))+ break;+ }+ }++ if (ptr >= paramsLen) {+ return ENOENT;+ }++ if (type != params[ptr].type) {+ return EINVAL;+ }++ if (params[ptr].type & PARAM_RONLY) {+ return EACCES;+ }++ switch (params[ptr].type & PARAM_BYTES_MASK)+ {+ case PARAM_1BYTE:+ *(uint8_t*)params[ptr].address = *(uint8_t*)valptr;+ break;+ case PARAM_2BYTES:+ *(uint16_t*)params[ptr].address = *(uint16_t*)valptr;+ break;+ case PARAM_4BYTES:+ *(uint32_t*)params[ptr].address = *(uint32_t*)valptr;+ break;+ case PARAM_8BYTES:+ *(uint64_t*)params[ptr].address = *(uint64_t*)valptr;+ break;+ }++ return 0;+}++static void paramReadProcess()+{+ if (useV2) {+ uint16_t ident;+ memcpy(&ident, &p.data[0], 2);+ int id = variableGetIndex(ident);++ if (id<0) {+ p.data[2] = ENOENT;+ p.size = 3;++ crtpSendPacket(&p);+ return;+ }++ p.data[2] = 0;+ switch (params[id].type & PARAM_BYTES_MASK)+ {+ case PARAM_1BYTE:+ memcpy(&p.data[3], params[id].address, sizeof(uint8_t));+ p.size = 3+sizeof(uint8_t);+ break;+ break;+ case PARAM_2BYTES:+ memcpy(&p.data[3], params[id].address, sizeof(uint16_t));+ p.size = 3+sizeof(uint16_t);+ break;+ case PARAM_4BYTES:+ memcpy(&p.data[3], params[id].address, sizeof(uint32_t));+ p.size = 3+sizeof(uint32_t);+ break;+ case PARAM_8BYTES:+ memcpy(&p.data[3], params[id].address, sizeof(uint64_t));+ p.size = 3+sizeof(uint64_t);+ break;+ }+ } else {+ uint8_t ident = p.data[0];+ int id = variableGetIndex(ident);++ if (id<0) {+ p.data[0] = -1;+ p.data[1] = ident;+ p.data[2] = ENOENT;+ p.size = 3;++ crtpSendPacket(&p);+ return;+ }++ switch (params[id].type & PARAM_BYTES_MASK)+ {+ case PARAM_1BYTE:+ memcpy(&p.data[1], params[id].address, sizeof(uint8_t));+ p.size = 1+sizeof(uint8_t);+ break;+ break;+ case PARAM_2BYTES:+ memcpy(&p.data[1], params[id].address, sizeof(uint16_t));+ p.size = 1+sizeof(uint16_t);+ break;+ case PARAM_4BYTES:+ memcpy(&p.data[1], params[id].address, sizeof(uint32_t));+ p.size = 1+sizeof(uint32_t);+ break;+ case PARAM_8BYTES:+ memcpy(&p.data[1], params[id].address, sizeof(uint64_t));+ p.size = 1+sizeof(uint64_t);+ break;+ }+ }++ crtpSendPacket(&p);+}++static int variableGetIndex(int id)+{+ int i;+ int n=0;++ for (i=0; i<paramsLen; i++)+ {+ if(!(params[i].type & PARAM_GROUP))+ {+ if(n==id)+ break;+ n++;+ }+ }++ if (i>=paramsLen)+ return -1;++ return i;+}++/* Public API to access param TOC from within the copter */+static paramVarId_t invalidVarId = {0xffffu, 0xffffu};++paramVarId_t paramGetVarId(char* group, char* name)+{+ int ptr;+ int id = 0;+ paramVarId_t varId = invalidVarId;+ char * currgroup = "";++ for(ptr=0; ptr<paramsLen; ptr++)+ {+ if (params[ptr].type & PARAM_GROUP) {+ if (params[ptr].type & PARAM_START) {+ currgroup = params[ptr].name;+ }+ } else {+ id += 1;+ }++ if ((!strcmp(group, currgroup)) && (!strcmp(name, params[ptr].name))) {+ varId.ptr = ptr;+ varId.id = id - 1;+ return varId;+ }+ }++ return invalidVarId;+}++int paramGetType(paramVarId_t varid)+{+ return params[varid.ptr].type;+}++void paramGetGroupAndName(paramVarId_t varid, char** group, char** name)+{+ char * currgroup = "";+ *group = 0;+ *name = 0;++ for(int i=0; i<paramsLen; i++) {+ if (params[i].type & PARAM_GROUP) {+ if (params[i].type & PARAM_START) {+ currgroup = params[i].name;+ }+ }++ if (i == varid.ptr) {+ *group = currgroup;+ *name = params[i].name;+ break;+ }+ }+}++uint8_t paramVarSize(int type)+{+ return typeLength[type];+}++int paramGetInt(paramVarId_t varid)+{+ int valuei = 0;++ ASSERT(PARAM_VARID_IS_VALID(varid));++ switch(params[varid.ptr].type)+ {+ case PARAM_UINT8:+ valuei = *(uint8_t *)params[varid.ptr].address;+ break;+ case PARAM_INT8:+ valuei = *(int8_t *)params[varid.ptr].address;+ break;+ case PARAM_UINT16:+ valuei = *(uint16_t *)params[varid.ptr].address;+ break;+ case PARAM_INT16:+ valuei = *(int16_t *)params[varid.ptr].address;+ break;+ case PARAM_UINT32:+ valuei = *(uint32_t *)params[varid.ptr].address;+ break;+ case PARAM_INT32:+ valuei = *(int32_t *)params[varid.ptr].address;+ break;+ case PARAM_FLOAT:+ valuei = *(float *)params[varid.ptr].address;+ break;+ case PARAM_UINT8 | PARAM_RONLY:+ valuei = *(uint8_t *)params[varid.ptr].address;+ break;+ case PARAM_INT8 | PARAM_RONLY:+ valuei = *(int8_t *)params[varid.ptr].address;+ break;+ case PARAM_UINT16 | PARAM_RONLY:+ valuei = *(uint16_t *)params[varid.ptr].address;+ break;+ case PARAM_INT16 | PARAM_RONLY:+ valuei = *(int16_t *)params[varid.ptr].address;+ break;+ case PARAM_UINT32 | PARAM_RONLY:+ valuei = *(uint32_t *)params[varid.ptr].address;+ break;+ case PARAM_INT32 | PARAM_RONLY:+ valuei = *(int32_t *)params[varid.ptr].address;+ break;+ case PARAM_FLOAT | PARAM_RONLY:+ valuei = *(float *)params[varid.ptr].address;+ break;+ }++ return valuei;+}++float paramGetFloat(paramVarId_t varid)+{+ ASSERT(PARAM_VARID_IS_VALID(varid));++ if (params[varid.ptr].type == PARAM_FLOAT || params[varid.ptr].type == (PARAM_FLOAT | PARAM_RONLY))+ return *(float *)params[varid.ptr].address;++ return paramGetInt(varid);+}++unsigned int paramGetUint(paramVarId_t varid)+{+ return (unsigned int)paramGetInt(varid);+}++void paramSetInt(paramVarId_t varid, int valuei)+{+ ASSERT(PARAM_VARID_IS_VALID(varid));++ static CRTPPacket pk;+ pk.header=CRTP_HEADER(CRTP_PORT_PARAM, MISC_CH);+ pk.data[0] = MISC_VALUE_UPDATED;+ pk.data[1] = varid.id & 0xffu;+ pk.data[2] = (varid.id >> 8) & 0xffu;+ pk.size=3;++ switch(params[varid.ptr].type)+ {+ case PARAM_UINT8:+ *(uint8_t *)params[varid.ptr].address = (uint8_t) valuei;+ memcpy(&pk.data[2], &valuei, 1);+ pk.size += 1;+ break;+ case PARAM_INT8:+ *(int8_t *)params[varid.ptr].address = (int8_t) valuei;+ memcpy(&pk.data[2], &valuei, 1);+ pk.size += 1;+ break;+ case PARAM_UINT16:+ *(uint16_t *)params[varid.ptr].address = (uint16_t) valuei;+ memcpy(&pk.data[2], &valuei, 2);+ pk.size += 2;+ break;+ case PARAM_INT16:+ *(int16_t *)params[varid.ptr].address = (int16_t) valuei;+ memcpy(&pk.data[2], &valuei, 2);+ pk.size += 2;+ break;+ case PARAM_UINT32:+ *(uint32_t *)params[varid.ptr].address = (uint32_t) valuei;+ memcpy(&pk.data[2], &valuei, 4);+ pk.size += 4;+ break;+ case PARAM_INT32:+ *(int32_t *)params[varid.ptr].address = (int32_t) valuei;+ memcpy(&pk.data[2], &valuei, 4);+ pk.size += 4;+ break;+ case PARAM_FLOAT:+ // Todo: are floats handy to have here?+ *(float *)params[varid.ptr].address = (float) valuei;+ memcpy(&pk.data[2], &valuei, 4);+ pk.size += 4;++ break;+ }++#ifndef SILENT_PARAM_UPDATES+ crtpSendPacket(&pk);+#endif+}++void paramSetFloat(paramVarId_t varid, float valuef)+{+ ASSERT(PARAM_VARID_IS_VALID(varid));++ static CRTPPacket pk;+ pk.header=CRTP_HEADER(CRTP_PORT_PARAM, MISC_CH);+ pk.data[0] = MISC_VALUE_UPDATED;+ pk.data[1] = varid.id & 0xffu;+ pk.data[2] = (varid.id >> 8) & 0xffu;+ pk.size=3;++ if (params[varid.ptr].type == PARAM_FLOAT ) {+ *(float *)params[varid.ptr].address = valuef;++ memcpy(&pk.data[2], &valuef, 4);+ pk.size += 4;+ }++#ifndef SILENT_PARAM_UPDATES+ crtpSendPacket(&pk);+#endif+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/peer_localization.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/peer_localization.cnew file mode 100644index 0000000..a3ea8d6--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/peer_localization.c@@ -0,0 +1,64 @@+#include "config.h"+#include "debug.h"+#include "FreeRTOS.h"+#include "task.h"+#include "peer_localization.h"+++void peerLocalizationInit()+{+ // All other_positions[in].id will be set to zero due to static initialization.+ // If we ever switch to dynamic allocation, we need to set them to zero explicitly.+}++bool peerLocalizationTest()+{+ return true;+}++// array of other's position+static peerLocalizationOtherPosition_t other_positions[PEER_LOCALIZATION_MAX_NEIGHBORS];++bool peerLocalizationTellPosition(int cfid, positionMeasurement_t const *pos)+{+ for (uint8_t i = 0; i < PEER_LOCALIZATION_MAX_NEIGHBORS; ++i) {+ if (other_positions[i].id == 0 || other_positions[i].id == cfid) {+ other_positions[i].id = cfid;+ other_positions[i].pos.x = pos->x;+ other_positions[i].pos.y = pos->y;+ other_positions[i].pos.z = pos->z;+ other_positions[i].pos.timestamp = xTaskGetTickCount();+ return true;+ }+ }+ return false;+}++bool peerLocalizationIsIDActive(uint8_t cfid)+{+ for (uint8_t i = 0; i < PEER_LOCALIZATION_MAX_NEIGHBORS; ++i) {+ if (other_positions[i].id == cfid) {+ return true;+ }+ }+ return false;+}++peerLocalizationOtherPosition_t *peerLocalizationGetPositionByID(uint8_t cfid)+{+ for (uint8_t i = 0; i < PEER_LOCALIZATION_MAX_NEIGHBORS; ++i) {+ if (other_positions[i].id == cfid) {+ return &other_positions[i];+ }+ }+ return NULL;+}++peerLocalizationOtherPosition_t *peerLocalizationGetPositionByIdx(uint8_t idx)+{+ // TODO: should we return NULL if the id == 0?+ if (idx < PEER_LOCALIZATION_MAX_NEIGHBORS) {+ return &other_positions[idx];+ }+ return NULL;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/pid.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/pid.cnew file mode 100644index 0000000..4c160bf--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/pid.c@@ -0,0 +1,160 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * pid.c - implementation of the PID regulator+ */++#include "pid.h"+#include "num.h"+#include <math.h>+#include <float.h>++void pidInit(PidObject* pid, const float desired, const float kp,+ const float ki, const float kd, const float dt,+ const float samplingRate, const float cutoffFreq,+ bool enableDFilter)+{+ pid->error = 0;+ pid->prevError = 0;+ pid->integ = 0;+ pid->deriv = 0;+ pid->desired = desired;+ pid->kp = kp;+ pid->ki = ki;+ pid->kd = kd;+ pid->iLimit = DEFAULT_PID_INTEGRATION_LIMIT;+ pid->outputLimit = DEFAULT_PID_OUTPUT_LIMIT;+ pid->dt = dt;+ pid->enableDFilter = enableDFilter;+ if (pid->enableDFilter)+ {+ lpf2pInit(&pid->dFilter, samplingRate, cutoffFreq);+ }+}++float pidUpdate(PidObject* pid, const float measured, const bool updateError)+{+ float output = 0.0f;++ if (updateError)+ {+ pid->error = pid->desired - measured;+ }++ pid->outP = pid->kp * pid->error;+ output += pid->outP;++ float deriv = (pid->error - pid->prevError) / pid->dt;+ if (pid->enableDFilter)+ {+ pid->deriv = lpf2pApply(&pid->dFilter, deriv);+ } else {+ pid->deriv = deriv;+ }+ if (isnan(pid->deriv)) {+ pid->deriv = 0;+ }+ pid->outD = pid->kd * pid->deriv;+ output += pid->outD;++ pid->integ += pid->error * pid->dt;++ // Constrain the integral (unless the iLimit is zero)+ if(pid->iLimit != 0)+ {+ pid->integ = constrain(pid->integ, -pid->iLimit, pid->iLimit);+ }++ pid->outI = pid->ki * pid->integ;+ output += pid->outI;++ // Constrain the total PID output (unless the outputLimit is zero)+ if(pid->outputLimit != 0)+ {+ output = constrain(output, -pid->outputLimit, pid->outputLimit);+ }+++ pid->prevError = pid->error;++ return output;+}++void pidSetIntegralLimit(PidObject* pid, const float limit) {+ pid->iLimit = limit;+}+++void pidReset(PidObject* pid)+{+ pid->error = 0;+ pid->prevError = 0;+ pid->integ = 0;+ pid->deriv = 0;+}++void pidSetError(PidObject* pid, const float error)+{+ pid->error = error;+}++void pidSetDesired(PidObject* pid, const float desired)+{+ pid->desired = desired;+}++float pidGetDesired(PidObject* pid)+{+ return pid->desired;+}++bool pidIsActive(PidObject* pid)+{+ bool isActive = true;++ if (pid->kp < 0.0001f && pid->ki < 0.0001f && pid->kd < 0.0001f)+ {+ isActive = false;+ }++ return isActive;+}++void pidSetKp(PidObject* pid, const float kp)+{+ pid->kp = kp;+}++void pidSetKi(PidObject* pid, const float ki)+{+ pid->ki = ki;+}++void pidSetKd(PidObject* pid, const float kd)+{+ pid->kd = kd;+}+void pidSetDt(PidObject* pid, const float dt) {+ pid->dt = dt;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/planner.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/planner.cnew file mode 100644index 0000000..456a8d1--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/planner.c@@ -0,0 +1,209 @@+/*+ * ______+ * / ____/________ _____ __ ________ ______ __________ ___+ * / / / ___/ __ `/_ / / / / / ___/ | /| / / __ `/ ___/ __ `__ \+ * / /___/ / / /_/ / / /_/ /_/ (__ )| |/ |/ / /_/ / / / / / / / /+ * \____/_/ \__,_/ /___/\__, /____/ |__/|__/\__,_/_/ /_/ /_/ /_/+ * /____/+ *+ * Crazyswarm advanced control firmware for Crazyflie+ *++The MIT License (MIT)++Copyright (c) 2018 Wolfgang Hoenig and James Alan Preiss++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+*/++/*+implementation of planning state machine+*/+#include <stddef.h>+#define DEBUG_MODULE "PLANNER"+#include "planner.h"+#include "debug_cf.h"++static struct traj_eval plan_eval(struct planner *p, float t);++static void plan_takeoff_or_landing(struct planner *p, struct vec curr_pos, float curr_yaw, float hover_height, float hover_yaw, float duration)+{+ struct vec hover_pos = curr_pos;+ hover_pos.z = hover_height;++ piecewise_plan_7th_order_no_jerk(&p->planned_trajectory, duration,+ curr_pos, curr_yaw, vzero(), 0, vzero(),+ hover_pos, hover_yaw, vzero(), 0, vzero());+}++// ----------------- //+// public functions. //+// ----------------- //++void plan_init(struct planner *p)+{+ p->state = TRAJECTORY_STATE_IDLE;+ p->type = TRAJECTORY_TYPE_PIECEWISE;+ p->reversed = false;+ p->trajectory = NULL;+ p->compressed_trajectory = NULL;+ p->planned_trajectory.pieces = p->pieces;+}++void plan_stop(struct planner *p)+{+ p->state = TRAJECTORY_STATE_IDLE;+}++bool plan_is_finished(struct planner *p, float t)+{+ switch (p->type) {+ case TRAJECTORY_TYPE_PIECEWISE:+ return piecewise_is_finished(p->trajectory, t);++ case TRAJECTORY_TYPE_PIECEWISE_COMPRESSED:+ return piecewise_compressed_is_finished(p->compressed_trajectory, t);++ default:+ return 1;+ }+}++bool plan_is_stopped(struct planner *p)+{+ return p->state == TRAJECTORY_STATE_IDLE;+}++struct traj_eval plan_current_goal(struct planner *p, float t)+{+ switch (p->state) {+ case TRAJECTORY_STATE_LANDING:+ if (plan_is_finished(p, t)) {+ p->state = TRAJECTORY_STATE_IDLE;+ }+ // intentional fall-thru+ case TRAJECTORY_STATE_FLYING:+ return plan_eval(p, t);++ default:+ return traj_eval_invalid();+ }+}++struct traj_eval plan_eval(struct planner *p, float t)+{+ switch (p->type) {+ case TRAJECTORY_TYPE_PIECEWISE:+ if (p->reversed) {+ return piecewise_eval_reversed(p->trajectory, t);+ }+ else {+ return piecewise_eval(p->trajectory, t);+ }+ break;++ case TRAJECTORY_TYPE_PIECEWISE_COMPRESSED:+ if (p->reversed) {+ /* not supported */+ return traj_eval_invalid();+ }+ else {+ return piecewise_compressed_eval(p->compressed_trajectory, t);+ }+ break;++ default:+ return traj_eval_invalid();+ }+}++int plan_takeoff(struct planner *p, struct vec curr_pos, float curr_yaw, float hover_height, float hover_yaw, float duration, float t)+{+ if (p->state != TRAJECTORY_STATE_IDLE) {+ return 1;+ }++ plan_takeoff_or_landing(p, curr_pos, curr_yaw, hover_height, hover_yaw, duration);+ p->reversed = false;+ p->state = TRAJECTORY_STATE_FLYING;+ p->type = TRAJECTORY_TYPE_PIECEWISE;+ p->planned_trajectory.t_begin = t;+ p->trajectory = &p->planned_trajectory;+ return 0;+}++int plan_land(struct planner *p, struct vec curr_pos, float curr_yaw, float hover_height, float hover_yaw, float duration, float t)+{+ if (p->state == TRAJECTORY_STATE_LANDING) {+ return 1;+ }++ plan_takeoff_or_landing(p, curr_pos, curr_yaw, hover_height, hover_yaw, duration);+ p->reversed = false;+ p->state = TRAJECTORY_STATE_LANDING;+ p->type = TRAJECTORY_TYPE_PIECEWISE;+ p->planned_trajectory.t_begin = t;+ p->trajectory = &p->planned_trajectory;+ return 0;+}++int plan_go_to_from(struct planner *p, const struct traj_eval *curr_eval, bool relative, struct vec hover_pos, float hover_yaw, float duration, float t)+{+ if (relative) {+ hover_pos = vadd(hover_pos, curr_eval->pos);+ hover_yaw += curr_eval->yaw;+ }++ piecewise_plan_7th_order_no_jerk(&p->planned_trajectory, duration,+ curr_eval->pos, curr_eval->yaw, curr_eval->vel, curr_eval->omega.z, curr_eval->acc,+ hover_pos, hover_yaw, vzero(), 0, vzero());++ p->reversed = false;+ p->state = TRAJECTORY_STATE_FLYING;+ p->type = TRAJECTORY_TYPE_PIECEWISE;+ p->planned_trajectory.t_begin = t;+ p->trajectory = &p->planned_trajectory;+ return 0;+}++int plan_go_to(struct planner *p, bool relative, struct vec hover_pos, float hover_yaw, float duration, float t)+{+ struct traj_eval setpoint = plan_current_goal(p, t);+ return plan_go_to_from(p, &setpoint, relative, hover_pos, hover_yaw, duration, t);+}++int plan_start_trajectory( struct planner *p, const struct piecewise_traj* trajectory, bool reversed)+{+ p->reversed = reversed;+ p->state = TRAJECTORY_STATE_FLYING;+ p->type = TRAJECTORY_TYPE_PIECEWISE;+ p->trajectory = trajectory;++ return 0;+}++int plan_start_compressed_trajectory( struct planner *p, struct piecewise_traj_compressed* trajectory)+{+ p->reversed = 0;+ p->state = TRAJECTORY_STATE_FLYING;+ p->type = TRAJECTORY_TYPE_PIECEWISE_COMPRESSED;+ p->compressed_trajectory = trajectory;++ return 0;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/platformservice.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/platformservice.cnew file mode 100644index 0000000..c3746ed--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/platformservice.c@@ -0,0 +1,149 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * crtpservice.c - Implements low level services for CRTP+ */++#include <stdbool.h>++/* FreeRtos includes */+#include "FreeRTOS.h"+#include <stdint.h>+#include <string.h>++#include "config.h"+#include "crtp.h"+#include "platformservice.h"+//#include "syslink.h"+#include "version.h"+#include "platform.h"+#include "app_channel.h"++static bool isInit=false;++typedef enum {+ platformCommand = 0x00,+ versionCommand = 0x01,+ appChannel = 0x02,+} Channel;++typedef enum {+ setContinousWave = 0x00,+} PlatformCommand;++typedef enum {+ getProtocolVersion = 0x00,+ getFirmwareVersion = 0x01,+ getDeviceTypeName = 0x02,+} VersionCommand;++void platformserviceHandler(CRTPPacket *p);+static void platformCommandProcess(uint8_t command, uint8_t *data);+static void versionCommandProcess(CRTPPacket *p);++void platformserviceInit(void)+{+ if (isInit)+ return;++ appchannelInit();++ // Register a callback to service the Platform port+ crtpRegisterPortCB(CRTP_PORT_PLATFORM, platformserviceHandler);++ isInit = true;+}++bool platformserviceTest(void)+{+ return isInit;+}++void platformserviceHandler(CRTPPacket *p)+{+ switch (p->channel)+ {+ case platformCommand:+ platformCommandProcess(p->data[0], &p->data[1]);+ crtpSendPacket(p);+ break;+ case versionCommand:+ versionCommandProcess(p);+ break;+ case appChannel:+ appchannelIncomingPacket(p);+ break;+ default:+ break;+ }+}++static void platformCommandProcess(uint8_t command, uint8_t *data)+{+ // SyslinkPacket slp;++ switch (command) {+ case setContinousWave:+ // slp.type = SYSLINK_RADIO_CONTWAVE;+ // slp.length = 1;+ // slp.data[0] = data[0];+ // syslinkSendPacket(&slp);+ break;+ default:+ break;+ }+}++void platformserviceSendAppchannelPacket(CRTPPacket *p)+{+ p->port = CRTP_PORT_PLATFORM;+ p->channel = appChannel;+ crtpSendPacket(p);+}++static void versionCommandProcess(CRTPPacket *p)+{+ switch (p->data[0]) {+ case getProtocolVersion:+ *(int*)&p->data[1] = PROTOCOL_VERSION;+ p->size = 5;+ crtpSendPacket(p);+ break;+ case getFirmwareVersion:+ strncpy((char*)&p->data[1], V_STAG, CRTP_MAX_DATA_SIZE-1);+ p->size = (strlen(V_STAG)>CRTP_MAX_DATA_SIZE-1)?CRTP_MAX_DATA_SIZE:strlen(V_STAG)+1;+ crtpSendPacket(p);+ break;+ case getDeviceTypeName:+ {+ const char* name = platformConfigGetDeviceTypeName();+ strncpy((char*)&p->data[1], name, CRTP_MAX_DATA_SIZE-1);+ p->size = (strlen(name)>CRTP_MAX_DATA_SIZE-1)?CRTP_MAX_DATA_SIZE:strlen(name)+1;+ crtpSendPacket(p);+ }+ break;+ default:+ break;+ }+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/position_controller_indi.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/position_controller_indi.cnew file mode 100644index 0000000..9496cb6--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/position_controller_indi.c@@ -0,0 +1,352 @@+/*+ *+ * Copyright (c) 2019 Ewoud Smeur and Evghenii Volodscoi+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * This control algorithm is the Incremental Nonlinear Dynamic Inversion (INDI)+ * controller to control the position of the Crazyflie. It can be seen as an extension+ * (outer loop) to the already existing INDI attitude controller (inner loop).+ *+ * The control algorithm was implemented according to the publication in the+ * journal od Control Engineering Practice: Cascaded Incremental Nonlinear Dynamic+ * Inversion for MAV Disturbance Rejection+ * https://doi.org/10.1016/j.conengprac.2018.01.003+ */+++#include "position_controller_indi.h"+#include "math3d.h"++// Position controller gains+float K_xi_x = 1.0f;+float K_xi_y = 1.0f;+float K_xi_z = 1.0f;+// Velocity controller gains+float K_dxi_x = 5.0f;+float K_dxi_y = 5.0f;+float K_dxi_z = 5.0f;+// Thrust mapping parameter+float K_thr = 0.00024730f;++static float posS_x, posS_y, posS_z; // Current position+static float velS_x, velS_y, velS_z; // Current velocity+static float gyr_p, gyr_q, gyr_r; // Current rates++// Reference values+static struct Vectr positionRef;+static struct Vectr velocityRef;+++static struct IndiOuterVariables indiOuter = {+ .filt_cutoff = POSITION_INDI_FILT_CUTOFF,+ .act_dyn_posINDI = STABILIZATION_INDI_ACT_DYN_P+};+++void position_indi_init_filters(void)+{+ // tau = 1/(2*pi*Fc)+ float tau = 1.0f / (2.0f * M_PI_F * indiOuter.filt_cutoff);+ float tau_axis[3] = {tau, tau, tau};+ float sample_time = 1.0f / ATTITUDE_RATE;+ // Filtering of linear acceleration, attitude and thrust+ for (int8_t i = 0; i < 3; i++) {+ init_butterworth_2_low_pass(&indiOuter.ddxi[i], tau_axis[i], sample_time, 0.0f);+ init_butterworth_2_low_pass(&indiOuter.ang[i], tau_axis[i], sample_time, 0.0f);+ init_butterworth_2_low_pass(&indiOuter.thr[i], tau_axis[i], sample_time, 0.0f);+ }+}++// Linear acceleration filter+static inline void filter_ddxi(Butterworth2LowPass *filter, struct Vectr *old_values, struct Vectr *new_values)+{+ new_values->x = update_butterworth_2_low_pass(&filter[0], old_values->x);+ new_values->y = update_butterworth_2_low_pass(&filter[1], old_values->y);+ new_values->z = update_butterworth_2_low_pass(&filter[2], old_values->z);+}++// Attitude filter+static inline void filter_ang(Butterworth2LowPass *filter, struct Angles *old_values, struct Angles *new_values)+{+ new_values->phi = update_butterworth_2_low_pass(&filter[0], old_values->phi);+ new_values->theta = update_butterworth_2_low_pass(&filter[1], old_values->theta);+ new_values->psi = update_butterworth_2_low_pass(&filter[2], old_values->psi);+}++// Thrust filter+static inline void filter_thrust(Butterworth2LowPass *filter, float *old_thrust, float *new_thrust)+{+ *new_thrust = update_butterworth_2_low_pass(&filter[0], *old_thrust);+}+++// Computes transformation matrix from body frame (index B) into NED frame (index O)+void m_ob(struct Angles att, float matrix[3][3]) {++ matrix[0][0] = cosf(att.theta)*cosf(att.psi);+ matrix[0][1] = sinf(att.phi)*sinf(att.theta)*cosf(att.psi) - cosf(att.phi)*sinf(att.psi);+ matrix[0][2] = cosf(att.phi)*sinf(att.theta)*cosf(att.psi) + sinf(att.phi)*sinf(att.psi);+ matrix[1][0] = cosf(att.theta)*sinf(att.psi);+ matrix[1][1] = sinf(att.phi)*sinf(att.theta)*sinf(att.psi) + cosf(att.phi)*cosf(att.psi);+ matrix[1][2] = cosf(att.phi)*sinf(att.theta)*sinf(att.psi) - sinf(att.phi)*cosf(att.psi);+ matrix[2][0] = -sinf(att.theta);+ matrix[2][1] = sinf(att.phi)*cosf(att.theta);+ matrix[2][2] = cosf(att.phi)*cosf(att.theta);+}+++void positionControllerINDIInit(void)+{+ // Re-initialize filters+ position_indi_init_filters();+}+++void positionControllerINDI(const sensorData_t *sensors,+ setpoint_t *setpoint,+ const state_t *state,+ vector_t *refOuterINDI){++ // Read states (position, velocity)+ posS_x = state->position.x;+ posS_y = -state->position.y;+ posS_z = -state->position.z;+ velS_x = state->velocity.x;+ velS_y = -state->velocity.y;+ velS_z = -state->velocity.z;+ gyr_p = sensors->gyro.x;+ gyr_q = sensors->gyro.y;+ gyr_r = sensors->gyro.z;++ // Read in velocity setpoints+ velocityRef.x = setpoint->velocity.x;+ velocityRef.y = -setpoint->velocity.y;+ velocityRef.z = -setpoint->velocity.z;++ // Position controller (Proportional)+ if (setpoint->mode.x == modeAbs) {+ positionRef.x = setpoint->position.x;+ velocityRef.x = K_xi_x*(positionRef.x - posS_x);+ }+ if (setpoint->mode.y == modeAbs) {+ positionRef.y = -setpoint->position.y;+ velocityRef.y = K_xi_y*(positionRef.y - posS_y);+ }+ if (setpoint->mode.z == modeAbs) {+ positionRef.z = -setpoint->position.z;+ velocityRef.z = K_xi_z*(positionRef.z - posS_z);+ }++ // Velocity controller (Proportional)+ indiOuter.linear_accel_ref.x = K_dxi_x*(velocityRef.x - velS_x);+ indiOuter.linear_accel_ref.y = K_dxi_y*(velocityRef.y - velS_y);+ indiOuter.linear_accel_ref.z = K_dxi_z*(velocityRef.z - velS_z);++ // Acceleration controller (INDI)+ // Read lin. acceleration (Body-fixed) obtained from sensors CHECKED+ indiOuter.linear_accel_s.x = (sensors->acc.x)*9.81f;+ indiOuter.linear_accel_s.y = (-sensors->acc.y)*9.81f;+ indiOuter.linear_accel_s.z = (-sensors->acc.z)*9.81f;++ // Filter lin. acceleration+ filter_ddxi(indiOuter.ddxi, &indiOuter.linear_accel_s, &indiOuter.linear_accel_f);++ // Obtain actual attitude values (in deg)+ indiOuter.attitude_s.phi = state->attitude.roll;+ indiOuter.attitude_s.theta = state->attitude.pitch;+ indiOuter.attitude_s.psi = -state->attitude.yaw;+ filter_ang(indiOuter.ang, &indiOuter.attitude_s, &indiOuter.attitude_f);+++ // Actual attitude (in rad)+ struct Angles att = {+ .phi = indiOuter.attitude_f.phi/180*M_PI_F,+ .theta = indiOuter.attitude_f.theta/180*M_PI_F,+ .psi = indiOuter.attitude_f.psi/180*M_PI_F,+ };++ // Compute transformation matrix from body frame (index B) into NED frame (index O)+ float M_OB[3][3] = {0};+ m_ob(att, M_OB);++ // Transform lin. acceleration in NED (add gravity to the z-component)+ indiOuter.linear_accel_ft.x = M_OB[0][0]*indiOuter.linear_accel_f.x + M_OB[0][1]*indiOuter.linear_accel_f.y + M_OB[0][2]*indiOuter.linear_accel_f.z;+ indiOuter.linear_accel_ft.y = M_OB[1][0]*indiOuter.linear_accel_f.x + M_OB[1][1]*indiOuter.linear_accel_f.y + M_OB[1][2]*indiOuter.linear_accel_f.z;+ indiOuter.linear_accel_ft.z = M_OB[2][0]*indiOuter.linear_accel_f.x + M_OB[2][1]*indiOuter.linear_accel_f.y + M_OB[2][2]*indiOuter.linear_accel_f.z + 9.81f;++ // Compute lin. acceleration error+ indiOuter.linear_accel_err.x = indiOuter.linear_accel_ref.x - indiOuter.linear_accel_ft.x;+ indiOuter.linear_accel_err.y = indiOuter.linear_accel_ref.y - indiOuter.linear_accel_ft.y;+ indiOuter.linear_accel_err.z = indiOuter.linear_accel_ref.z - indiOuter.linear_accel_ft.z;++ // Elements of the G matrix (see publication for more information)+ // ("-" because T points in neg. z-direction, "*9.81" because T/m=a=g,+ // negative psi to account for wrong coordinate frame in the implementation of the inner loop)+ float g11 = (cosf(att.phi)*sinf(-att.psi) - sinf(att.phi)*sinf(att.theta)*cosf(-att.psi))*(-9.81f);+ float g12 = (cosf(att.phi)*cosf(-att.theta)*cosf(-att.psi))*(-9.81f);+ float g13 = (sinf(att.phi)*sinf(-att.psi) + cosf(att.phi)*sinf(att.theta)*cosf(-att.psi));+ float g21 = (-cosf(att.phi)*cosf(-att.psi) - sinf(att.phi)*sinf(att.theta)*sinf(-att.psi))*(-9.81f);+ float g22 = (cosf(att.phi)*cosf(att.theta)*sinf(-att.psi))*(-9.81f);+ float g23 = (-sinf(att.phi)*cosf(-att.psi) + cosf(att.phi)*sinf(att.theta)*sinf(-att.psi));+ float g31 = (-sinf(att.phi)*cosf(att.theta))*(-9.81f);+ float g32 = (-cosf(att.phi)*sinf(att.theta))*(-9.81f);+ float g33 = (cosf(att.phi)*cosf(att.theta));++ // Next four blocks of the code are to compute the Moore-Penrose inverse of the G matrix+ // (G'*G)+ float a11 = g11*g11 + g21*g21 + g31*g31;+ float a12 = g11*g12 + g21*g22 + g31*g32;+ float a13 = g11*g13 + g21*g23 + g31*g33;+ float a21 = g12*g11 + g22*g21 + g32*g31;+ float a22 = g12*g12 + g22*g22 + g32*g32;+ float a23 = g12*g13 + g22*g23 + g32*g33;+ float a31 = g13*g11 + g23*g21 + g33*g31;+ float a32 = g13*g12 + g23*g22 + g33*g32;+ float a33 = g13*g13 + g23*g23 + g33*g33;++ // Determinant of (G'*G)+ float detG = (a11*a22*a33 + a12*a23*a31 + a21*a32*a13) - (a13*a22*a31 + a11*a32*a23 + a12*a21*a33);++ // Inverse of (G'*G)+ float a11_inv = (a22*a33 - a23*a32)/detG;+ float a12_inv = (a13*a32 - a12*a33)/detG;+ float a13_inv = (a12*a23 - a13*a22)/detG;+ float a21_inv = (a23*a31 - a21*a33)/detG;+ float a22_inv = (a11*a33 - a13*a31)/detG;+ float a23_inv = (a13*a21 - a11*a23)/detG;+ float a31_inv = (a21*a32 - a22*a31)/detG;+ float a32_inv = (a12*a31 - a11*a32)/detG;+ float a33_inv = (a11*a22 - a12*a21)/detG;++ // G_inv = (G'*G)_inv*G'+ float g11_inv = a11_inv*g11 + a12_inv*g12 + a13_inv*g13;+ float g12_inv = a11_inv*g21 + a12_inv*g22 + a13_inv*g23;+ float g13_inv = a11_inv*g31 + a12_inv*g32 + a13_inv*g33;+ float g21_inv = a21_inv*g11 + a22_inv*g12 + a23_inv*g13;+ float g22_inv = a21_inv*g21 + a22_inv*g22 + a23_inv*g23;+ float g23_inv = a21_inv*g31 + a22_inv*g32 + a23_inv*g33;+ float g31_inv = a31_inv*g11 + a32_inv*g12 + a33_inv*g13;+ float g32_inv = a31_inv*g21 + a32_inv*g22 + a33_inv*g23;+ float g33_inv = a31_inv*g31 + a32_inv*g32 + a33_inv*g33;++ // Lin. accel. error multiplied G^(-1) matrix (T_tilde negated because motor accepts only positiv commands, angles are in rad)+ indiOuter.phi_tilde = (g11_inv*indiOuter.linear_accel_err.x + g12_inv*indiOuter.linear_accel_err.y + g13_inv*indiOuter.linear_accel_err.z);+ indiOuter.theta_tilde = (g21_inv*indiOuter.linear_accel_err.x + g22_inv*indiOuter.linear_accel_err.y + g23_inv*indiOuter.linear_accel_err.z);+ indiOuter.T_tilde = -(g31_inv*indiOuter.linear_accel_err.x + g32_inv*indiOuter.linear_accel_err.y + g33_inv*indiOuter.linear_accel_err.z)/K_thr;++ // Filter thrust+ filter_thrust(indiOuter.thr, &indiOuter.T_incremented, &indiOuter.T_inner_f);++ // Pass thrust through the model of the actuator dynamics+ indiOuter.T_inner = indiOuter.T_inner + indiOuter.act_dyn_posINDI*(indiOuter.T_inner_f - indiOuter.T_inner);++ // Compute trust that goes into the inner loop+ indiOuter.T_incremented = indiOuter.T_tilde + indiOuter.T_inner;++ // Compute commanded attitude to the inner INDI+ indiOuter.attitude_c.phi = indiOuter.attitude_f.phi + indiOuter.phi_tilde*180/M_PI_F;+ indiOuter.attitude_c.theta = indiOuter.attitude_f.theta + indiOuter.theta_tilde*180/M_PI_F;++ // Clamp commands+ indiOuter.T_incremented = clamp(indiOuter.T_incremented, MIN_THRUST, MAX_THRUST);+ indiOuter.attitude_c.phi = clamp(indiOuter.attitude_c.phi, -10.0f, 10.0f);+ indiOuter.attitude_c.theta = clamp(indiOuter.attitude_c.theta, -10.0f, 10.0f);++ // Reference values, which are passed to the inner loop INDI (attitude controller)+ refOuterINDI->x = indiOuter.attitude_c.phi;+ refOuterINDI->y = indiOuter.attitude_c.theta;+ refOuterINDI->z = indiOuter.T_incremented;++}+++PARAM_GROUP_START(posCtrlIndi)++// Position controller gain+PARAM_ADD(PARAM_FLOAT, K_xi_x, &K_xi_x)+PARAM_ADD(PARAM_FLOAT, K_xi_y, &K_xi_y)+PARAM_ADD(PARAM_FLOAT, K_xi_z, &K_xi_z)++// Velocity Controller gain+PARAM_ADD(PARAM_FLOAT, K_dxi_x, &K_dxi_x)+PARAM_ADD(PARAM_FLOAT, K_dxi_y, &K_dxi_y)+PARAM_ADD(PARAM_FLOAT, K_dxi_z, &K_dxi_z)++PARAM_GROUP_STOP(posCtrlIndi)++++LOG_GROUP_START(posCtrlIndi)++// Angular veocity+LOG_ADD(LOG_FLOAT, gyr_p, &gyr_p)+LOG_ADD(LOG_FLOAT, gyr_q, &gyr_q)+LOG_ADD(LOG_FLOAT, gyr_r, &gyr_r)++LOG_ADD(LOG_FLOAT, posRef_x, &positionRef.x)+LOG_ADD(LOG_FLOAT, posRef_y, &positionRef.y)+LOG_ADD(LOG_FLOAT, posRef_z, &positionRef.z)++// Velocity+LOG_ADD(LOG_FLOAT, velS_x, &velS_x)+LOG_ADD(LOG_FLOAT, velS_y, &velS_y)+LOG_ADD(LOG_FLOAT, velS_z, &velS_z)++LOG_ADD(LOG_FLOAT, velRef_x, &velocityRef.x)+LOG_ADD(LOG_FLOAT, velRef_y, &velocityRef.y)+LOG_ADD(LOG_FLOAT, velRef_z, &velocityRef.z)++// Attitude+LOG_ADD(LOG_FLOAT, angS_roll, &indiOuter.attitude_s.phi)+LOG_ADD(LOG_FLOAT, angS_pitch, &indiOuter.attitude_s.theta)+LOG_ADD(LOG_FLOAT, angS_yaw, &indiOuter.attitude_s.psi)++LOG_ADD(LOG_FLOAT, angF_roll, &indiOuter.attitude_f.phi)+LOG_ADD(LOG_FLOAT, angF_pitch, &indiOuter.attitude_f.theta)+LOG_ADD(LOG_FLOAT, angF_yaw, &indiOuter.attitude_f.psi)++// Acceleration+LOG_ADD(LOG_FLOAT, accRef_x, &indiOuter.linear_accel_ref.x)+LOG_ADD(LOG_FLOAT, accRef_y, &indiOuter.linear_accel_ref.y)+LOG_ADD(LOG_FLOAT, accRef_z, &indiOuter.linear_accel_ref.z)++LOG_ADD(LOG_FLOAT, accS_x, &indiOuter.linear_accel_s.x)+LOG_ADD(LOG_FLOAT, accS_y, &indiOuter.linear_accel_s.y)+LOG_ADD(LOG_FLOAT, accS_z, &indiOuter.linear_accel_s.z)++LOG_ADD(LOG_FLOAT, accF_x, &indiOuter.linear_accel_f.x)+LOG_ADD(LOG_FLOAT, accF_y, &indiOuter.linear_accel_f.y)+LOG_ADD(LOG_FLOAT, accF_z, &indiOuter.linear_accel_f.z)++LOG_ADD(LOG_FLOAT, accFT_x, &indiOuter.linear_accel_ft.x)+LOG_ADD(LOG_FLOAT, accFT_y, &indiOuter.linear_accel_ft.y)+LOG_ADD(LOG_FLOAT, accFT_z, &indiOuter.linear_accel_ft.z)++LOG_ADD(LOG_FLOAT, accErr_x, &indiOuter.linear_accel_err.x)+LOG_ADD(LOG_FLOAT, accErr_y, &indiOuter.linear_accel_err.y)+LOG_ADD(LOG_FLOAT, accErr_z, &indiOuter.linear_accel_err.z)++// INDI outer loop variables+LOG_ADD(LOG_FLOAT, phi_tilde, &indiOuter.phi_tilde)+LOG_ADD(LOG_FLOAT, theta_tilde, &indiOuter.theta_tilde)+LOG_ADD(LOG_FLOAT, T_tilde, &indiOuter.T_tilde)++LOG_ADD(LOG_FLOAT, T_inner, &indiOuter.T_inner)+LOG_ADD(LOG_FLOAT, T_inner_f, &indiOuter.T_inner_f)+LOG_ADD(LOG_FLOAT, T_incremented, &indiOuter.T_incremented)++LOG_ADD(LOG_FLOAT, cmd_phi, &indiOuter.attitude_c.phi)+LOG_ADD(LOG_FLOAT, cmd_theta, &indiOuter.attitude_c.theta)++LOG_GROUP_STOP(posCtrlIndi)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/position_controller_pid.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/position_controller_pid.cnew file mode 100644index 0000000..5bdfb80--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/position_controller_pid.c@@ -0,0 +1,325 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * position_estimator_pid.c: PID-based implementation of the position controller+ */++#include <math.h>+#include "num.h"++#include "commander.h"+#include "log.h"+#include "param.h"+#include "pid.h"+#include "num.h"+#include "position_controller.h"+#define DEBUG_MODULE "POSITION_CONTROLLER"+#include "debug_cf.h"++#ifndef M_PI+#define M_PI 3.14159265358979323846+#endif++struct pidInit_s {+ float kp;+ float ki;+ float kd;+};++struct pidAxis_s {+ PidObject pid;++ struct pidInit_s init;+ stab_mode_t previousMode;+ float setpoint;++ float output;+};++struct this_s {+ struct pidAxis_s pidVX;+ struct pidAxis_s pidVY;+ struct pidAxis_s pidVZ;++ struct pidAxis_s pidX;+ struct pidAxis_s pidY;+ struct pidAxis_s pidZ;++ uint16_t thrustBase; // approximate throttle needed when in perfect hover. More weight/older battery can use a higher value+ uint16_t thrustMin; // Minimum thrust value to output+};++// Maximum roll/pitch angle permited+static float rpLimit = 20;+static float rpLimitOverhead = 1.10f;+// Velocity maximums+static float xyVelMax = 1.0f;+static float zVelMax = 1.0f;+static float velMaxOverhead = 1.10f;+static const float thrustScale = 1000.0f;++#define DT (float)(1.0f/POSITION_RATE)+#define POSITION_LPF_CUTOFF_FREQ 20.0f+#define POSITION_LPF_ENABLE true++#ifndef UNIT_TEST+static struct this_s this = {+ .pidVX = {+ .init = {+ .kp = 25.0f,+ .ki = 1.0f,+ .kd = 0.0f,+ },+ .pid.dt = DT,+ },++ .pidVY = {+ .init = {+ .kp = 25.0f,+ .ki = 1.0f,+ .kd = 0.0f,+ },+ .pid.dt = DT,+ },++ .pidVZ = {+ .init = {+ .kp = 22,+ .ki = 15,+ .kd = 0,+ },+ .pid.dt = DT,+ },++ .pidX = {+ .init = {+ .kp = 1.9f,+ .ki = 0.1f,+ .kd = 0,+ },+ .pid.dt = DT,+ },++ .pidY = {+ .init = {+ .kp = 1.9f,+ .ki = 0.1f,+ .kd = 0,+ },+ .pid.dt = DT,+ },++ .pidZ = {+ .init = {+ .kp = 1.6f,+ .ki = 0.5,+ .kd = 0,+ },+ .pid.dt = DT,+ },++//thrustBase should just lift the drone+#ifdef CONFIG_MOTOR_BRUSHED_715+ #ifdef CONFIG_TARGET_ESP32_S2_DRONE_V1_2+ .thrustBase = 42000,+ .thrustMin = 8000,+ #else+ .thrustBase = 36000,+ .thrustMin = 20000,+ #endif+#else+ .thrustBase = 24000,+ .thrustMin = 5000,+#endif++};+#endif++void positionControllerInit()+{+ pidInit(&this.pidX.pid, this.pidX.setpoint, this.pidX.init.kp, this.pidX.init.ki, this.pidX.init.kd,+ this.pidX.pid.dt, POSITION_RATE, POSITION_LPF_CUTOFF_FREQ, POSITION_LPF_ENABLE);+ pidInit(&this.pidY.pid, this.pidY.setpoint, this.pidY.init.kp, this.pidY.init.ki, this.pidY.init.kd,+ this.pidY.pid.dt, POSITION_RATE, POSITION_LPF_CUTOFF_FREQ, POSITION_LPF_ENABLE);+ pidInit(&this.pidZ.pid, this.pidZ.setpoint, this.pidZ.init.kp, this.pidZ.init.ki, this.pidZ.init.kd,+ this.pidZ.pid.dt, POSITION_RATE, POSITION_LPF_CUTOFF_FREQ, POSITION_LPF_ENABLE);++ pidInit(&this.pidVX.pid, this.pidVX.setpoint, this.pidVX.init.kp, this.pidVX.init.ki, this.pidVX.init.kd,+ this.pidVX.pid.dt, POSITION_RATE, POSITION_LPF_CUTOFF_FREQ, POSITION_LPF_ENABLE);+ pidInit(&this.pidVY.pid, this.pidVY.setpoint, this.pidVY.init.kp, this.pidVY.init.ki, this.pidVY.init.kd,+ this.pidVY.pid.dt, POSITION_RATE, POSITION_LPF_CUTOFF_FREQ, POSITION_LPF_ENABLE);+ pidInit(&this.pidVZ.pid, this.pidVZ.setpoint, this.pidVZ.init.kp, this.pidVZ.init.ki, this.pidVZ.init.kd,+ this.pidVZ.pid.dt, POSITION_RATE, POSITION_LPF_CUTOFF_FREQ, POSITION_LPF_ENABLE);+ DEBUG_PRINTI("thrustBase = %d,thrustMin = %d",this.thrustBase,this.thrustMin);+}++static float runPid(float input, struct pidAxis_s *axis, float setpoint, float dt) {+ axis->setpoint = setpoint;++ pidSetDesired(&axis->pid, axis->setpoint);+ return pidUpdate(&axis->pid, input, true);+}++void positionController(float* thrust, attitude_t *attitude, setpoint_t *setpoint,+ const state_t *state)+{+ this.pidX.pid.outputLimit = xyVelMax * velMaxOverhead;+ this.pidY.pid.outputLimit = xyVelMax * velMaxOverhead;+ // The ROS landing detector will prematurely trip if+ // this value is below 0.5+ this.pidZ.pid.outputLimit = fmaxf(zVelMax, 0.5f) * velMaxOverhead;++ float cosyaw = cosf(state->attitude.yaw * (float)M_PI / 180.0f);+ float sinyaw = sinf(state->attitude.yaw * (float)M_PI / 180.0f);+ float bodyvx = setpoint->velocity.x;+ float bodyvy = setpoint->velocity.y;++ // X, Y+ if (setpoint->mode.x == modeAbs) {+ setpoint->velocity.x = runPid(state->position.x, &this.pidX, setpoint->position.x, DT);+ } else if (setpoint->velocity_body) {+ setpoint->velocity.x = bodyvx * cosyaw - bodyvy * sinyaw;+ }+ if (setpoint->mode.y == modeAbs) {+ setpoint->velocity.y = runPid(state->position.y, &this.pidY, setpoint->position.y, DT);+ } else if (setpoint->velocity_body) {+ setpoint->velocity.y = bodyvy * cosyaw + bodyvx * sinyaw;+ }+ if (setpoint->mode.z == modeAbs) {+ setpoint->velocity.z = runPid(state->position.z, &this.pidZ, setpoint->position.z, DT);+ }++ velocityController(thrust, attitude, setpoint, state);+}++void velocityController(float* thrust, attitude_t *attitude, setpoint_t *setpoint,+ const state_t *state)+{+ this.pidVX.pid.outputLimit = rpLimit * rpLimitOverhead;+ this.pidVY.pid.outputLimit = rpLimit * rpLimitOverhead;+ // Set the output limit to the maximum thrust range+ this.pidVZ.pid.outputLimit = (UINT16_MAX / 2 / thrustScale);+ //this.pidVZ.pid.outputLimit = (this.thrustBase - this.thrustMin) / thrustScale;++ // Roll and Pitch+ float rollRaw = runPid(state->velocity.x, &this.pidVX, setpoint->velocity.x, DT);+ float pitchRaw = runPid(state->velocity.y, &this.pidVY, setpoint->velocity.y, DT);++ float yawRad = state->attitude.yaw * (float)M_PI / 180;+ attitude->pitch = -(rollRaw * cosf(yawRad)) - (pitchRaw * sinf(yawRad));+ attitude->roll = -(pitchRaw * cosf(yawRad)) + (rollRaw * sinf(yawRad));++ attitude->roll = constrain(attitude->roll, -rpLimit, rpLimit);+ attitude->pitch = constrain(attitude->pitch, -rpLimit, rpLimit);++ // Thrust+ float thrustRaw = runPid(state->velocity.z, &this.pidVZ, setpoint->velocity.z, DT);+ // Scale the thrust and add feed forward term+ *thrust = thrustRaw*thrustScale + this.thrustBase;+ // Check for minimum thrust+ if (*thrust < this.thrustMin) {+ *thrust = this.thrustMin;+ }+}++void positionControllerResetAllPID()+{+ pidReset(&this.pidX.pid);+ pidReset(&this.pidY.pid);+ pidReset(&this.pidZ.pid);+ pidReset(&this.pidVX.pid);+ pidReset(&this.pidVY.pid);+ pidReset(&this.pidVZ.pid);+}++LOG_GROUP_START(posCtl)++LOG_ADD(LOG_FLOAT, targetVX, &this.pidVX.pid.desired)+LOG_ADD(LOG_FLOAT, targetVY, &this.pidVY.pid.desired)+LOG_ADD(LOG_FLOAT, targetVZ, &this.pidVZ.pid.desired)++LOG_ADD(LOG_FLOAT, targetX, &this.pidX.pid.desired)+LOG_ADD(LOG_FLOAT, targetY, &this.pidY.pid.desired)+LOG_ADD(LOG_FLOAT, targetZ, &this.pidZ.pid.desired)++LOG_ADD(LOG_FLOAT, Xp, &this.pidX.pid.outP)+LOG_ADD(LOG_FLOAT, Xi, &this.pidX.pid.outI)+LOG_ADD(LOG_FLOAT, Xd, &this.pidX.pid.outD)++LOG_ADD(LOG_FLOAT, Yp, &this.pidY.pid.outP)+LOG_ADD(LOG_FLOAT, Yi, &this.pidY.pid.outI)+LOG_ADD(LOG_FLOAT, Yd, &this.pidY.pid.outD)++LOG_ADD(LOG_FLOAT, Zp, &this.pidZ.pid.outP)+LOG_ADD(LOG_FLOAT, Zi, &this.pidZ.pid.outI)+LOG_ADD(LOG_FLOAT, Zd, &this.pidZ.pid.outD)++LOG_ADD(LOG_FLOAT, VXp, &this.pidVX.pid.outP)+LOG_ADD(LOG_FLOAT, VXi, &this.pidVX.pid.outI)+LOG_ADD(LOG_FLOAT, VXd, &this.pidVX.pid.outD)++LOG_ADD(LOG_FLOAT, VZp, &this.pidVZ.pid.outP)+LOG_ADD(LOG_FLOAT, VZi, &this.pidVZ.pid.outI)+LOG_ADD(LOG_FLOAT, VZd, &this.pidVZ.pid.outD)++LOG_GROUP_STOP(posCtl)++PARAM_GROUP_START(velCtlPid)++PARAM_ADD(PARAM_FLOAT, vxKp, &this.pidVX.pid.kp)+PARAM_ADD(PARAM_FLOAT, vxKi, &this.pidVX.pid.ki)+PARAM_ADD(PARAM_FLOAT, vxKd, &this.pidVX.pid.kd)++PARAM_ADD(PARAM_FLOAT, vyKp, &this.pidVY.pid.kp)+PARAM_ADD(PARAM_FLOAT, vyKi, &this.pidVY.pid.ki)+PARAM_ADD(PARAM_FLOAT, vyKd, &this.pidVY.pid.kd)++PARAM_ADD(PARAM_FLOAT, vzKp, &this.pidVZ.pid.kp)+PARAM_ADD(PARAM_FLOAT, vzKi, &this.pidVZ.pid.ki)+PARAM_ADD(PARAM_FLOAT, vzKd, &this.pidVZ.pid.kd)++PARAM_GROUP_STOP(velCtlPid)++PARAM_GROUP_START(posCtlPid)++PARAM_ADD(PARAM_FLOAT, xKp, &this.pidX.pid.kp)+PARAM_ADD(PARAM_FLOAT, xKi, &this.pidX.pid.ki)+PARAM_ADD(PARAM_FLOAT, xKd, &this.pidX.pid.kd)++PARAM_ADD(PARAM_FLOAT, yKp, &this.pidY.pid.kp)+PARAM_ADD(PARAM_FLOAT, yKi, &this.pidY.pid.ki)+PARAM_ADD(PARAM_FLOAT, yKd, &this.pidY.pid.kd)++PARAM_ADD(PARAM_FLOAT, zKp, &this.pidZ.pid.kp)+PARAM_ADD(PARAM_FLOAT, zKi, &this.pidZ.pid.ki)+PARAM_ADD(PARAM_FLOAT, zKd, &this.pidZ.pid.kd)++PARAM_ADD(PARAM_UINT16, thrustBase, &this.thrustBase)+PARAM_ADD(PARAM_UINT16, thrustMin, &this.thrustMin)++PARAM_ADD(PARAM_FLOAT, rpLimit, &rpLimit)+PARAM_ADD(PARAM_FLOAT, xyVelMax, &xyVelMax)+PARAM_ADD(PARAM_FLOAT, zVelMax, &zVelMax)++PARAM_GROUP_STOP(posCtlPid)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/position_estimator_altitude.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/position_estimator_altitude.cnew file mode 100644index 0000000..ae73df9--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/position_estimator_altitude.c@@ -0,0 +1,131 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * position_estimator_altitude.c: Altitude-only position estimator+ */++#include "stm32_legacy.h"+#include "FreeRTOS.h"+#include "task.h"++#include "log.h"+#include "param.h"+#include "num.h"+#include "position_estimator.h"++#define G 9.81f;++struct selfState_s {+ float estimatedZ; // The current Z estimate, has same offset as asl+ float velocityZ; // Vertical speed (world frame) integrated from vertical acceleration (m/s)+ float estAlphaZrange;+ float estAlphaAsl;+ float velocityFactor;+ float vAccDeadband; // Vertical acceleration deadband+ float velZAlpha; // Blending factor to avoid vertical speed to accumulate error+ float estimatedVZ;+};++static struct selfState_s state = {+ .estimatedZ = 0.0f,+ .velocityZ = 0.0f,+ .estAlphaZrange = 0.90f,+ .estAlphaAsl = 0.997f,+ .velocityFactor = 1.0f,+ .vAccDeadband = 0.04f,+ .velZAlpha = 0.995f,+ .estimatedVZ = 0.0f,+};++static void positionEstimateInternal(state_t* estimate, const sensorData_t* sensorData, const tofMeasurement_t* tofMeasurement, float dt, uint32_t tick, struct selfState_s* state);+static void positionUpdateVelocityInternal(float accWZ, float dt, struct selfState_s* state);++void positionEstimate(state_t* estimate, const sensorData_t* sensorData, const tofMeasurement_t* tofMeasurement, float dt, uint32_t tick) {+ positionEstimateInternal(estimate, sensorData, tofMeasurement, dt, tick, &state);+}++void positionUpdateVelocity(float accWZ, float dt) {+ positionUpdateVelocityInternal(accWZ, dt, &state);+}++static void positionEstimateInternal(state_t* estimate, const sensorData_t* sensorData, const tofMeasurement_t* tofMeasurement, float dt, uint32_t tick, struct selfState_s* state) {+ float filteredZ;+ static float prev_estimatedZ = 0;+ static bool surfaceFollowingMode = false;++ const uint32_t MAX_SAMPLE_AGE = M2T(50);++ uint32_t now = xTaskGetTickCount();+ bool isSampleUseful = ((now - tofMeasurement->timestamp) <= MAX_SAMPLE_AGE);++ if (isSampleUseful) {+ surfaceFollowingMode = true;+ }++ if (surfaceFollowingMode) {+ if (isSampleUseful) {+ // IIR filter zrange+ filteredZ = (state->estAlphaZrange ) * state->estimatedZ ++ (1.0f - state->estAlphaZrange) * tofMeasurement->distance;+ // Use zrange as base and add velocity changes.+ state->estimatedZ = filteredZ + (state->velocityFactor * state->velocityZ * dt);+ }+ } else {+ // FIXME: A bit of an hack to init IIR filter+ if (state->estimatedZ == 0.0f) {+ filteredZ = sensorData->baro.asl;+ } else {+ // IIR filter asl+ filteredZ = (state->estAlphaAsl ) * state->estimatedZ ++ (1.0f - state->estAlphaAsl) * sensorData->baro.asl;+ }+ // Use asl as base and add velocity changes.+ state->estimatedZ = filteredZ + (state->velocityFactor * state->velocityZ * dt);+ }++ estimate->position.x = 0.0f;+ estimate->position.y = 0.0f;+ estimate->position.z = state->estimatedZ;+ estimate->velocity.z = (state->estimatedZ - prev_estimatedZ) / dt;+ state->estimatedVZ = estimate->velocity.z;+ prev_estimatedZ = state->estimatedZ;+}++static void positionUpdateVelocityInternal(float accWZ, float dt, struct selfState_s* state) {+ state->velocityZ += deadband(accWZ, state->vAccDeadband) * dt * G;+ state->velocityZ *= state->velZAlpha;+}++LOG_GROUP_START(posEstAlt)+LOG_ADD(LOG_FLOAT, estimatedZ, &state.estimatedZ)+LOG_ADD(LOG_FLOAT, estVZ, &state.estimatedVZ)+LOG_ADD(LOG_FLOAT, velocityZ, &state.velocityZ)+LOG_GROUP_STOP(posEstAlt)++PARAM_GROUP_START(posEstAlt)+PARAM_ADD(PARAM_FLOAT, estAlphaAsl, &state.estAlphaAsl)+PARAM_ADD(PARAM_FLOAT, estAlphaZr, &state.estAlphaZrange)+PARAM_ADD(PARAM_FLOAT, velFactor, &state.velocityFactor)+PARAM_ADD(PARAM_FLOAT, velZAlpha, &state.velZAlpha)+PARAM_ADD(PARAM_FLOAT, vAccDeadband, &state.vAccDeadband)+PARAM_GROUP_STOP(posEstAlt)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/power_distribution_stock.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/power_distribution_stock.cnew file mode 100644index 0000000..59e4354--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/power_distribution_stock.c@@ -0,0 +1,152 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * power_distribution_stock.c - Crazyflie stock power distribution code+ */++#include <string.h>++#include "power_distribution.h"++#include <string.h>+#include "log.h"+#include "param.h"+#include "num.h"+#include "platform.h"+#include "motors.h"+#define DEBUG_MODULE "PWR_DIST"+#include "debug_cf.h"++static bool motorSetEnable = false;++static struct {+ uint32_t m1;+ uint32_t m2;+ uint32_t m3;+ uint32_t m4;+} motorPower;++static struct {+ uint16_t m1;+ uint16_t m2;+ uint16_t m3;+ uint16_t m4;+} motorPowerSet;++#ifndef DEFAULT_IDLE_THRUST+#define DEFAULT_IDLE_THRUST 0+#endif++static uint32_t idleThrust = DEFAULT_IDLE_THRUST;++void powerDistributionInit(void)+{+ motorsInit(platformConfigGetMotorMapping());+}++bool powerDistributionTest(void)+{+ bool pass = true;++ pass &= motorsTest();++ return pass;+}++#define limitThrust(VAL) limitUint16(VAL)++void powerStop()+{+ motorsSetRatio(MOTOR_M1, 0);+ motorsSetRatio(MOTOR_M2, 0);+ motorsSetRatio(MOTOR_M3, 0);+ motorsSetRatio(MOTOR_M4, 0);+}++void powerDistribution(const control_t *control)+{+ #ifdef QUAD_FORMATION_X+ int16_t r = control->roll / 2.0f;+ int16_t p = control->pitch / 2.0f;+ motorPower.m1 = limitThrust(control->thrust - r + p + control->yaw);+ motorPower.m2 = limitThrust(control->thrust - r - p - control->yaw);+ motorPower.m3 = limitThrust(control->thrust + r - p + control->yaw);+ motorPower.m4 = limitThrust(control->thrust + r + p - control->yaw);+ #else // QUAD_FORMATION_NORMAL+ motorPower.m1 = limitThrust(control->thrust + control->pitch ++ control->yaw);+ motorPower.m2 = limitThrust(control->thrust - control->roll -+ control->yaw);+ motorPower.m3 = limitThrust(control->thrust - control->pitch ++ control->yaw);+ motorPower.m4 = limitThrust(control->thrust + control->roll -+ control->yaw);+ #endif++ if (motorSetEnable)+ {+ motorsSetRatio(MOTOR_M1, motorPowerSet.m1);+ motorsSetRatio(MOTOR_M2, motorPowerSet.m2);+ motorsSetRatio(MOTOR_M3, motorPowerSet.m3);+ motorsSetRatio(MOTOR_M4, motorPowerSet.m4);+ }+ else+ {+ if (motorPower.m1 < idleThrust) {+ motorPower.m1 = idleThrust;+ }+ if (motorPower.m2 < idleThrust) {+ motorPower.m2 = idleThrust;+ }+ if (motorPower.m3 < idleThrust) {+ motorPower.m3 = idleThrust;+ }+ if (motorPower.m4 < idleThrust) {+ motorPower.m4 = idleThrust;+ }++ motorsSetRatio(MOTOR_M1, motorPower.m1);+ motorsSetRatio(MOTOR_M2, motorPower.m2);+ motorsSetRatio(MOTOR_M3, motorPower.m3);+ motorsSetRatio(MOTOR_M4, motorPower.m4);+ }+}++PARAM_GROUP_START(motorPowerSet)+PARAM_ADD(PARAM_UINT8, enable, &motorSetEnable)+PARAM_ADD(PARAM_UINT16, m1, &motorPowerSet.m1)+PARAM_ADD(PARAM_UINT16, m2, &motorPowerSet.m2)+PARAM_ADD(PARAM_UINT16, m3, &motorPowerSet.m3)+PARAM_ADD(PARAM_UINT16, m4, &motorPowerSet.m4)+PARAM_GROUP_STOP(motorPowerSet)++PARAM_GROUP_START(powerDist)+PARAM_ADD(PARAM_UINT32, idleThrust, &idleThrust)+PARAM_GROUP_STOP(powerDist)++LOG_GROUP_START(motor)+LOG_ADD(LOG_UINT32, m1, &motorPower.m1)+LOG_ADD(LOG_UINT32, m2, &motorPower.m2)+LOG_ADD(LOG_UINT32, m3, &motorPower.m3)+LOG_ADD(LOG_UINT32, m4, &motorPower.m4)+LOG_GROUP_STOP(motor)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/pptraj.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/pptraj.cnew file mode 100644index 0000000..d24dc2f--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/pptraj.c@@ -0,0 +1,425 @@+/*+ * ______+ * / ____/________ _____ __ ________ ______ __________ ___+ * / / / ___/ __ `/_ / / / / / ___/ | /| / / __ `/ ___/ __ `__ \+ * / /___/ / / /_/ / / /_/ /_/ (__ )| |/ |/ / /_/ / / / / / / / /+ * \____/_/ \__,_/ /___/\__, /____/ |__/|__/\__,_/_/ /_/ /_/ /_/+ * /____/+ *+ * Crazyswarm advanced control firmware for Crazyflie+ *++The MIT License (MIT)++Copyright (c) 2018 Wolfgang Hoenig and James Alan Preiss++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.+*/++/*+implementation of piecewise polynomial trajectories+See Daniel Mellinger, Vijay Kumar: "Minimum snap trajectory generation and control for quadrotors". ICRA 2011: 2520-2525+*/++#include "pptraj.h"++#define GRAV (9.81f)++static struct poly4d poly4d_tmp;++// polynomials are stored with ascending degree++void polylinear(float p[PP_SIZE], float duration, float x0, float x1)+{+ p[0] = x0;+ p[1] = (x1 - x0) / duration;+ for (int i = 2; i < PP_SIZE; ++i) {+ p[i] = 0;+ }+}++// precalculated factorials that we will need+static const int facs[PP_SIZE] = { 1, 1, 2, 6, 24, 120, 720, 5040 };++void polybezier(float p[PP_SIZE], float duration, float* x, int dim) {+ int i, j, n, sign;+ float coeff;++ if (dim <= 0) {+ /* nothing to do */+ } else if (dim == 1) {+ p[0] = x[0];+ } else if (dim == 2) {+ polylinear(p, duration, x[0], x[1]);+ } else {+ n = ((dim < PP_SIZE) ? dim : PP_SIZE) - 1;+ sign = 1;+ for (j = 0; j <= n; j++) {+ coeff = 0;+ sign = (j % 2) ? -1 : 1;+ for (i = 0; i <= j; i++, sign *= -1) {+ coeff += sign * x[i] / facs[i] / facs[j-i];+ }+ p[j] = coeff * facs[n] / facs[n-j];+ }+ polystretchtime(p, duration);+ }+}++void polyscale(float p[PP_SIZE], float s)+{+ for (int i = 0; i < PP_SIZE; ++i) {+ p[i] *= s;+ }+}++// e.g. if s==2 the new polynomial will be stretched to take 2x longer+void polystretchtime(float p[PP_SIZE], float s)+{+ float recip = 1.0f / s;+ float scale = recip;+ for (int i = 1; i < PP_SIZE; ++i) {+ p[i] *= scale;+ scale *= recip;+ }+}++void polyreflect(float p[PP_SIZE])+{+ for (int i = 1; i < PP_SIZE; i += 2) {+ p[i] = -p[i];+ }+}++// evaluate a polynomial using horner's rule.+float polyval(float const p[PP_SIZE], float t)+{+ float x = 0.0;+ for (int i = PP_DEGREE; i >= 0; --i) {+ x = x * t + p[i];+ }+ return x;+}++// compute derivative of a polynomial in place+void polyder(float p[PP_SIZE])+{+ for (int i = 1; i <= PP_DEGREE; ++i) {+ p[i-1] = i * p[i];+ }+ p[PP_DEGREE] = 0;+}++void poly5(float poly[PP_SIZE], float T,+ float x0, float dx0, float ddx0,+ float xf, float dxf, float ddxf)+{+ float T2 = T * T;+ float T3 = T2 * T;+ float T4 = T3 * T;+ float T5 = T4 * T;+ poly[0] = x0;+ poly[1] = dx0;+ poly[2] = ddx0 / 2;+ poly[3] = (-12*dx0*T - 8*dxf*T - 3*ddx0*T2 + ddxf*T2 - 20*x0 + 20*xf)/(2*T3);+ poly[4] = (16*dx0*T + 14*dxf*T + 3*ddx0*T2 - 2*ddxf*T2 + 30*x0 - 30*xf)/(2*T4);+ poly[5] = (-6*dx0*T - 6*dxf*T - ddx0*T2 + ddxf*T2 - 12*x0 + 12*xf)/(2*T5);+ for (int i = 6; i < PP_SIZE; ++i) {+ poly[i] = 0;+ }+}++static void poly7_nojerk(float poly[PP_SIZE], float T,+ float x0, float dx0, float ddx0,+ float xf, float dxf, float ddxf)+{+ if (T <= 0.0f) {+ poly[0] = xf;+ poly[1] = dxf;+ poly[2] = ddxf/2;+ for (int i = 3; i < PP_SIZE; ++i) {+ poly[i] = 0;+ }+ } else {+ float T2 = T * T;+ float T3 = T2 * T;+ float T4 = T3 * T;+ float T5 = T4 * T;+ float T6 = T5 * T;+ float T7 = T6 * T;+ poly[0] = x0;+ poly[1] = dx0;+ poly[2] = ddx0/2;+ poly[3] = 0;+ poly[4] = -(5*(14*x0 - 14*xf + 8*T*dx0 + 6*T*dxf + 2*T2*ddx0 - T2*ddxf))/(2*T4);+ poly[5] = (84*x0 - 84*xf + 45*T*dx0 + 39*T*dxf + 10*T2*ddx0 - 7*T2*ddxf)/T5;+ poly[6] = -(140*x0 - 140*xf + 72*T*dx0 + 68*T*dxf + 15*T2*ddx0 - 13*T2*ddxf)/(2*T6);+ poly[7] = (2*(10*x0 - 10*xf + 5*T*dx0 + 5*T*dxf + T2*ddx0 - T2*ddxf))/T7;+ for (int i = 8; i < PP_SIZE; ++i) {+ poly[i] = 0;+ }+ }+}+++//+// 4d single-piece polynomials+//++// construct a 4d zero polynomial.+struct poly4d poly4d_zero(float duration)+{+ struct poly4d p = {+ .p = {{0}},+ .duration = duration,+ };+ return p;+}++struct poly4d poly4d_linear(float duration, struct vec p0, struct vec p1, float yaw0, float yaw1)+{+ struct poly4d p;+ p.duration = duration;+ polylinear(p.p[0], duration, p0.x, p1.x);+ polylinear(p.p[1], duration, p0.y, p1.y);+ polylinear(p.p[2], duration, p0.z, p1.z);+ polylinear(p.p[3], duration, yaw0, yaw1);+ return p;+}++void poly4d_scale(struct poly4d *p, float x, float y, float z, float yaw)+{+ polyscale(p->p[0], x);+ polyscale(p->p[1], y);+ polyscale(p->p[2], z);+ polyscale(p->p[3], yaw);+}++void poly4d_shift(struct poly4d *p, float x, float y, float z, float yaw)+{+ p->p[0][0] += x;+ p->p[1][0] += y;+ p->p[2][0] += z;+ p->p[3][0] += yaw;+}++void poly4d_stretchtime(struct poly4d *p, float s)+{+ for (int i = 0; i < 4; ++i) {+ polystretchtime(p->p[i], s);+ }+ p->duration *= s;+}++void polyder4d(struct poly4d *p)+{+ for (int i = 0; i < 4; ++i) {+ polyder(p->p[i]);+ }+}++static struct vec polyval_xyz(struct poly4d const *p, float t)+{+ return mkvec(polyval(p->p[0], t), polyval(p->p[1], t), polyval(p->p[2], t));+}++static float polyval_yaw(struct poly4d const *p, float t)+{+ return polyval(p->p[3], t);+}++// compute loose maximum of acceleration -+// uses L1 norm instead of Euclidean, evaluates polynomial instead of root-finding+float poly4d_max_accel_approx(struct poly4d const *p)+{+ struct poly4d* acc = &poly4d_tmp;+ *acc = *p;+ polyder4d(acc);+ polyder4d(acc);+ int steps = 10 * p->duration;+ float step = p->duration / (steps - 1);+ float t = 0;+ float amax = 0;+ for (int i = 0; i < steps; ++i) {+ struct vec ddx = polyval_xyz(acc, t);+ float ddx_minkowski = vnorm1(ddx);+ if (ddx_minkowski > amax) amax = ddx_minkowski;+ t += step;+ }+ return amax;+}++struct traj_eval traj_eval_zero()+{+ struct traj_eval ev = {+ .pos = vzero(),+ .vel = vzero(),+ .acc = vzero(),+ .yaw = 0.0f,+ .omega = vzero(),+ };+ return ev;+}++struct traj_eval traj_eval_invalid()+{+ struct traj_eval ev;+ ev.pos = vrepeat(NAN);+ return ev;+}++bool is_traj_eval_valid(struct traj_eval const *ev)+{+ return !visnan(ev->pos);+}++struct traj_eval poly4d_eval(struct poly4d const *p, float t)+{+ // flat variables+ struct traj_eval out;+ out.pos = polyval_xyz(p, t);+ out.yaw = polyval_yaw(p, t);++ // 1st derivative+ struct poly4d* deriv = &poly4d_tmp;+ *deriv = *p;+ polyder4d(deriv);+ out.vel = polyval_xyz(deriv, t);+ float dyaw = polyval_yaw(deriv, t);++ // 2nd derivative+ polyder4d(deriv);+ out.acc = polyval_xyz(deriv, t);++ // 3rd derivative+ polyder4d(deriv);+ struct vec jerk = polyval_xyz(deriv, t);++ struct vec thrust = vadd(out.acc, mkvec(0, 0, GRAV));+ // float thrust_mag = mass * vmag(thrust);++ struct vec z_body = vnormalize(thrust);+ struct vec x_world = mkvec(cosf(out.yaw), sinf(out.yaw), 0);+ struct vec y_body = vnormalize(vcross(z_body, x_world));+ struct vec x_body = vcross(y_body, z_body);++ struct vec jerk_orth_zbody = vorthunit(jerk, z_body);+ struct vec h_w = vscl(1.0f / vmag(thrust), jerk_orth_zbody);++ out.omega.x = -vdot(h_w, y_body);+ out.omega.y = vdot(h_w, x_body);+ out.omega.z = z_body.z * dyaw;++ return out;+}++//+// piecewise 4d polynomials+//++// piecewise eval+struct traj_eval piecewise_eval(+ struct piecewise_traj const *traj, float t)+{+ int cursor = 0;+ t = t - traj->t_begin;+ while (cursor < traj->n_pieces) {+ struct poly4d const *piece = &(traj->pieces[cursor]);+ if (t <= piece->duration * traj->timescale) {+ poly4d_tmp = *piece;+ poly4d_shift(&poly4d_tmp, traj->shift.x, traj->shift.y, traj->shift.z, 0);+ poly4d_stretchtime(&poly4d_tmp, traj->timescale);+ return poly4d_eval(&poly4d_tmp, t);+ }+ t -= piece->duration * traj->timescale;+ ++cursor;+ }+ // if we get here, the trajectory has ended+ struct poly4d const *end_piece = &(traj->pieces[traj->n_pieces - 1]);+ struct traj_eval ev = poly4d_eval(end_piece, end_piece->duration);+ ev.pos = vadd(ev.pos, traj->shift);+ ev.vel = vzero();+ ev.acc = vzero();+ ev.omega = vzero();+ return ev;+}++struct traj_eval piecewise_eval_reversed(+ struct piecewise_traj const *traj, float t)+{+ int cursor = traj->n_pieces - 1;+ t = t - traj->t_begin;+ while (cursor >= 0) {+ struct poly4d const *piece = &(traj->pieces[cursor]);+ if (t <= piece->duration * traj->timescale) {+ poly4d_tmp = *piece;+ poly4d_shift(&poly4d_tmp, traj->shift.x, traj->shift.y, traj->shift.z, 0);+ poly4d_stretchtime(&poly4d_tmp, traj->timescale);+ for (int i = 0; i < 4; ++i) {+ polyreflect(poly4d_tmp.p[i]);+ }+ t = t - piece->duration * traj->timescale;+ return poly4d_eval(&poly4d_tmp, t);+ }+ t -= piece->duration * traj->timescale;+ --cursor;+ }+ // if we get here, the trajectory has ended+ struct poly4d const *end_piece = &(traj->pieces[0]);+ struct traj_eval ev = poly4d_eval(end_piece, 0.0f);+ ev.pos = vadd(ev.pos, traj->shift);+ ev.vel = vzero();+ ev.acc = vzero();+ ev.omega = vzero();+ return ev;+}+++// y, dy == yaw, derivative of yaw+void piecewise_plan_5th_order(struct piecewise_traj *pp, float duration,+ struct vec p0, float y0, struct vec v0, float dy0, struct vec a0,+ struct vec p1, float y1, struct vec v1, float dy1, struct vec a1)+{+ struct poly4d *p = &pp->pieces[0];+ p->duration = duration;+ pp->timescale = 1.0;+ pp->shift = vzero();+ pp->n_pieces = 1;+ poly5(p->p[0], duration, p0.x, v0.x, a0.x, p1.x, v1.x, a1.x);+ poly5(p->p[1], duration, p0.y, v0.y, a0.y, p1.y, v1.y, a1.y);+ poly5(p->p[2], duration, p0.z, v0.z, a0.z, p1.z, v1.z, a1.z);+ poly5(p->p[3], duration, y0, dy0, 0, y1, dy1, 0);+}++// y, dy == yaw, derivative of yaw+void piecewise_plan_7th_order_no_jerk(struct piecewise_traj *pp, float duration,+ struct vec p0, float y0, struct vec v0, float dy0, struct vec a0,+ struct vec p1, float y1, struct vec v1, float dy1, struct vec a1)+{+ struct poly4d *p = &pp->pieces[0];+ p->duration = duration;+ pp->timescale = 1.0;+ pp->shift = vzero();+ pp->n_pieces = 1;+ poly7_nojerk(p->p[0], duration, p0.x, v0.x, a0.x, p1.x, v1.x, a1.x);+ poly7_nojerk(p->p[1], duration, p0.y, v0.y, a0.y, p1.y, v1.y, a1.y);+ poly7_nojerk(p->p[2], duration, p0.z, v0.z, a0.z, p1.z, v1.z, a1.z);+ poly7_nojerk(p->p[3], duration, y0, dy0, 0, y1, dy1, 0);+}+diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/pptraj_compressed.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/pptraj_compressed.cnew file mode 100644index 0000000..899d8d5--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/pptraj_compressed.c@@ -0,0 +1,298 @@+/*+ * _____ ______ ___ __ ___ __ __ _+ * / ___/__ / / / |/ /__ / /_ / _ \___ / / ___ / /_(_)______+ * / /__/ _ \/ / / /|_/ / _ \/ __/ / , _/ _ \/ _ \/ _ \/ __/ / __(_-<+ * \___/\___/_/_/_/ /_/\___/\__/ /_/|_|\___/_.__/\___/\__/_/\__/___/+ *+ * Compressed piecewise polynomial trajectories for Crazyflie.+ *+ * Copyright (c) 2019 CollMot Robotics. All rights reserved.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * pptraj_compressed.c - Implementation of compressed piecewise polynomial+ * trajectories+ */++#include <stdint.h>+#include <string.h>++#include "pptraj_compressed.h"++// In the stored version, we store durations in milliseconds, hence this factor+#define STORED_DURATION_SCALE 1000.0++// In the stored version, we store distances in millimeters, hence this factor+#define STORED_DISTANCE_SCALE 1000.0++// In the stored version, we store angles in 1/10th degrees, hence this factor+#define STORED_ANGLE_SCALE 0.1++// Numbers of control points that we store for each storage method. Note that+// we always store one less than the degree because the first control point of+// each piece is the same as the last control point of the previous piece.+static const uint8_t control_points_by_type[] = { 0, 1, 3, 7 };++typedef int16_t compressed_piece_coordinate;+typedef const uint8_t* compressed_piece_ptr;++struct compressed_piece_parsed_header+{+ uint16_t duration_in_msec;++ enum piecewise_traj_storage_type x_type;+ enum piecewise_traj_storage_type y_type;+ enum piecewise_traj_storage_type z_type;+ enum piecewise_traj_storage_type yaw_type;++ compressed_piece_ptr body;+};++static float calculate_total_duration(compressed_piece_ptr ptr);+static compressed_piece_ptr next_coordinate(compressed_piece_ptr ptr, compressed_piece_coordinate* coord);+static compressed_piece_ptr next_duration(compressed_piece_ptr ptr, uint16_t* coord);+static compressed_piece_ptr next_piece(compressed_piece_ptr ptr);+static compressed_piece_ptr parse_header_of_current_piece(+ struct compressed_piece_parsed_header* result, compressed_piece_ptr ptr);++static inline float end_time_of_current_piece(const struct piecewise_traj_compressed *traj);+static inline float start_time_of_current_piece(const struct piecewise_traj_compressed *traj);+static inline float time_relative_to_start_of_current_piece(const struct piecewise_traj_compressed *traj, float t);++static void piecewise_compressed_advance_playhead(struct piecewise_traj_compressed *traj);+static void piecewise_compressed_rewind(struct piecewise_traj_compressed *traj);+static void piecewise_compressed_update_current_poly4d(+ struct piecewise_traj_compressed *traj, const struct traj_eval *end_of_previous_piece);++// Calculates the coefficients of a 7D polynomial from the compressed+// representation starting at the given pointer. Returns a pointer that+// points to _after_ the part that has been processed.+static compressed_piece_ptr calculate_polynomial_coefficients(+ float *result, compressed_piece_ptr ptr,+ enum piecewise_traj_storage_type storage_type,+ float initial_condition, float duration, float scale)+{+ compressed_piece_coordinate value;+ float control_points[PP_SIZE];+ uint8_t i, n;++ n = control_points_by_type[storage_type] + 1;++ control_points[0] = initial_condition;+ for (i = 1; i < n; i++) {+ ptr = next_coordinate(ptr, &value);+ control_points[i] = value / scale;+ }++ polybezier(result, duration, control_points, n);++ return ptr;+}++// Calculates the total duration of a compressed trajectory, starting at the+// given piece+static float calculate_total_duration(compressed_piece_ptr ptr)+{+ uint32_t duration_in_msec = 0;+ struct compressed_piece_parsed_header header;++ while (1) {+ ptr = parse_header_of_current_piece(&header, ptr);+ if (ptr) {+ duration_in_msec += header.duration_in_msec;+ } else {+ return duration_in_msec / STORED_DURATION_SCALE;+ }+ }+}++// Returns the end time of the current piece being executed+static inline float end_time_of_current_piece(const struct piecewise_traj_compressed *traj) {+ return start_time_of_current_piece(traj) + traj->current_piece.poly4d.duration;+}++// Parses the two bytes pointed to by the given pointer as a signed 16-bit+// integer, in little endian order, and returns the pointer advanced by two+// bytes+static compressed_piece_ptr next_coordinate(compressed_piece_ptr ptr, compressed_piece_coordinate* coord) {+ *coord = ptr[0] + (ptr[1] << 8);+ return ptr + 2;+}++// Parses the two bytes pointed to by the given pointer as an unsigned 16-bit+// integer, in little endian order, and returns the pointer advanced by two+// bytes+static compressed_piece_ptr next_duration(compressed_piece_ptr ptr, uint16_t* coord) {+ *coord = ptr[0] + (ptr[1] << 8);+ return ptr + 2;+}++// Given a pointer that points to the start of a piece inside the data section+// of a compressed trajectory, returns the pointer that points to the next+// piece or zero if this is the last piece+static compressed_piece_ptr next_piece(compressed_piece_ptr ptr)+{+ struct compressed_piece_parsed_header header;+ return parse_header_of_current_piece(&header, ptr);+}++// Given a pointer that points to the start of a piece inside the data section+// of a compressed trajeectory, parses the header of the piece, which includes+// the duration of the piece as well as the storage types of the XY, Z and+// yaw coordinates. Returns a pointer that points to the next piece or 0 if+// this was the last piece.+static compressed_piece_ptr parse_header_of_current_piece(+ struct compressed_piece_parsed_header* result, compressed_piece_ptr ptr)+{+ uint8_t header;+ int length;++ if (!ptr) {+ result->x_type = result->y_type = result->z_type = result->yaw_type = PPTRAJ_STORAGE_CONSTANT;+ result->body = 0;+ result->duration_in_msec = 0;+ return 0;+ }++ header = *ptr;++ result->x_type = (enum piecewise_traj_storage_type) (header & 0x03);+ result->y_type = (enum piecewise_traj_storage_type) ((header >> 2) & 0x03);+ result->z_type = (enum piecewise_traj_storage_type) ((header >> 4) & 0x03);+ result->yaw_type = (enum piecewise_traj_storage_type) ((header >> 6) & 0x03);+ ptr++;++ result->body = ptr = next_duration(ptr, &result->duration_in_msec);++ if (result->duration_in_msec > 0) {+ length = (+ control_points_by_type[result->x_type] ++ control_points_by_type[result->y_type] ++ control_points_by_type[result->z_type] ++ control_points_by_type[result->yaw_type]+ ) * sizeof(compressed_piece_coordinate);+ return ptr + length;+ } else {+ return 0;+ }+}++// Returns the start time of the current piece being executed+static inline float start_time_of_current_piece(const struct piecewise_traj_compressed *traj) {+ return traj->t_begin + traj->current_piece.t_begin_relative;+}++// Returns the number of seconds elapsed since the start time of the current+// piece being executed+static inline float time_relative_to_start_of_current_piece(const struct piecewise_traj_compressed *traj, float t) {+ return t - start_time_of_current_piece(traj);+}++/* ************************************************************************ */++struct traj_eval piecewise_compressed_eval(+ struct piecewise_traj_compressed *traj, float t)+{+ struct traj_eval eval;++ /* TODO(ntamas): timescale is currently limited to 1.+ * We could support other timescales, but then we would need to update+ * piecewise_compressed_update_current_poly4d() to stretch the time of+ * the poly4d. The problem is that the user may set the timescale to+ * a different value while the poly4d is already pre-calculated, and we+ * have no way of detecting it */++ if (t < start_time_of_current_piece(traj)) {+ piecewise_compressed_rewind(traj);+ }++ while (traj->current_piece.data && t >= end_time_of_current_piece(traj)) {+ piecewise_compressed_advance_playhead(traj);+ }++ t = time_relative_to_start_of_current_piece(traj, t);++ eval = poly4d_eval(&traj->current_piece.poly4d, t);+ eval.pos = vadd(eval.pos, traj->shift);++ return eval;+}++void piecewise_compressed_load(struct piecewise_traj_compressed *traj, const void* data)+{+ traj->t_begin = 0;+ traj->timescale = 1;++ traj->data = data;+ traj->shift = vzero();+ piecewise_compressed_rewind(traj);++ traj->duration = calculate_total_duration(traj->current_piece.data);+}++static void piecewise_compressed_rewind(struct piecewise_traj_compressed *traj)+{+ struct traj_eval stopped;+ compressed_piece_coordinate value;+ compressed_piece_ptr ptr;++ /* Parse header that stores the start coordinates */+ bzero(&stopped, sizeof(stopped));+ ptr = traj->data;+ ptr = next_coordinate(ptr, &value); stopped.pos.x = value / STORED_DISTANCE_SCALE;+ ptr = next_coordinate(ptr, &value); stopped.pos.y = value / STORED_DISTANCE_SCALE;+ ptr = next_coordinate(ptr, &value); stopped.pos.z = value / STORED_DISTANCE_SCALE;+ ptr = next_coordinate(ptr, &value); stopped.yaw = value / STORED_ANGLE_SCALE;+ traj->current_piece.t_begin_relative = 0;+ traj->current_piece.data = ptr;++ piecewise_compressed_update_current_poly4d(traj, &stopped);+}++static void piecewise_compressed_update_current_poly4d(+ struct piecewise_traj_compressed *traj, const struct traj_eval *prev_end)+{+ struct poly4d* poly4d = &traj->current_piece.poly4d;+ compressed_piece_ptr ptr;+ struct compressed_piece_parsed_header header;++ /* First, clear everything in the poly4d */+ bzero(poly4d, sizeof(*poly4d));++ /* Parse the header of the current piece, extract the storage types and the duration */+ ptr = traj->current_piece.data;+ parse_header_of_current_piece(&header, ptr);+ poly4d->duration = header.duration_in_msec / STORED_DURATION_SCALE;++ /* Process the body */+ ptr = header.body;+ ptr = calculate_polynomial_coefficients(+ poly4d->p[0], ptr, header.x_type, prev_end->pos.x, poly4d->duration, STORED_DISTANCE_SCALE);+ ptr = calculate_polynomial_coefficients(+ poly4d->p[1], ptr, header.y_type, prev_end->pos.y, poly4d->duration, STORED_DISTANCE_SCALE);+ ptr = calculate_polynomial_coefficients(+ poly4d->p[2], ptr, header.z_type, prev_end->pos.z, poly4d->duration, STORED_DISTANCE_SCALE);+ calculate_polynomial_coefficients(+ poly4d->p[3], ptr, header.yaw_type, prev_end->yaw, poly4d->duration, STORED_ANGLE_SCALE);+}++static void piecewise_compressed_advance_playhead(struct piecewise_traj_compressed *traj)+{+ float duration = traj->current_piece.poly4d.duration;+ struct traj_eval end_of_previous_piece = poly4d_eval(&traj->current_piece.poly4d, duration);++ traj->current_piece.t_begin_relative += duration;+ traj->current_piece.data = next_piece(traj->current_piece.data);++ piecewise_compressed_update_current_poly4d(traj, &end_of_previous_piece);+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/queuemonitor.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/queuemonitor.cnew file mode 100644index 0000000..34c1a43--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/queuemonitor.c@@ -0,0 +1,174 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * queuemonitor.c - Monitoring functionality for queues+ */+#define DEBUG_MODULE "QM"++#include "queuemonitor.h"++#ifdef DEBUG_QUEUE_MONITOR++#include <stdbool.h>+#include "timers.h"+#include "debug_cf.h"+#include "cfassert.h"++#define MAX_NR_OF_QUEUES 20+#define TIMER_PERIOD M2T(10000)++#define RESET_COUNTERS_AFTER_DISPLAY true+#define DISPLAY_ONLY_OVERFLOW_QUEUES true++typedef struct+{+ char* fileName;+ char* queueName;+ int sendCount;+ int maxWaiting;+ int fullCount;+} Data;++static Data data[MAX_NR_OF_QUEUES];++static xTimerHandle timer;+static StaticTimer_t timerBuffer;+static unsigned char nrOfQueues = 1; // Unregistered queues will end up at 0+static bool initialized = false;++static void timerHandler(xTimerHandle timer);+static void debugPrint();+static bool filter(Data* queueData);+static void debugPrintQueue(Data* queueData);+static Data* getQueueData(xQueueHandle* xQueue);+static int getMaxWaiting(xQueueHandle* xQueue, int prevPeak);+static void resetCounters();++unsigned char ucQueueGetQueueNumber( xQueueHandle xQueue );+++void queueMonitorInit() {+ ASSERT(!initialized);+ timer = xTimerCreateStatic( "queueMonitorTimer", TIMER_PERIOD,+ pdTRUE, NULL, timerHandler, &timerBuffer);+ xTimerStart(timer, 100);++ data[0].fileName = "Na";+ data[0].queueName = "Na";++ initialized = true;+}++void qm_traceQUEUE_SEND(void* xQueue) {+ if(initialized) {+ Data* queueData = getQueueData(xQueue);++ queueData->sendCount++;+ queueData->maxWaiting = getMaxWaiting(xQueue, queueData->maxWaiting);+ }+}++void qm_traceQUEUE_SEND_FAILED(void* xQueue) {+ if(initialized) {+ Data* queueData = getQueueData(xQueue);++ queueData->fullCount++;+ }+}++void qmRegisterQueue(xQueueHandle* xQueue, char* fileName, char* queueName) {+ ASSERT(initialized);+ ASSERT(nrOfQueues < MAX_NR_OF_QUEUES);+ Data* queueData = &data[nrOfQueues];++ queueData->fileName = fileName;+ queueData->queueName = queueName;+ vQueueSetQueueNumber(xQueue, nrOfQueues);++ nrOfQueues++;+}++static Data* getQueueData(xQueueHandle* xQueue) {+ unsigned char number = uxQueueGetQueueNumber(xQueue);+ ASSERT(number < MAX_NR_OF_QUEUES);+ return &data[number];+}++static int getMaxWaiting(xQueueHandle* xQueue, int prevPeak) {+ // We get here before the current item is added to the queue.+ // Must add 1 to get the peak value.+ unsigned portBASE_TYPE waiting = uxQueueMessagesWaitingFromISR(xQueue) + 1;++ if (waiting > prevPeak) {+ return waiting;+ }+ return prevPeak;+}++static void debugPrint() {+ int i = 0;+ for (i = 0; i < nrOfQueues; i++) {+ Data* queueData = &data[i];+ if (filter(queueData)) {+ debugPrintQueue(queueData);+ }+ }++ if (RESET_COUNTERS_AFTER_DISPLAY) {+ resetCounters();+ }+}++static bool filter(Data* queueData) {+ bool doDisplay = false;+ if (DISPLAY_ONLY_OVERFLOW_QUEUES) {+ doDisplay = (queueData->fullCount != 0);+ } else {+ doDisplay = true;+ }+ return doDisplay;+}++static void debugPrintQueue(Data* queueData) {+ DEBUG_PRINT("%s:%s, sent: %i, peak: %i, full: %i\n",+ queueData->fileName, queueData->queueName, queueData->sendCount,+ queueData->maxWaiting, queueData->fullCount);+}++static void resetCounters() {+ int i = 0;+ for (i = 0; i < nrOfQueues; i++) {+ Data* queueData = &data[i];++ queueData->sendCount = 0;+ queueData->maxWaiting = 0;+ queueData->fullCount = 0;+ }+}++static void timerHandler(xTimerHandle timer) {+ debugPrint();+}++#endif // DEBUG_QUEUE_MONITORdiff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/range.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/range.cnew file mode 100644index 0000000..775158c--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/range.c@@ -0,0 +1,67 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2018 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * ranges.c: Centralize range measurements for different directions+ * and make them available as log+ */+#include <stdint.h>++#include "log.h"++#include "range.h"+#include "stabilizer_types.h"+#include "estimator.h"++static uint16_t ranges[RANGE_T_END] = {0,};++void rangeSet(rangeDirection_t direction, float range_m)+{+ if (direction > (RANGE_T_END-1)) return;++ ranges[direction] = range_m * 1000;+}++float rangeGet(rangeDirection_t direction)+{+ if (direction > (RANGE_T_END-1)) return 0;++ return ranges[direction];+}++bool rangeEnqueueDownRangeInEstimator(float distance, float stdDev, uint32_t timeStamp) {+ tofMeasurement_t tofData;+ tofData.timestamp = timeStamp;+ tofData.distance = distance;+ tofData.stdDev = stdDev;++ return estimatorEnqueueTOF(&tofData);+}++LOG_GROUP_START(range)+LOG_ADD(LOG_UINT16, front, &ranges[rangeFront])+LOG_ADD(LOG_UINT16, back, &ranges[rangeBack])+LOG_ADD(LOG_UINT16, up, &ranges[rangeUp])+LOG_ADD(LOG_UINT16, left, &ranges[rangeLeft])+LOG_ADD(LOG_UINT16, right, &ranges[rangeRight])+LOG_ADD(LOG_UINT16, zrange, &ranges[rangeDown])+LOG_GROUP_STOP(range)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/sensfusion6.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/sensfusion6.cnew file mode 100644index 0000000..f512bca--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/sensfusion6.c@@ -0,0 +1,338 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */+#include <math.h>++#include "sensfusion6.h"+#include "log.h"+#include "param.h"+#include "physicalConstants.h"++//#define MADWICK_QUATERNION_IMU++#ifdef MADWICK_QUATERNION_IMU+ #define BETA_DEF 0.01f // 2 * proportional gain+#else // MAHONY_QUATERNION_IMU+ #define TWO_KP_DEF (2.0f * 0.4f) // 2 * proportional gain+ #define TWO_KI_DEF (2.0f * 0.001f) // 2 * integral gain+#endif++#ifdef MADWICK_QUATERNION_IMU+ float beta = BETA_DEF; // 2 * proportional gain (Kp)+#else // MAHONY_QUATERNION_IMU+ float twoKp = TWO_KP_DEF; // 2 * proportional gain (Kp)+ float twoKi = TWO_KI_DEF; // 2 * integral gain (Ki)+ float integralFBx = 0.0f;+ float integralFBy = 0.0f;+ float integralFBz = 0.0f; // integral error terms scaled by Ki+#endif++float qw = 1.0f;+float qx = 0.0f;+float qy = 0.0f;+float qz = 0.0f; // quaternion of sensor frame relative to auxiliary frame++static float gravX, gravY, gravZ; // Unit vector in the estimated gravity direction++// The acc in Z for static position (g)+// Set on first update, assuming we are in a static position since the sensors were just calibrates.+// This value will be better the more level the copter is at calibration time+static float baseZacc = 1.0;++static bool isInit;++static bool isCalibrated = false;++static void sensfusion6UpdateQImpl(float gx, float gy, float gz, float ax, float ay, float az, float dt);+static float sensfusion6GetAccZ(const float ax, const float ay, const float az);+static void estimatedGravityDirection(float* gx, float* gy, float* gz);++// TODO: Make math util file+static float invSqrt(float x);++void sensfusion6Init()+{+ if(isInit)+ return;++ isInit = true;+}++bool sensfusion6Test(void)+{+ return isInit;+}++void sensfusion6UpdateQ(float gx, float gy, float gz, float ax, float ay, float az, float dt)+{+ sensfusion6UpdateQImpl(gx, gy, gz, ax, ay, az, dt);+ estimatedGravityDirection(&gravX, &gravY, &gravZ);++ if (!isCalibrated) {+ baseZacc = sensfusion6GetAccZ(ax, ay, az);+ isCalibrated = true;+ }+}++#ifdef MADWICK_QUATERNION_IMU+// Implementation of Madgwick's IMU and AHRS algorithms.+// See: http://www.x-io.co.uk/open-source-ahrs-with-x-imu+//+// Date Author Notes+// 29/09/2011 SOH Madgwick Initial release+// 02/10/2011 SOH Madgwick Optimised for reduced CPU load+static void sensfusion6UpdateQImpl(float gx, float gy, float gz, float ax, float ay, float az, float dt)+{+ float recipNorm;+ float s0, s1, s2, s3;+ float qDot1, qDot2, qDot3, qDot4;+ float _2qw, _2qx, _2qy, _2qz, _4qw, _4qx, _4qy ,_8qx, _8qy, qwqw, qxqx, qyqy, qzqz;++ // Rate of change of quaternion from gyroscope+ qDot1 = 0.5f * (-qx * gx - qy * gy - qz * gz);+ qDot2 = 0.5f * (qw * gx + qy * gz - qz * gy);+ qDot3 = 0.5f * (qw * gy - qx * gz + qz * gx);+ qDot4 = 0.5f * (qw * gz + qx * gy - qy * gx);++ // Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation)+ if(!((ax == 0.0f) && (ay == 0.0f) && (az == 0.0f)))+ {+ // Normalise accelerometer measurement+ recipNorm = invSqrt(ax * ax + ay * ay + az * az);+ ax *= recipNorm;+ ay *= recipNorm;+ az *= recipNorm;++ // Auxiliary variables to avoid repeated arithmetic+ _2qw = 2.0f * qw;+ _2qx = 2.0f * qx;+ _2qy = 2.0f * qy;+ _2qz = 2.0f * qz;+ _4qw = 4.0f * qw;+ _4qx = 4.0f * qx;+ _4qy = 4.0f * qy;+ _8qx = 8.0f * qx;+ _8qy = 8.0f * qy;+ qwqw = qw * qw;+ qxqx = qx * qx;+ qyqy = qy * qy;+ qzqz = qz * qz;++ // Gradient decent algorithm corrective step+ s0 = _4qw * qyqy + _2qy * ax + _4qw * qxqx - _2qx * ay;+ s1 = _4qx * qzqz - _2qz * ax + 4.0f * qwqw * qx - _2qw * ay - _4qx + _8qx * qxqx + _8qx * qyqy + _4qx * az;+ s2 = 4.0f * qwqw * qy + _2qw * ax + _4qy * qzqz - _2qz * ay - _4qy + _8qy * qxqx + _8qy * qyqy + _4qy * az;+ s3 = 4.0f * qxqx * qz - _2qx * ax + 4.0f * qyqy * qz - _2qy * ay;+ recipNorm = invSqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3); // normalise step magnitude+ s0 *= recipNorm;+ s1 *= recipNorm;+ s2 *= recipNorm;+ s3 *= recipNorm;++ // Apply feedback step+ qDot1 -= beta * s0;+ qDot2 -= beta * s1;+ qDot3 -= beta * s2;+ qDot4 -= beta * s3;+ }++ // Integrate rate of change of quaternion to yield quaternion+ qw += qDot1 * dt;+ qx += qDot2 * dt;+ qy += qDot3 * dt;+ qz += qDot4 * dt;++ // Normalise quaternion+ recipNorm = invSqrt(qw*qw + qx*qx + qy*qy + qz*qz);+ qw *= recipNorm;+ qx *= recipNorm;+ qy *= recipNorm;+ qz *= recipNorm;+}+#else // MAHONY_QUATERNION_IMU+// Madgwick's implementation of Mayhony's AHRS algorithm.+// See: http://www.x-io.co.uk/open-source-ahrs-with-x-imu+//+// Date Author Notes+// 29/09/2011 SOH Madgwick Initial release+// 02/10/2011 SOH Madgwick Optimised for reduced CPU load+static void sensfusion6UpdateQImpl(float gx, float gy, float gz, float ax, float ay, float az, float dt)+{+ float recipNorm;+ float halfvx, halfvy, halfvz;+ float halfex, halfey, halfez;+ float qa, qb, qc;++ gx = gx * M_PI_F / 180;+ gy = gy * M_PI_F / 180;+ gz = gz * M_PI_F / 180;++ // Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation)+ if(!((ax == 0.0f) && (ay == 0.0f) && (az == 0.0f)))+ {+ // Normalise accelerometer measurement+ recipNorm = invSqrt(ax * ax + ay * ay + az * az);+ ax *= recipNorm;+ ay *= recipNorm;+ az *= recipNorm;++ // Estimated direction of gravity and vector perpendicular to magnetic flux+ halfvx = qx * qz - qw * qy;+ halfvy = qw * qx + qy * qz;+ halfvz = qw * qw - 0.5f + qz * qz;++ // Error is sum of cross product between estimated and measured direction of gravity+ halfex = (ay * halfvz - az * halfvy);+ halfey = (az * halfvx - ax * halfvz);+ halfez = (ax * halfvy - ay * halfvx);++ // Compute and apply integral feedback if enabled+ if(twoKi > 0.0f)+ {+ integralFBx += twoKi * halfex * dt; // integral error scaled by Ki+ integralFBy += twoKi * halfey * dt;+ integralFBz += twoKi * halfez * dt;+ gx += integralFBx; // apply integral feedback+ gy += integralFBy;+ gz += integralFBz;+ }+ else+ {+ integralFBx = 0.0f; // prevent integral windup+ integralFBy = 0.0f;+ integralFBz = 0.0f;+ }++ // Apply proportional feedback+ gx += twoKp * halfex;+ gy += twoKp * halfey;+ gz += twoKp * halfez;+ }++ // Integrate rate of change of quaternion+ gx *= (0.5f * dt); // pre-multiply common factors+ gy *= (0.5f * dt);+ gz *= (0.5f * dt);+ qa = qw;+ qb = qx;+ qc = qy;+ qw += (-qb * gx - qc * gy - qz * gz);+ qx += (qa * gx + qc * gz - qz * gy);+ qy += (qa * gy - qb * gz + qz * gx);+ qz += (qa * gz + qb * gy - qc * gx);++ // Normalise quaternion+ recipNorm = invSqrt(qw * qw + qx * qx + qy * qy + qz * qz);+ qw *= recipNorm;+ qx *= recipNorm;+ qy *= recipNorm;+ qz *= recipNorm;+}+#endif++void sensfusion6GetQuaternion(float* q_x, float* q_y, float* q_z, float* q_w)+{+ *q_x = qx;+ *q_y = qy;+ *q_z = qz;+ *q_w = qw;+}++void sensfusion6GetEulerRPY(float* roll, float* pitch, float* yaw)+{+ float gx = gravX;+ float gy = gravY;+ float gz = gravZ;++ if (gx>1) gx=1;+ if (gx<-1) gx=-1;++ *yaw = atan2f(2*(qw*qz + qx*qy), qw*qw + qx*qx - qy*qy - qz*qz) * 180 / M_PI_F;+ *pitch = asinf(gx) * 180 / M_PI_F; //Pitch seems to be inverted+ *roll = atan2f(gy, gz) * 180 / M_PI_F;+}++float sensfusion6GetAccZWithoutGravity(const float ax, const float ay, const float az)+{+ return sensfusion6GetAccZ(ax, ay, az) - baseZacc;+}++float sensfusion6GetInvThrustCompensationForTilt()+{+ // Return the z component of the estimated gravity direction+ // (0, 0, 1) dot G+ return gravZ;+}++//---------------------------------------------------------------------------------------------------+// Fast inverse square-root+// See: http://en.wikipedia.org/wiki/Fast_inverse_square_root+float invSqrt(float x)+{+ float halfx = 0.5f * x;+ float y = x;+ long i = *(long*)&y;+ i = 0x5f3759df - (i>>1);+ y = *(float*)&i;+ y = y * (1.5f - (halfx * y * y));+ return y;+}++static float sensfusion6GetAccZ(const float ax, const float ay, const float az)+{+ // return vertical acceleration+ // (A dot G) / |G|, (|G| = 1) -> (A dot G)+ return (ax * gravX + ay * gravY + az * gravZ);+}++static void estimatedGravityDirection(float* gx, float* gy, float* gz)+{+ *gx = 2 * (qx * qz - qw * qy);+ *gy = 2 * (qw * qx + qy * qz);+ *gz = qw * qw - qx * qx - qy * qy + qz * qz;+}++LOG_GROUP_START(sensfusion6)+ LOG_ADD(LOG_FLOAT, qw, &qw)+ LOG_ADD(LOG_FLOAT, qx, &qx)+ LOG_ADD(LOG_FLOAT, qy, &qy)+ LOG_ADD(LOG_FLOAT, qz, &qz)+ LOG_ADD(LOG_FLOAT, gravityX, &gravX)+ LOG_ADD(LOG_FLOAT, gravityY, &gravY)+ LOG_ADD(LOG_FLOAT, gravityZ, &gravZ)+ LOG_ADD(LOG_FLOAT, accZbase, &baseZacc)+ LOG_ADD(LOG_UINT8, isInit, &isInit)+ LOG_ADD(LOG_UINT8, isCalibrated, &isCalibrated)+LOG_GROUP_STOP(sensfusion6)++PARAM_GROUP_START(sensfusion6)+#ifdef MADWICK_QUATERNION_IMU+PARAM_ADD(PARAM_FLOAT, beta, &beta)+#else // MAHONY_QUATERNION_IMU+PARAM_ADD(PARAM_FLOAT, kp, &twoKp)+PARAM_ADD(PARAM_FLOAT, ki, &twoKi)+#endif+PARAM_ADD(PARAM_FLOAT, baseZacc, &baseZacc)+PARAM_GROUP_STOP(sensfusion6)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/sitaw.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/sitaw.cnew file mode 100644index 0000000..4f76f18--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/sitaw.c@@ -0,0 +1,347 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2015 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sitAw.h - Implementation of situation awareness.+ */++#include <stddef.h>+#include <stdlib.h>+#include <math.h>++#include "log.h"+#include "param.h"+#include "trigger.h"+#include "sitaw.h"+#include "commander.h"+#include "stabilizer.h"+#include "motors.h"++/* Trigger object used to detect Free Fall situation. */+static trigger_t sitAwFFAccWZ;++/* Trigger object used to detect At Rest situation. */+static trigger_t sitAwARAccZ;++/* Trigger object used to detect Tumbled situation. */+static trigger_t sitAwTuAcc;++#if defined(SITAW_ENABLED)++#if defined(SITAW_LOG_ENABLED) /* Enable the log group. */+LOG_GROUP_START(sitAw)+#if defined(SITAW_FF_LOG_ENABLED) /* Log trigger variables for Free Fall detection. */+LOG_ADD(LOG_UINT32, FFAccWZTestCounter, &sitAwFFAccWZ.testCounter)+LOG_ADD(LOG_UINT8, FFAccWZDetected, &sitAwFFAccWZ.released)+#endif+#if defined(SITAW_AR_LOG_ENABLED) /* Log trigger variables for At Rest detection. */+LOG_ADD(LOG_UINT32, ARTestCounter, &sitAwARAccZ.testCounter)+LOG_ADD(LOG_UINT8, ARDetected, &sitAwARAccZ.released)+#endif+#if defined(SITAW_TU_LOG_ENABLED) /* Log trigger variables for Tumbled detection. */+LOG_ADD(LOG_UINT32, TuTestCounter, &sitAwTuAcc.testCounter)+LOG_ADD(LOG_UINT8, TuDetected, &sitAwTuAcc.released)+#endif+#if defined(SITAW_LOG_ALL_DETECT_ENABLED) /* Log all the 'Detected' flags. */+LOG_ADD(LOG_UINT8, FFAccWZDetected, &sitAwFFAccWZ.released)+LOG_ADD(LOG_UINT8, ARDetected, &sitAwARAccZ.released)+LOG_ADD(LOG_UINT8, TuDetected, &sitAwTuAcc.released)+#endif+LOG_GROUP_STOP(sitAw)+#endif /* SITAW_LOG_ENABLED */++#if defined(SITAW_PARAM_ENABLED) /* Enable the param group. */+PARAM_GROUP_START(sitAw)+#if defined(SITAW_FF_PARAM_ENABLED) /* Param variables for Free Fall detection. */+PARAM_ADD(PARAM_UINT8, FFActive, &sitAwFFAccWZ.active)+PARAM_ADD(PARAM_UINT32, FFTriggerCount, &sitAwFFAccWZ.triggerCount)+PARAM_ADD(PARAM_FLOAT, FFaccWZ, &sitAwFFAccWZ.threshold)+#endif+#if defined(SITAW_AR_PARAM_ENABLED) /* Param variables for At Rest detection. */+PARAM_ADD(PARAM_UINT8, ARActive, &sitAwARAccZ.active)+PARAM_ADD(PARAM_UINT32, ARTriggerCount, &sitAwARAccZ.triggerCount)+PARAM_ADD(PARAM_FLOAT, ARaccZ, &sitAwARAccZ.threshold)+#endif+#if defined(SITAW_TU_PARAM_ENABLED) /* Param variables for Tumbled detection. */+PARAM_ADD(PARAM_UINT8, TuActive, &sitAwTuAcc.active)+PARAM_ADD(PARAM_UINT32, TuTriggerCount, &sitAwTuAcc.triggerCount)+PARAM_ADD(PARAM_FLOAT, TuAcc, &sitAwTuAcc.threshold)+#endif+PARAM_GROUP_STOP(sitAw)+#endif /* SITAW_PARAM_ENABLED */++#endif /* SITAW_ENABLED */++// forward declaration of private functions+#ifdef SITAW_FF_ENABLED+static void sitAwFFTest(float accWZ, float accMag);+#endif+#ifdef SITAW_AR_ENABLED+static void sitAwARTest(float accX, float accY, float accZ);+#endif+#ifdef SITAW_TU_ENABLED+static void sitAwTuTest(float accz);+#endif++static void sitAwPostStateUpdateCallOut(const sensorData_t *sensorData,+ const state_t *state)+{+ /* Code that shall run AFTER each attitude update, should be placed here. */++#if defined(SITAW_ENABLED)+#ifdef SITAW_FF_ENABLED+ float accMAG = (sensorData->acc.x*sensorData->acc.x) ++ (sensorData->acc.y*sensorData->acc.y) ++ (sensorData->acc.z*sensorData->acc.z);++ /* Test values for Free Fall detection. */+ sitAwFFTest(state->acc.z, accMAG);+#endif+#ifdef SITAW_TU_ENABLED+ /* check if we actually fly */+ int sumRatio = 0;+ for (int i = 0; i < NBR_OF_MOTORS; ++i) {+ sumRatio += motorsGetRatio(i);+ }+ bool isFlying = sumRatio > SITAW_TU_IN_FLIGHT_THRESHOLD;+ if (isFlying) {+ /* Test values for Tumbled detection. */+ sitAwTuTest(sensorData->acc.z);+ }+#endif+#ifdef SITAW_AR_ENABLED+/* Test values for At Rest detection. */+ sitAwARTest(sensorData->acc.x, sensorData->acc.y, sensorData->acc.z);+#endif+#endif+}++static void sitAwPreThrustUpdateCallOut(setpoint_t *setpoint)+{+ /* Code that shall run BEFORE each thrust distribution update, should be placed here. */++#if defined(SITAW_ENABLED)+#ifdef SITAW_TU_ENABLED+ if(sitAwTuDetected()) {+ /* Kill the thrust to the motors if a Tumbled situation is detected. */+ stabilizerSetEmergencyStop();+ }+#endif++#ifdef SITAW_FF_ENABLED+ /* Force altHold mode if free fall is detected.+ FIXME: Needs a flying/landing state (as soon as althold is enabled,+ we are not freefalling anymore)+ */+ if(sitAwFFDetected() && !sitAwTuDetected()) {+ setpoint->mode.z = modeVelocity;+ setpoint->velocity.z = 0;+ }+#endif+#endif+}++/**+ * Update setpoint according to current situation+ *+ * Called by the stabilizer after state and setpoint update. This function+ * should update the setpoint accordig to the current state situation+ */+void sitAwUpdateSetpoint(setpoint_t *setpoint, const sensorData_t *sensorData,+ const state_t *state)+{+ sitAwPostStateUpdateCallOut(sensorData, state);+ sitAwPreThrustUpdateCallOut(setpoint);+}++#ifdef SITAW_FF_ENABLED+/**+ * Initialize the Free Fall detection.+ *+ * See the sitAwFFTest() function for details.+ */+void sitAwFFInit(void)+{+ triggerInit(&sitAwFFAccWZ, triggerFuncIsLE, SITAW_FF_THRESHOLD, SITAW_FF_TRIGGER_COUNT);+ triggerActivate(&sitAwFFAccWZ, true);+}++/**+ * Test values for a Free Fall situation.+ *+ * A free fall situation is considered identified when the vertical+ * acceleration of the crazyflie (regardless of orientation - given by+ * AccWZ) is approaching -1 (AccWZ is 0 when crazyflie is at rest). We+ * will look for when AccWZ is within SITAW_FF_THRESHOLD of -1.+ *+ * At the same time, there should be no other accelerations experienced+ * by the crazyflie.++ * This can be checked by looking at the accMAG (total acceleration). If+ * the accMAG is approaching 0, there are no other accelerations than accWZ.+ * This helps to distinguish free fall situations from other movements+ * such as shaking.+ *+ * @param accWZ Vertical acceleration (regardless of orientation)+ * @param accMAG All experienced accelerations.+ */+void sitAwFFTest(float accWZ, float accMAG)+{+ /* Check that the total acceleration is close to zero. */+ if(fabs(accMAG) > SITAW_FF_THRESHOLD) {+ /* If the total acceleration deviates from 0, this is not a free fall situation. */+ triggerReset(&sitAwFFAccWZ);+ } else {++ /**+ * AccWZ approaches -1 in free fall. Check that the value stays within+ * SITAW_FF_THRESHOLD of -1 for the triggerCount specified.+ */+ triggerTestValue(&sitAwFFAccWZ, fabs(accWZ + 1));+ }+}++/**+ * Check if a Free Fall situation has been detected.+ *+ * @return True if the situation has been detected, otherwise false.+ */+bool sitAwFFDetected(void)+{+ return sitAwFFAccWZ.released;+}+#endif++#ifdef SITAW_AR_ENABLED+/**+ * Initialize the At Rest detection.+ *+ * See the sitAwARTest() function for details.+ */+void sitAwARInit(void)+{+ triggerInit(&sitAwARAccZ, triggerFuncIsLE, SITAW_AR_THRESHOLD, SITAW_AR_TRIGGER_COUNT);+ triggerActivate(&sitAwARAccZ, true);+}++/**+ * Test values for an At Rest situation.+ *+ * An At Rest situation is considered identified when the crazyflie is+ * placed on its feet (accZ = 1) and with no horizontal accelerations+ * (accX = accY = 0).+ *+ * Since there is always some minor noise in the measurements, we use+ * a margin of SITAW_AR_THRESHOLD from the ideal values. Since this function+ * does not check for thrust, the SITAW_AR_THRESHOLD is assumed to be set+ * sufficiently close to the absolute resting values so that these values cannot+ * be achieved (over time) during hovering or flight.+ *+ * @param accX Horizontal X acceleration (when crazyflie is placed on its feet)+ * @param accY Horizontal Y acceleration (when crazyflie is placed on its feet)+ * @param accZ Vertical Z acceleration (when crazyflie is placed on its feet)+ */+void sitAwARTest(float accX, float accY, float accZ)+{+ /* Check that there are no horizontal accelerations. At rest, these are 0. */+ if((fabs(accX) > SITAW_AR_THRESHOLD) || (fabs(accY) > SITAW_AR_THRESHOLD)) {+ /* If the X or Y accelerations are different than 0, the crazyflie is not at rest. */+ triggerReset(&sitAwARAccZ);+ }++ /**+ * If the test above indicates that there are no horizontal movements, test the+ * vertical acceleration value against the trigger.+ *+ * The vertical acceleration must be close to 1, but is allowed to oscillate slightly+ * around 1. Testing that the deviation from 1 stays within SITAW_AR_THRESHOLD.+ */+ triggerTestValue(&sitAwARAccZ, fabs(accZ - 1));+}++/**+ * Check if an At Rest situation has been detected.+ *+ * @return True if the situation has been detected, otherwise false.+ */+bool sitAwARDetected(void)+{+ return sitAwARAccZ.released;+}+#endif++#ifdef SITAW_TU_ENABLED+/**+ * Initialize the Tumbled detection.+ *+ * See the sitAwTuTest() function for details.+ */+void sitAwTuInit(void)+{+ triggerInit(&sitAwTuAcc, triggerFuncIsLE, SITAW_TU_ACC_THRESHOLD, SITAW_TU_ACC_TRIGGER_COUNT);+ triggerActivate(&sitAwTuAcc, true);+}++/**+ * Test values for a Tumbled situation.+ *+ * A tumbled situation is considered identified when accelerometer reports+ * a negative value.+ *+ * Once a tumbled situation is identified, this can be used for instance to+ * cut the thrust to the motors, avoiding the crazyflie from running+ * propellers at significant thrust when accidentally crashing into walls+ * or the ground.++ * @param The current accelerometer reading in z direction+ */+void sitAwTuTest(float accz)+{+ triggerTestValue(&sitAwTuAcc, accz);+}++/**+ * Check if a Tumbled situation has been detected.+ *+ * @return True if the situation has been detected, otherwise false.+ */+bool sitAwTuDetected(void)+{+ return sitAwTuAcc.released;+}+#endif++/**+ * Initialize the situation awareness subsystem.+ */+void sitAwInit(void)+{+#ifdef SITAW_FF_ENABLED+ sitAwFFInit();+#endif+#ifdef SITAW_AR_ENABLED+ sitAwARInit();+#endif+#ifdef SITAW_TU_ENABLED+ sitAwTuInit();+#endif+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/sound_cf2.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/sound_cf2.cnew file mode 100644index 0000000..d97ac81--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/sound_cf2.c@@ -0,0 +1,376 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2015 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sound_cf2.c - Module used to play melodies and system sounds though a buzzer+ */++#include <stdbool.h>++/* FreeRtos includes */+#include <stdint.h>+#include <string.h>+#include <stdlib.h>++#include "FreeRTOS.h"+#include "timers.h"++#include "config.h"+#include "param.h"+#include "log.h"+#include "sound.h"+#include "buzzer.h"+#include "stm32_legacy.h"+#include "sdkconfig.h"++/**+ * Credit to http://tny.cz/e525c1b2 for supplying the tones+ */+#define OFF 0+#define C0 16+#define Db0 17+#define D0 18+#define Eb0 19+#define E0 20+#define F0 21+#define Gb0 23+#define G0 24+#define Ab0 25+#define A0 27+#define Bb0 29+#define B0 30+#define C1 32+#define Db1 34+#define D1 36+#define Eb1 38+#define E1 41+#define F1 43+#define Gb1 46+#define G1 49+#define Ab1 51+#define A1 55+#define Bb1 58+#define B1 61+#define C2 65+#define Db2 69+#define D2 73+#define Eb2 77+#define E2 82+#define F2 87+#define Gb2 92+#define G2 98+#define Ab2 103+#define A2 110+#define Bb2 116+#define B2 123+#define C3 130+#define Db3 138+#define D3 146+#define Eb3 155+#define E3 164+#define F3 174+#define Gb3 185+#define G3 196+#define Ab3 207+#define A3 220+#define Bb3 233+#define B3 246+#define C4 261+#define Db4 277+#define D4 293+#define Eb4 311+#define E4 329+#define F4 349+#define Gb4 369+#define G4 392+#define Ab4 415+#define A4 440+#define Bb4 466+#define B4 493+#define C5 523+#define Db5 554+#define D5 587+#define Eb5 622+#define E5 659+#define F5 698+#define Gb5 739+#define G5 783+#define Ab5 830+#define A5 880+#define Bb5 932+#define B5 987+#define C6 1046+#define Db6 1108+#define D6 1174+#define Eb6 1244+#define E6 1318+#define F6 1396+#define Gb6 1479+#define G6 1567+#define Ab6 1661+#define A6 1760+#define Bb6 1864+#define B6 1975+#define C7 2093+#define Db7 2217+#define D7 2349+#define Eb7 2489+#define E7 2637+#define F7 2793+#define Gb7 2959+#define G7 3135+#define Ab7 3322+#define A7 3520+#define Bb7 3729+#define B7 3951+#define C8 4186+#define Db8 4434+#define D8 4698+#define Eb8 4978+/* Duration of notes */+#define W 1 // 1/1+#define H 2 // 1/2+#define Q 4 // 1/4+#define E 8 // 1/8+#define S 16 // 1/16+#define ES 6+/* End markers */+#define STOP {0xFE, 0}+#define REPEAT {0xFF, 0}++#define MAX_NOTE_LENGTH 80++static bool isInit=false;++typedef const struct {+ uint16_t tone;+ uint16_t duration;+} Note;++typedef const struct {+ uint32_t bpm;+ uint32_t delay;+ Note notes[MAX_NOTE_LENGTH];+} Melody;++static uint32_t neffect = 0;+static uint32_t sys_effect = 0;+static uint32_t user_effect = 0;++static Melody range_slow = {.bpm = 120, .delay = 1, .notes = {{C4, H}, {D4, H}, {E4, H}, {F4, H}, {G4, H}, {A4, H}, {B4, H}, REPEAT}};+static Melody range_fast = {.bpm = 120, .delay = 1, .notes = {{C4, S}, {D4, S}, {E4, S}, {F4, S}, {G4, S}, {A4, S}, {B4, S}, REPEAT}};+static Melody startup = {.bpm = 120, .delay = 1, .notes = {{C6, S}, {C6, S}, STOP}};+static Melody calibrated = {.bpm = 120, .delay = 1, .notes = {{C4, S}, {E4, S}, {G4, S}, {C5, E}, STOP}};+static Melody chg_done = {.bpm = 120, .delay = 1, .notes = {{D4, Q}, {A4, Q}, STOP}};+static Melody lowbatt = {.bpm = 120, .delay = 1, .notes = {{D4, E}, {A4, E}, {D4, E}, REPEAT}};+static Melody usb_disconnect = {.bpm = 120, .delay = 1, .notes = {{C4, E}, STOP}};+static Melody usb_connect = {.bpm = 120, .delay = 1, .notes = {{A4, E}, STOP}};+static Melody factory_test = {.bpm = 120, .delay = 1, .notes = {{A1, Q}, {OFF, S}, {A2, Q}, {OFF, S}, REPEAT}};+static Melody starwars = {.bpm = 120, .delay = 1, .notes = {{A3, Q}, {A3, Q}, {A3, Q}, {F3, ES}, {C4, S},+ {A3, Q}, {F3, ES}, {C4, S}, {A3, H},+ {E4, Q}, {E4, Q}, {E4, Q}, {F4, ES}, {C4, S},+ {Ab3, Q}, {F3, ES}, {C4, S}, {A3, H},+ {A4, Q}, {A3, ES}, {A3, S}, {A4, Q}, {Ab4, ES}, {G4, S},+ {Gb4, S}, {E4, S}, {F4, E}, {0, E}, {Bb3, E}, {Eb4, Q}, {D4, ES}, {Db4, S},+ {C4, S}, {B3, S}, {C4, E}, {0, E}, {F3, E}, {Ab3, Q}, {F3, ES}, {A3, S},+ {C4, Q}, {A3, ES}, {C4, S}, {E4, H},+ {A4, Q}, {A3, ES}, {A3, S}, {A4, Q}, {Ab4, ES}, {G4, S},+ {Gb4, S}, {E4, S}, {F4, E}, {0, E}, {Bb3, E}, {Eb4, Q}, {D4, ES}, {Db4, S},+ {Gb4, S}, {E4, S}, {F4, E}, {0, E}, {Bb3, E}, {Eb4, Q}, {D4, ES}, {Db4, S},+ {C4,S}, {B3, S}, {C4, E}, {0, E}, {F3, E}, {Ab3, Q}, {F3, ES}, {C4, S},+ {A3, Q}, {F3, ES}, {C4, S}, {A3, H}, {0, H},+ REPEAT}};+static Melody valkyries = {.bpm = 140, .delay = 1, .notes = {{Gb3, Q}, {B3, Q},+ {Gb3, S}, {B3, E}, {D4, Q}, {B3, Q}, {D4, Q}, {B3, S}, {D4, E}, {Gb4, Q},+ {D4, Q}, {Gb4, Q}, {D4, S}, {Gb4, E}, {A4, Q}, {A3, Q}, {D4, Q}, {A3, S},+ {D4, E}, {Gb4, H},+ REPEAT}};++typedef void (*BuzzerEffect)(uint32_t timer, uint32_t * mi, Melody * melody);++static void off(uint32_t counter, uint32_t * mi, Melody * m) {+ buzzerOff();+}++static void turnCurrentEffectOff() {+ if (sys_effect != 0) {+ sys_effect = 0;+ } else {+ user_effect = 0;+ }+}++static uint32_t mcounter = 0;+static void melodyplayer(uint32_t counter, uint32_t * mi, Melody * m) {+ uint16_t tone = m->notes[(*mi)].tone;+ uint16_t duration = m->notes[(*mi)].duration;++ if (mcounter == 0) {+ if (tone == 0xFE) {+ // Turn off buzzer since we're at the end+ (*mi) = 0;+ turnCurrentEffectOff();+ } else if (tone == 0xFF) {+ // Loop the melody+ (*mi) = 0;+ } else {+ // Play current note+ buzzerOn(tone);+ mcounter = (100 * 4 * 60) / (m->bpm * duration) - 1;+ (*mi)++;+ }+ } else {+ if (mcounter == 1) {+ buzzerOff();+ }+ mcounter--;+ }+}++static uint8_t static_ratio = 0;+static uint16_t static_freq = 4000;+static void bypass(uint32_t counter, uint32_t * mi, Melody * melody)+{+ buzzerOn(static_freq);+}++static uint16_t siren_start = 2000;+static uint16_t siren_freq = 2000;+static uint16_t siren_stop = 4000;+static int16_t siren_step = 40;+static void siren(uint32_t counter, uint32_t * mi, Melody * melody)+{+ siren_freq += siren_step;+ if (siren_freq > siren_stop) {+ siren_step *= -1;+ siren_freq = siren_stop;+ }+ if (siren_freq < siren_start) {+ siren_step *= -1;+ siren_freq = siren_start;+ }+ buzzerOn(siren_freq);+}++static int pitchid;+static int rollid;+static int pitch;+static int roll;+static int tilt_freq;+static int tilt_ratio;+static void tilt(uint32_t counter, uint32_t * mi, Melody * melody)+{+ pitchid = logGetVarId("stabilizer", "pitch");+ rollid = logGetVarId("stabilizer", "roll");++ pitch = logGetInt(pitchid);+ roll = logGetInt(rollid);+ tilt_freq = 0;+ tilt_ratio = 127;++ if (abs(pitch) > 5) {+ tilt_freq = 3000 - 50 * pitch;+ }++ buzzerOn(tilt_freq);+}++typedef struct {+ BuzzerEffect call;+ uint32_t mi;+ Melody * melody;+} EffectCall;++static EffectCall effects[] = {+ [SND_OFF] = {.call = &off},+ [FACTORY_TEST] = {.call = &melodyplayer, .melody = &factory_test},+ [SND_USB_CONN] = {.call = &melodyplayer, .melody = &usb_connect},+ [SND_USB_DISC] = {.call = &melodyplayer, .melody = &usb_disconnect},+ [SND_BAT_FULL] = {.call = &melodyplayer, .melody = &chg_done},+ [SND_BAT_LOW] = {.call = &melodyplayer, .melody = &lowbatt},+ [SND_STARTUP] = {.call = &melodyplayer, .melody = &startup},+ [SND_CALIB] = {.call = &melodyplayer, .melody = &calibrated},+ {.call = &melodyplayer, .melody = &range_slow},+ {.call = &melodyplayer, .melody = &range_fast},+ {.call = &melodyplayer, .melody = &starwars},+ {.call = &melodyplayer, .melody = &valkyries},+ {.call = &bypass},+ {.call = &siren},+ {.call = &tilt}+};++static xTimerHandle timer;+static StaticTimer_t timerBuffer;+static uint32_t counter = 0;++static void soundTimer(xTimerHandle timer)+{+ int effect;+ counter++;++ if (sys_effect != 0) {+ effect = sys_effect;+ } else {+ effect = user_effect;+ }++ if (effects[effect].call != 0) {+ effects[effect].call(counter * 10, &effects[effect].mi, effects[effect].melody);+ }+}++void soundInit(void)+{+#ifdef CONFIG_BUZZER_ON+ if (isInit) {+ return;+ }++ neffect = sizeof(effects) / sizeof(effects[0]) - 1;++ timer = xTimerCreateStatic("SoundTimer", M2T(10), pdTRUE, NULL, soundTimer, &timerBuffer);+ xTimerStart(timer, 100);++ isInit = true;+#endif+}++bool soundTest(void)+{+ return isInit;+}++void soundSetEffect(uint32_t effect)+{+ sys_effect = effect;+}++void soundSetFreq(uint32_t freq) {++}++PARAM_GROUP_START(sound)+PARAM_ADD(PARAM_UINT8, effect, &user_effect)+PARAM_ADD(PARAM_UINT32 | PARAM_RONLY, neffect, &neffect)+PARAM_ADD(PARAM_UINT16, freq, &static_freq)+PARAM_ADD(PARAM_UINT8, ratio, &static_ratio)+PARAM_GROUP_STOP(sound)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/stabilizer.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/stabilizer.cnew file mode 100644index 0000000..fe67fa3--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/stabilizer.c@@ -0,0 +1,707 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie Firmware+ *+ * Copyright (C) 2011-2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ */++#include <math.h>+#include <inttypes.h>++#include "FreeRTOS.h"+#include "task.h"++#include "stm32_legacy.h"+#include "system.h"+#include "log.h"+#include "param.h"+#include "motors.h"+#include "pm_esplane.h"+#include "esp_timer.h"+#include "stabilizer.h"+#include "sensors.h"+#include "commander.h"+#include "crtp_localization_service.h"+#include "sitaw.h"+#include "controller.h"+#include "power_distribution.h"+//#include "collision_avoidance.h"++#include "estimator.h"+//#include "usddeck.h" //usddeckLoggingMode_e+#include "quatcompress.h"+#include "statsCnt.h"+#define DEBUG_MODULE "STAB"+#include "debug_cf.h"+#include "static_mem.h"+#include "rateSupervisor.h"++static bool isInit;+static bool emergencyStop = false;+static int emergencyStopTimeout = EMERGENCY_STOP_TIMEOUT_DISABLED;++static bool checkStops;++#define PROPTEST_NBR_OF_VARIANCE_VALUES 100+static bool startPropTest = false;++uint32_t inToOutLatency;++// State variables for the stabilizer+static setpoint_t setpoint;+static sensorData_t sensorData;+static state_t state;+static control_t control;++static StateEstimatorType estimatorType;+static ControllerType controllerType;++typedef enum { configureAcc, measureNoiseFloor, measureProp, testBattery, restartBatTest, evaluateResult, testDone } TestState;+#ifdef RUN_PROP_TEST_AT_STARTUP+ static TestState testState = configureAcc;+#else+ static TestState testState = testDone;+#endif++static STATS_CNT_RATE_DEFINE(stabilizerRate, 500);+static rateSupervisor_t rateSupervisorContext;+static bool rateWarningDisplayed = false;++static struct {+ // position - mm+ int16_t x;+ int16_t y;+ int16_t z;+ // velocity - mm / sec+ int16_t vx;+ int16_t vy;+ int16_t vz;+ // acceleration - mm / sec^2+ int16_t ax;+ int16_t ay;+ int16_t az;+ // compressed quaternion, see quatcompress.h+ int32_t quat;+ // angular velocity - milliradians / sec+ int16_t rateRoll;+ int16_t ratePitch;+ int16_t rateYaw;+} stateCompressed;++static struct {+ // position - mm+ int16_t x;+ int16_t y;+ int16_t z;+ // velocity - mm / sec+ int16_t vx;+ int16_t vy;+ int16_t vz;+ // acceleration - mm / sec^2+ int16_t ax;+ int16_t ay;+ int16_t az;+} setpointCompressed;++static float accVarX[NBR_OF_MOTORS];+static float accVarY[NBR_OF_MOTORS];+static float accVarZ[NBR_OF_MOTORS];+// Bit field indicating if the motors passed the motor test.+// Bit 0 - 1 = M1 passed+// Bit 1 - 1 = M2 passed+// Bit 2 - 1 = M3 passed+// Bit 3 - 1 = M4 passed+static uint8_t motorPass = 0;+static uint16_t motorTestCount = 0;++STATIC_MEM_TASK_ALLOC(stabilizerTask, STABILIZER_TASK_STACKSIZE);++static void stabilizerTask(void* param);+static void testProps(sensorData_t *sensors);++static void calcSensorToOutputLatency(const sensorData_t *sensorData)+{+ uint64_t outTimestamp = usecTimestamp();+ inToOutLatency = outTimestamp - sensorData->interruptTimestamp;+}++static void compressState()+{+ stateCompressed.x = state.position.x * 1000.0f;+ stateCompressed.y = state.position.y * 1000.0f;+ stateCompressed.z = state.position.z * 1000.0f;++ stateCompressed.vx = state.velocity.x * 1000.0f;+ stateCompressed.vy = state.velocity.y * 1000.0f;+ stateCompressed.vz = state.velocity.z * 1000.0f;++ stateCompressed.ax = state.acc.x * 9.81f * 1000.0f;+ stateCompressed.ay = state.acc.y * 9.81f * 1000.0f;+ stateCompressed.az = (state.acc.z + 1) * 9.81f * 1000.0f;++ float const q[4] = {+ state.attitudeQuaternion.x,+ state.attitudeQuaternion.y,+ state.attitudeQuaternion.z,+ state.attitudeQuaternion.w};+ stateCompressed.quat = quatcompress(q);++ float const deg2millirad = ((float)M_PI * 1000.0f) / 180.0f;+ stateCompressed.rateRoll = sensorData.gyro.x * deg2millirad;+ stateCompressed.ratePitch = -sensorData.gyro.y * deg2millirad;+ stateCompressed.rateYaw = sensorData.gyro.z * deg2millirad;+}++static void compressSetpoint()+{+ setpointCompressed.x = setpoint.position.x * 1000.0f;+ setpointCompressed.y = setpoint.position.y * 1000.0f;+ setpointCompressed.z = setpoint.position.z * 1000.0f;++ setpointCompressed.vx = setpoint.velocity.x * 1000.0f;+ setpointCompressed.vy = setpoint.velocity.y * 1000.0f;+ setpointCompressed.vz = setpoint.velocity.z * 1000.0f;++ setpointCompressed.ax = setpoint.acceleration.x * 1000.0f;+ setpointCompressed.ay = setpoint.acceleration.y * 1000.0f;+ setpointCompressed.az = setpoint.acceleration.z * 1000.0f;+}++void stabilizerInit(StateEstimatorType estimator)+{+ if(isInit)+ return;++ sensorsInit();+ if (estimator == anyEstimator) {+ estimator = deckGetRequiredEstimator();+ }+ stateEstimatorInit(estimator);+ controllerInit(ControllerTypeAny);+ powerDistributionInit();+ sitAwInit();+ //collisionAvoidanceInit();+ estimatorType = getStateEstimator();+ controllerType = getControllerType();++ STATIC_MEM_TASK_CREATE(stabilizerTask, stabilizerTask, STABILIZER_TASK_NAME, NULL, STABILIZER_TASK_PRI);++ isInit = true;+}++bool stabilizerTest(void)+{+ bool pass = true;++ pass &= sensorsTest();+ pass &= stateEstimatorTest();+ pass &= controllerTest();+ pass &= powerDistributionTest();+ //pass &= collisionAvoidanceTest();++ return pass;+}++static void checkEmergencyStopTimeout()+{+ if (emergencyStopTimeout >= 0) {+ emergencyStopTimeout -= 1;++ if (emergencyStopTimeout == 0) {+ emergencyStop = true;+ }+ }+}++/* The stabilizer loop runs at 1kHz (stock) or 500Hz (kalman). It is the+ * responsibility of the different functions to run slower by skipping call+ * (ie. returning without modifying the output structure).+ */++static void stabilizerTask(void* param)+{+ uint32_t tick;+ uint32_t lastWakeTime;++#ifdef configUSE_APPLICATION_TASK_TAG+ #if configUSE_APPLICATION_TASK_TAG == 1+ vTaskSetApplicationTaskTag(0, (void*)TASK_STABILIZER_ID_NBR);+ #endif+#endif++ //Wait for the system to be fully started to start stabilization loop+ systemWaitStart();++ DEBUG_PRINTI("Wait for sensor calibration...\n");++ // Wait for sensors to be calibrated+ lastWakeTime = xTaskGetTickCount();+ while(!sensorsAreCalibrated()) {+ vTaskDelayUntil(&lastWakeTime, F2T(RATE_MAIN_LOOP));+ }+ // Initialize tick to something else then 0+ tick = 1;++ rateSupervisorInit(&rateSupervisorContext, xTaskGetTickCount(), M2T(1000), 997, 1003, 1);++ DEBUG_PRINTI("Ready to fly.\n");++ while(1) {+ // The sensor should unlock at 1kHz+ sensorsWaitDataReady();++ if (startPropTest != false) {+ // TODO: What happens with estimator when we run tests after startup?+ testState = configureAcc;+ startPropTest = false;+ }++ if (testState != testDone) {+ sensorsAcquire(&sensorData, tick);+ testProps(&sensorData);+ } else {+ // allow to update estimator dynamically+ if (getStateEstimator() != estimatorType) {+ stateEstimatorSwitchTo(estimatorType);+ estimatorType = getStateEstimator();+ }+ // allow to update controller dynamically+ if (getControllerType() != controllerType) {+ controllerInit(controllerType);+ controllerType = getControllerType();+ }++ stateEstimator(&state, &sensorData, &control, tick);+ compressState();++ commanderGetSetpoint(&setpoint, &state);+ compressSetpoint();++ sitAwUpdateSetpoint(&setpoint, &sensorData, &state);+ //collisionAvoidanceUpdateSetpoint(&setpoint, &sensorData, &state, tick);++ controller(&control, &setpoint, &sensorData, &state, tick);++ checkEmergencyStopTimeout();++ checkStops = systemIsArmed();+ if (emergencyStop || (systemIsArmed() == false)) {+ powerStop();+ } else {+ powerDistribution(&control);+ }++ //TODO: Log data to uSD card if configured+ /*if (usddeckLoggingEnabled()+ && usddeckLoggingMode() == usddeckLoggingMode_SynchronousStabilizer+ && RATE_DO_EXECUTE(usddeckFrequency(), tick)) {+ usddeckTriggerLogging();+ }*/+ }+ calcSensorToOutputLatency(&sensorData);+ tick++;+ STATS_CNT_RATE_EVENT(&stabilizerRate);++ if (!rateSupervisorValidate(&rateSupervisorContext, xTaskGetTickCount())) {+ if (!rateWarningDisplayed) {+ DEBUG_PRINT("WARNING: stabilizer loop rate is off (%"PRIu32")\n", rateSupervisorLatestCount(&rateSupervisorContext));+ rateWarningDisplayed = true;+ }+ }+ }+}++void stabilizerSetEmergencyStop()+{+ emergencyStop = true;+}++void stabilizerResetEmergencyStop()+{+ emergencyStop = false;+}++void stabilizerSetEmergencyStopTimeout(int timeout)+{+ emergencyStop = false;+ emergencyStopTimeout = timeout;+}++static float variance(float *buffer, uint32_t length)+{+ uint32_t i;+ float sum = 0;+ float sumSq = 0;++ for (i = 0; i < length; i++)+ {+ sum += buffer[i];+ sumSq += buffer[i] * buffer[i];+ }++ return sumSq - (sum * sum) / length;+}++/** Evaluate the values from the propeller test+ * @param low The low limit of the self test+ * @param high The high limit of the self test+ * @param value The value to compare with.+ * @param string A pointer to a string describing the value.+ * @return True if self test within low - high limit, false otherwise+ */+static bool evaluateTest(float low, float high, float value, uint8_t motor)+{+ if (value < low || value > high)+ {+ DEBUG_PRINTI("Propeller test on M%d [FAIL]. low: %0.2f, high: %0.2f, measured: %0.2f\n",+ motor + 1, (double)low, (double)high, (double)value);+ return false;+ }++ motorPass |= (1 << motor);++ return true;+}+++static void testProps(sensorData_t *sensors)+{+ static uint32_t i = 0;+ NO_DMA_CCM_SAFE_ZERO_INIT static float accX[PROPTEST_NBR_OF_VARIANCE_VALUES];+ NO_DMA_CCM_SAFE_ZERO_INIT static float accY[PROPTEST_NBR_OF_VARIANCE_VALUES];+ NO_DMA_CCM_SAFE_ZERO_INIT static float accZ[PROPTEST_NBR_OF_VARIANCE_VALUES];+ static float accVarXnf;+ static float accVarYnf;+ static float accVarZnf;+ static int motorToTest = 0;+ static uint8_t nrFailedTests = 0;+ static float idleVoltage;+ static float minSingleLoadedVoltage[NBR_OF_MOTORS];+ static float minLoadedVoltage;++ if (testState == configureAcc)+ {+ motorPass = 0;+ sensorsSetAccMode(ACC_MODE_PROPTEST);+ testState = measureNoiseFloor;+ minLoadedVoltage = idleVoltage = pmGetBatteryVoltage();+ minSingleLoadedVoltage[MOTOR_M1] = minLoadedVoltage;+ minSingleLoadedVoltage[MOTOR_M2] = minLoadedVoltage;+ minSingleLoadedVoltage[MOTOR_M3] = minLoadedVoltage;+ minSingleLoadedVoltage[MOTOR_M4] = minLoadedVoltage;+ }+ if (testState == measureNoiseFloor)+ {+ accX[i] = sensors->acc.x;+ accY[i] = sensors->acc.y;+ accZ[i] = sensors->acc.z;++ if (++i >= PROPTEST_NBR_OF_VARIANCE_VALUES)+ {+ i = 0;+ accVarXnf = variance(accX, PROPTEST_NBR_OF_VARIANCE_VALUES);+ accVarYnf = variance(accY, PROPTEST_NBR_OF_VARIANCE_VALUES);+ accVarZnf = variance(accZ, PROPTEST_NBR_OF_VARIANCE_VALUES);+ DEBUG_PRINTI("Acc noise floor variance X+Y:%f, (Z:%f)\n",+ (double)accVarXnf + (double)accVarYnf, (double)accVarZnf);+ testState = measureProp;+ }++ }+ else if (testState == measureProp)+ {+ if (i < PROPTEST_NBR_OF_VARIANCE_VALUES)+ {+ accX[i] = sensors->acc.x;+ accY[i] = sensors->acc.y;+ accZ[i] = sensors->acc.z;+ if (pmGetBatteryVoltage() < minSingleLoadedVoltage[motorToTest])+ {+ minSingleLoadedVoltage[motorToTest] = pmGetBatteryVoltage();+ }+ }+ i++;++ if (i == 1)+ {+ motorsSetRatio(motorToTest, 0xFFFF);+ }+ else if (i == 50)+ {+ motorsSetRatio(motorToTest, 0);+ }+ else if (i == PROPTEST_NBR_OF_VARIANCE_VALUES)+ {+ accVarX[motorToTest] = variance(accX, PROPTEST_NBR_OF_VARIANCE_VALUES);+ accVarY[motorToTest] = variance(accY, PROPTEST_NBR_OF_VARIANCE_VALUES);+ accVarZ[motorToTest] = variance(accZ, PROPTEST_NBR_OF_VARIANCE_VALUES);+ DEBUG_PRINTI("Motor M%d variance X+Y:%f (Z:%f)\n",+ motorToTest+1, (double)accVarX[motorToTest] + (double)accVarY[motorToTest],+ (double)accVarZ[motorToTest]);+ }+ else if (i >= 1000)+ {+ i = 0;+ motorToTest++;+ if (motorToTest >= NBR_OF_MOTORS)+ {+ i = 0;+ motorToTest = 0;+ testState = evaluateResult;+ sensorsSetAccMode(ACC_MODE_FLIGHT);+ }+ }+ }+ else if (testState == testBattery)+ {+ if (i == 0)+ {+ minLoadedVoltage = idleVoltage = pmGetBatteryVoltage();+ }+ if (i == 1)+ {+ motorsSetRatio(MOTOR_M1, 0xFFFF);+ motorsSetRatio(MOTOR_M2, 0xFFFF);+ motorsSetRatio(MOTOR_M3, 0xFFFF);+ motorsSetRatio(MOTOR_M4, 0xFFFF);+ }+ else if (i < 50)+ {+ if (pmGetBatteryVoltage() < minLoadedVoltage)+ minLoadedVoltage = pmGetBatteryVoltage();+ }+ else if (i == 50)+ {+ motorsSetRatio(MOTOR_M1, 0);+ motorsSetRatio(MOTOR_M2, 0);+ motorsSetRatio(MOTOR_M3, 0);+ motorsSetRatio(MOTOR_M4, 0);+// DEBUG_PRINT("IdleV: %f, minV: %f, M1V: %f, M2V: %f, M3V: %f, M4V: %f\n", (double)idleVoltage,+// (double)minLoadedVoltage,+// (double)minSingleLoadedVoltage[MOTOR_M1],+// (double)minSingleLoadedVoltage[MOTOR_M2],+// (double)minSingleLoadedVoltage[MOTOR_M3],+// (double)minSingleLoadedVoltage[MOTOR_M4]);+ DEBUG_PRINTI("%f %f %f %f %f %f\n", (double)idleVoltage,+ (double)(idleVoltage - minLoadedVoltage),+ (double)(idleVoltage - minSingleLoadedVoltage[MOTOR_M1]),+ (double)(idleVoltage - minSingleLoadedVoltage[MOTOR_M2]),+ (double)(idleVoltage - minSingleLoadedVoltage[MOTOR_M3]),+ (double)(idleVoltage - minSingleLoadedVoltage[MOTOR_M4]));+ testState = restartBatTest;+ i = 0;+ }+ i++;+ }+ else if (testState == restartBatTest)+ {+ if (i++ > 2000)+ {+ testState = configureAcc;+ i = 0;+ }+ }+ else if (testState == evaluateResult)+ {+ for (int m = 0; m < NBR_OF_MOTORS; m++)+ {+ if (!evaluateTest(0, PROPELLER_BALANCE_TEST_THRESHOLD, accVarX[m] + accVarY[m], m))+ {+ nrFailedTests++;+ for (int j = 0; j < 3; j++)+ {+ motorsBeep(m, true, testsound[m], (uint16_t)(MOTORS_TIM_BEEP_CLK_FREQ / A4)/ 20);+ vTaskDelay(M2T(MOTORS_TEST_ON_TIME_MS));+ motorsBeep(m, false, 0, 0);+ vTaskDelay(M2T(100));+ }+ }+ }+#ifdef PLAY_STARTUP_MELODY_ON_MOTORS+ if (nrFailedTests == 0)+ {+ for (int m = 0; m < NBR_OF_MOTORS; m++)+ {+ motorsBeep(m, true, testsound[m], (uint16_t)(MOTORS_TIM_BEEP_CLK_FREQ / A4)/ 20);+ vTaskDelay(M2T(MOTORS_TEST_ON_TIME_MS));+ motorsBeep(m, false, 0, 0);+ vTaskDelay(M2T(MOTORS_TEST_DELAY_TIME_MS));+ }+ }+#endif+ motorTestCount++;+ testState = testDone;+ }+}+PARAM_GROUP_START(health)+PARAM_ADD(PARAM_UINT8, startPropTest, &startPropTest)+PARAM_GROUP_STOP(health)+++PARAM_GROUP_START(stabilizer)+PARAM_ADD(PARAM_UINT8, estimator, &estimatorType)+PARAM_ADD(PARAM_UINT8, controller, &controllerType)+PARAM_ADD(PARAM_UINT8, stop, &emergencyStop)+PARAM_GROUP_STOP(stabilizer)++LOG_GROUP_START(health)+LOG_ADD(LOG_FLOAT, motorVarXM1, &accVarX[0])+LOG_ADD(LOG_FLOAT, motorVarYM1, &accVarY[0])+LOG_ADD(LOG_FLOAT, motorVarXM2, &accVarX[1])+LOG_ADD(LOG_FLOAT, motorVarYM2, &accVarY[1])+LOG_ADD(LOG_FLOAT, motorVarXM3, &accVarX[2])+LOG_ADD(LOG_FLOAT, motorVarYM3, &accVarY[2])+LOG_ADD(LOG_FLOAT, motorVarXM4, &accVarX[3])+LOG_ADD(LOG_FLOAT, motorVarYM4, &accVarY[3])+LOG_ADD(LOG_UINT8, motorPass, &motorPass)+LOG_ADD(LOG_UINT16, motorTestCount, &motorTestCount)+LOG_ADD(LOG_UINT8, checkStops, &checkStops)+LOG_GROUP_STOP(health)++LOG_GROUP_START(ctrltarget)+LOG_ADD(LOG_FLOAT, x, &setpoint.position.x)+LOG_ADD(LOG_FLOAT, y, &setpoint.position.y)+LOG_ADD(LOG_FLOAT, z, &setpoint.position.z)++LOG_ADD(LOG_FLOAT, vx, &setpoint.velocity.x)+LOG_ADD(LOG_FLOAT, vy, &setpoint.velocity.y)+LOG_ADD(LOG_FLOAT, vz, &setpoint.velocity.z)++LOG_ADD(LOG_FLOAT, ax, &setpoint.acceleration.x)+LOG_ADD(LOG_FLOAT, ay, &setpoint.acceleration.y)+LOG_ADD(LOG_FLOAT, az, &setpoint.acceleration.z)++LOG_ADD(LOG_FLOAT, roll, &setpoint.attitude.roll)+LOG_ADD(LOG_FLOAT, pitch, &setpoint.attitude.pitch)+LOG_ADD(LOG_FLOAT, yaw, &setpoint.attitudeRate.yaw)+LOG_GROUP_STOP(ctrltarget)++LOG_GROUP_START(ctrltargetZ)+LOG_ADD(LOG_INT16, x, &setpointCompressed.x) // position - mm+LOG_ADD(LOG_INT16, y, &setpointCompressed.y)+LOG_ADD(LOG_INT16, z, &setpointCompressed.z)++LOG_ADD(LOG_INT16, vx, &setpointCompressed.vx) // velocity - mm / sec+LOG_ADD(LOG_INT16, vy, &setpointCompressed.vy)+LOG_ADD(LOG_INT16, vz, &setpointCompressed.vz)++LOG_ADD(LOG_INT16, ax, &setpointCompressed.ax) // acceleration - mm / sec^2+LOG_ADD(LOG_INT16, ay, &setpointCompressed.ay)+LOG_ADD(LOG_INT16, az, &setpointCompressed.az)+LOG_GROUP_STOP(ctrltargetZ)++LOG_GROUP_START(stabilizer)+LOG_ADD(LOG_FLOAT, roll, &state.attitude.roll)+LOG_ADD(LOG_FLOAT, pitch, &state.attitude.pitch)+LOG_ADD(LOG_FLOAT, yaw, &state.attitude.yaw)+LOG_ADD(LOG_FLOAT, thrust, &control.thrust)++STATS_CNT_RATE_LOG_ADD(rtStab, &stabilizerRate)+LOG_ADD(LOG_UINT32, intToOut, &inToOutLatency)+LOG_GROUP_STOP(stabilizer)++LOG_GROUP_START(acc)+LOG_ADD(LOG_FLOAT, x, &sensorData.acc.x)+LOG_ADD(LOG_FLOAT, y, &sensorData.acc.y)+LOG_ADD(LOG_FLOAT, z, &sensorData.acc.z)+LOG_GROUP_STOP(acc)++#ifdef LOG_SEC_IMU+LOG_GROUP_START(accSec)+LOG_ADD(LOG_FLOAT, x, &sensorData.accSec.x)+LOG_ADD(LOG_FLOAT, y, &sensorData.accSec.y)+LOG_ADD(LOG_FLOAT, z, &sensorData.accSec.z)+LOG_GROUP_STOP(accSec)+#endif++LOG_GROUP_START(baro)+LOG_ADD(LOG_FLOAT, asl, &sensorData.baro.asl)+LOG_ADD(LOG_FLOAT, temp, &sensorData.baro.temperature)+LOG_ADD(LOG_FLOAT, pressure, &sensorData.baro.pressure)+LOG_GROUP_STOP(baro)++LOG_GROUP_START(gyro)+LOG_ADD(LOG_FLOAT, x, &sensorData.gyro.x)+LOG_ADD(LOG_FLOAT, y, &sensorData.gyro.y)+LOG_ADD(LOG_FLOAT, z, &sensorData.gyro.z)+LOG_GROUP_STOP(gyro)++#ifdef LOG_SEC_IMU+LOG_GROUP_START(gyroSec)+LOG_ADD(LOG_FLOAT, x, &sensorData.gyroSec.x)+LOG_ADD(LOG_FLOAT, y, &sensorData.gyroSec.y)+LOG_ADD(LOG_FLOAT, z, &sensorData.gyroSec.z)+LOG_GROUP_STOP(gyroSec)+#endif++LOG_GROUP_START(mag)+LOG_ADD(LOG_FLOAT, x, &sensorData.mag.x)+LOG_ADD(LOG_FLOAT, y, &sensorData.mag.y)+LOG_ADD(LOG_FLOAT, z, &sensorData.mag.z)+LOG_GROUP_STOP(mag)++LOG_GROUP_START(controller)+LOG_ADD(LOG_INT16, ctr_yaw, &control.yaw)+LOG_GROUP_STOP(controller)++LOG_GROUP_START(stateEstimate)+LOG_ADD(LOG_FLOAT, x, &state.position.x)+LOG_ADD(LOG_FLOAT, y, &state.position.y)+LOG_ADD(LOG_FLOAT, z, &state.position.z)++LOG_ADD(LOG_FLOAT, vx, &state.velocity.x)+LOG_ADD(LOG_FLOAT, vy, &state.velocity.y)+LOG_ADD(LOG_FLOAT, vz, &state.velocity.z)++LOG_ADD(LOG_FLOAT, ax, &state.acc.x)+LOG_ADD(LOG_FLOAT, ay, &state.acc.y)+LOG_ADD(LOG_FLOAT, az, &state.acc.z)++LOG_ADD(LOG_FLOAT, roll, &state.attitude.roll)+LOG_ADD(LOG_FLOAT, pitch, &state.attitude.pitch)+LOG_ADD(LOG_FLOAT, yaw, &state.attitude.yaw)++LOG_ADD(LOG_FLOAT, qx, &state.attitudeQuaternion.x)+LOG_ADD(LOG_FLOAT, qy, &state.attitudeQuaternion.y)+LOG_ADD(LOG_FLOAT, qz, &state.attitudeQuaternion.z)+LOG_ADD(LOG_FLOAT, qw, &state.attitudeQuaternion.w)+LOG_GROUP_STOP(stateEstimate)++LOG_GROUP_START(stateEstimateZ)+LOG_ADD(LOG_INT16, x, &stateCompressed.x) // position - mm+LOG_ADD(LOG_INT16, y, &stateCompressed.y)+LOG_ADD(LOG_INT16, z, &stateCompressed.z)++LOG_ADD(LOG_INT16, vx, &stateCompressed.vx) // velocity - mm / sec+LOG_ADD(LOG_INT16, vy, &stateCompressed.vy)+LOG_ADD(LOG_INT16, vz, &stateCompressed.vz)++LOG_ADD(LOG_INT16, ax, &stateCompressed.ax) // acceleration - mm / sec^2+LOG_ADD(LOG_INT16, ay, &stateCompressed.ay)+LOG_ADD(LOG_INT16, az, &stateCompressed.az)++LOG_ADD(LOG_UINT32, quat, &stateCompressed.quat) // compressed quaternion, see quatcompress.h++LOG_ADD(LOG_INT16, rateRoll, &stateCompressed.rateRoll) // angular velocity - milliradians / sec+LOG_ADD(LOG_INT16, ratePitch, &stateCompressed.ratePitch)+LOG_ADD(LOG_INT16, rateYaw, &stateCompressed.rateYaw)+LOG_GROUP_STOP(stateEstimateZ)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/static_mem.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/static_mem.cnew file mode 100644index 0000000..a36a9cb--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/static_mem.c@@ -0,0 +1,65 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--' | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * @file static_mem.c+ * @brief Support for OS objects that use static memory, such as+ * queues, tasks and semaphores+ *+ * @copyright Copyright (c) 2019 Bitcraze AB+ */++#include <FreeRTOS.h>+#include "static_mem.h"++/**+ * @brief configSUPPORT_STATIC_ALLOCATION is set to 1, so the application must provide an+ * implementation of vApplicationGetIdleTaskMemory() to provide the memory that is+ * used by the Idle task.+ */+void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer,+ StackType_t **ppxIdleTaskStackBuffer,+ uint32_t *pulIdleTaskStackSize )+{+ NO_DMA_CCM_SAFE_ZERO_INIT static StaticTask_t xIdleTaskTCB;+ NO_DMA_CCM_SAFE_ZERO_INIT static StackType_t uxIdleTaskStack[ configMINIMAL_STACK_SIZE ];++ *ppxIdleTaskTCBBuffer = &xIdleTaskTCB;+ *ppxIdleTaskStackBuffer = uxIdleTaskStack;+ *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;+}+/*———————————————————–*/++/**+ * @brief configSUPPORT_STATIC_ALLOCATION and configUSE_TIMERS are both set to 1, so the+ * application must provide an implementation of vApplicationGetTimerTaskMemory()+ * to provide the memory that is used by the Timer service task.+ */+void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer,+ StackType_t **ppxTimerTaskStackBuffer,+ uint32_t *pulTimerTaskStackSize )+{+ NO_DMA_CCM_SAFE_ZERO_INIT static StaticTask_t xTimerTaskTCB;+ NO_DMA_CCM_SAFE_ZERO_INIT static StackType_t uxTimerTaskStack[ configTIMER_TASK_STACK_DEPTH ];++ *ppxTimerTaskTCBBuffer = &xTimerTaskTCB;+ *ppxTimerTaskStackBuffer = uxTimerTaskStack;+ *pulTimerTaskStackSize = configTIMER_TASK_STACK_DEPTH;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/sysload.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/sysload.cnew file mode 100644index 0000000..bc6d23d--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/sysload.c@@ -0,0 +1,128 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2016 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * sysload.c - System load monitor+ */++++#include <stdbool.h>+#include <inttypes.h>+#include "FreeRTOS.h"+#include "timers.h"+#include "cfassert.h"+#include "param.h"+#include "static_mem.h"++#include "sysload.h"+#include "stm32_legacy.h"+#define DEBUG_MODULE "SYSLOAD"+#include "debug_cf.h"++#define TIMER_PERIOD M2T(5000)++static void timerHandler(xTimerHandle timer);++static bool initialized = false;+static uint8_t triggerDump = 1;++typedef struct {+ uint32_t ulRunTimeCounter;+ uint32_t xTaskNumber;+} taskData_t;++#define TASK_MAX_COUNT 32+NO_DMA_CCM_SAFE_ZERO_INIT static taskData_t previousSnapshot[TASK_MAX_COUNT];+static int taskTopIndex = 0;+static uint32_t previousTotalRunTime = 0;++static StaticTimer_t timerBuffer;++void sysLoadInit() {+ ASSERT(!initialized);++ xTimerHandle timer = xTimerCreateStatic( "sysLoadMonitorTimer", TIMER_PERIOD, pdTRUE, NULL, timerHandler, &timerBuffer);+ xTimerStart(timer, 100);++ initialized = true;+}+++static taskData_t* getPreviousTaskData(uint32_t xTaskNumber) {+ // Try to find the task in the list of tasks+ for (int i = 0; i < taskTopIndex; i++) {+ if (previousSnapshot[i].xTaskNumber == xTaskNumber) {+ return &previousSnapshot[i];+ }+ }++ // Allocate a new entry+ ASSERT(taskTopIndex < TASK_MAX_COUNT);+ taskData_t* result = &previousSnapshot[taskTopIndex];+ result->xTaskNumber = xTaskNumber;++ taskTopIndex++;++ return result;+}++static void timerHandler(xTimerHandle timer) {+ if (triggerDump != 0) {+ uint32_t totalRunTime;++ TaskStatus_t taskStats[TASK_MAX_COUNT];+ uint32_t taskCount = uxTaskGetSystemState(taskStats, TASK_MAX_COUNT, &totalRunTime);+ ASSERT(taskCount < TASK_MAX_COUNT);++ uint32_t totalDelta = totalRunTime - previousTotalRunTime;+ float f = 100.0 / totalDelta;++ // Dumps the the CPU load and stack usage for all tasks+ // CPU usage is since last dump in % compared to total time spent in tasks. Note that time spent in interrupts will be included in measured time.+ // Stack usage is displayed as nr of unused bytes at peak stack usage.++ DEBUG_PRINTI("Task dump");+ DEBUG_PRINTI("Load\tStack left\tName\tPRI");+ for (uint32_t i = 0; i < taskCount; i++) {+ TaskStatus_t* stats = &taskStats[i];+ taskData_t* previousTaskData = getPreviousTaskData(stats->xTaskNumber);++ uint32_t taskRunTime = stats->ulRunTimeCounter;+ float load = f * (taskRunTime - previousTaskData->ulRunTimeCounter);+ DEBUG_PRINTI("%.2f \t%"PRIu32" \t%s \t%d", (double)load, stats->usStackHighWaterMark, stats->pcTaskName,stats->uxBasePriority);++ previousTaskData->ulRunTimeCounter = taskRunTime;+ }++ DEBUG_PRINTI("Free heap: %"PRIu32" bytes", xPortGetFreeHeapSize());+ previousTotalRunTime = totalRunTime;++ triggerDump = 0;+ }+}+++PARAM_GROUP_START(system)+PARAM_ADD(PARAM_UINT8, taskDump, &triggerDump)+PARAM_GROUP_STOP(system)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/system.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/system.cnew file mode 100644index 0000000..36e7c04--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/system.c@@ -0,0 +1,353 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * ESP-Drone Firmware+ *+ * Copyright 2019-2020 Espressif Systems (Shanghai)+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * system.c - Top level module implementation+ */++#include <stdbool.h>+#include <inttypes.h>+/* FreeRtos includes */+#include "FreeRTOS.h"+#include "task.h"+#include "semphr.h"++#include "version.h"+#include "config.h"+#include "param.h"+#include "log.h"+#include "ledseq.h"+#include "adc_esp32.h"+#include "pm_esplane.h"+#include "config.h"+#include "system.h"+#include "platform.h"+//#include "storage.h"+#include "configblock.h"+#include "worker.h"+#include "freeRTOSdebug.h"+//#include "uart_syslink.h"+//#include "uart1.h"+//#include "uart2.h"+#include "wifi_esp32.h"+#include "comm.h"+#include "stabilizer.h"+#include "commander.h"+#include "console.h"+#include "wifilink.h"+#include "mem.h"+//#include "proximity.h"+//#include "watchdog.h"+#include "queuemonitor.h"+#include "buzzer.h"+#include "sound.h"+#include "sysload.h"+#include "estimator_kalman.h"+//#include "deck.h"+//#include "extrx.h"+#include "app.h"+#include "stm32_legacy.h"+#define DEBUG_MODULE "SYS"+#include "debug_cf.h"+#include "static_mem.h"+//#include "peer_localization.h"+#include "cfassert.h"++#ifndef START_DISARMED+#define ARM_INIT true+#else+#define ARM_INIT false+#endif++/* Private variable */+static bool selftestPassed;+static bool canFly;+static bool armed = ARM_INIT;+static bool forceArm;+static bool isInit;++STATIC_MEM_TASK_ALLOC(systemTask, SYSTEM_TASK_STACKSIZE);++/* System wide synchronisation */+xSemaphoreHandle canStartMutex;+static StaticSemaphore_t canStartMutexBuffer;++/* Private functions */+static void systemTask(void *arg);++/* Public functions */+void systemLaunch(void)+{+ STATIC_MEM_TASK_CREATE(systemTask, systemTask, SYSTEM_TASK_NAME, NULL, SYSTEM_TASK_PRI);+}++// This must be the first module to be initialized!+void systemInit(void)+{+ if(isInit)+ return;++ DEBUG_PRINT_LOCAL("----------------------------\n");+ DEBUG_PRINT_LOCAL("%s is up and running!\n", platformConfigGetDeviceTypeName());++ canStartMutex = xSemaphoreCreateMutexStatic(&canStartMutexBuffer);+ xSemaphoreTake(canStartMutex, portMAX_DELAY);++ wifilinkInit();+ sysLoadInit();++ /* Initialized here so that DEBUG_PRINT (buffered) can be used early */+ debugInit();+ crtpInit();+ consoleInit();++ /* DEBUG_PRINT("----------------------------\n");+ DEBUG_PRINT("%s is up and running!\n", platformConfigGetDeviceTypeName());++ if (V_PRODUCTION_RELEASE) {+ DEBUG_PRINT("Production release %s\n", V_STAG);+ } else {+ DEBUG_PRINT("Build %s:%s (%s) %s\n", V_SLOCAL_REVISION,+ V_SREVISION, V_STAG, (V_MODIFIED)?"MODIFIED":"CLEAN");+ }+ DEBUG_PRINT("I am 0x%08X%08X%08X and I have %dKB of flash!\n",+ *((int*)(MCU_ID_ADDRESS+8)), *((int*)(MCU_ID_ADDRESS+4)),+ *((int*)(MCU_ID_ADDRESS+0)), *((short*)(MCU_FLASH_SIZE_ADDRESS)));*/++ configblockInit();+ //storageInit();+ workerInit();+ adcInit();+ ledseqInit();+ pmInit();+ buzzerInit();+// peerLocalizationInit();++#ifdef APP_ENABLED+ appInit();+#endif++ isInit = true;+}++bool systemTest()+{+ bool pass=isInit;++ pass &= ledseqTest();+ pass &= pmTest();+ DEBUG_PRINTI("pmTest = %d", pass);+ pass &= workerTest();+ DEBUG_PRINTI("workerTest = %d", pass);+ pass &= buzzerTest();+ return pass;+}++/* Private functions implementation */++void systemTask(void *arg)+{+ bool pass = true;++ ledInit();+ ledSet(CHG_LED, 1);+ wifiInit();+ vTaskDelay(M2T(500));++#ifdef DEBUG_QUEUE_MONITOR+ queueMonitorInit();+#endif++#ifdef ENABLE_UART1+ uart1Init(9600);+#endif+#ifdef ENABLE_UART2+ uart2Init(115200);+#endif++ //Init the high-levels modules+ systemInit();+ commInit();+ commanderInit();++ StateEstimatorType estimator = anyEstimator;+ estimatorKalmanTaskInit();+ //deckInit();+ //estimator = deckGetRequiredEstimator();+ stabilizerInit(estimator);+ //if (deckGetRequiredLowInterferenceRadioMode() && platformConfigPhysicalLayoutAntennasAreClose())+ //{+ // platformSetLowInterferenceRadioMode();+ //}+ soundInit();+ memInit();++#ifdef PROXIMITY_ENABLED+ proximityInit();+#endif++ /* Test each modules */+ pass &= wifiTest();+ DEBUG_PRINTI("wifilinkTest = %d ", pass);+ pass &= systemTest();+ DEBUG_PRINTI("systemTest = %d ", pass);+ pass &= configblockTest();+ DEBUG_PRINTI("configblockTest = %d ", pass);+ //pass &= storageTest();+ pass &= commTest();+ DEBUG_PRINTI("commTest = %d ", pass);+ pass &= commanderTest();+ DEBUG_PRINTI("commanderTest = %d ", pass);+ pass &= stabilizerTest();+ DEBUG_PRINTI("stabilizerTest = %d ", pass);+ pass &= estimatorKalmanTaskTest();+ DEBUG_PRINTI("estimatorKalmanTaskTest = %d ", pass);+ //pass &= deckTest();+ //pass &= soundTest();+ //pass &= memTest();+ DEBUG_PRINTI("memTest = %d ", pass);+ //pass &= watchdogNormalStartTest();+ pass &= cfAssertNormalStartTest();+// pass &= peerLocalizationTest();++ //Start the firmware+ if(pass)+ {+ selftestPassed = 1;+ systemStart();+ DEBUG_PRINTI("systemStart ! selftestPassed = %d", selftestPassed);+ soundSetEffect(SND_STARTUP);+ ledseqRun(&seq_alive);+ ledseqRun(&seq_testPassed);+ }+ else+ {+ selftestPassed = 0;+ if (systemTest())+ {+ while(1)+ {+ ledseqRun(&seq_testFailed);+ vTaskDelay(M2T(2000));+ // System can be forced to start by setting the param to 1 from the cfclient+ if (selftestPassed)+ {+ DEBUG_PRINT("Start forced.\n");+ systemStart();+ break;+ }+ }+ }+ else+ {+ ledInit();+ ledSet(SYS_LED, true);+ }+ }+ DEBUG_PRINT("Free heap: %"PRIu32" bytes\n", xPortGetFreeHeapSize());++ workerLoop();++ //Should never reach this point!+ while(1)+ vTaskDelay(portMAX_DELAY);+}+++/* Global system variables */+void systemStart()+{+ xSemaphoreGive(canStartMutex);+#ifndef DEBUG_EP2+ //watchdogInit();+#endif+}++void systemWaitStart(void)+{+ //This permits to guarantee that the system task is initialized before other+ //tasks waits for the start event.+ while(!isInit)+ vTaskDelay(2);++ xSemaphoreTake(canStartMutex, portMAX_DELAY);+ xSemaphoreGive(canStartMutex);+}++void systemSetCanFly(bool val)+{+ canFly = val;+}++bool systemCanFly(void)+{+ return canFly;+}++void systemSetArmed(bool val)+{+ armed = val;+}++bool systemIsArmed()+{++ return armed || forceArm;+}+// void vApplicationIdleHook( void )+// {+// static uint32_t tickOfLatestWatchdogReset = M2T(0);++// portTickType tickCount = xTaskGetTickCount();++// if (tickCount - tickOfLatestWatchdogReset > M2T(WATCHDOG_RESET_PERIOD_MS))+// {+// tickOfLatestWatchdogReset = tickCount;+// watchdogReset();+// }++// // Enter sleep mode. Does not work when debugging chip with SWD.+// // Currently saves about 20mA STM32F405 current consumption (~30%).+// #ifndef DEBUG+// { __asm volatile ("wfi"); }+// #endif+// }++/*System parameters (mostly for test, should be removed from here) */+/*PARAM_GROUP_START(cpu)+PARAM_ADD(PARAM_UINT16 | PARAM_RONLY, flash, MCU_FLASH_SIZE_ADDRESS)+PARAM_ADD(PARAM_UINT32 | PARAM_RONLY, id0, MCU_ID_ADDRESS+0)+PARAM_ADD(PARAM_UINT32 | PARAM_RONLY, id1, MCU_ID_ADDRESS+4)+PARAM_ADD(PARAM_UINT32 | PARAM_RONLY, id2, MCU_ID_ADDRESS+8)+PARAM_GROUP_STOP(cpu)*/++PARAM_GROUP_START(system)+PARAM_ADD(PARAM_INT8 | PARAM_RONLY, selftestPassed, &selftestPassed)+PARAM_ADD(PARAM_INT8, forceArm, &forceArm)+PARAM_GROUP_STOP(sytem)++/* Loggable variables */+LOG_GROUP_START(sys)+LOG_ADD(LOG_INT8, canfly, &canFly)+LOG_ADD(LOG_INT8, armed, &armed)+LOG_GROUP_STOP(sys)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/tdoaEngineInstance.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/tdoaEngineInstance.cnew file mode 100644index 0000000..23056f6--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/tdoaEngineInstance.c@@ -0,0 +1,58 @@+/**+ * ,---------, ____ _ __+ * | ,-^-, | / __ )(_) /_______________ _____ ___+ * | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2020 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ *+ * tdoaEngineInstance.c - holds the tdoa engine state instance+ */++#include "tdoaEngineInstance.h"+#include "log.h"+#include "param.h"+#include "static_mem.h"++NO_DMA_CCM_SAFE_ZERO_INIT tdoaEngineState_t tdoaEngineState;++LOG_GROUP_START(tdoaEngine)+STATS_CNT_RATE_LOG_ADD(stRx, &tdoaEngineState.stats.packetsReceived)+STATS_CNT_RATE_LOG_ADD(stEst, &tdoaEngineState.stats.packetsToEstimator)+STATS_CNT_RATE_LOG_ADD(stTime, &tdoaEngineState.stats.timeIsGood)+STATS_CNT_RATE_LOG_ADD(stFound, &tdoaEngineState.stats.suitableDataFound)+STATS_CNT_RATE_LOG_ADD(stCc, &tdoaEngineState.stats.clockCorrectionCount)+STATS_CNT_RATE_LOG_ADD(stHit, &tdoaEngineState.stats.contextHitCount)+STATS_CNT_RATE_LOG_ADD(stMiss, &tdoaEngineState.stats.contextMissCount)++LOG_ADD(LOG_FLOAT, cc, &tdoaEngineState.stats.clockCorrection)+LOG_ADD(LOG_UINT16, tof, &tdoaEngineState.stats.tof)+LOG_ADD(LOG_FLOAT, tdoa, &tdoaEngineState.stats.tdoa)+LOG_GROUP_STOP(tdoaEngine)+++PARAM_GROUP_START(tdoaEngine)+PARAM_ADD(PARAM_UINT8, logId, &tdoaEngineState.stats.newAnchorId)+PARAM_ADD(PARAM_UINT8, logOthrId, &tdoaEngineState.stats.newRemoteAnchorId)++// This variable should not be exposed as a parameter since it is changed from inside the CF FW.+// It only happens when the LPS system mode is changed to TDoA2 or TDoA3 though, and as this is+// not a frequent action, we chose to expose it anyway.+PARAM_ADD(PARAM_UINT8, matchAlgo, &tdoaEngineState.matchingAlgorithm)+PARAM_GROUP_STOP(tdoaEngine)diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/trigger.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/trigger.cnew file mode 100644index 0000000..c19482d--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/trigger.c@@ -0,0 +1,214 @@+/*+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2015 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * trigger.c - Implementation of trigger mechanism.+ */++#include <stddef.h>+#include <stdlib.h>+#include "stm32_legacy.h"+#include "trigger.h"++/**+ * Initialize a trigger object.+ *+ * Note that to activate the trigger, the triggerActivate() function must be called after+ * calling triggerInit().+ *+ * @param trigger The trigger object.+ * @param func The trigger function type.+ * @param threshold The threshold to use with the trigger function.+ * @param triggerCount When testCounter reaches this value, a trigger is reported.+ */+void triggerInit(trigger_t *trigger, triggerFunc_t func, float threshold, uint32_t triggerCount)+{+ assert_param(trigger != NULL);+ assert_param(func != triggerFuncNone);++ trigger->active = false;+ trigger->func = func;+ trigger->threshold = threshold;+ trigger->triggerCount = triggerCount;++ triggerReset(trigger);+}++/**+ * Register a trigger handler.+ *+ * @param trigger The trigger object.+ * @param handler If a handler is registered, this handler function is called when the trigger is released. Otherwise NULL.+ * @param handlerArg Argument to pass to the handler function. NULL if not used.+ */+void triggerRegisterHandler(trigger_t *trigger, triggerHandler_t handler, void *handlerArg)+{+ assert_param(trigger != NULL);+ assert_param(handler != NULL);++ trigger->handler = handler;+ trigger->handlerArg = handlerArg;+ trigger->handlerCalled = false;+}++/**+ * DeInitialize a trigger object.+ *+ * @param trigger The trigger object.+ */+void triggerDeInit(trigger_t *trigger)+{+ assert_param(trigger != NULL);++ triggerInit(trigger, triggerFuncNone, 0, 0);+ triggerRegisterHandler(trigger, NULL, NULL);+ triggerReset(trigger);+}++/**+ * Activate or deactivate a trigger object.+ *+ * This function does not influence the attributes of the trigger object as initialized by+ * triggerInitialize() or triggerRegisterHandler() functions.+ *+ * Calling this function will reset all counters and flags, in addition to activating or+ * deactivating the trigger.+ *+ * @param trigger The trigger object.+ * @param active Set the trigger active (true) or deactive (false).+ */+void triggerActivate(trigger_t *trigger, bool active)+{+ assert_param(trigger != NULL);++ triggerReset(trigger);+ trigger->active = active;+}++/**+ * Reset a trigger object.+ *+ * This function does not influence the attributes of the trigger object as initialized by+ * triggerInitialize(), triggerRegisterHandler() or triggerActivate() functions.+ *+ * Calling this function will reset all other counters and flags.+ *+ * @param trigger The trigger object.+ */+void triggerReset(trigger_t *trigger)+{+ assert_param(trigger != NULL);++ trigger->testCounter = 0;+ trigger->released = false;+ trigger->handlerCalled = false;+}++/**+ * Internal function incrementing the testCounter, but never further than the triggerCount value.+ *+ * @param trigger The trigger object.+ */+static void triggerIncTestCounter(trigger_t *trigger)+{+ assert_param(trigger != NULL);++ if(trigger->testCounter < trigger->triggerCount) {+ trigger->testCounter++;+ }+}++/**+ * Test a value against the trigger.+ *+ * Note that this function will call the registered handler function synchronously. The handler function+ * is called only once, when the trigger is released. Subsequent calls to this function will not call+ * the handler function again (until triggerReset() or triggerActivate() has been called to reset the+ * trigger).+ *+ * This function will continue to return a value of true as long as the condition for the trigger release+ * has been met (or exceeds the triggerCount value).+ *+ * This function will increment the testCounter until it reaches triggerCount.+ *+ * @param trigger The trigger object.+ * @param testValue The test value to compare against the threshold with the trigger function.+ *+ * @return True when the trigger has been released.+ */+bool triggerTestValue(trigger_t *trigger, float testValue)+{+ assert_param(trigger != NULL);++ /* Do not do anything if the trigger has been deactivated. */+ if(!trigger->active) {+ return false;+ }++ switch(trigger->func) {+ case triggerFuncIsLE: {+ if(testValue <= trigger->threshold) {+ triggerIncTestCounter(trigger);+ break;+ }+ else {+ /* Reset the trigger if the test failed. */+ triggerReset(trigger);+ return false;+ }+ }+ case triggerFuncIsGE: {+ if(testValue >= trigger->threshold) {+ triggerIncTestCounter(trigger);+ break;+ }+ else {+ /* Reset the trigger if the test failed. */+ triggerReset(trigger);+ return false;+ }+ }+ case triggerFuncNone: {+ /* No action, included to avoid compiler warnings. */+ break;+ }+ }++ /* Check if the triggerCount has been reached. */+ trigger->released = (trigger->testCounter >= trigger->triggerCount);++ /* If the trigger has not been release, exit immediately. */+ if(!trigger->released) {+ return false;+ }++ /* The trigger object may be reset by the handler, thus make an internal copy of the released flag. */+ bool iReleased = trigger->released;+ if(trigger->released && (trigger->handler != NULL) && (!trigger->handlerCalled)) {+ /* Set the handlerCalled = true before calling, since the handler may choose to reset the object. */+ trigger->handlerCalled = true;+ trigger->handler(trigger->handlerArg);+ }++ /* Return the release flag. This may return the value true more than once. */+ return iReleased;+}diff --git a/Firmware/esp-drone/components/core/crazyflie/modules/src/worker.c b/Firmware/esp-drone/components/core/crazyflie/modules/src/worker.cnew file mode 100644index 0000000..289ddec--- /dev/null+++ b/Firmware/esp-drone/components/core/crazyflie/modules/src/worker.c@@ -0,0 +1,91 @@+/**+ * || ____ _ __+ * +------+ / __ )(_) /_______________ _____ ___+ * | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \+ * +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/+ * || || /_____/_/\__/\___/_/ \__,_/ /___/\___/+ *+ * Crazyflie control firmware+ *+ * Copyright (C) 2011-2012 Bitcraze AB+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU General Public License as published by+ * the Free Software Foundation, in version 3.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU General Public License for more details.+ *+ * You should have received a copy of the GNU General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ *+ * worker.c - Worker system that can execute asynchronous actions in tasks+ */+#include "worker.h"++#include <errno.h>++#include "FreeRTOS.h"+#include "task.h"+#include "queue.h"+#include "queuemonitor.h"+#include "static_mem.h"++#include "console.h"++#define WORKER_QUEUE_LENGTH 5++struct worker_work {+ void (*function)(void*);+ void* arg;+};++static xQueueHandle workerQueue;+STATIC_MEM_QUEUE_ALLOC(workerQueue, WORKER_QUEUE_LENGTH, sizeof(struct worker_work));++void workerInit()+{+ if (workerQueue)+ return;++ workerQueue = STATIC_MEM_QUEUE_CREATE(workerQueue);+ DEBUG_QUEUE_MONITOR_REGISTER(workerQueue);+}++bool workerTest()+{+ return (workerQueue != NULL);+}++void workerLoop()+{+ struct worker_work work;++ if (!workerQueue)+ return;++ while (1)+ {+ xQueueReceive(workerQueue, &work, portMAX_DELAY);++ if (work.function)+ work.function(work.arg);+ }+}++int workerSchedule(void (*function)(void*), void *arg)+{+ struct worker_work work;++ if (!function)+ return ENOEXEC;++ work.function = function;+ work.arg = arg;+ if (xQueueSend(workerQueue, &work, 0) == pdFALSE)+ return ENOMEM;++ return 0;+}