ELRS SPI Fix eeprom write and reboot for msp over telemetry
[betaflight.git] / src / main / msp / msp.c
blobd2b60a254d671638c3743cd8f5a3038bfa8abd19
1 /*
2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
8 * any later version.
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
21 #include <stdbool.h>
22 #include <stdint.h>
23 #include <string.h>
24 #include <math.h>
25 #include <stdlib.h>
26 #include <limits.h>
27 #include <ctype.h>
29 #include "platform.h"
31 #include "blackbox/blackbox.h"
32 #include "blackbox/blackbox_io.h"
34 #include "build/build_config.h"
35 #include "build/debug.h"
36 #include "build/version.h"
38 #include "cli/cli.h"
40 #include "common/axis.h"
41 #include "common/bitarray.h"
42 #include "common/color.h"
43 #include "common/huffman.h"
44 #include "common/maths.h"
45 #include "common/streambuf.h"
46 #include "common/utils.h"
48 #include "config/config.h"
49 #include "config/config_eeprom.h"
50 #include "config/feature.h"
51 #include "config/simplified_tuning.h"
53 #include "drivers/accgyro/accgyro.h"
54 #include "drivers/bus_i2c.h"
55 #include "drivers/bus_spi.h"
56 #include "drivers/camera_control.h"
57 #include "drivers/compass/compass.h"
58 #include "drivers/display.h"
59 #include "drivers/dshot.h"
60 #include "drivers/dshot_command.h"
61 #include "drivers/flash.h"
62 #include "drivers/io.h"
63 #include "drivers/motor.h"
64 #include "drivers/osd.h"
65 #include "drivers/pwm_output.h"
66 #include "drivers/sdcard.h"
67 #include "drivers/serial.h"
68 #include "drivers/serial_escserial.h"
69 #include "drivers/system.h"
70 #include "drivers/transponder_ir.h"
71 #include "drivers/usb_msc.h"
72 #include "drivers/vtx_common.h"
73 #include "drivers/vtx_table.h"
75 #include "fc/board_info.h"
76 #include "fc/controlrate_profile.h"
77 #include "fc/core.h"
78 #include "fc/dispatch.h"
79 #include "fc/rc.h"
80 #include "fc/rc_adjustments.h"
81 #include "fc/rc_controls.h"
82 #include "fc/rc_modes.h"
83 #include "fc/runtime_config.h"
85 #include "flight/failsafe.h"
86 #include "flight/gps_rescue.h"
87 #include "flight/imu.h"
88 #include "flight/mixer.h"
89 #include "flight/pid.h"
90 #include "flight/pid_init.h"
91 #include "flight/position.h"
92 #include "flight/rpm_filter.h"
93 #include "flight/servos.h"
95 #include "io/asyncfatfs/asyncfatfs.h"
96 #include "io/beeper.h"
97 #include "io/flashfs.h"
98 #include "io/gimbal.h"
99 #include "io/gps.h"
100 #include "io/ledstrip.h"
101 #include "io/serial.h"
102 #include "io/serial_4way.h"
103 #include "io/servos.h"
104 #include "io/transponder_ir.h"
105 #include "io/usb_msc.h"
106 #include "io/vtx_control.h"
107 #include "io/vtx.h"
109 #include "msp/msp_box.h"
110 #include "msp/msp_protocol.h"
111 #include "msp/msp_protocol_v2_betaflight.h"
112 #include "msp/msp_protocol_v2_common.h"
113 #include "msp/msp_serial.h"
115 #include "osd/osd.h"
116 #include "osd/osd_elements.h"
117 #include "osd/osd_warnings.h"
119 #include "pg/beeper.h"
120 #include "pg/board.h"
121 #include "pg/dyn_notch.h"
122 #include "pg/gyrodev.h"
123 #include "pg/motor.h"
124 #include "pg/rx.h"
125 #include "pg/rx_spi.h"
126 #include "pg/usb.h"
127 #include "pg/vcd.h"
128 #include "pg/vtx_table.h"
130 #include "rx/rx.h"
131 #include "rx/rx_bind.h"
132 #include "rx/msp.h"
134 #include "scheduler/scheduler.h"
136 #include "sensors/acceleration.h"
137 #include "sensors/barometer.h"
138 #include "sensors/battery.h"
139 #include "sensors/boardalignment.h"
140 #include "sensors/compass.h"
141 #include "sensors/esc_sensor.h"
142 #include "sensors/gyro.h"
143 #include "sensors/gyro_init.h"
144 #include "sensors/rangefinder.h"
146 #include "telemetry/msp_shared.h"
147 #include "telemetry/telemetry.h"
149 #ifdef USE_HARDWARE_REVISION_DETECTION
150 #include "hardware_revision.h"
151 #endif
153 #include "msp.h"
156 static const char * const flightControllerIdentifier = FC_FIRMWARE_IDENTIFIER; // 4 UPPER CASE alpha numeric characters that identify the flight controller.
158 enum {
159 MSP_REBOOT_FIRMWARE = 0,
160 MSP_REBOOT_BOOTLOADER_ROM,
161 MSP_REBOOT_MSC,
162 MSP_REBOOT_MSC_UTC,
163 MSP_REBOOT_BOOTLOADER_FLASH,
164 MSP_REBOOT_COUNT,
167 static uint8_t rebootMode;
169 typedef enum {
170 MSP_SDCARD_STATE_NOT_PRESENT = 0,
171 MSP_SDCARD_STATE_FATAL = 1,
172 MSP_SDCARD_STATE_CARD_INIT = 2,
173 MSP_SDCARD_STATE_FS_INIT = 3,
174 MSP_SDCARD_STATE_READY = 4
175 } mspSDCardState_e;
177 typedef enum {
178 MSP_SDCARD_FLAG_SUPPORTED = 1
179 } mspSDCardFlags_e;
181 typedef enum {
182 MSP_FLASHFS_FLAG_READY = 1,
183 MSP_FLASHFS_FLAG_SUPPORTED = 2
184 } mspFlashFsFlags_e;
186 typedef enum {
187 MSP_PASSTHROUGH_ESC_SIMONK = PROTOCOL_SIMONK,
188 MSP_PASSTHROUGH_ESC_BLHELI = PROTOCOL_BLHELI,
189 MSP_PASSTHROUGH_ESC_KISS = PROTOCOL_KISS,
190 MSP_PASSTHROUGH_ESC_KISSALL = PROTOCOL_KISSALL,
191 MSP_PASSTHROUGH_ESC_CASTLE = PROTOCOL_CASTLE,
193 MSP_PASSTHROUGH_SERIAL_ID = 0xFD,
194 MSP_PASSTHROUGH_SERIAL_FUNCTION_ID = 0xFE,
196 MSP_PASSTHROUGH_ESC_4WAY = 0xFF,
197 } mspPassthroughType_e;
199 #define RATEPROFILE_MASK (1 << 7)
201 #define RTC_NOT_SUPPORTED 0xff
203 typedef enum {
204 DEFAULTS_TYPE_BASE = 0,
205 DEFAULTS_TYPE_CUSTOM,
206 } defaultsType_e;
208 #ifdef USE_VTX_TABLE
209 static bool vtxTableNeedsInit = false;
210 #endif
212 static int mspDescriptor = 0;
214 mspDescriptor_t mspDescriptorAlloc(void)
216 return (mspDescriptor_t)mspDescriptor++;
219 static uint32_t mspArmingDisableFlags = 0;
221 static void mspArmingDisableByDescriptor(mspDescriptor_t desc)
223 mspArmingDisableFlags |= (1 << desc);
226 static void mspArmingEnableByDescriptor(mspDescriptor_t desc)
228 mspArmingDisableFlags &= ~(1 << desc);
231 static bool mspIsMspArmingEnabled(void)
233 return mspArmingDisableFlags == 0;
236 #define MSP_PASSTHROUGH_ESC_4WAY 0xff
238 static uint8_t mspPassthroughMode;
239 static uint8_t mspPassthroughArgument;
241 #ifdef USE_ESCSERIAL
242 static void mspEscPassthroughFn(serialPort_t *serialPort)
244 escEnablePassthrough(serialPort, &motorConfig()->dev, mspPassthroughArgument, mspPassthroughMode);
246 #endif
248 static serialPort_t *mspFindPassthroughSerialPort(void)
250 serialPortUsage_t *portUsage = NULL;
252 switch (mspPassthroughMode) {
253 case MSP_PASSTHROUGH_SERIAL_ID:
255 portUsage = findSerialPortUsageByIdentifier(mspPassthroughArgument);
256 break;
258 case MSP_PASSTHROUGH_SERIAL_FUNCTION_ID:
260 const serialPortConfig_t *portConfig = findSerialPortConfig(1 << mspPassthroughArgument);
261 if (portConfig) {
262 portUsage = findSerialPortUsageByIdentifier(portConfig->identifier);
264 break;
267 return portUsage ? portUsage->serialPort : NULL;
270 static void mspSerialPassthroughFn(serialPort_t *serialPort)
272 serialPort_t *passthroughPort = mspFindPassthroughSerialPort();
273 if (passthroughPort && serialPort) {
274 serialPassthrough(passthroughPort, serialPort, NULL, NULL);
278 static void mspFcSetPassthroughCommand(sbuf_t *dst, sbuf_t *src, mspPostProcessFnPtr *mspPostProcessFn)
280 const unsigned int dataSize = sbufBytesRemaining(src);
281 if (dataSize == 0) {
282 // Legacy format
283 mspPassthroughMode = MSP_PASSTHROUGH_ESC_4WAY;
284 } else {
285 mspPassthroughMode = sbufReadU8(src);
286 mspPassthroughArgument = sbufReadU8(src);
289 switch (mspPassthroughMode) {
290 case MSP_PASSTHROUGH_SERIAL_ID:
291 case MSP_PASSTHROUGH_SERIAL_FUNCTION_ID:
292 if (mspFindPassthroughSerialPort()) {
293 if (mspPostProcessFn) {
294 *mspPostProcessFn = mspSerialPassthroughFn;
296 sbufWriteU8(dst, 1);
297 } else {
298 sbufWriteU8(dst, 0);
300 break;
301 #ifdef USE_SERIAL_4WAY_BLHELI_INTERFACE
302 case MSP_PASSTHROUGH_ESC_4WAY:
303 // get channel number
304 // switch all motor lines HI
305 // reply with the count of ESC found
306 sbufWriteU8(dst, esc4wayInit());
308 if (mspPostProcessFn) {
309 *mspPostProcessFn = esc4wayProcess;
311 break;
313 #ifdef USE_ESCSERIAL
314 case MSP_PASSTHROUGH_ESC_SIMONK:
315 case MSP_PASSTHROUGH_ESC_BLHELI:
316 case MSP_PASSTHROUGH_ESC_KISS:
317 case MSP_PASSTHROUGH_ESC_KISSALL:
318 case MSP_PASSTHROUGH_ESC_CASTLE:
319 if (mspPassthroughArgument < getMotorCount() || (mspPassthroughMode == MSP_PASSTHROUGH_ESC_KISS && mspPassthroughArgument == ALL_MOTORS)) {
320 sbufWriteU8(dst, 1);
322 if (mspPostProcessFn) {
323 *mspPostProcessFn = mspEscPassthroughFn;
326 break;
328 FALLTHROUGH;
329 #endif // USE_ESCSERIAL
330 #endif //USE_SERIAL_4WAY_BLHELI_INTERFACE
331 default:
332 sbufWriteU8(dst, 0);
336 // TODO: Remove the pragma once this is called from unconditional code
337 #pragma GCC diagnostic ignored "-Wunused-function"
338 static void configRebootUpdateCheckU8(uint8_t *parm, uint8_t value)
340 if (*parm != value) {
341 setRebootRequired();
343 *parm = value;
345 #pragma GCC diagnostic pop
347 static void mspRebootFn(serialPort_t *serialPort)
349 UNUSED(serialPort);
351 motorShutdown();
353 switch (rebootMode) {
354 case MSP_REBOOT_FIRMWARE:
355 systemReset();
357 break;
358 case MSP_REBOOT_BOOTLOADER_ROM:
359 systemResetToBootloader(BOOTLOADER_REQUEST_ROM);
361 break;
362 #if defined(USE_USB_MSC)
363 case MSP_REBOOT_MSC:
364 case MSP_REBOOT_MSC_UTC: {
365 #ifdef USE_RTC_TIME
366 const int16_t timezoneOffsetMinutes = (rebootMode == MSP_REBOOT_MSC) ? timeConfig()->tz_offsetMinutes : 0;
367 systemResetToMsc(timezoneOffsetMinutes);
368 #else
369 systemResetToMsc(0);
370 #endif
372 break;
373 #endif
374 #if defined(USE_FLASH_BOOT_LOADER)
375 case MSP_REBOOT_BOOTLOADER_FLASH:
376 systemResetToBootloader(BOOTLOADER_REQUEST_FLASH);
378 break;
379 #endif
380 default:
382 return;
385 // control should never return here.
386 while (true) ;
389 #define MSP_DISPATCH_DELAY_US 1000000
391 void mspReboot(dispatchEntry_t* self)
393 UNUSED(self);
395 if (ARMING_FLAG(ARMED)) {
396 return;
399 mspRebootFn(NULL);
402 dispatchEntry_t mspRebootEntry =
404 mspReboot, 0, NULL, false
407 void writeReadEeprom(dispatchEntry_t* self)
409 UNUSED(self);
411 if (ARMING_FLAG(ARMED)) {
412 return;
415 writeEEPROM();
416 readEEPROM();
418 #ifdef USE_VTX_TABLE
419 if (vtxTableNeedsInit) {
420 vtxTableNeedsInit = false;
421 vtxTableInit(); // Reinitialize and refresh the in-memory copies
423 #endif
426 dispatchEntry_t writeReadEepromEntry =
428 writeReadEeprom, 0, NULL, false
431 static void serializeSDCardSummaryReply(sbuf_t *dst)
433 uint8_t flags = 0;
434 uint8_t state = 0;
435 uint8_t lastError = 0;
436 uint32_t freeSpace = 0;
437 uint32_t totalSpace = 0;
439 #if defined(USE_SDCARD)
440 if (sdcardConfig()->mode != SDCARD_MODE_NONE) {
441 flags = MSP_SDCARD_FLAG_SUPPORTED;
443 // Merge the card and filesystem states together
444 if (!sdcard_isInserted()) {
445 state = MSP_SDCARD_STATE_NOT_PRESENT;
446 } else if (!sdcard_isFunctional()) {
447 state = MSP_SDCARD_STATE_FATAL;
448 } else {
449 switch (afatfs_getFilesystemState()) {
450 case AFATFS_FILESYSTEM_STATE_READY:
451 state = MSP_SDCARD_STATE_READY;
452 break;
454 case AFATFS_FILESYSTEM_STATE_INITIALIZATION:
455 if (sdcard_isInitialized()) {
456 state = MSP_SDCARD_STATE_FS_INIT;
457 } else {
458 state = MSP_SDCARD_STATE_CARD_INIT;
460 break;
462 case AFATFS_FILESYSTEM_STATE_FATAL:
463 case AFATFS_FILESYSTEM_STATE_UNKNOWN:
464 default:
465 state = MSP_SDCARD_STATE_FATAL;
466 break;
470 lastError = afatfs_getLastError();
471 // Write free space and total space in kilobytes
472 if (state == MSP_SDCARD_STATE_READY) {
473 freeSpace = afatfs_getContiguousFreeSpace() / 1024;
474 totalSpace = sdcard_getMetadata()->numBlocks / 2;
477 #endif
479 sbufWriteU8(dst, flags);
480 sbufWriteU8(dst, state);
481 sbufWriteU8(dst, lastError);
482 sbufWriteU32(dst, freeSpace);
483 sbufWriteU32(dst, totalSpace);
486 static void serializeDataflashSummaryReply(sbuf_t *dst)
488 #ifdef USE_FLASHFS
489 if (flashfsIsSupported()) {
490 uint8_t flags = MSP_FLASHFS_FLAG_SUPPORTED;
491 flags |= (flashfsIsReady() ? MSP_FLASHFS_FLAG_READY : 0);
493 const flashPartition_t *flashPartition = flashPartitionFindByType(FLASH_PARTITION_TYPE_FLASHFS);
495 sbufWriteU8(dst, flags);
496 sbufWriteU32(dst, FLASH_PARTITION_SECTOR_COUNT(flashPartition));
497 sbufWriteU32(dst, flashfsGetSize());
498 sbufWriteU32(dst, flashfsGetOffset()); // Effectively the current number of bytes stored on the volume
499 } else
500 #endif
502 // FlashFS is not configured or valid device is not detected
504 sbufWriteU8(dst, 0);
505 sbufWriteU32(dst, 0);
506 sbufWriteU32(dst, 0);
507 sbufWriteU32(dst, 0);
511 #ifdef USE_FLASHFS
512 enum compressionType_e {
513 NO_COMPRESSION,
514 HUFFMAN
517 static void serializeDataflashReadReply(sbuf_t *dst, uint32_t address, const uint16_t size, bool useLegacyFormat, bool allowCompression)
519 STATIC_ASSERT(MSP_PORT_DATAFLASH_INFO_SIZE >= 16, MSP_PORT_DATAFLASH_INFO_SIZE_invalid);
521 uint16_t readLen = size;
522 const int bytesRemainingInBuf = sbufBytesRemaining(dst) - MSP_PORT_DATAFLASH_INFO_SIZE;
523 if (readLen > bytesRemainingInBuf) {
524 readLen = bytesRemainingInBuf;
526 // size will be lower than that requested if we reach end of volume
527 const uint32_t flashfsSize = flashfsGetSize();
528 if (readLen > flashfsSize - address) {
529 // truncate the request
530 readLen = flashfsSize - address;
532 sbufWriteU32(dst, address);
534 // legacy format does not support compression
535 #ifdef USE_HUFFMAN
536 const uint8_t compressionMethod = (!allowCompression || useLegacyFormat) ? NO_COMPRESSION : HUFFMAN;
537 #else
538 const uint8_t compressionMethod = NO_COMPRESSION;
539 UNUSED(allowCompression);
540 #endif
542 if (compressionMethod == NO_COMPRESSION) {
544 uint16_t *readLenPtr = (uint16_t *)sbufPtr(dst);
545 if (!useLegacyFormat) {
546 // new format supports variable read lengths
547 sbufWriteU16(dst, readLen);
548 sbufWriteU8(dst, 0); // placeholder for compression format
551 const int bytesRead = flashfsReadAbs(address, sbufPtr(dst), readLen);
553 if (!useLegacyFormat) {
554 // update the 'read length' with the actual amount read from flash.
555 *readLenPtr = bytesRead;
558 sbufAdvance(dst, bytesRead);
560 if (useLegacyFormat) {
561 // pad the buffer with zeros
562 for (int i = bytesRead; i < size; i++) {
563 sbufWriteU8(dst, 0);
566 } else {
567 #ifdef USE_HUFFMAN
568 // compress in 256-byte chunks
569 const uint16_t READ_BUFFER_SIZE = 256;
570 // This may be DMAable, so make it cache aligned
571 __attribute__ ((aligned(32))) uint8_t readBuffer[READ_BUFFER_SIZE];
573 huffmanState_t state = {
574 .bytesWritten = 0,
575 .outByte = sbufPtr(dst) + sizeof(uint16_t) + sizeof(uint8_t) + HUFFMAN_INFO_SIZE,
576 .outBufLen = readLen,
577 .outBit = 0x80,
579 *state.outByte = 0;
581 uint16_t bytesReadTotal = 0;
582 // read until output buffer overflows or flash is exhausted
583 while (state.bytesWritten < state.outBufLen && address + bytesReadTotal < flashfsSize) {
584 const int bytesRead = flashfsReadAbs(address + bytesReadTotal, readBuffer,
585 MIN(sizeof(readBuffer), flashfsSize - address - bytesReadTotal));
587 const int status = huffmanEncodeBufStreaming(&state, readBuffer, bytesRead, huffmanTable);
588 if (status == -1) {
589 // overflow
590 break;
593 bytesReadTotal += bytesRead;
596 if (state.outBit != 0x80) {
597 ++state.bytesWritten;
600 // header
601 sbufWriteU16(dst, HUFFMAN_INFO_SIZE + state.bytesWritten);
602 sbufWriteU8(dst, compressionMethod);
603 // payload
604 sbufWriteU16(dst, bytesReadTotal);
605 sbufAdvance(dst, state.bytesWritten);
606 #endif
609 #endif // USE_FLASHFS
612 * Returns true if the command was processd, false otherwise.
613 * May set mspPostProcessFunc to a function to be called once the command has been processed
615 static bool mspCommonProcessOutCommand(int16_t cmdMSP, sbuf_t *dst, mspPostProcessFnPtr *mspPostProcessFn)
617 UNUSED(mspPostProcessFn);
619 switch (cmdMSP) {
620 case MSP_API_VERSION:
621 sbufWriteU8(dst, MSP_PROTOCOL_VERSION);
622 sbufWriteU8(dst, API_VERSION_MAJOR);
623 sbufWriteU8(dst, API_VERSION_MINOR);
624 break;
626 case MSP_FC_VARIANT:
627 sbufWriteData(dst, flightControllerIdentifier, FLIGHT_CONTROLLER_IDENTIFIER_LENGTH);
628 break;
630 case MSP_FC_VERSION:
631 sbufWriteU8(dst, FC_VERSION_MAJOR);
632 sbufWriteU8(dst, FC_VERSION_MINOR);
633 sbufWriteU8(dst, FC_VERSION_PATCH_LEVEL);
634 break;
636 case MSP_BOARD_INFO:
638 sbufWriteData(dst, systemConfig()->boardIdentifier, BOARD_IDENTIFIER_LENGTH);
639 #ifdef USE_HARDWARE_REVISION_DETECTION
640 sbufWriteU16(dst, hardwareRevision);
641 #else
642 sbufWriteU16(dst, 0); // No other build targets currently have hardware revision detection.
643 #endif
644 #if defined(USE_MAX7456)
645 sbufWriteU8(dst, 2); // 2 == FC with MAX7456
646 #else
647 sbufWriteU8(dst, 0); // 0 == FC
648 #endif
650 // Target capabilities (uint8)
651 #define TARGET_HAS_VCP 0
652 #define TARGET_HAS_SOFTSERIAL 1
653 #define TARGET_IS_UNIFIED 2
654 #define TARGET_HAS_FLASH_BOOTLOADER 3
655 #define TARGET_SUPPORTS_CUSTOM_DEFAULTS 4
656 #define TARGET_HAS_CUSTOM_DEFAULTS 5
657 #define TARGET_SUPPORTS_RX_BIND 6
659 uint8_t targetCapabilities = 0;
660 #ifdef USE_VCP
661 targetCapabilities |= BIT(TARGET_HAS_VCP);
662 #endif
663 #if defined(USE_SOFTSERIAL1) || defined(USE_SOFTSERIAL2)
664 targetCapabilities |= BIT(TARGET_HAS_SOFTSERIAL);
665 #endif
666 #if defined(USE_UNIFIED_TARGET)
667 targetCapabilities |= BIT(TARGET_IS_UNIFIED);
668 #endif
669 #if defined(USE_FLASH_BOOT_LOADER)
670 targetCapabilities |= BIT(TARGET_HAS_FLASH_BOOTLOADER);
671 #endif
672 #if defined(USE_CUSTOM_DEFAULTS)
673 targetCapabilities |= BIT(TARGET_SUPPORTS_CUSTOM_DEFAULTS);
674 if (hasCustomDefaults()) {
675 targetCapabilities |= BIT(TARGET_HAS_CUSTOM_DEFAULTS);
677 #endif
678 #if defined(USE_RX_BIND)
679 if (getRxBindSupported()) {
680 targetCapabilities |= BIT(TARGET_SUPPORTS_RX_BIND);
682 #endif
684 sbufWriteU8(dst, targetCapabilities);
686 // Target name with explicit length
687 sbufWriteU8(dst, strlen(targetName));
688 sbufWriteData(dst, targetName, strlen(targetName));
690 #if defined(USE_BOARD_INFO)
691 // Board name with explicit length
692 char *value = getBoardName();
693 sbufWriteU8(dst, strlen(value));
694 sbufWriteString(dst, value);
696 // Manufacturer id with explicit length
697 value = getManufacturerId();
698 sbufWriteU8(dst, strlen(value));
699 sbufWriteString(dst, value);
700 #else
701 sbufWriteU8(dst, 0);
702 sbufWriteU8(dst, 0);
703 #endif
705 #if defined(USE_SIGNATURE)
706 // Signature
707 sbufWriteData(dst, getSignature(), SIGNATURE_LENGTH);
708 #else
709 uint8_t emptySignature[SIGNATURE_LENGTH];
710 memset(emptySignature, 0, sizeof(emptySignature));
711 sbufWriteData(dst, &emptySignature, sizeof(emptySignature));
712 #endif
714 sbufWriteU8(dst, getMcuTypeId());
716 // Added in API version 1.42
717 sbufWriteU8(dst, systemConfig()->configurationState);
719 // Added in API version 1.43
720 sbufWriteU16(dst, gyro.sampleRateHz); // informational so the configurator can display the correct gyro/pid frequencies in the drop-down
722 // Configuration warnings / problems (uint32_t)
723 #define PROBLEM_ACC_NEEDS_CALIBRATION 0
724 #define PROBLEM_MOTOR_PROTOCOL_DISABLED 1
726 uint32_t configurationProblems = 0;
728 #if defined(USE_ACC)
729 if (!accHasBeenCalibrated()) {
730 configurationProblems |= BIT(PROBLEM_ACC_NEEDS_CALIBRATION);
732 #endif
734 if (!checkMotorProtocolEnabled(&motorConfig()->dev, NULL)) {
735 configurationProblems |= BIT(PROBLEM_MOTOR_PROTOCOL_DISABLED);
738 sbufWriteU32(dst, configurationProblems);
740 // Added in MSP API 1.44
741 #if defined(USE_SPI)
742 sbufWriteU8(dst, spiGetRegisteredDeviceCount());
743 #else
744 sbufWriteU8(dst, 0);
745 #endif
746 #if defined(USE_I2C)
747 sbufWriteU8(dst, i2cGetRegisteredDeviceCount());
748 #else
749 sbufWriteU8(dst, 0);
750 #endif
752 break;
755 case MSP_BUILD_INFO:
756 sbufWriteData(dst, buildDate, BUILD_DATE_LENGTH);
757 sbufWriteData(dst, buildTime, BUILD_TIME_LENGTH);
758 sbufWriteData(dst, shortGitRevision, GIT_SHORT_REVISION_LENGTH);
759 break;
761 case MSP_ANALOG:
762 sbufWriteU8(dst, (uint8_t)constrain(getLegacyBatteryVoltage(), 0, 255));
763 sbufWriteU16(dst, (uint16_t)constrain(getMAhDrawn(), 0, 0xFFFF)); // milliamp hours drawn from battery
764 sbufWriteU16(dst, getRssi());
765 sbufWriteU16(dst, (int16_t)constrain(getAmperage(), -0x8000, 0x7FFF)); // send current in 0.01 A steps, range is -320A to 320A
766 sbufWriteU16(dst, getBatteryVoltage());
767 break;
769 case MSP_DEBUG:
770 for (int i = 0; i < DEBUG16_VALUE_COUNT; i++) {
771 sbufWriteU16(dst, debug[i]); // 4 variables are here for general monitoring purpose
773 break;
775 case MSP_UID:
776 sbufWriteU32(dst, U_ID_0);
777 sbufWriteU32(dst, U_ID_1);
778 sbufWriteU32(dst, U_ID_2);
779 break;
781 case MSP_FEATURE_CONFIG:
782 sbufWriteU32(dst, featureConfig()->enabledFeatures);
783 break;
785 #ifdef USE_BEEPER
786 case MSP_BEEPER_CONFIG:
787 sbufWriteU32(dst, beeperConfig()->beeper_off_flags);
788 sbufWriteU8(dst, beeperConfig()->dshotBeaconTone);
789 sbufWriteU32(dst, beeperConfig()->dshotBeaconOffFlags);
790 break;
791 #endif
793 case MSP_BATTERY_STATE: {
794 // battery characteristics
795 sbufWriteU8(dst, (uint8_t)constrain(getBatteryCellCount(), 0, 255)); // 0 indicates battery not detected.
796 sbufWriteU16(dst, batteryConfig()->batteryCapacity); // in mAh
798 // battery state
799 sbufWriteU8(dst, (uint8_t)constrain(getLegacyBatteryVoltage(), 0, 255)); // in 0.1V steps
800 sbufWriteU16(dst, (uint16_t)constrain(getMAhDrawn(), 0, 0xFFFF)); // milliamp hours drawn from battery
801 sbufWriteU16(dst, (int16_t)constrain(getAmperage(), -0x8000, 0x7FFF)); // send current in 0.01 A steps, range is -320A to 320A
803 // battery alerts
804 sbufWriteU8(dst, (uint8_t)getBatteryState());
806 sbufWriteU16(dst, getBatteryVoltage()); // in 0.01V steps
807 break;
810 case MSP_VOLTAGE_METERS: {
811 // write out id and voltage meter values, once for each meter we support
812 uint8_t count = supportedVoltageMeterCount;
813 #ifdef USE_ESC_SENSOR
814 count -= VOLTAGE_METER_ID_ESC_COUNT - getMotorCount();
815 #endif
817 for (int i = 0; i < count; i++) {
819 voltageMeter_t meter;
820 uint8_t id = (uint8_t)voltageMeterIds[i];
821 voltageMeterRead(id, &meter);
823 sbufWriteU8(dst, id);
824 sbufWriteU8(dst, (uint8_t)constrain((meter.displayFiltered + 5) / 10, 0, 255));
826 break;
829 case MSP_CURRENT_METERS: {
830 // write out id and current meter values, once for each meter we support
831 uint8_t count = supportedCurrentMeterCount;
832 #ifdef USE_ESC_SENSOR
833 count -= VOLTAGE_METER_ID_ESC_COUNT - getMotorCount();
834 #endif
835 for (int i = 0; i < count; i++) {
837 currentMeter_t meter;
838 uint8_t id = (uint8_t)currentMeterIds[i];
839 currentMeterRead(id, &meter);
841 sbufWriteU8(dst, id);
842 sbufWriteU16(dst, (uint16_t)constrain(meter.mAhDrawn, 0, 0xFFFF)); // milliamp hours drawn from battery
843 sbufWriteU16(dst, (uint16_t)constrain(meter.amperage * 10, 0, 0xFFFF)); // send amperage in 0.001 A steps (mA). Negative range is truncated to zero
845 break;
848 case MSP_VOLTAGE_METER_CONFIG:
850 // by using a sensor type and a sub-frame length it's possible to configure any type of voltage meter,
851 // e.g. an i2c/spi/can sensor or any sensor not built directly into the FC such as ESC/RX/SPort/SBus that has
852 // different configuration requirements.
853 STATIC_ASSERT(VOLTAGE_SENSOR_ADC_VBAT == 0, VOLTAGE_SENSOR_ADC_VBAT_incorrect); // VOLTAGE_SENSOR_ADC_VBAT should be the first index
854 sbufWriteU8(dst, MAX_VOLTAGE_SENSOR_ADC); // voltage meters in payload
855 for (int i = VOLTAGE_SENSOR_ADC_VBAT; i < MAX_VOLTAGE_SENSOR_ADC; i++) {
856 const uint8_t adcSensorSubframeLength = 1 + 1 + 1 + 1 + 1; // length of id, type, vbatscale, vbatresdivval, vbatresdivmultipler, in bytes
857 sbufWriteU8(dst, adcSensorSubframeLength); // ADC sensor sub-frame length
859 sbufWriteU8(dst, voltageMeterADCtoIDMap[i]); // id of the sensor
860 sbufWriteU8(dst, VOLTAGE_SENSOR_TYPE_ADC_RESISTOR_DIVIDER); // indicate the type of sensor that the next part of the payload is for
862 sbufWriteU8(dst, voltageSensorADCConfig(i)->vbatscale);
863 sbufWriteU8(dst, voltageSensorADCConfig(i)->vbatresdivval);
864 sbufWriteU8(dst, voltageSensorADCConfig(i)->vbatresdivmultiplier);
866 // if we had any other voltage sensors, this is where we would output any needed configuration
869 break;
870 case MSP_CURRENT_METER_CONFIG: {
871 // the ADC and VIRTUAL sensors have the same configuration requirements, however this API reflects
872 // that this situation may change and allows us to support configuration of any current sensor with
873 // specialist configuration requirements.
875 int currentMeterCount = 1;
877 #ifdef USE_VIRTUAL_CURRENT_METER
878 currentMeterCount++;
879 #endif
880 sbufWriteU8(dst, currentMeterCount);
882 const uint8_t adcSensorSubframeLength = 1 + 1 + 2 + 2; // length of id, type, scale, offset, in bytes
883 sbufWriteU8(dst, adcSensorSubframeLength);
884 sbufWriteU8(dst, CURRENT_METER_ID_BATTERY_1); // the id of the meter
885 sbufWriteU8(dst, CURRENT_SENSOR_ADC); // indicate the type of sensor that the next part of the payload is for
886 sbufWriteU16(dst, currentSensorADCConfig()->scale);
887 sbufWriteU16(dst, currentSensorADCConfig()->offset);
889 #ifdef USE_VIRTUAL_CURRENT_METER
890 const int8_t virtualSensorSubframeLength = 1 + 1 + 2 + 2; // length of id, type, scale, offset, in bytes
891 sbufWriteU8(dst, virtualSensorSubframeLength);
892 sbufWriteU8(dst, CURRENT_METER_ID_VIRTUAL_1); // the id of the meter
893 sbufWriteU8(dst, CURRENT_SENSOR_VIRTUAL); // indicate the type of sensor that the next part of the payload is for
894 sbufWriteU16(dst, currentSensorVirtualConfig()->scale);
895 sbufWriteU16(dst, currentSensorVirtualConfig()->offset);
896 #endif
898 // if we had any other current sensors, this is where we would output any needed configuration
899 break;
902 case MSP_BATTERY_CONFIG:
903 sbufWriteU8(dst, (batteryConfig()->vbatmincellvoltage + 5) / 10);
904 sbufWriteU8(dst, (batteryConfig()->vbatmaxcellvoltage + 5) / 10);
905 sbufWriteU8(dst, (batteryConfig()->vbatwarningcellvoltage + 5) / 10);
906 sbufWriteU16(dst, batteryConfig()->batteryCapacity);
907 sbufWriteU8(dst, batteryConfig()->voltageMeterSource);
908 sbufWriteU8(dst, batteryConfig()->currentMeterSource);
909 sbufWriteU16(dst, batteryConfig()->vbatmincellvoltage);
910 sbufWriteU16(dst, batteryConfig()->vbatmaxcellvoltage);
911 sbufWriteU16(dst, batteryConfig()->vbatwarningcellvoltage);
912 break;
914 case MSP_TRANSPONDER_CONFIG: {
915 #ifdef USE_TRANSPONDER
916 // Backward compatibility to BFC 3.1.1 is lost for this message type
917 sbufWriteU8(dst, TRANSPONDER_PROVIDER_COUNT);
918 for (unsigned int i = 0; i < TRANSPONDER_PROVIDER_COUNT; i++) {
919 sbufWriteU8(dst, transponderRequirements[i].provider);
920 sbufWriteU8(dst, transponderRequirements[i].dataLength);
923 uint8_t provider = transponderConfig()->provider;
924 sbufWriteU8(dst, provider);
926 if (provider) {
927 uint8_t requirementIndex = provider - 1;
928 uint8_t providerDataLength = transponderRequirements[requirementIndex].dataLength;
930 for (unsigned int i = 0; i < providerDataLength; i++) {
931 sbufWriteU8(dst, transponderConfig()->data[i]);
934 #else
935 sbufWriteU8(dst, 0); // no providers
936 #endif
937 break;
940 case MSP_OSD_CONFIG: {
941 #define OSD_FLAGS_OSD_FEATURE (1 << 0)
942 //#define OSD_FLAGS_OSD_SLAVE (1 << 1)
943 #define OSD_FLAGS_RESERVED_1 (1 << 2)
944 #define OSD_FLAGS_OSD_HARDWARE_FRSKYOSD (1 << 3)
945 #define OSD_FLAGS_OSD_HARDWARE_MAX_7456 (1 << 4)
946 #define OSD_FLAGS_OSD_DEVICE_DETECTED (1 << 5)
948 uint8_t osdFlags = 0;
949 #if defined(USE_OSD)
950 osdFlags |= OSD_FLAGS_OSD_FEATURE;
952 osdDisplayPortDevice_e deviceType;
953 displayPort_t *osdDisplayPort = osdGetDisplayPort(&deviceType);
954 bool displayIsReady = osdDisplayPort && displayCheckReady(osdDisplayPort, true);
955 switch (deviceType) {
956 case OSD_DISPLAYPORT_DEVICE_MAX7456:
957 osdFlags |= OSD_FLAGS_OSD_HARDWARE_MAX_7456;
958 if (displayIsReady) {
959 osdFlags |= OSD_FLAGS_OSD_DEVICE_DETECTED;
962 break;
963 case OSD_DISPLAYPORT_DEVICE_FRSKYOSD:
964 osdFlags |= OSD_FLAGS_OSD_HARDWARE_FRSKYOSD;
965 if (displayIsReady) {
966 osdFlags |= OSD_FLAGS_OSD_DEVICE_DETECTED;
969 break;
970 default:
971 break;
973 #endif
974 sbufWriteU8(dst, osdFlags);
976 #ifdef USE_MAX7456
977 // send video system (AUTO/PAL/NTSC)
978 sbufWriteU8(dst, vcdProfile()->video_system);
979 #else
980 sbufWriteU8(dst, 0);
981 #endif
983 #ifdef USE_OSD
984 // OSD specific, not applicable to OSD slaves.
986 // Configuration
987 sbufWriteU8(dst, osdConfig()->units);
989 // Alarms
990 sbufWriteU8(dst, osdConfig()->rssi_alarm);
991 sbufWriteU16(dst, osdConfig()->cap_alarm);
993 // Reuse old timer alarm (U16) as OSD_ITEM_COUNT
994 sbufWriteU8(dst, 0);
995 sbufWriteU8(dst, OSD_ITEM_COUNT);
997 sbufWriteU16(dst, osdConfig()->alt_alarm);
999 // Element position and visibility
1000 for (int i = 0; i < OSD_ITEM_COUNT; i++) {
1001 sbufWriteU16(dst, osdElementConfig()->item_pos[i]);
1004 // Post flight statistics
1005 sbufWriteU8(dst, OSD_STAT_COUNT);
1006 for (int i = 0; i < OSD_STAT_COUNT; i++ ) {
1007 sbufWriteU8(dst, osdStatGetState(i));
1010 // Timers
1011 sbufWriteU8(dst, OSD_TIMER_COUNT);
1012 for (int i = 0; i < OSD_TIMER_COUNT; i++) {
1013 sbufWriteU16(dst, osdConfig()->timers[i]);
1016 // Enabled warnings
1017 // Send low word first for backwards compatibility (API < 1.41)
1018 sbufWriteU16(dst, (uint16_t)(osdConfig()->enabledWarnings & 0xFFFF));
1019 // API >= 1.41
1020 // Send the warnings count and 32bit enabled warnings flags.
1021 // Add currently active OSD profile (0 indicates OSD profiles not available).
1022 // Add OSD stick overlay mode (0 indicates OSD stick overlay not available).
1023 sbufWriteU8(dst, OSD_WARNING_COUNT);
1024 sbufWriteU32(dst, osdConfig()->enabledWarnings);
1026 #ifdef USE_OSD_PROFILES
1027 sbufWriteU8(dst, OSD_PROFILE_COUNT); // available profiles
1028 sbufWriteU8(dst, osdConfig()->osdProfileIndex); // selected profile
1029 #else
1030 // If the feature is not available there is only 1 profile and it's always selected
1031 sbufWriteU8(dst, 1);
1032 sbufWriteU8(dst, 1);
1033 #endif // USE_OSD_PROFILES
1035 #ifdef USE_OSD_STICK_OVERLAY
1036 sbufWriteU8(dst, osdConfig()->overlay_radio_mode);
1037 #else
1038 sbufWriteU8(dst, 0);
1039 #endif // USE_OSD_STICK_OVERLAY
1041 // API >= 1.43
1042 // Add the camera frame element width/height
1043 sbufWriteU8(dst, osdConfig()->camera_frame_width);
1044 sbufWriteU8(dst, osdConfig()->camera_frame_height);
1046 #endif // USE_OSD
1047 break;
1050 default:
1051 return false;
1053 return true;
1056 static bool mspProcessOutCommand(int16_t cmdMSP, sbuf_t *dst)
1058 bool unsupportedCommand = false;
1060 switch (cmdMSP) {
1061 case MSP_STATUS_EX:
1062 case MSP_STATUS:
1064 boxBitmask_t flightModeFlags;
1065 const int flagBits = packFlightModeFlags(&flightModeFlags);
1067 sbufWriteU16(dst, getTaskDeltaTimeUs(TASK_PID));
1068 #ifdef USE_I2C
1069 sbufWriteU16(dst, i2cGetErrorCounter());
1070 #else
1071 sbufWriteU16(dst, 0);
1072 #endif
1073 sbufWriteU16(dst, sensors(SENSOR_ACC) | sensors(SENSOR_BARO) << 1 | sensors(SENSOR_MAG) << 2 | sensors(SENSOR_GPS) << 3 | sensors(SENSOR_RANGEFINDER) << 4 | sensors(SENSOR_GYRO) << 5);
1074 sbufWriteData(dst, &flightModeFlags, 4); // unconditional part of flags, first 32 bits
1075 sbufWriteU8(dst, getCurrentPidProfileIndex());
1076 sbufWriteU16(dst, constrain(getAverageSystemLoadPercent(), 0, LOAD_PERCENTAGE_ONE));
1077 if (cmdMSP == MSP_STATUS_EX) {
1078 sbufWriteU8(dst, PID_PROFILE_COUNT);
1079 sbufWriteU8(dst, getCurrentControlRateProfileIndex());
1080 } else { // MSP_STATUS
1081 sbufWriteU16(dst, 0); // gyro cycle time
1084 // write flightModeFlags header. Lowest 4 bits contain number of bytes that follow
1085 // header is emited even when all bits fit into 32 bits to allow future extension
1086 int byteCount = (flagBits - 32 + 7) / 8; // 32 already stored, round up
1087 byteCount = constrain(byteCount, 0, 15); // limit to 16 bytes (128 bits)
1088 sbufWriteU8(dst, byteCount);
1089 sbufWriteData(dst, ((uint8_t*)&flightModeFlags) + 4, byteCount);
1091 // Write arming disable flags
1092 // 1 byte, flag count
1093 sbufWriteU8(dst, ARMING_DISABLE_FLAGS_COUNT);
1094 // 4 bytes, flags
1095 const uint32_t armingDisableFlags = getArmingDisableFlags();
1096 sbufWriteU32(dst, armingDisableFlags);
1098 // config state flags - bits to indicate the state of the configuration, reboot required, etc.
1099 // other flags can be added as needed
1100 sbufWriteU8(dst, (getRebootRequired() << 0));
1102 break;
1104 case MSP_RAW_IMU:
1106 #if defined(USE_ACC)
1107 // Hack scale due to choice of units for sensor data in multiwii
1109 uint8_t scale;
1110 if (acc.dev.acc_1G > 512 * 4) {
1111 scale = 8;
1112 } else if (acc.dev.acc_1G > 512 * 2) {
1113 scale = 4;
1114 } else if (acc.dev.acc_1G >= 512) {
1115 scale = 2;
1116 } else {
1117 scale = 1;
1119 #endif
1121 for (int i = 0; i < 3; i++) {
1122 #if defined(USE_ACC)
1123 sbufWriteU16(dst, lrintf(acc.accADC[i] / scale));
1124 #else
1125 sbufWriteU16(dst, 0);
1126 #endif
1128 for (int i = 0; i < 3; i++) {
1129 sbufWriteU16(dst, gyroRateDps(i));
1131 for (int i = 0; i < 3; i++) {
1132 #if defined(USE_MAG)
1133 sbufWriteU16(dst, lrintf(mag.magADC[i]));
1134 #else
1135 sbufWriteU16(dst, 0);
1136 #endif
1139 break;
1141 case MSP_NAME:
1143 const int nameLen = strlen(pilotConfig()->name);
1144 for (int i = 0; i < nameLen; i++) {
1145 sbufWriteU8(dst, pilotConfig()->name[i]);
1148 break;
1150 #ifdef USE_SERVOS
1151 case MSP_SERVO:
1152 sbufWriteData(dst, &servo, MAX_SUPPORTED_SERVOS * 2);
1153 break;
1154 case MSP_SERVO_CONFIGURATIONS:
1155 for (int i = 0; i < MAX_SUPPORTED_SERVOS; i++) {
1156 sbufWriteU16(dst, servoParams(i)->min);
1157 sbufWriteU16(dst, servoParams(i)->max);
1158 sbufWriteU16(dst, servoParams(i)->middle);
1159 sbufWriteU8(dst, servoParams(i)->rate);
1160 sbufWriteU8(dst, servoParams(i)->forwardFromChannel);
1161 sbufWriteU32(dst, servoParams(i)->reversedSources);
1163 break;
1165 case MSP_SERVO_MIX_RULES:
1166 for (int i = 0; i < MAX_SERVO_RULES; i++) {
1167 sbufWriteU8(dst, customServoMixers(i)->targetChannel);
1168 sbufWriteU8(dst, customServoMixers(i)->inputSource);
1169 sbufWriteU8(dst, customServoMixers(i)->rate);
1170 sbufWriteU8(dst, customServoMixers(i)->speed);
1171 sbufWriteU8(dst, customServoMixers(i)->min);
1172 sbufWriteU8(dst, customServoMixers(i)->max);
1173 sbufWriteU8(dst, customServoMixers(i)->box);
1175 break;
1176 #endif
1178 case MSP_MOTOR:
1179 for (unsigned i = 0; i < 8; i++) {
1180 #ifdef USE_MOTOR
1181 if (!motorIsEnabled() || i >= MAX_SUPPORTED_MOTORS || !motorIsMotorEnabled(i)) {
1182 sbufWriteU16(dst, 0);
1183 continue;
1186 sbufWriteU16(dst, motorConvertToExternal(motor[i]));
1187 #else
1188 sbufWriteU16(dst, 0);
1189 #endif
1192 break;
1194 // Added in API version 1.42
1195 case MSP_MOTOR_TELEMETRY:
1196 sbufWriteU8(dst, getMotorCount());
1197 for (unsigned i = 0; i < getMotorCount(); i++) {
1198 int rpm = 0;
1199 uint16_t invalidPct = 0;
1200 uint8_t escTemperature = 0; // degrees celcius
1201 uint16_t escVoltage = 0; // 0.01V per unit
1202 uint16_t escCurrent = 0; // 0.01A per unit
1203 uint16_t escConsumption = 0; // mAh
1205 bool rpmDataAvailable = false;
1207 #ifdef USE_DSHOT_TELEMETRY
1208 if (motorConfig()->dev.useDshotTelemetry) {
1209 rpm = (int)getDshotTelemetry(i) * 100 * 2 / motorConfig()->motorPoleCount;
1210 rpmDataAvailable = true;
1211 invalidPct = 10000; // 100.00%
1212 #ifdef USE_DSHOT_TELEMETRY_STATS
1213 if (isDshotMotorTelemetryActive(i)) {
1214 invalidPct = getDshotTelemetryMotorInvalidPercent(i);
1216 #endif
1218 #endif
1220 #ifdef USE_ESC_SENSOR
1221 if (featureIsEnabled(FEATURE_ESC_SENSOR)) {
1222 escSensorData_t *escData = getEscSensorData(i);
1223 if (!rpmDataAvailable) { // We want DSHOT telemetry RPM data (if available) to have precedence
1224 rpm = calcEscRpm(escData->rpm);
1225 rpmDataAvailable = true;
1227 escTemperature = escData->temperature;
1228 escVoltage = escData->voltage;
1229 escCurrent = escData->current;
1230 escConsumption = escData->consumption;
1232 #endif
1234 sbufWriteU32(dst, (rpmDataAvailable ? rpm : 0));
1235 sbufWriteU16(dst, invalidPct);
1236 sbufWriteU8(dst, escTemperature);
1237 sbufWriteU16(dst, escVoltage);
1238 sbufWriteU16(dst, escCurrent);
1239 sbufWriteU16(dst, escConsumption);
1241 break;
1243 case MSP2_MOTOR_OUTPUT_REORDERING:
1245 sbufWriteU8(dst, MAX_SUPPORTED_MOTORS);
1247 for (unsigned i = 0; i < MAX_SUPPORTED_MOTORS; i++) {
1248 sbufWriteU8(dst, motorConfig()->dev.motorOutputReordering[i]);
1251 break;
1253 #ifdef USE_VTX_COMMON
1254 case MSP2_GET_VTX_DEVICE_STATUS:
1256 const vtxDevice_t *vtxDevice = vtxCommonDevice();
1257 vtxCommonSerializeDeviceStatus(vtxDevice, dst);
1259 break;
1260 #endif
1262 #ifdef USE_OSD
1263 case MSP2_GET_OSD_WARNINGS:
1265 bool isBlinking;
1266 uint8_t displayAttr;
1267 char warningsBuffer[OSD_FORMAT_MESSAGE_BUFFER_SIZE];
1269 renderOsdWarning(warningsBuffer, &isBlinking, &displayAttr);
1270 const uint8_t warningsLen = strlen(warningsBuffer);
1272 if (isBlinking) {
1273 displayAttr |= DISPLAYPORT_ATTR_BLINK;
1275 sbufWriteU8(dst, displayAttr); // see displayPortAttr_e
1276 sbufWriteU8(dst, warningsLen); // length byte followed by the actual characters
1277 for (unsigned i = 0; i < warningsLen; i++) {
1278 sbufWriteU8(dst, warningsBuffer[i]);
1280 break;
1282 #endif
1284 case MSP_RC:
1285 for (int i = 0; i < rxRuntimeState.channelCount; i++) {
1286 sbufWriteU16(dst, rcData[i]);
1288 break;
1290 case MSP_ATTITUDE:
1291 sbufWriteU16(dst, attitude.values.roll);
1292 sbufWriteU16(dst, attitude.values.pitch);
1293 sbufWriteU16(dst, DECIDEGREES_TO_DEGREES(attitude.values.yaw));
1294 break;
1296 case MSP_ALTITUDE:
1297 sbufWriteU32(dst, getEstimatedAltitudeCm());
1298 #ifdef USE_VARIO
1299 sbufWriteU16(dst, getEstimatedVario());
1300 #else
1301 sbufWriteU16(dst, 0);
1302 #endif
1303 break;
1305 case MSP_SONAR_ALTITUDE:
1306 #if defined(USE_RANGEFINDER)
1307 sbufWriteU32(dst, rangefinderGetLatestAltitude());
1308 #else
1309 sbufWriteU32(dst, 0);
1310 #endif
1311 break;
1313 case MSP_BOARD_ALIGNMENT_CONFIG:
1314 sbufWriteU16(dst, boardAlignment()->rollDegrees);
1315 sbufWriteU16(dst, boardAlignment()->pitchDegrees);
1316 sbufWriteU16(dst, boardAlignment()->yawDegrees);
1317 break;
1319 case MSP_ARMING_CONFIG:
1320 sbufWriteU8(dst, armingConfig()->auto_disarm_delay);
1321 sbufWriteU8(dst, 0);
1322 sbufWriteU8(dst, imuConfig()->small_angle);
1323 break;
1325 case MSP_RC_TUNING:
1326 sbufWriteU8(dst, currentControlRateProfile->rcRates[FD_ROLL]);
1327 sbufWriteU8(dst, currentControlRateProfile->rcExpo[FD_ROLL]);
1328 for (int i = 0 ; i < 3; i++) {
1329 sbufWriteU8(dst, currentControlRateProfile->rates[i]); // R,P,Y see flight_dynamics_index_t
1331 sbufWriteU8(dst, currentControlRateProfile->tpa_rate);
1332 sbufWriteU8(dst, currentControlRateProfile->thrMid8);
1333 sbufWriteU8(dst, currentControlRateProfile->thrExpo8);
1334 sbufWriteU16(dst, currentControlRateProfile->tpa_breakpoint);
1335 sbufWriteU8(dst, currentControlRateProfile->rcExpo[FD_YAW]);
1336 sbufWriteU8(dst, currentControlRateProfile->rcRates[FD_YAW]);
1337 sbufWriteU8(dst, currentControlRateProfile->rcRates[FD_PITCH]);
1338 sbufWriteU8(dst, currentControlRateProfile->rcExpo[FD_PITCH]);
1340 // added in 1.41
1341 sbufWriteU8(dst, currentControlRateProfile->throttle_limit_type);
1342 sbufWriteU8(dst, currentControlRateProfile->throttle_limit_percent);
1344 // added in 1.42
1345 sbufWriteU16(dst, currentControlRateProfile->rate_limit[FD_ROLL]);
1346 sbufWriteU16(dst, currentControlRateProfile->rate_limit[FD_PITCH]);
1347 sbufWriteU16(dst, currentControlRateProfile->rate_limit[FD_YAW]);
1349 // added in 1.43
1350 sbufWriteU8(dst, currentControlRateProfile->rates_type);
1352 break;
1354 case MSP_PID:
1355 for (int i = 0; i < PID_ITEM_COUNT; i++) {
1356 sbufWriteU8(dst, currentPidProfile->pid[i].P);
1357 sbufWriteU8(dst, currentPidProfile->pid[i].I);
1358 sbufWriteU8(dst, currentPidProfile->pid[i].D);
1360 break;
1362 case MSP_PIDNAMES:
1363 for (const char *c = pidNames; *c; c++) {
1364 sbufWriteU8(dst, *c);
1366 break;
1368 case MSP_PID_CONTROLLER:
1369 sbufWriteU8(dst, PID_CONTROLLER_BETAFLIGHT);
1370 break;
1372 case MSP_MODE_RANGES:
1373 for (int i = 0; i < MAX_MODE_ACTIVATION_CONDITION_COUNT; i++) {
1374 const modeActivationCondition_t *mac = modeActivationConditions(i);
1375 const box_t *box = findBoxByBoxId(mac->modeId);
1376 sbufWriteU8(dst, box->permanentId);
1377 sbufWriteU8(dst, mac->auxChannelIndex);
1378 sbufWriteU8(dst, mac->range.startStep);
1379 sbufWriteU8(dst, mac->range.endStep);
1381 break;
1383 case MSP_MODE_RANGES_EXTRA:
1384 sbufWriteU8(dst, MAX_MODE_ACTIVATION_CONDITION_COUNT); // prepend number of EXTRAs array elements
1386 for (int i = 0; i < MAX_MODE_ACTIVATION_CONDITION_COUNT; i++) {
1387 const modeActivationCondition_t *mac = modeActivationConditions(i);
1388 const box_t *box = findBoxByBoxId(mac->modeId);
1389 const box_t *linkedBox = findBoxByBoxId(mac->linkedTo);
1390 sbufWriteU8(dst, box->permanentId); // each element is aligned with MODE_RANGES by the permanentId
1391 sbufWriteU8(dst, mac->modeLogic);
1392 sbufWriteU8(dst, linkedBox->permanentId);
1394 break;
1396 case MSP_ADJUSTMENT_RANGES:
1397 for (int i = 0; i < MAX_ADJUSTMENT_RANGE_COUNT; i++) {
1398 const adjustmentRange_t *adjRange = adjustmentRanges(i);
1399 sbufWriteU8(dst, 0); // was adjRange->adjustmentIndex
1400 sbufWriteU8(dst, adjRange->auxChannelIndex);
1401 sbufWriteU8(dst, adjRange->range.startStep);
1402 sbufWriteU8(dst, adjRange->range.endStep);
1403 sbufWriteU8(dst, adjRange->adjustmentConfig);
1404 sbufWriteU8(dst, adjRange->auxSwitchChannelIndex);
1406 break;
1408 case MSP_MOTOR_CONFIG:
1409 sbufWriteU16(dst, motorConfig()->minthrottle);
1410 sbufWriteU16(dst, motorConfig()->maxthrottle);
1411 sbufWriteU16(dst, motorConfig()->mincommand);
1413 // API 1.42
1414 sbufWriteU8(dst, getMotorCount());
1415 sbufWriteU8(dst, motorConfig()->motorPoleCount);
1416 #ifdef USE_DSHOT_TELEMETRY
1417 sbufWriteU8(dst, motorConfig()->dev.useDshotTelemetry);
1418 #else
1419 sbufWriteU8(dst, 0);
1420 #endif
1422 #ifdef USE_ESC_SENSOR
1423 sbufWriteU8(dst, featureIsEnabled(FEATURE_ESC_SENSOR)); // ESC sensor available
1424 #else
1425 sbufWriteU8(dst, 0);
1426 #endif
1427 break;
1429 #if defined(USE_ESC_SENSOR)
1430 // Deprecated in favor of MSP_MOTOR_TELEMETY as of API version 1.42
1431 case MSP_ESC_SENSOR_DATA:
1432 if (featureIsEnabled(FEATURE_ESC_SENSOR)) {
1433 sbufWriteU8(dst, getMotorCount());
1434 for (int i = 0; i < getMotorCount(); i++) {
1435 const escSensorData_t *escData = getEscSensorData(i);
1436 sbufWriteU8(dst, escData->temperature);
1437 sbufWriteU16(dst, escData->rpm);
1439 } else {
1440 unsupportedCommand = true;
1443 break;
1444 #endif
1446 #ifdef USE_GPS
1447 case MSP_GPS_CONFIG:
1448 sbufWriteU8(dst, gpsConfig()->provider);
1449 sbufWriteU8(dst, gpsConfig()->sbasMode);
1450 sbufWriteU8(dst, gpsConfig()->autoConfig);
1451 sbufWriteU8(dst, gpsConfig()->autoBaud);
1452 // Added in API version 1.43
1453 sbufWriteU8(dst, gpsConfig()->gps_set_home_point_once);
1454 sbufWriteU8(dst, gpsConfig()->gps_ublox_use_galileo);
1455 break;
1457 case MSP_RAW_GPS:
1458 sbufWriteU8(dst, STATE(GPS_FIX));
1459 sbufWriteU8(dst, gpsSol.numSat);
1460 sbufWriteU32(dst, gpsSol.llh.lat);
1461 sbufWriteU32(dst, gpsSol.llh.lon);
1462 sbufWriteU16(dst, (uint16_t)constrain(gpsSol.llh.altCm / 100, 0, UINT16_MAX)); // alt changed from 1m to 0.01m per lsb since MSP API 1.39 by RTH. To maintain backwards compatibility compensate to 1m per lsb in MSP again.
1463 sbufWriteU16(dst, gpsSol.groundSpeed);
1464 sbufWriteU16(dst, gpsSol.groundCourse);
1465 // Added in API version 1.44
1466 sbufWriteU16(dst, gpsSol.hdop);
1467 break;
1469 case MSP_COMP_GPS:
1470 sbufWriteU16(dst, GPS_distanceToHome);
1471 sbufWriteU16(dst, GPS_directionToHome);
1472 sbufWriteU8(dst, GPS_update & 1);
1473 break;
1475 case MSP_GPSSVINFO:
1476 sbufWriteU8(dst, GPS_numCh);
1477 for (int i = 0; i < GPS_numCh; i++) {
1478 sbufWriteU8(dst, GPS_svinfo_chn[i]);
1479 sbufWriteU8(dst, GPS_svinfo_svid[i]);
1480 sbufWriteU8(dst, GPS_svinfo_quality[i]);
1481 sbufWriteU8(dst, GPS_svinfo_cno[i]);
1483 break;
1485 #ifdef USE_GPS_RESCUE
1486 case MSP_GPS_RESCUE:
1487 sbufWriteU16(dst, gpsRescueConfig()->angle);
1488 sbufWriteU16(dst, gpsRescueConfig()->initialAltitudeM);
1489 sbufWriteU16(dst, gpsRescueConfig()->descentDistanceM);
1490 sbufWriteU16(dst, gpsRescueConfig()->rescueGroundspeed);
1491 sbufWriteU16(dst, gpsRescueConfig()->throttleMin);
1492 sbufWriteU16(dst, gpsRescueConfig()->throttleMax);
1493 sbufWriteU16(dst, gpsRescueConfig()->throttleHover);
1494 sbufWriteU8(dst, gpsRescueConfig()->sanityChecks);
1495 sbufWriteU8(dst, gpsRescueConfig()->minSats);
1496 // Added in API version 1.43
1497 sbufWriteU16(dst, gpsRescueConfig()->ascendRate);
1498 sbufWriteU16(dst, gpsRescueConfig()->descendRate);
1499 sbufWriteU8(dst, gpsRescueConfig()->allowArmingWithoutFix);
1500 sbufWriteU8(dst, gpsRescueConfig()->altitudeMode);
1501 // Added in API version 1.44
1502 sbufWriteU16(dst, gpsRescueConfig()->minRescueDth);
1503 break;
1505 case MSP_GPS_RESCUE_PIDS:
1506 sbufWriteU16(dst, gpsRescueConfig()->throttleP);
1507 sbufWriteU16(dst, gpsRescueConfig()->throttleI);
1508 sbufWriteU16(dst, gpsRescueConfig()->throttleD);
1509 sbufWriteU16(dst, gpsRescueConfig()->velP);
1510 sbufWriteU16(dst, gpsRescueConfig()->velI);
1511 sbufWriteU16(dst, gpsRescueConfig()->velD);
1512 sbufWriteU16(dst, gpsRescueConfig()->yawP);
1513 break;
1514 #endif
1515 #endif
1517 #if defined(USE_ACC)
1518 case MSP_ACC_TRIM:
1519 sbufWriteU16(dst, accelerometerConfig()->accelerometerTrims.values.pitch);
1520 sbufWriteU16(dst, accelerometerConfig()->accelerometerTrims.values.roll);
1522 break;
1523 #endif
1524 case MSP_MIXER_CONFIG:
1525 sbufWriteU8(dst, mixerConfig()->mixerMode);
1526 sbufWriteU8(dst, mixerConfig()->yaw_motors_reversed);
1527 break;
1529 case MSP_RX_CONFIG:
1530 sbufWriteU8(dst, rxConfig()->serialrx_provider);
1531 sbufWriteU16(dst, rxConfig()->maxcheck);
1532 sbufWriteU16(dst, rxConfig()->midrc);
1533 sbufWriteU16(dst, rxConfig()->mincheck);
1534 sbufWriteU8(dst, rxConfig()->spektrum_sat_bind);
1535 sbufWriteU16(dst, rxConfig()->rx_min_usec);
1536 sbufWriteU16(dst, rxConfig()->rx_max_usec);
1537 sbufWriteU8(dst, 0); // not required in API 1.44, was rxConfig()->rcInterpolation
1538 sbufWriteU8(dst, 0); // not required in API 1.44, was rxConfig()->rcInterpolationInterval
1539 sbufWriteU16(dst, rxConfig()->airModeActivateThreshold * 10 + 1000);
1540 #ifdef USE_RX_SPI
1541 sbufWriteU8(dst, rxSpiConfig()->rx_spi_protocol);
1542 sbufWriteU32(dst, rxSpiConfig()->rx_spi_id);
1543 sbufWriteU8(dst, rxSpiConfig()->rx_spi_rf_channel_count);
1544 #else
1545 sbufWriteU8(dst, 0);
1546 sbufWriteU32(dst, 0);
1547 sbufWriteU8(dst, 0);
1548 #endif
1549 sbufWriteU8(dst, rxConfig()->fpvCamAngleDegrees);
1550 sbufWriteU8(dst, 0); // not required in API 1.44, was rxConfig()->rcSmoothingChannels
1551 #if defined(USE_RC_SMOOTHING_FILTER)
1552 sbufWriteU8(dst, 0); // not required in API 1.44, was rxConfig()->rc_smoothing_type
1553 sbufWriteU8(dst, rxConfig()->rc_smoothing_setpoint_cutoff);
1554 sbufWriteU8(dst, rxConfig()->rc_smoothing_feedforward_cutoff);
1555 sbufWriteU8(dst, 0); // not required in API 1.44, was rxConfig()->rc_smoothing_input_type
1556 sbufWriteU8(dst, 0); // not required in API 1.44, was rxConfig()->rc_smoothing_derivative_type
1557 #else
1558 sbufWriteU8(dst, 0);
1559 sbufWriteU8(dst, 0);
1560 sbufWriteU8(dst, 0);
1561 sbufWriteU8(dst, 0);
1562 sbufWriteU8(dst, 0);
1563 #endif
1564 #if defined(USE_USB_CDC_HID)
1565 sbufWriteU8(dst, usbDevConfig()->type);
1566 #else
1567 sbufWriteU8(dst, 0);
1568 #endif
1569 // Added in MSP API 1.42
1570 #if defined(USE_RC_SMOOTHING_FILTER)
1571 sbufWriteU8(dst, rxConfig()->rc_smoothing_auto_factor_rpy);
1572 #else
1573 sbufWriteU8(dst, 0);
1574 #endif
1575 // Added in MSP API 1.44
1576 #if defined(USE_RC_SMOOTHING_FILTER)
1577 sbufWriteU8(dst, rxConfig()->rc_smoothing_mode);
1578 #else
1579 sbufWriteU8(dst, 0);
1580 #endif
1581 break;
1582 case MSP_FAILSAFE_CONFIG:
1583 sbufWriteU8(dst, failsafeConfig()->failsafe_delay);
1584 sbufWriteU8(dst, failsafeConfig()->failsafe_off_delay);
1585 sbufWriteU16(dst, failsafeConfig()->failsafe_throttle);
1586 sbufWriteU8(dst, failsafeConfig()->failsafe_switch_mode);
1587 sbufWriteU16(dst, failsafeConfig()->failsafe_throttle_low_delay);
1588 sbufWriteU8(dst, failsafeConfig()->failsafe_procedure);
1589 break;
1591 case MSP_RXFAIL_CONFIG:
1592 for (int i = 0; i < rxRuntimeState.channelCount; i++) {
1593 sbufWriteU8(dst, rxFailsafeChannelConfigs(i)->mode);
1594 sbufWriteU16(dst, RXFAIL_STEP_TO_CHANNEL_VALUE(rxFailsafeChannelConfigs(i)->step));
1596 break;
1598 case MSP_RSSI_CONFIG:
1599 sbufWriteU8(dst, rxConfig()->rssi_channel);
1600 break;
1602 case MSP_RX_MAP:
1603 sbufWriteData(dst, rxConfig()->rcmap, RX_MAPPABLE_CHANNEL_COUNT);
1604 break;
1606 case MSP_CF_SERIAL_CONFIG:
1607 for (int i = 0; i < SERIAL_PORT_COUNT; i++) {
1608 if (!serialIsPortAvailable(serialConfig()->portConfigs[i].identifier)) {
1609 continue;
1611 sbufWriteU8(dst, serialConfig()->portConfigs[i].identifier);
1612 sbufWriteU16(dst, serialConfig()->portConfigs[i].functionMask);
1613 sbufWriteU8(dst, serialConfig()->portConfigs[i].msp_baudrateIndex);
1614 sbufWriteU8(dst, serialConfig()->portConfigs[i].gps_baudrateIndex);
1615 sbufWriteU8(dst, serialConfig()->portConfigs[i].telemetry_baudrateIndex);
1616 sbufWriteU8(dst, serialConfig()->portConfigs[i].blackbox_baudrateIndex);
1618 break;
1619 case MSP2_COMMON_SERIAL_CONFIG: {
1620 uint8_t count = 0;
1621 for (int i = 0; i < SERIAL_PORT_COUNT; i++) {
1622 if (serialIsPortAvailable(serialConfig()->portConfigs[i].identifier)) {
1623 count++;
1626 sbufWriteU8(dst, count);
1627 for (int i = 0; i < SERIAL_PORT_COUNT; i++) {
1628 if (!serialIsPortAvailable(serialConfig()->portConfigs[i].identifier)) {
1629 continue;
1631 sbufWriteU8(dst, serialConfig()->portConfigs[i].identifier);
1632 sbufWriteU32(dst, serialConfig()->portConfigs[i].functionMask);
1633 sbufWriteU8(dst, serialConfig()->portConfigs[i].msp_baudrateIndex);
1634 sbufWriteU8(dst, serialConfig()->portConfigs[i].gps_baudrateIndex);
1635 sbufWriteU8(dst, serialConfig()->portConfigs[i].telemetry_baudrateIndex);
1636 sbufWriteU8(dst, serialConfig()->portConfigs[i].blackbox_baudrateIndex);
1638 break;
1641 #ifdef USE_LED_STRIP_STATUS_MODE
1642 case MSP_LED_COLORS:
1643 for (int i = 0; i < LED_CONFIGURABLE_COLOR_COUNT; i++) {
1644 const hsvColor_t *color = &ledStripStatusModeConfig()->colors[i];
1645 sbufWriteU16(dst, color->h);
1646 sbufWriteU8(dst, color->s);
1647 sbufWriteU8(dst, color->v);
1649 break;
1650 #endif
1652 #ifdef USE_LED_STRIP
1653 case MSP_LED_STRIP_CONFIG:
1654 for (int i = 0; i < LED_MAX_STRIP_LENGTH; i++) {
1655 #ifdef USE_LED_STRIP_STATUS_MODE
1656 const ledConfig_t *ledConfig = &ledStripStatusModeConfig()->ledConfigs[i];
1657 sbufWriteU32(dst, *ledConfig);
1658 #else
1659 sbufWriteU32(dst, 0);
1660 #endif
1663 // API 1.41 - add indicator for advanced profile support and the current profile selection
1664 // 0 = basic ledstrip available
1665 // 1 = advanced ledstrip available
1666 #ifdef USE_LED_STRIP_STATUS_MODE
1667 sbufWriteU8(dst, 1); // advanced ledstrip available
1668 #else
1669 sbufWriteU8(dst, 0); // only simple ledstrip available
1670 #endif
1671 sbufWriteU8(dst, ledStripConfig()->ledstrip_profile);
1672 break;
1673 #endif
1675 #ifdef USE_LED_STRIP_STATUS_MODE
1676 case MSP_LED_STRIP_MODECOLOR:
1677 for (int i = 0; i < LED_MODE_COUNT; i++) {
1678 for (int j = 0; j < LED_DIRECTION_COUNT; j++) {
1679 sbufWriteU8(dst, i);
1680 sbufWriteU8(dst, j);
1681 sbufWriteU8(dst, ledStripStatusModeConfig()->modeColors[i].color[j]);
1685 for (int j = 0; j < LED_SPECIAL_COLOR_COUNT; j++) {
1686 sbufWriteU8(dst, LED_MODE_COUNT);
1687 sbufWriteU8(dst, j);
1688 sbufWriteU8(dst, ledStripStatusModeConfig()->specialColors.color[j]);
1691 sbufWriteU8(dst, LED_AUX_CHANNEL);
1692 sbufWriteU8(dst, 0);
1693 sbufWriteU8(dst, ledStripStatusModeConfig()->ledstrip_aux_channel);
1694 break;
1695 #endif
1697 case MSP_DATAFLASH_SUMMARY:
1698 serializeDataflashSummaryReply(dst);
1699 break;
1701 case MSP_BLACKBOX_CONFIG:
1702 #ifdef USE_BLACKBOX
1703 sbufWriteU8(dst, 1); //Blackbox supported
1704 sbufWriteU8(dst, blackboxConfig()->device);
1705 sbufWriteU8(dst, 1); // Rate numerator, not used anymore
1706 sbufWriteU8(dst, blackboxGetRateDenom());
1707 sbufWriteU16(dst, blackboxGetPRatio());
1708 sbufWriteU8(dst, blackboxConfig()->sample_rate);
1709 #else
1710 sbufWriteU8(dst, 0); // Blackbox not supported
1711 sbufWriteU8(dst, 0);
1712 sbufWriteU8(dst, 0);
1713 sbufWriteU8(dst, 0);
1714 sbufWriteU16(dst, 0);
1715 sbufWriteU8(dst, 0);
1716 #endif
1717 break;
1719 case MSP_SDCARD_SUMMARY:
1720 serializeSDCardSummaryReply(dst);
1721 break;
1723 case MSP_MOTOR_3D_CONFIG:
1724 sbufWriteU16(dst, flight3DConfig()->deadband3d_low);
1725 sbufWriteU16(dst, flight3DConfig()->deadband3d_high);
1726 sbufWriteU16(dst, flight3DConfig()->neutral3d);
1727 break;
1729 case MSP_RC_DEADBAND:
1730 sbufWriteU8(dst, rcControlsConfig()->deadband);
1731 sbufWriteU8(dst, rcControlsConfig()->yaw_deadband);
1732 sbufWriteU8(dst, rcControlsConfig()->alt_hold_deadband);
1733 sbufWriteU16(dst, flight3DConfig()->deadband3d_throttle);
1734 break;
1737 case MSP_SENSOR_ALIGNMENT: {
1738 uint8_t gyroAlignment;
1739 #ifdef USE_MULTI_GYRO
1740 switch (gyroConfig()->gyro_to_use) {
1741 case GYRO_CONFIG_USE_GYRO_2:
1742 gyroAlignment = gyroDeviceConfig(1)->alignment;
1743 break;
1744 case GYRO_CONFIG_USE_GYRO_BOTH:
1745 // for dual-gyro in "BOTH" mode we only read/write gyro 0
1746 default:
1747 gyroAlignment = gyroDeviceConfig(0)->alignment;
1748 break;
1750 #else
1751 gyroAlignment = gyroDeviceConfig(0)->alignment;
1752 #endif
1753 sbufWriteU8(dst, gyroAlignment);
1754 sbufWriteU8(dst, gyroAlignment); // Starting with 4.0 gyro and acc alignment are the same
1755 #if defined(USE_MAG)
1756 sbufWriteU8(dst, compassConfig()->mag_alignment);
1757 #else
1758 sbufWriteU8(dst, 0);
1759 #endif
1761 // API 1.41 - Add multi-gyro indicator, selected gyro, and support for separate gyro 1 & 2 alignment
1762 sbufWriteU8(dst, getGyroDetectionFlags());
1763 #ifdef USE_MULTI_GYRO
1764 sbufWriteU8(dst, gyroConfig()->gyro_to_use);
1765 sbufWriteU8(dst, gyroDeviceConfig(0)->alignment);
1766 sbufWriteU8(dst, gyroDeviceConfig(1)->alignment);
1767 #else
1768 sbufWriteU8(dst, GYRO_CONFIG_USE_GYRO_1);
1769 sbufWriteU8(dst, gyroDeviceConfig(0)->alignment);
1770 sbufWriteU8(dst, ALIGN_DEFAULT);
1771 #endif
1773 break;
1775 case MSP_ADVANCED_CONFIG:
1776 sbufWriteU8(dst, 1); // was gyroConfig()->gyro_sync_denom - removed in API 1.43
1777 sbufWriteU8(dst, pidConfig()->pid_process_denom);
1778 sbufWriteU8(dst, motorConfig()->dev.useUnsyncedPwm);
1779 sbufWriteU8(dst, motorConfig()->dev.motorPwmProtocol);
1780 sbufWriteU16(dst, motorConfig()->dev.motorPwmRate);
1781 sbufWriteU16(dst, motorConfig()->digitalIdleOffsetValue);
1782 sbufWriteU8(dst, 0); // DEPRECATED: gyro_use_32kHz
1783 sbufWriteU8(dst, motorConfig()->dev.motorPwmInversion);
1784 sbufWriteU8(dst, gyroConfig()->gyro_to_use);
1785 sbufWriteU8(dst, gyroConfig()->gyro_high_fsr);
1786 sbufWriteU8(dst, gyroConfig()->gyroMovementCalibrationThreshold);
1787 sbufWriteU16(dst, gyroConfig()->gyroCalibrationDuration);
1788 sbufWriteU16(dst, gyroConfig()->gyro_offset_yaw);
1789 sbufWriteU8(dst, gyroConfig()->checkOverflow);
1790 //Added in MSP API 1.42
1791 sbufWriteU8(dst, systemConfig()->debug_mode);
1792 sbufWriteU8(dst, DEBUG_COUNT);
1794 break;
1795 case MSP_FILTER_CONFIG :
1796 sbufWriteU8(dst, gyroConfig()->gyro_lpf1_static_hz);
1797 sbufWriteU16(dst, currentPidProfile->dterm_lpf1_static_hz);
1798 sbufWriteU16(dst, currentPidProfile->yaw_lowpass_hz);
1799 sbufWriteU16(dst, gyroConfig()->gyro_soft_notch_hz_1);
1800 sbufWriteU16(dst, gyroConfig()->gyro_soft_notch_cutoff_1);
1801 sbufWriteU16(dst, currentPidProfile->dterm_notch_hz);
1802 sbufWriteU16(dst, currentPidProfile->dterm_notch_cutoff);
1803 sbufWriteU16(dst, gyroConfig()->gyro_soft_notch_hz_2);
1804 sbufWriteU16(dst, gyroConfig()->gyro_soft_notch_cutoff_2);
1805 sbufWriteU8(dst, currentPidProfile->dterm_lpf1_type);
1806 sbufWriteU8(dst, gyroConfig()->gyro_hardware_lpf);
1807 sbufWriteU8(dst, 0); // DEPRECATED: gyro_32khz_hardware_lpf
1808 sbufWriteU16(dst, gyroConfig()->gyro_lpf1_static_hz);
1809 sbufWriteU16(dst, gyroConfig()->gyro_lpf2_static_hz);
1810 sbufWriteU8(dst, gyroConfig()->gyro_lpf1_type);
1811 sbufWriteU8(dst, gyroConfig()->gyro_lpf2_type);
1812 sbufWriteU16(dst, currentPidProfile->dterm_lpf2_static_hz);
1813 // Added in MSP API 1.41
1814 sbufWriteU8(dst, currentPidProfile->dterm_lpf2_type);
1815 #if defined(USE_DYN_LPF)
1816 sbufWriteU16(dst, gyroConfig()->gyro_lpf1_dyn_min_hz);
1817 sbufWriteU16(dst, gyroConfig()->gyro_lpf1_dyn_max_hz);
1818 sbufWriteU16(dst, currentPidProfile->dterm_lpf1_dyn_min_hz);
1819 sbufWriteU16(dst, currentPidProfile->dterm_lpf1_dyn_max_hz);
1820 #else
1821 sbufWriteU16(dst, 0);
1822 sbufWriteU16(dst, 0);
1823 sbufWriteU16(dst, 0);
1824 sbufWriteU16(dst, 0);
1825 #endif
1826 // Added in MSP API 1.42
1827 #if defined(USE_DYN_NOTCH_FILTER)
1828 sbufWriteU8(dst, 0); // DEPRECATED 1.43: dyn_notch_range
1829 sbufWriteU8(dst, 0); // DEPRECATED 1.44: dyn_notch_width_percent
1830 sbufWriteU16(dst, dynNotchConfig()->dyn_notch_q);
1831 sbufWriteU16(dst, dynNotchConfig()->dyn_notch_min_hz);
1832 #else
1833 sbufWriteU8(dst, 0);
1834 sbufWriteU8(dst, 0);
1835 sbufWriteU16(dst, 0);
1836 sbufWriteU16(dst, 0);
1837 #endif
1838 #if defined(USE_RPM_FILTER)
1839 sbufWriteU8(dst, rpmFilterConfig()->rpm_filter_harmonics);
1840 sbufWriteU8(dst, rpmFilterConfig()->rpm_filter_min_hz);
1841 #else
1842 sbufWriteU8(dst, 0);
1843 sbufWriteU8(dst, 0);
1844 #endif
1845 #if defined(USE_DYN_NOTCH_FILTER)
1846 // Added in MSP API 1.43
1847 sbufWriteU16(dst, dynNotchConfig()->dyn_notch_max_hz);
1848 #else
1849 sbufWriteU16(dst, 0);
1850 #endif
1851 #if defined(USE_DYN_LPF)
1852 // Added in MSP API 1.44
1853 sbufWriteU8(dst, currentPidProfile->dterm_lpf1_dyn_expo);
1854 #else
1855 sbufWriteU8(dst, 0);
1856 #endif
1857 #if defined(USE_DYN_NOTCH_FILTER)
1858 sbufWriteU8(dst, dynNotchConfig()->dyn_notch_count);
1859 #else
1860 sbufWriteU8(dst, 0);
1861 #endif
1863 break;
1864 case MSP_PID_ADVANCED:
1865 sbufWriteU16(dst, 0);
1866 sbufWriteU16(dst, 0);
1867 sbufWriteU16(dst, 0); // was pidProfile.yaw_p_limit
1868 sbufWriteU8(dst, 0); // reserved
1869 sbufWriteU8(dst, 0); // was vbatPidCompensation
1870 #if defined(USE_FEEDFORWARD)
1871 sbufWriteU8(dst, currentPidProfile->feedforward_transition);
1872 #else
1873 sbufWriteU8(dst, 0);
1874 #endif
1875 sbufWriteU8(dst, 0); // was low byte of currentPidProfile->dtermSetpointWeight
1876 sbufWriteU8(dst, 0); // reserved
1877 sbufWriteU8(dst, 0); // reserved
1878 sbufWriteU8(dst, 0); // reserved
1879 sbufWriteU16(dst, currentPidProfile->rateAccelLimit);
1880 sbufWriteU16(dst, currentPidProfile->yawRateAccelLimit);
1881 sbufWriteU8(dst, currentPidProfile->levelAngleLimit);
1882 sbufWriteU8(dst, 0); // was pidProfile.levelSensitivity
1883 sbufWriteU16(dst, currentPidProfile->itermThrottleThreshold);
1884 sbufWriteU16(dst, currentPidProfile->itermAcceleratorGain);
1885 sbufWriteU16(dst, 0); // was currentPidProfile->dtermSetpointWeight
1886 sbufWriteU8(dst, currentPidProfile->iterm_rotation);
1887 sbufWriteU8(dst, 0); // was currentPidProfile->smart_feedforward
1888 #if defined(USE_ITERM_RELAX)
1889 sbufWriteU8(dst, currentPidProfile->iterm_relax);
1890 sbufWriteU8(dst, currentPidProfile->iterm_relax_type);
1891 #else
1892 sbufWriteU8(dst, 0);
1893 sbufWriteU8(dst, 0);
1894 #endif
1895 #if defined(USE_ABSOLUTE_CONTROL)
1896 sbufWriteU8(dst, currentPidProfile->abs_control_gain);
1897 #else
1898 sbufWriteU8(dst, 0);
1899 #endif
1900 #if defined(USE_THROTTLE_BOOST)
1901 sbufWriteU8(dst, currentPidProfile->throttle_boost);
1902 #else
1903 sbufWriteU8(dst, 0);
1904 #endif
1905 #if defined(USE_ACRO_TRAINER)
1906 sbufWriteU8(dst, currentPidProfile->acro_trainer_angle_limit);
1907 #else
1908 sbufWriteU8(dst, 0);
1909 #endif
1910 sbufWriteU16(dst, currentPidProfile->pid[PID_ROLL].F);
1911 sbufWriteU16(dst, currentPidProfile->pid[PID_PITCH].F);
1912 sbufWriteU16(dst, currentPidProfile->pid[PID_YAW].F);
1914 sbufWriteU8(dst, currentPidProfile->antiGravityMode);
1915 #if defined(USE_D_MIN)
1916 sbufWriteU8(dst, currentPidProfile->d_min[PID_ROLL]);
1917 sbufWriteU8(dst, currentPidProfile->d_min[PID_PITCH]);
1918 sbufWriteU8(dst, currentPidProfile->d_min[PID_YAW]);
1919 sbufWriteU8(dst, currentPidProfile->d_min_gain);
1920 sbufWriteU8(dst, currentPidProfile->d_min_advance);
1921 #else
1922 sbufWriteU8(dst, 0);
1923 sbufWriteU8(dst, 0);
1924 sbufWriteU8(dst, 0);
1925 sbufWriteU8(dst, 0);
1926 sbufWriteU8(dst, 0);
1927 #endif
1928 #if defined(USE_INTEGRATED_YAW_CONTROL)
1929 sbufWriteU8(dst, currentPidProfile->use_integrated_yaw);
1930 sbufWriteU8(dst, currentPidProfile->integrated_yaw_relax);
1931 #else
1932 sbufWriteU8(dst, 0);
1933 sbufWriteU8(dst, 0);
1934 #endif
1935 #if defined(USE_ITERM_RELAX)
1936 // Added in MSP API 1.42
1937 sbufWriteU8(dst, currentPidProfile->iterm_relax_cutoff);
1938 #else
1939 sbufWriteU8(dst, 0);
1940 #endif
1941 // Added in MSP API 1.43
1942 sbufWriteU8(dst, currentPidProfile->motor_output_limit);
1943 sbufWriteU8(dst, currentPidProfile->auto_profile_cell_count);
1944 #if defined(USE_DYN_IDLE)
1945 sbufWriteU8(dst, currentPidProfile->dyn_idle_min_rpm);
1946 #else
1947 sbufWriteU8(dst, 0);
1948 #endif
1949 // Added in MSP API 1.44
1950 #if defined(USE_FEEDFORWARD)
1951 sbufWriteU8(dst, currentPidProfile->feedforward_averaging);
1952 sbufWriteU8(dst, currentPidProfile->feedforward_smooth_factor);
1953 sbufWriteU8(dst, currentPidProfile->feedforward_boost);
1954 sbufWriteU8(dst, currentPidProfile->feedforward_max_rate_limit);
1955 sbufWriteU8(dst, currentPidProfile->feedforward_jitter_factor);
1956 #else
1957 sbufWriteU8(dst, 0);
1958 sbufWriteU8(dst, 0);
1959 sbufWriteU8(dst, 0);
1960 sbufWriteU8(dst, 0);
1961 sbufWriteU8(dst, 0);
1962 #endif
1963 #if defined(USE_BATTERY_VOLTAGE_SAG_COMPENSATION)
1964 sbufWriteU8(dst, currentPidProfile->vbat_sag_compensation);
1965 #else
1966 sbufWriteU8(dst, 0);
1967 #endif
1968 #if defined(USE_THRUST_LINEARIZATION)
1969 sbufWriteU8(dst, currentPidProfile->thrustLinearization);
1970 #else
1971 sbufWriteU8(dst, 0);
1972 #endif
1973 break;
1974 case MSP_SENSOR_CONFIG:
1975 #if defined(USE_ACC)
1976 sbufWriteU8(dst, accelerometerConfig()->acc_hardware);
1977 #else
1978 sbufWriteU8(dst, 0);
1979 #endif
1980 #ifdef USE_BARO
1981 sbufWriteU8(dst, barometerConfig()->baro_hardware);
1982 #else
1983 sbufWriteU8(dst, BARO_NONE);
1984 #endif
1985 #ifdef USE_MAG
1986 sbufWriteU8(dst, compassConfig()->mag_hardware);
1987 #else
1988 sbufWriteU8(dst, MAG_NONE);
1989 #endif
1990 break;
1992 #if defined(USE_VTX_COMMON)
1993 case MSP_VTX_CONFIG:
1995 const vtxDevice_t *vtxDevice = vtxCommonDevice();
1996 unsigned vtxStatus = 0;
1997 vtxDevType_e vtxType = VTXDEV_UNKNOWN;
1998 uint8_t deviceIsReady = 0;
1999 if (vtxDevice) {
2000 vtxCommonGetStatus(vtxDevice, &vtxStatus);
2001 vtxType = vtxCommonGetDeviceType(vtxDevice);
2002 deviceIsReady = vtxCommonDeviceIsReady(vtxDevice) ? 1 : 0;
2004 sbufWriteU8(dst, vtxType);
2005 sbufWriteU8(dst, vtxSettingsConfig()->band);
2006 sbufWriteU8(dst, vtxSettingsConfig()->channel);
2007 sbufWriteU8(dst, vtxSettingsConfig()->power);
2008 sbufWriteU8(dst, (vtxStatus & VTX_STATUS_PIT_MODE) ? 1 : 0);
2009 sbufWriteU16(dst, vtxSettingsConfig()->freq);
2010 sbufWriteU8(dst, deviceIsReady);
2011 sbufWriteU8(dst, vtxSettingsConfig()->lowPowerDisarm);
2013 // API version 1.42
2014 sbufWriteU16(dst, vtxSettingsConfig()->pitModeFreq);
2015 #ifdef USE_VTX_TABLE
2016 sbufWriteU8(dst, 1); // vtxtable is available
2017 sbufWriteU8(dst, vtxTableConfig()->bands);
2018 sbufWriteU8(dst, vtxTableConfig()->channels);
2019 sbufWriteU8(dst, vtxTableConfig()->powerLevels);
2020 #else
2021 sbufWriteU8(dst, 0);
2022 sbufWriteU8(dst, 0);
2023 sbufWriteU8(dst, 0);
2024 sbufWriteU8(dst, 0);
2025 #endif
2028 break;
2029 #endif
2031 case MSP_TX_INFO:
2032 sbufWriteU8(dst, rssiSource);
2033 uint8_t rtcDateTimeIsSet = 0;
2034 #ifdef USE_RTC_TIME
2035 dateTime_t dt;
2036 if (rtcGetDateTime(&dt)) {
2037 rtcDateTimeIsSet = 1;
2039 #else
2040 rtcDateTimeIsSet = RTC_NOT_SUPPORTED;
2041 #endif
2042 sbufWriteU8(dst, rtcDateTimeIsSet);
2044 break;
2045 #ifdef USE_RTC_TIME
2046 case MSP_RTC:
2048 dateTime_t dt;
2049 if (rtcGetDateTime(&dt)) {
2050 sbufWriteU16(dst, dt.year);
2051 sbufWriteU8(dst, dt.month);
2052 sbufWriteU8(dst, dt.day);
2053 sbufWriteU8(dst, dt.hours);
2054 sbufWriteU8(dst, dt.minutes);
2055 sbufWriteU8(dst, dt.seconds);
2056 sbufWriteU16(dst, dt.millis);
2060 break;
2061 #endif
2062 default:
2063 unsupportedCommand = true;
2065 return !unsupportedCommand;
2069 #ifdef USE_SIMPLIFIED_TUNING
2070 // Reads simplified PID tuning values from MSP buffer
2071 static void readSimplifiedPids(pidProfile_t* pidProfile, sbuf_t *src)
2073 pidProfile->simplified_pids_mode = sbufReadU8(src);
2074 pidProfile->simplified_master_multiplier = sbufReadU8(src);
2075 pidProfile->simplified_roll_pitch_ratio = sbufReadU8(src);
2076 pidProfile->simplified_i_gain = sbufReadU8(src);
2077 pidProfile->simplified_d_gain = sbufReadU8(src);
2078 pidProfile->simplified_pi_gain = sbufReadU8(src);
2079 #ifdef USE_D_MIN
2080 pidProfile->simplified_dmin_ratio = sbufReadU8(src);
2081 #else
2082 sbufReadU8(src);
2083 #endif
2084 pidProfile->simplified_feedforward_gain = sbufReadU8(src);
2085 pidProfile->simplified_pitch_pi_gain = sbufReadU8(src);
2086 sbufReadU32(src); // reserved for future use
2087 sbufReadU32(src); // reserved for future use
2090 // Writes simplified PID tuning values to MSP buffer
2091 static void writeSimplifiedPids(const pidProfile_t *pidProfile, sbuf_t *dst)
2093 sbufWriteU8(dst, pidProfile->simplified_pids_mode);
2094 sbufWriteU8(dst, pidProfile->simplified_master_multiplier);
2095 sbufWriteU8(dst, pidProfile->simplified_roll_pitch_ratio);
2096 sbufWriteU8(dst, pidProfile->simplified_i_gain);
2097 sbufWriteU8(dst, pidProfile->simplified_d_gain);
2098 sbufWriteU8(dst, pidProfile->simplified_pi_gain);
2099 #ifdef USE_D_MIN
2100 sbufWriteU8(dst, pidProfile->simplified_dmin_ratio);
2101 #else
2102 sbufWriteU8(dst, 0);
2103 #endif
2104 sbufWriteU8(dst, pidProfile->simplified_feedforward_gain);
2105 sbufWriteU8(dst, pidProfile->simplified_pitch_pi_gain);
2106 sbufWriteU32(dst, 0); // reserved for future use
2107 sbufWriteU32(dst, 0); // reserved for future use
2110 // Reads simplified Dterm Filter values from MSP buffer
2111 static void readSimplifiedDtermFilters(pidProfile_t* pidProfile, sbuf_t *src)
2113 pidProfile->simplified_dterm_filter = sbufReadU8(src);
2114 pidProfile->simplified_dterm_filter_multiplier = sbufReadU8(src);
2115 pidProfile->dterm_lpf1_static_hz = sbufReadU16(src);
2116 pidProfile->dterm_lpf2_static_hz = sbufReadU16(src);
2117 #if defined(USE_DYN_LPF)
2118 pidProfile->dterm_lpf1_dyn_min_hz = sbufReadU16(src);
2119 pidProfile->dterm_lpf1_dyn_max_hz = sbufReadU16(src);
2120 #else
2121 sbufReadU16(src);
2122 sbufReadU16(src);
2123 #endif
2124 sbufReadU32(src); // reserved for future use
2125 sbufReadU32(src); // reserved for future use
2128 // Writes simplified Dterm Filter values into MSP buffer
2129 static void writeSimplifiedDtermFilters(const pidProfile_t* pidProfile, sbuf_t *dst)
2131 sbufWriteU8(dst, pidProfile->simplified_dterm_filter);
2132 sbufWriteU8(dst, pidProfile->simplified_dterm_filter_multiplier);
2133 sbufWriteU16(dst, pidProfile->dterm_lpf1_static_hz);
2134 sbufWriteU16(dst, pidProfile->dterm_lpf2_static_hz);
2135 #if defined(USE_DYN_LPF)
2136 sbufWriteU16(dst, pidProfile->dterm_lpf1_dyn_min_hz);
2137 sbufWriteU16(dst, pidProfile->dterm_lpf1_dyn_max_hz);
2138 #else
2139 sbufWriteU16(dst, 0);
2140 sbufWriteU16(dst, 0);
2141 #endif
2142 sbufWriteU32(dst, 0); // reserved for future use
2143 sbufWriteU32(dst, 0); // reserved for future use
2146 // Writes simplified Gyro Filter values from MSP buffer
2147 static void readSimplifiedGyroFilters(gyroConfig_t *gyroConfig, sbuf_t *src)
2149 gyroConfig->simplified_gyro_filter = sbufReadU8(src);
2150 gyroConfig->simplified_gyro_filter_multiplier = sbufReadU8(src);
2151 gyroConfig->gyro_lpf1_static_hz = sbufReadU16(src);
2152 gyroConfig->gyro_lpf2_static_hz = sbufReadU16(src);
2153 #if defined(USE_DYN_LPF)
2154 gyroConfig->gyro_lpf1_dyn_min_hz = sbufReadU16(src);
2155 gyroConfig->gyro_lpf1_dyn_max_hz = sbufReadU16(src);
2156 #else
2157 sbufReadU16(src);
2158 sbufReadU16(src);
2159 #endif
2160 sbufReadU32(src); // reserved for future use
2161 sbufReadU32(src); // reserved for future use
2164 // Writes simplified Gyro Filter values into MSP buffer
2165 static void writeSimplifiedGyroFilters(const gyroConfig_t *gyroConfig, sbuf_t *dst)
2167 sbufWriteU8(dst, gyroConfig->simplified_gyro_filter);
2168 sbufWriteU8(dst, gyroConfig->simplified_gyro_filter_multiplier);
2169 sbufWriteU16(dst, gyroConfig->gyro_lpf1_static_hz);
2170 sbufWriteU16(dst, gyroConfig->gyro_lpf2_static_hz);
2171 #if defined(USE_DYN_LPF)
2172 sbufWriteU16(dst, gyroConfig->gyro_lpf1_dyn_min_hz);
2173 sbufWriteU16(dst, gyroConfig->gyro_lpf1_dyn_max_hz);
2174 #else
2175 sbufWriteU16(dst, 0);
2176 sbufWriteU16(dst, 0);
2177 #endif
2178 sbufWriteU32(dst, 0); // reserved for future use
2179 sbufWriteU32(dst, 0); // reserved for future use
2182 // writes results of simplified PID tuning values to MSP buffer
2183 static void writePidfs(pidProfile_t* pidProfile, sbuf_t *dst)
2185 for (int i = 0; i < XYZ_AXIS_COUNT; i++) {
2186 sbufWriteU8(dst, pidProfile->pid[i].P);
2187 sbufWriteU8(dst, pidProfile->pid[i].I);
2188 sbufWriteU8(dst, pidProfile->pid[i].D);
2189 sbufWriteU8(dst, pidProfile->d_min[i]);
2190 sbufWriteU16(dst, pidProfile->pid[i].F);
2193 #endif // USE_SIMPLIFIED_TUNING
2195 static mspResult_e mspFcProcessOutCommandWithArg(mspDescriptor_t srcDesc, int16_t cmdMSP, sbuf_t *src, sbuf_t *dst, mspPostProcessFnPtr *mspPostProcessFn)
2198 switch (cmdMSP) {
2199 case MSP_BOXNAMES:
2201 const int page = sbufBytesRemaining(src) ? sbufReadU8(src) : 0;
2202 serializeBoxReply(dst, page, &serializeBoxNameFn);
2204 break;
2205 case MSP_BOXIDS:
2207 const int page = sbufBytesRemaining(src) ? sbufReadU8(src) : 0;
2208 serializeBoxReply(dst, page, &serializeBoxPermanentIdFn);
2210 break;
2211 case MSP_REBOOT:
2212 if (sbufBytesRemaining(src)) {
2213 rebootMode = sbufReadU8(src);
2215 if (rebootMode >= MSP_REBOOT_COUNT
2216 #if !defined(USE_USB_MSC)
2217 || rebootMode == MSP_REBOOT_MSC || rebootMode == MSP_REBOOT_MSC_UTC
2218 #endif
2220 return MSP_RESULT_ERROR;
2222 } else {
2223 rebootMode = MSP_REBOOT_FIRMWARE;
2226 sbufWriteU8(dst, rebootMode);
2228 #if defined(USE_USB_MSC)
2229 if (rebootMode == MSP_REBOOT_MSC) {
2230 if (mscCheckFilesystemReady()) {
2231 sbufWriteU8(dst, 1);
2232 } else {
2233 sbufWriteU8(dst, 0);
2235 return MSP_RESULT_ACK;
2238 #endif
2240 #if defined(USE_MSP_OVER_TELEMETRY)
2241 if (featureIsEnabled(FEATURE_RX_SPI) && srcDesc == getMspTelemetryDescriptor()) {
2242 dispatchAdd(&mspRebootEntry, MSP_DISPATCH_DELAY_US);
2243 } else
2244 #endif
2245 if (mspPostProcessFn) {
2246 *mspPostProcessFn = mspRebootFn;
2249 break;
2250 case MSP_MULTIPLE_MSP:
2252 uint8_t maxMSPs = 0;
2253 if (sbufBytesRemaining(src) == 0) {
2254 return MSP_RESULT_ERROR;
2256 int bytesRemaining = sbufBytesRemaining(dst) - 1; // need to keep one byte for checksum
2257 mspPacket_t packetIn, packetOut;
2258 sbufInit(&packetIn.buf, src->end, src->end);
2259 uint8_t* resetInputPtr = src->ptr;
2260 while (sbufBytesRemaining(src) && bytesRemaining > 0) {
2261 uint8_t newMSP = sbufReadU8(src);
2262 sbufInit(&packetOut.buf, dst->ptr, dst->end);
2263 packetIn.cmd = newMSP;
2264 mspFcProcessCommand(srcDesc, &packetIn, &packetOut, NULL);
2265 uint8_t mspSize = sbufPtr(&packetOut.buf) - dst->ptr;
2266 mspSize++; // need to add length information for each MSP
2267 bytesRemaining -= mspSize;
2268 if (bytesRemaining >= 0) {
2269 maxMSPs++;
2272 src->ptr = resetInputPtr;
2273 sbufInit(&packetOut.buf, dst->ptr, dst->end);
2274 for (int i = 0; i < maxMSPs; i++) {
2275 uint8_t* sizePtr = sbufPtr(&packetOut.buf);
2276 sbufWriteU8(&packetOut.buf, 0); // dummy
2277 packetIn.cmd = sbufReadU8(src);
2278 mspFcProcessCommand(srcDesc, &packetIn, &packetOut, NULL);
2279 (*sizePtr) = sbufPtr(&packetOut.buf) - (sizePtr + 1);
2281 dst->ptr = packetOut.buf.ptr;
2283 break;
2285 #ifdef USE_VTX_TABLE
2286 case MSP_VTXTABLE_BAND:
2288 const uint8_t band = sbufBytesRemaining(src) ? sbufReadU8(src) : 0;
2289 if (band > 0 && band <= VTX_TABLE_MAX_BANDS) {
2290 sbufWriteU8(dst, band); // band number (same as request)
2291 sbufWriteU8(dst, VTX_TABLE_BAND_NAME_LENGTH); // band name length
2292 for (int i = 0; i < VTX_TABLE_BAND_NAME_LENGTH; i++) { // band name bytes
2293 sbufWriteU8(dst, vtxTableConfig()->bandNames[band - 1][i]);
2295 sbufWriteU8(dst, vtxTableConfig()->bandLetters[band - 1]); // band letter
2296 sbufWriteU8(dst, vtxTableConfig()->isFactoryBand[band - 1]); // CUSTOM = 0; FACTORY = 1
2297 sbufWriteU8(dst, vtxTableConfig()->channels); // number of channel frequencies to follow
2298 for (int i = 0; i < vtxTableConfig()->channels; i++) { // the frequency for each channel
2299 sbufWriteU16(dst, vtxTableConfig()->frequency[band - 1][i]);
2301 } else {
2302 return MSP_RESULT_ERROR;
2305 break;
2307 case MSP_VTXTABLE_POWERLEVEL:
2309 const uint8_t powerLevel = sbufBytesRemaining(src) ? sbufReadU8(src) : 0;
2310 if (powerLevel > 0 && powerLevel <= VTX_TABLE_MAX_POWER_LEVELS) {
2311 sbufWriteU8(dst, powerLevel); // powerLevel number (same as request)
2312 sbufWriteU16(dst, vtxTableConfig()->powerValues[powerLevel - 1]);
2313 sbufWriteU8(dst, VTX_TABLE_POWER_LABEL_LENGTH); // powerLevel label length
2314 for (int i = 0; i < VTX_TABLE_POWER_LABEL_LENGTH; i++) { // powerlevel label bytes
2315 sbufWriteU8(dst, vtxTableConfig()->powerLabels[powerLevel - 1][i]);
2317 } else {
2318 return MSP_RESULT_ERROR;
2321 break;
2322 #endif // USE_VTX_TABLE
2324 #ifdef USE_SIMPLIFIED_TUNING
2325 // Added in MSP API 1.44
2326 case MSP_SIMPLIFIED_TUNING:
2328 writeSimplifiedPids(currentPidProfile, dst);
2329 writeSimplifiedDtermFilters(currentPidProfile, dst);
2330 writeSimplifiedGyroFilters(gyroConfig(), dst);
2332 break;
2334 case MSP_CALCULATE_SIMPLIFIED_PID:
2336 pidProfile_t tempPidProfile = *currentPidProfile;
2337 readSimplifiedPids(&tempPidProfile, src);
2338 applySimplifiedTuningPids(&tempPidProfile);
2339 writePidfs(&tempPidProfile, dst);
2341 break;
2343 case MSP_CALCULATE_SIMPLIFIED_DTERM:
2345 pidProfile_t tempPidProfile = *currentPidProfile;
2346 readSimplifiedDtermFilters(&tempPidProfile, src);
2347 applySimplifiedTuningDtermFilters(&tempPidProfile);
2348 writeSimplifiedDtermFilters(&tempPidProfile, dst);
2350 break;
2352 case MSP_CALCULATE_SIMPLIFIED_GYRO:
2354 gyroConfig_t tempGyroConfig = *gyroConfig();
2355 readSimplifiedGyroFilters(&tempGyroConfig, src);
2356 applySimplifiedTuningGyroFilters(&tempGyroConfig);
2357 writeSimplifiedGyroFilters(&tempGyroConfig, dst);
2359 break;
2361 case MSP_VALIDATE_SIMPLIFIED_TUNING:
2363 pidProfile_t tempPidProfile = *currentPidProfile;
2364 applySimplifiedTuningPids(&tempPidProfile);
2365 bool result = true;
2367 for (int i = 0; i < XYZ_AXIS_COUNT; i++) {
2368 result = result &&
2369 tempPidProfile.pid[i].P == currentPidProfile->pid[i].P &&
2370 tempPidProfile.pid[i].I == currentPidProfile->pid[i].I &&
2371 tempPidProfile.pid[i].D == currentPidProfile->pid[i].D &&
2372 tempPidProfile.d_min[i] == currentPidProfile->d_min[i] &&
2373 tempPidProfile.pid[i].F == currentPidProfile->pid[i].F;
2376 sbufWriteU8(dst, result);
2378 gyroConfig_t tempGyroConfig = *gyroConfig();
2379 applySimplifiedTuningGyroFilters(&tempGyroConfig);
2380 result =
2381 tempGyroConfig.gyro_lpf1_static_hz == gyroConfig()->gyro_lpf1_static_hz &&
2382 tempGyroConfig.gyro_lpf2_static_hz == gyroConfig()->gyro_lpf2_static_hz;
2384 #if defined(USE_DYN_LPF)
2385 result = result &&
2386 tempGyroConfig.gyro_lpf1_dyn_min_hz == gyroConfig()->gyro_lpf1_dyn_min_hz &&
2387 tempGyroConfig.gyro_lpf1_dyn_max_hz == gyroConfig()->gyro_lpf1_dyn_max_hz;
2388 #endif
2390 sbufWriteU8(dst, result);
2392 applySimplifiedTuningDtermFilters(&tempPidProfile);
2393 result =
2394 tempPidProfile.dterm_lpf1_static_hz == currentPidProfile->dterm_lpf1_static_hz &&
2395 tempPidProfile.dterm_lpf2_static_hz == currentPidProfile->dterm_lpf2_static_hz;
2397 #if defined(USE_DYN_LPF)
2398 result = result &&
2399 tempPidProfile.dterm_lpf1_dyn_min_hz == currentPidProfile->dterm_lpf1_dyn_min_hz &&
2400 tempPidProfile.dterm_lpf1_dyn_max_hz == currentPidProfile->dterm_lpf1_dyn_max_hz;
2401 #endif
2403 sbufWriteU8(dst, result);
2405 break;
2406 #endif
2408 case MSP_RESET_CONF:
2410 #if defined(USE_CUSTOM_DEFAULTS)
2411 defaultsType_e defaultsType = DEFAULTS_TYPE_CUSTOM;
2412 #endif
2413 if (sbufBytesRemaining(src) >= 1) {
2414 // Added in MSP API 1.42
2415 #if defined(USE_CUSTOM_DEFAULTS)
2416 defaultsType = sbufReadU8(src);
2417 #else
2418 sbufReadU8(src);
2419 #endif
2422 bool success = false;
2423 if (!ARMING_FLAG(ARMED)) {
2424 #if defined(USE_CUSTOM_DEFAULTS)
2425 success = resetEEPROM(defaultsType == DEFAULTS_TYPE_CUSTOM);
2426 #else
2427 success = resetEEPROM(false);
2428 #endif
2430 if (success && mspPostProcessFn) {
2431 rebootMode = MSP_REBOOT_FIRMWARE;
2432 *mspPostProcessFn = mspRebootFn;
2436 // Added in API version 1.42
2437 sbufWriteU8(dst, success);
2440 break;
2441 default:
2442 return MSP_RESULT_CMD_UNKNOWN;
2444 return MSP_RESULT_ACK;
2447 #ifdef USE_FLASHFS
2448 static void mspFcDataFlashReadCommand(sbuf_t *dst, sbuf_t *src)
2450 const unsigned int dataSize = sbufBytesRemaining(src);
2451 const uint32_t readAddress = sbufReadU32(src);
2452 uint16_t readLength;
2453 bool allowCompression = false;
2454 bool useLegacyFormat;
2455 if (dataSize >= sizeof(uint32_t) + sizeof(uint16_t)) {
2456 readLength = sbufReadU16(src);
2457 if (sbufBytesRemaining(src)) {
2458 allowCompression = sbufReadU8(src);
2460 useLegacyFormat = false;
2461 } else {
2462 readLength = 128;
2463 useLegacyFormat = true;
2466 serializeDataflashReadReply(dst, readAddress, readLength, useLegacyFormat, allowCompression);
2468 #endif
2470 static mspResult_e mspProcessInCommand(mspDescriptor_t srcDesc, int16_t cmdMSP, sbuf_t *src)
2472 uint32_t i;
2473 uint8_t value;
2474 const unsigned int dataSize = sbufBytesRemaining(src);
2475 switch (cmdMSP) {
2476 case MSP_SELECT_SETTING:
2477 value = sbufReadU8(src);
2478 if ((value & RATEPROFILE_MASK) == 0) {
2479 if (!ARMING_FLAG(ARMED)) {
2480 if (value >= PID_PROFILE_COUNT) {
2481 value = 0;
2483 changePidProfile(value);
2485 } else {
2486 value = value & ~RATEPROFILE_MASK;
2488 if (value >= CONTROL_RATE_PROFILE_COUNT) {
2489 value = 0;
2491 changeControlRateProfile(value);
2493 break;
2495 case MSP_COPY_PROFILE:
2496 value = sbufReadU8(src); // 0 = pid profile, 1 = control rate profile
2497 uint8_t dstProfileIndex = sbufReadU8(src);
2498 uint8_t srcProfileIndex = sbufReadU8(src);
2499 if (value == 0) {
2500 pidCopyProfile(dstProfileIndex, srcProfileIndex);
2502 else if (value == 1) {
2503 copyControlRateProfile(dstProfileIndex, srcProfileIndex);
2505 break;
2507 #if defined(USE_GPS) || defined(USE_MAG)
2508 case MSP_SET_HEADING:
2509 magHold = sbufReadU16(src);
2510 break;
2511 #endif
2513 case MSP_SET_RAW_RC:
2514 #ifdef USE_RX_MSP
2516 uint8_t channelCount = dataSize / sizeof(uint16_t);
2517 if (channelCount > MAX_SUPPORTED_RC_CHANNEL_COUNT) {
2518 return MSP_RESULT_ERROR;
2519 } else {
2520 uint16_t frame[MAX_SUPPORTED_RC_CHANNEL_COUNT];
2521 for (int i = 0; i < channelCount; i++) {
2522 frame[i] = sbufReadU16(src);
2524 rxMspFrameReceive(frame, channelCount);
2527 #endif
2528 break;
2529 #if defined(USE_ACC)
2530 case MSP_SET_ACC_TRIM:
2531 accelerometerConfigMutable()->accelerometerTrims.values.pitch = sbufReadU16(src);
2532 accelerometerConfigMutable()->accelerometerTrims.values.roll = sbufReadU16(src);
2534 break;
2535 #endif
2536 case MSP_SET_ARMING_CONFIG:
2537 armingConfigMutable()->auto_disarm_delay = sbufReadU8(src);
2538 sbufReadU8(src); // reserved
2539 if (sbufBytesRemaining(src)) {
2540 imuConfigMutable()->small_angle = sbufReadU8(src);
2542 break;
2544 case MSP_SET_PID_CONTROLLER:
2545 break;
2547 case MSP_SET_PID:
2548 for (int i = 0; i < PID_ITEM_COUNT; i++) {
2549 currentPidProfile->pid[i].P = sbufReadU8(src);
2550 currentPidProfile->pid[i].I = sbufReadU8(src);
2551 currentPidProfile->pid[i].D = sbufReadU8(src);
2553 pidInitConfig(currentPidProfile);
2554 break;
2556 case MSP_SET_MODE_RANGE:
2557 i = sbufReadU8(src);
2558 if (i < MAX_MODE_ACTIVATION_CONDITION_COUNT) {
2559 modeActivationCondition_t *mac = modeActivationConditionsMutable(i);
2560 i = sbufReadU8(src);
2561 const box_t *box = findBoxByPermanentId(i);
2562 if (box) {
2563 mac->modeId = box->boxId;
2564 mac->auxChannelIndex = sbufReadU8(src);
2565 mac->range.startStep = sbufReadU8(src);
2566 mac->range.endStep = sbufReadU8(src);
2567 if (sbufBytesRemaining(src) != 0) {
2568 mac->modeLogic = sbufReadU8(src);
2570 i = sbufReadU8(src);
2571 mac->linkedTo = findBoxByPermanentId(i)->boxId;
2573 rcControlsInit();
2574 } else {
2575 return MSP_RESULT_ERROR;
2577 } else {
2578 return MSP_RESULT_ERROR;
2580 break;
2582 case MSP_SET_ADJUSTMENT_RANGE:
2583 i = sbufReadU8(src);
2584 if (i < MAX_ADJUSTMENT_RANGE_COUNT) {
2585 adjustmentRange_t *adjRange = adjustmentRangesMutable(i);
2586 sbufReadU8(src); // was adjRange->adjustmentIndex
2587 adjRange->auxChannelIndex = sbufReadU8(src);
2588 adjRange->range.startStep = sbufReadU8(src);
2589 adjRange->range.endStep = sbufReadU8(src);
2590 adjRange->adjustmentConfig = sbufReadU8(src);
2591 adjRange->auxSwitchChannelIndex = sbufReadU8(src);
2593 activeAdjustmentRangeReset();
2594 } else {
2595 return MSP_RESULT_ERROR;
2597 break;
2599 case MSP_SET_RC_TUNING:
2600 if (sbufBytesRemaining(src) >= 10) {
2601 value = sbufReadU8(src);
2602 if (currentControlRateProfile->rcRates[FD_PITCH] == currentControlRateProfile->rcRates[FD_ROLL]) {
2603 currentControlRateProfile->rcRates[FD_PITCH] = value;
2605 currentControlRateProfile->rcRates[FD_ROLL] = value;
2607 value = sbufReadU8(src);
2608 if (currentControlRateProfile->rcExpo[FD_PITCH] == currentControlRateProfile->rcExpo[FD_ROLL]) {
2609 currentControlRateProfile->rcExpo[FD_PITCH] = value;
2611 currentControlRateProfile->rcExpo[FD_ROLL] = value;
2613 for (int i = 0; i < 3; i++) {
2614 currentControlRateProfile->rates[i] = sbufReadU8(src);
2617 value = sbufReadU8(src);
2618 currentControlRateProfile->tpa_rate = MIN(value, CONTROL_RATE_CONFIG_TPA_MAX);
2619 currentControlRateProfile->thrMid8 = sbufReadU8(src);
2620 currentControlRateProfile->thrExpo8 = sbufReadU8(src);
2621 currentControlRateProfile->tpa_breakpoint = sbufReadU16(src);
2623 if (sbufBytesRemaining(src) >= 1) {
2624 currentControlRateProfile->rcExpo[FD_YAW] = sbufReadU8(src);
2627 if (sbufBytesRemaining(src) >= 1) {
2628 currentControlRateProfile->rcRates[FD_YAW] = sbufReadU8(src);
2631 if (sbufBytesRemaining(src) >= 1) {
2632 currentControlRateProfile->rcRates[FD_PITCH] = sbufReadU8(src);
2635 if (sbufBytesRemaining(src) >= 1) {
2636 currentControlRateProfile->rcExpo[FD_PITCH] = sbufReadU8(src);
2639 // version 1.41
2640 if (sbufBytesRemaining(src) >= 2) {
2641 currentControlRateProfile->throttle_limit_type = sbufReadU8(src);
2642 currentControlRateProfile->throttle_limit_percent = sbufReadU8(src);
2645 // version 1.42
2646 if (sbufBytesRemaining(src) >= 6) {
2647 currentControlRateProfile->rate_limit[FD_ROLL] = sbufReadU16(src);
2648 currentControlRateProfile->rate_limit[FD_PITCH] = sbufReadU16(src);
2649 currentControlRateProfile->rate_limit[FD_YAW] = sbufReadU16(src);
2652 // version 1.43
2653 if (sbufBytesRemaining(src) >= 1) {
2654 currentControlRateProfile->rates_type = sbufReadU8(src);
2657 initRcProcessing();
2658 } else {
2659 return MSP_RESULT_ERROR;
2661 break;
2663 case MSP_SET_MOTOR_CONFIG:
2664 motorConfigMutable()->minthrottle = sbufReadU16(src);
2665 motorConfigMutable()->maxthrottle = sbufReadU16(src);
2666 motorConfigMutable()->mincommand = sbufReadU16(src);
2668 // version 1.42
2669 if (sbufBytesRemaining(src) >= 2) {
2670 motorConfigMutable()->motorPoleCount = sbufReadU8(src);
2671 #if defined(USE_DSHOT_TELEMETRY)
2672 motorConfigMutable()->dev.useDshotTelemetry = sbufReadU8(src);
2673 #else
2674 sbufReadU8(src);
2675 #endif
2677 break;
2679 #ifdef USE_GPS
2680 case MSP_SET_GPS_CONFIG:
2681 gpsConfigMutable()->provider = sbufReadU8(src);
2682 gpsConfigMutable()->sbasMode = sbufReadU8(src);
2683 gpsConfigMutable()->autoConfig = sbufReadU8(src);
2684 gpsConfigMutable()->autoBaud = sbufReadU8(src);
2685 if (sbufBytesRemaining(src) >= 2) {
2686 // Added in API version 1.43
2687 gpsConfigMutable()->gps_set_home_point_once = sbufReadU8(src);
2688 gpsConfigMutable()->gps_ublox_use_galileo = sbufReadU8(src);
2690 break;
2692 #ifdef USE_GPS_RESCUE
2693 case MSP_SET_GPS_RESCUE:
2694 gpsRescueConfigMutable()->angle = sbufReadU16(src);
2695 gpsRescueConfigMutable()->initialAltitudeM = sbufReadU16(src);
2696 gpsRescueConfigMutable()->descentDistanceM = sbufReadU16(src);
2697 gpsRescueConfigMutable()->rescueGroundspeed = sbufReadU16(src);
2698 gpsRescueConfigMutable()->throttleMin = sbufReadU16(src);
2699 gpsRescueConfigMutable()->throttleMax = sbufReadU16(src);
2700 gpsRescueConfigMutable()->throttleHover = sbufReadU16(src);
2701 gpsRescueConfigMutable()->sanityChecks = sbufReadU8(src);
2702 gpsRescueConfigMutable()->minSats = sbufReadU8(src);
2703 if (sbufBytesRemaining(src) >= 6) {
2704 // Added in API version 1.43
2705 gpsRescueConfigMutable()->ascendRate = sbufReadU16(src);
2706 gpsRescueConfigMutable()->descendRate = sbufReadU16(src);
2707 gpsRescueConfigMutable()->allowArmingWithoutFix = sbufReadU8(src);
2708 gpsRescueConfigMutable()->altitudeMode = sbufReadU8(src);
2710 if (sbufBytesRemaining(src) >= 2) {
2711 // Added in API version 1.44
2712 gpsRescueConfigMutable()->minRescueDth = sbufReadU16(src);
2714 break;
2716 case MSP_SET_GPS_RESCUE_PIDS:
2717 gpsRescueConfigMutable()->throttleP = sbufReadU16(src);
2718 gpsRescueConfigMutable()->throttleI = sbufReadU16(src);
2719 gpsRescueConfigMutable()->throttleD = sbufReadU16(src);
2720 gpsRescueConfigMutable()->velP = sbufReadU16(src);
2721 gpsRescueConfigMutable()->velI = sbufReadU16(src);
2722 gpsRescueConfigMutable()->velD = sbufReadU16(src);
2723 gpsRescueConfigMutable()->yawP = sbufReadU16(src);
2724 break;
2725 #endif
2726 #endif
2728 case MSP_SET_MOTOR:
2729 for (int i = 0; i < getMotorCount(); i++) {
2730 motor_disarmed[i] = motorConvertFromExternal(sbufReadU16(src));
2732 break;
2734 case MSP_SET_SERVO_CONFIGURATION:
2735 #ifdef USE_SERVOS
2736 if (dataSize != 1 + 12) {
2737 return MSP_RESULT_ERROR;
2739 i = sbufReadU8(src);
2740 if (i >= MAX_SUPPORTED_SERVOS) {
2741 return MSP_RESULT_ERROR;
2742 } else {
2743 servoParamsMutable(i)->min = sbufReadU16(src);
2744 servoParamsMutable(i)->max = sbufReadU16(src);
2745 servoParamsMutable(i)->middle = sbufReadU16(src);
2746 servoParamsMutable(i)->rate = sbufReadU8(src);
2747 servoParamsMutable(i)->forwardFromChannel = sbufReadU8(src);
2748 servoParamsMutable(i)->reversedSources = sbufReadU32(src);
2750 #endif
2751 break;
2753 case MSP_SET_SERVO_MIX_RULE:
2754 #ifdef USE_SERVOS
2755 i = sbufReadU8(src);
2756 if (i >= MAX_SERVO_RULES) {
2757 return MSP_RESULT_ERROR;
2758 } else {
2759 customServoMixersMutable(i)->targetChannel = sbufReadU8(src);
2760 customServoMixersMutable(i)->inputSource = sbufReadU8(src);
2761 customServoMixersMutable(i)->rate = sbufReadU8(src);
2762 customServoMixersMutable(i)->speed = sbufReadU8(src);
2763 customServoMixersMutable(i)->min = sbufReadU8(src);
2764 customServoMixersMutable(i)->max = sbufReadU8(src);
2765 customServoMixersMutable(i)->box = sbufReadU8(src);
2766 loadCustomServoMixer();
2768 #endif
2769 break;
2771 case MSP_SET_MOTOR_3D_CONFIG:
2772 flight3DConfigMutable()->deadband3d_low = sbufReadU16(src);
2773 flight3DConfigMutable()->deadband3d_high = sbufReadU16(src);
2774 flight3DConfigMutable()->neutral3d = sbufReadU16(src);
2775 break;
2777 case MSP_SET_RC_DEADBAND:
2778 rcControlsConfigMutable()->deadband = sbufReadU8(src);
2779 rcControlsConfigMutable()->yaw_deadband = sbufReadU8(src);
2780 rcControlsConfigMutable()->alt_hold_deadband = sbufReadU8(src);
2781 flight3DConfigMutable()->deadband3d_throttle = sbufReadU16(src);
2782 break;
2784 case MSP_SET_RESET_CURR_PID:
2785 resetPidProfile(currentPidProfile);
2786 break;
2788 case MSP_SET_SENSOR_ALIGNMENT: {
2789 // maintain backwards compatibility for API < 1.41
2790 const uint8_t gyroAlignment = sbufReadU8(src);
2791 sbufReadU8(src); // discard deprecated acc_align
2792 #if defined(USE_MAG)
2793 compassConfigMutable()->mag_alignment = sbufReadU8(src);
2794 #else
2795 sbufReadU8(src);
2796 #endif
2798 if (sbufBytesRemaining(src) >= 3) {
2799 // API >= 1.41 - support the gyro_to_use and alignment for gyros 1 & 2
2800 #ifdef USE_MULTI_GYRO
2801 gyroConfigMutable()->gyro_to_use = sbufReadU8(src);
2802 gyroDeviceConfigMutable(0)->alignment = sbufReadU8(src);
2803 gyroDeviceConfigMutable(1)->alignment = sbufReadU8(src);
2804 #else
2805 sbufReadU8(src); // unused gyro_to_use
2806 gyroDeviceConfigMutable(0)->alignment = sbufReadU8(src);
2807 sbufReadU8(src); // unused gyro_2_sensor_align
2808 #endif
2809 } else {
2810 // maintain backwards compatibility for API < 1.41
2811 #ifdef USE_MULTI_GYRO
2812 switch (gyroConfig()->gyro_to_use) {
2813 case GYRO_CONFIG_USE_GYRO_2:
2814 gyroDeviceConfigMutable(1)->alignment = gyroAlignment;
2815 break;
2816 case GYRO_CONFIG_USE_GYRO_BOTH:
2817 // For dual-gyro in "BOTH" mode we'll only update gyro 0
2818 default:
2819 gyroDeviceConfigMutable(0)->alignment = gyroAlignment;
2820 break;
2822 #else
2823 gyroDeviceConfigMutable(0)->alignment = gyroAlignment;
2824 #endif
2827 break;
2830 case MSP_SET_ADVANCED_CONFIG:
2831 sbufReadU8(src); // was gyroConfigMutable()->gyro_sync_denom - removed in API 1.43
2832 pidConfigMutable()->pid_process_denom = sbufReadU8(src);
2833 motorConfigMutable()->dev.useUnsyncedPwm = sbufReadU8(src);
2834 motorConfigMutable()->dev.motorPwmProtocol = sbufReadU8(src);
2835 motorConfigMutable()->dev.motorPwmRate = sbufReadU16(src);
2836 if (sbufBytesRemaining(src) >= 2) {
2837 motorConfigMutable()->digitalIdleOffsetValue = sbufReadU16(src);
2839 if (sbufBytesRemaining(src)) {
2840 sbufReadU8(src); // DEPRECATED: gyro_use_32khz
2842 if (sbufBytesRemaining(src)) {
2843 motorConfigMutable()->dev.motorPwmInversion = sbufReadU8(src);
2845 if (sbufBytesRemaining(src) >= 8) {
2846 gyroConfigMutable()->gyro_to_use = sbufReadU8(src);
2847 gyroConfigMutable()->gyro_high_fsr = sbufReadU8(src);
2848 gyroConfigMutable()->gyroMovementCalibrationThreshold = sbufReadU8(src);
2849 gyroConfigMutable()->gyroCalibrationDuration = sbufReadU16(src);
2850 gyroConfigMutable()->gyro_offset_yaw = sbufReadU16(src);
2851 gyroConfigMutable()->checkOverflow = sbufReadU8(src);
2853 if (sbufBytesRemaining(src) >= 1) {
2854 //Added in MSP API 1.42
2855 systemConfigMutable()->debug_mode = sbufReadU8(src);
2858 validateAndFixGyroConfig();
2860 break;
2861 case MSP_SET_FILTER_CONFIG:
2862 gyroConfigMutable()->gyro_lpf1_static_hz = sbufReadU8(src);
2863 currentPidProfile->dterm_lpf1_static_hz = sbufReadU16(src);
2864 currentPidProfile->yaw_lowpass_hz = sbufReadU16(src);
2865 if (sbufBytesRemaining(src) >= 8) {
2866 gyroConfigMutable()->gyro_soft_notch_hz_1 = sbufReadU16(src);
2867 gyroConfigMutable()->gyro_soft_notch_cutoff_1 = sbufReadU16(src);
2868 currentPidProfile->dterm_notch_hz = sbufReadU16(src);
2869 currentPidProfile->dterm_notch_cutoff = sbufReadU16(src);
2871 if (sbufBytesRemaining(src) >= 4) {
2872 gyroConfigMutable()->gyro_soft_notch_hz_2 = sbufReadU16(src);
2873 gyroConfigMutable()->gyro_soft_notch_cutoff_2 = sbufReadU16(src);
2875 if (sbufBytesRemaining(src) >= 1) {
2876 currentPidProfile->dterm_lpf1_type = sbufReadU8(src);
2878 if (sbufBytesRemaining(src) >= 10) {
2879 gyroConfigMutable()->gyro_hardware_lpf = sbufReadU8(src);
2880 sbufReadU8(src); // DEPRECATED: gyro_32khz_hardware_lpf
2881 gyroConfigMutable()->gyro_lpf1_static_hz = sbufReadU16(src);
2882 gyroConfigMutable()->gyro_lpf2_static_hz = sbufReadU16(src);
2883 gyroConfigMutable()->gyro_lpf1_type = sbufReadU8(src);
2884 gyroConfigMutable()->gyro_lpf2_type = sbufReadU8(src);
2885 currentPidProfile->dterm_lpf2_static_hz = sbufReadU16(src);
2887 if (sbufBytesRemaining(src) >= 9) {
2888 // Added in MSP API 1.41
2889 currentPidProfile->dterm_lpf2_type = sbufReadU8(src);
2890 #if defined(USE_DYN_LPF)
2891 gyroConfigMutable()->gyro_lpf1_dyn_min_hz = sbufReadU16(src);
2892 gyroConfigMutable()->gyro_lpf1_dyn_max_hz = sbufReadU16(src);
2893 currentPidProfile->dterm_lpf1_dyn_min_hz = sbufReadU16(src);
2894 currentPidProfile->dterm_lpf1_dyn_max_hz = sbufReadU16(src);
2895 #else
2896 sbufReadU16(src);
2897 sbufReadU16(src);
2898 sbufReadU16(src);
2899 sbufReadU16(src);
2900 #endif
2902 if (sbufBytesRemaining(src) >= 8) {
2903 // Added in MSP API 1.42
2904 #if defined(USE_DYN_NOTCH_FILTER)
2905 sbufReadU8(src); // DEPRECATED 1.43: dyn_notch_range
2906 sbufReadU8(src); // DEPRECATED 1.44: dyn_notch_width_percent
2907 dynNotchConfigMutable()->dyn_notch_q = sbufReadU16(src);
2908 dynNotchConfigMutable()->dyn_notch_min_hz = sbufReadU16(src);
2909 #else
2910 sbufReadU8(src);
2911 sbufReadU8(src);
2912 sbufReadU16(src);
2913 sbufReadU16(src);
2914 #endif
2915 #if defined(USE_RPM_FILTER)
2916 rpmFilterConfigMutable()->rpm_filter_harmonics = sbufReadU8(src);
2917 rpmFilterConfigMutable()->rpm_filter_min_hz = sbufReadU8(src);
2918 #else
2919 sbufReadU8(src);
2920 sbufReadU8(src);
2921 #endif
2923 if (sbufBytesRemaining(src) >= 2) {
2924 #if defined(USE_DYN_NOTCH_FILTER)
2925 // Added in MSP API 1.43
2926 dynNotchConfigMutable()->dyn_notch_max_hz = sbufReadU16(src);
2927 #else
2928 sbufReadU16(src);
2929 #endif
2931 if (sbufBytesRemaining(src) >= 2) {
2932 // Added in MSP API 1.44
2933 #if defined(USE_DYN_LPF)
2934 currentPidProfile->dterm_lpf1_dyn_expo = sbufReadU8(src);
2935 #else
2936 sbufReadU8(src);
2937 #endif
2938 #if defined(USE_DYN_NOTCH_FILTER)
2939 dynNotchConfigMutable()->dyn_notch_count = sbufReadU8(src);
2940 #else
2941 sbufReadU8(src);
2942 #endif
2945 // reinitialize the gyro filters with the new values
2946 validateAndFixGyroConfig();
2947 gyroInitFilters();
2948 // reinitialize the PID filters with the new values
2949 pidInitFilters(currentPidProfile);
2951 break;
2952 case MSP_SET_PID_ADVANCED:
2953 sbufReadU16(src);
2954 sbufReadU16(src);
2955 sbufReadU16(src); // was pidProfile.yaw_p_limit
2956 sbufReadU8(src); // reserved
2957 sbufReadU8(src); // was vbatPidCompensation
2958 #if defined(USE_FEEDFORWARD)
2959 currentPidProfile->feedforward_transition = sbufReadU8(src);
2960 #else
2961 sbufReadU8(src);
2962 #endif
2963 sbufReadU8(src); // was low byte of currentPidProfile->dtermSetpointWeight
2964 sbufReadU8(src); // reserved
2965 sbufReadU8(src); // reserved
2966 sbufReadU8(src); // reserved
2967 currentPidProfile->rateAccelLimit = sbufReadU16(src);
2968 currentPidProfile->yawRateAccelLimit = sbufReadU16(src);
2969 if (sbufBytesRemaining(src) >= 2) {
2970 currentPidProfile->levelAngleLimit = sbufReadU8(src);
2971 sbufReadU8(src); // was pidProfile.levelSensitivity
2973 if (sbufBytesRemaining(src) >= 4) {
2974 currentPidProfile->itermThrottleThreshold = sbufReadU16(src);
2975 currentPidProfile->itermAcceleratorGain = sbufReadU16(src);
2977 if (sbufBytesRemaining(src) >= 2) {
2978 sbufReadU16(src); // was currentPidProfile->dtermSetpointWeight
2980 if (sbufBytesRemaining(src) >= 14) {
2981 // Added in MSP API 1.40
2982 currentPidProfile->iterm_rotation = sbufReadU8(src);
2983 sbufReadU8(src); // was currentPidProfile->smart_feedforward
2984 #if defined(USE_ITERM_RELAX)
2985 currentPidProfile->iterm_relax = sbufReadU8(src);
2986 currentPidProfile->iterm_relax_type = sbufReadU8(src);
2987 #else
2988 sbufReadU8(src);
2989 sbufReadU8(src);
2990 #endif
2991 #if defined(USE_ABSOLUTE_CONTROL)
2992 currentPidProfile->abs_control_gain = sbufReadU8(src);
2993 #else
2994 sbufReadU8(src);
2995 #endif
2996 #if defined(USE_THROTTLE_BOOST)
2997 currentPidProfile->throttle_boost = sbufReadU8(src);
2998 #else
2999 sbufReadU8(src);
3000 #endif
3001 #if defined(USE_ACRO_TRAINER)
3002 currentPidProfile->acro_trainer_angle_limit = sbufReadU8(src);
3003 #else
3004 sbufReadU8(src);
3005 #endif
3006 // PID controller feedforward terms
3007 currentPidProfile->pid[PID_ROLL].F = sbufReadU16(src);
3008 currentPidProfile->pid[PID_PITCH].F = sbufReadU16(src);
3009 currentPidProfile->pid[PID_YAW].F = sbufReadU16(src);
3011 currentPidProfile->antiGravityMode = sbufReadU8(src);
3013 if (sbufBytesRemaining(src) >= 7) {
3014 // Added in MSP API 1.41
3015 #if defined(USE_D_MIN)
3016 currentPidProfile->d_min[PID_ROLL] = sbufReadU8(src);
3017 currentPidProfile->d_min[PID_PITCH] = sbufReadU8(src);
3018 currentPidProfile->d_min[PID_YAW] = sbufReadU8(src);
3019 currentPidProfile->d_min_gain = sbufReadU8(src);
3020 currentPidProfile->d_min_advance = sbufReadU8(src);
3021 #else
3022 sbufReadU8(src);
3023 sbufReadU8(src);
3024 sbufReadU8(src);
3025 sbufReadU8(src);
3026 sbufReadU8(src);
3027 #endif
3028 #if defined(USE_INTEGRATED_YAW_CONTROL)
3029 currentPidProfile->use_integrated_yaw = sbufReadU8(src);
3030 currentPidProfile->integrated_yaw_relax = sbufReadU8(src);
3031 #else
3032 sbufReadU8(src);
3033 sbufReadU8(src);
3034 #endif
3036 if(sbufBytesRemaining(src) >= 1) {
3037 // Added in MSP API 1.42
3038 #if defined(USE_ITERM_RELAX)
3039 currentPidProfile->iterm_relax_cutoff = sbufReadU8(src);
3040 #else
3041 sbufReadU8(src);
3042 #endif
3044 if (sbufBytesRemaining(src) >= 3) {
3045 // Added in MSP API 1.43
3046 currentPidProfile->motor_output_limit = sbufReadU8(src);
3047 currentPidProfile->auto_profile_cell_count = sbufReadU8(src);
3048 #if defined(USE_DYN_IDLE)
3049 currentPidProfile->dyn_idle_min_rpm = sbufReadU8(src);
3050 #else
3051 sbufReadU8(src);
3052 #endif
3054 if (sbufBytesRemaining(src) >= 7) {
3055 // Added in MSP API 1.44
3056 #if defined(USE_FEEDFORWARD)
3057 currentPidProfile->feedforward_averaging = sbufReadU8(src);
3058 currentPidProfile->feedforward_smooth_factor = sbufReadU8(src);
3059 currentPidProfile->feedforward_boost = sbufReadU8(src);
3060 currentPidProfile->feedforward_max_rate_limit = sbufReadU8(src);
3061 currentPidProfile->feedforward_jitter_factor = sbufReadU8(src);
3062 #else
3063 sbufReadU8(src);
3064 sbufReadU8(src);
3065 sbufReadU8(src);
3066 sbufReadU8(src);
3067 sbufReadU8(src);
3068 #endif
3070 #if defined(USE_BATTERY_VOLTAGE_SAG_COMPENSATION)
3071 currentPidProfile->vbat_sag_compensation = sbufReadU8(src);
3072 #else
3073 sbufReadU8(src);
3074 #endif
3075 #if defined(USE_THRUST_LINEARIZATION)
3076 currentPidProfile->thrustLinearization = sbufReadU8(src);
3077 #else
3078 sbufReadU8(src);
3079 #endif
3081 pidInitConfig(currentPidProfile);
3082 initEscEndpoints();
3083 mixerInitProfile();
3085 break;
3086 case MSP_SET_SENSOR_CONFIG:
3087 #if defined(USE_ACC)
3088 accelerometerConfigMutable()->acc_hardware = sbufReadU8(src);
3089 #else
3090 sbufReadU8(src);
3091 #endif
3092 #if defined(USE_BARO)
3093 barometerConfigMutable()->baro_hardware = sbufReadU8(src);
3094 #else
3095 sbufReadU8(src);
3096 #endif
3097 #if defined(USE_MAG)
3098 compassConfigMutable()->mag_hardware = sbufReadU8(src);
3099 #else
3100 sbufReadU8(src);
3101 #endif
3102 break;
3104 #ifdef USE_ACC
3105 case MSP_ACC_CALIBRATION:
3106 if (!ARMING_FLAG(ARMED))
3107 accStartCalibration();
3108 break;
3109 #endif
3111 #if defined(USE_MAG)
3112 case MSP_MAG_CALIBRATION:
3113 if (!ARMING_FLAG(ARMED)) {
3114 compassStartCalibration();
3116 #endif
3118 break;
3119 case MSP_EEPROM_WRITE:
3120 if (ARMING_FLAG(ARMED)) {
3121 return MSP_RESULT_ERROR;
3124 // This is going to take some time and won't be done where real-time performance is needed so
3125 // ignore how long it takes to avoid confusing the scheduler
3126 schedulerIgnoreTaskStateTime();
3128 #if defined(USE_MSP_OVER_TELEMETRY)
3129 if (featureIsEnabled(FEATURE_RX_SPI) && srcDesc == getMspTelemetryDescriptor()) {
3130 dispatchAdd(&writeReadEepromEntry, MSP_DISPATCH_DELAY_US);
3131 } else
3132 #endif
3134 writeReadEeprom(NULL);
3137 break;
3139 #ifdef USE_BLACKBOX
3140 case MSP_SET_BLACKBOX_CONFIG:
3141 // Don't allow config to be updated while Blackbox is logging
3142 if (blackboxMayEditConfig()) {
3143 blackboxConfigMutable()->device = sbufReadU8(src);
3144 const int rateNum = sbufReadU8(src); // was rate_num
3145 const int rateDenom = sbufReadU8(src); // was rate_denom
3146 uint16_t pRatio = 0;
3147 if (sbufBytesRemaining(src) >= 2) {
3148 // p_ratio specified, so use it directly
3149 pRatio = sbufReadU16(src);
3150 } else {
3151 // p_ratio not specified in MSP, so calculate it from old rateNum and rateDenom
3152 pRatio = blackboxCalculatePDenom(rateNum, rateDenom);
3155 if (sbufBytesRemaining(src) >= 1) {
3156 // sample_rate specified, so use it directly
3157 blackboxConfigMutable()->sample_rate = sbufReadU8(src);
3158 } else {
3159 // sample_rate not specified in MSP, so calculate it from old p_ratio
3160 blackboxConfigMutable()->sample_rate = blackboxCalculateSampleRate(pRatio);
3163 break;
3164 #endif
3166 #ifdef USE_VTX_COMMON
3167 case MSP_SET_VTX_CONFIG:
3169 vtxDevice_t *vtxDevice = vtxCommonDevice();
3170 vtxDevType_e vtxType = VTXDEV_UNKNOWN;
3171 if (vtxDevice) {
3172 vtxType = vtxCommonGetDeviceType(vtxDevice);
3174 uint16_t newFrequency = sbufReadU16(src);
3175 if (newFrequency <= VTXCOMMON_MSP_BANDCHAN_CHKVAL) { // Value is band and channel
3176 const uint8_t newBand = (newFrequency / 8) + 1;
3177 const uint8_t newChannel = (newFrequency % 8) + 1;
3178 vtxSettingsConfigMutable()->band = newBand;
3179 vtxSettingsConfigMutable()->channel = newChannel;
3180 vtxSettingsConfigMutable()->freq = vtxCommonLookupFrequency(vtxDevice, newBand, newChannel);
3181 } else if (newFrequency <= VTX_SETTINGS_MAX_FREQUENCY_MHZ) { // Value is frequency in MHz
3182 vtxSettingsConfigMutable()->band = 0;
3183 vtxSettingsConfigMutable()->freq = newFrequency;
3186 if (sbufBytesRemaining(src) >= 2) {
3187 vtxSettingsConfigMutable()->power = sbufReadU8(src);
3188 const uint8_t newPitmode = sbufReadU8(src);
3189 if (vtxType != VTXDEV_UNKNOWN) {
3190 // Delegate pitmode to vtx directly
3191 unsigned vtxCurrentStatus;
3192 vtxCommonGetStatus(vtxDevice, &vtxCurrentStatus);
3193 if ((bool)(vtxCurrentStatus & VTX_STATUS_PIT_MODE) != (bool)newPitmode) {
3194 vtxCommonSetPitMode(vtxDevice, newPitmode);
3199 if (sbufBytesRemaining(src)) {
3200 vtxSettingsConfigMutable()->lowPowerDisarm = sbufReadU8(src);
3203 // API version 1.42 - this parameter kept separate since clients may already be supplying
3204 if (sbufBytesRemaining(src) >= 2) {
3205 vtxSettingsConfigMutable()->pitModeFreq = sbufReadU16(src);
3208 // API version 1.42 - extensions for non-encoded versions of the band, channel or frequency
3209 if (sbufBytesRemaining(src) >= 4) {
3210 // Added standalone values for band, channel and frequency to move
3211 // away from the flawed encoded combined method originally implemented.
3212 uint8_t newBand = sbufReadU8(src);
3213 const uint8_t newChannel = sbufReadU8(src);
3214 uint16_t newFreq = sbufReadU16(src);
3215 if (newBand) {
3216 newFreq = vtxCommonLookupFrequency(vtxDevice, newBand, newChannel);
3218 vtxSettingsConfigMutable()->band = newBand;
3219 vtxSettingsConfigMutable()->channel = newChannel;
3220 vtxSettingsConfigMutable()->freq = newFreq;
3223 // API version 1.42 - extensions for vtxtable support
3224 if (sbufBytesRemaining(src) >= 4) {
3225 #ifdef USE_VTX_TABLE
3226 const uint8_t newBandCount = sbufReadU8(src);
3227 const uint8_t newChannelCount = sbufReadU8(src);
3228 const uint8_t newPowerCount = sbufReadU8(src);
3230 if ((newBandCount > VTX_TABLE_MAX_BANDS) ||
3231 (newChannelCount > VTX_TABLE_MAX_CHANNELS) ||
3232 (newPowerCount > VTX_TABLE_MAX_POWER_LEVELS)) {
3233 return MSP_RESULT_ERROR;
3235 vtxTableConfigMutable()->bands = newBandCount;
3236 vtxTableConfigMutable()->channels = newChannelCount;
3237 vtxTableConfigMutable()->powerLevels = newPowerCount;
3239 // boolean to determine whether the vtxtable should be cleared in
3240 // expectation that the detailed band/channel and power level messages
3241 // will follow to repopulate the tables
3242 if (sbufReadU8(src)) {
3243 for (int i = 0; i < VTX_TABLE_MAX_BANDS; i++) {
3244 vtxTableConfigClearBand(vtxTableConfigMutable(), i);
3245 vtxTableConfigClearChannels(vtxTableConfigMutable(), i, 0);
3247 vtxTableConfigClearPowerLabels(vtxTableConfigMutable(), 0);
3248 vtxTableConfigClearPowerValues(vtxTableConfigMutable(), 0);
3250 #else
3251 sbufReadU8(src);
3252 sbufReadU8(src);
3253 sbufReadU8(src);
3254 sbufReadU8(src);
3255 #endif
3258 break;
3259 #endif
3261 #ifdef USE_VTX_TABLE
3262 case MSP_SET_VTXTABLE_BAND:
3264 char bandName[VTX_TABLE_BAND_NAME_LENGTH + 1];
3265 memset(bandName, 0, VTX_TABLE_BAND_NAME_LENGTH + 1);
3266 uint16_t frequencies[VTX_TABLE_MAX_CHANNELS];
3267 const uint8_t band = sbufReadU8(src);
3268 const uint8_t bandNameLength = sbufReadU8(src);
3269 for (int i = 0; i < bandNameLength; i++) {
3270 const char nameChar = sbufReadU8(src);
3271 if (i < VTX_TABLE_BAND_NAME_LENGTH) {
3272 bandName[i] = toupper(nameChar);
3275 const char bandLetter = toupper(sbufReadU8(src));
3276 const bool isFactoryBand = (bool)sbufReadU8(src);
3277 const uint8_t channelCount = sbufReadU8(src);
3278 for (int i = 0; i < channelCount; i++) {
3279 const uint16_t frequency = sbufReadU16(src);
3280 if (i < vtxTableConfig()->channels) {
3281 frequencies[i] = frequency;
3285 if (band > 0 && band <= vtxTableConfig()->bands) {
3286 vtxTableStrncpyWithPad(vtxTableConfigMutable()->bandNames[band - 1], bandName, VTX_TABLE_BAND_NAME_LENGTH);
3287 vtxTableConfigMutable()->bandLetters[band - 1] = bandLetter;
3288 vtxTableConfigMutable()->isFactoryBand[band - 1] = isFactoryBand;
3289 for (int i = 0; i < vtxTableConfig()->channels; i++) {
3290 vtxTableConfigMutable()->frequency[band - 1][i] = frequencies[i];
3292 // If this is the currently selected band then reset the frequency
3293 if (band == vtxSettingsConfig()->band) {
3294 uint16_t newFreq = 0;
3295 if (vtxSettingsConfig()->channel > 0 && vtxSettingsConfig()->channel <= vtxTableConfig()->channels) {
3296 newFreq = frequencies[vtxSettingsConfig()->channel - 1];
3298 vtxSettingsConfigMutable()->freq = newFreq;
3300 vtxTableNeedsInit = true; // reinintialize vtxtable after eeprom write
3301 } else {
3302 return MSP_RESULT_ERROR;
3305 break;
3307 case MSP_SET_VTXTABLE_POWERLEVEL:
3309 char powerLevelLabel[VTX_TABLE_POWER_LABEL_LENGTH + 1];
3310 memset(powerLevelLabel, 0, VTX_TABLE_POWER_LABEL_LENGTH + 1);
3311 const uint8_t powerLevel = sbufReadU8(src);
3312 const uint16_t powerValue = sbufReadU16(src);
3313 const uint8_t powerLevelLabelLength = sbufReadU8(src);
3314 for (int i = 0; i < powerLevelLabelLength; i++) {
3315 const char labelChar = sbufReadU8(src);
3316 if (i < VTX_TABLE_POWER_LABEL_LENGTH) {
3317 powerLevelLabel[i] = toupper(labelChar);
3321 if (powerLevel > 0 && powerLevel <= vtxTableConfig()->powerLevels) {
3322 vtxTableConfigMutable()->powerValues[powerLevel - 1] = powerValue;
3323 vtxTableStrncpyWithPad(vtxTableConfigMutable()->powerLabels[powerLevel - 1], powerLevelLabel, VTX_TABLE_POWER_LABEL_LENGTH);
3324 vtxTableNeedsInit = true; // reinintialize vtxtable after eeprom write
3325 } else {
3326 return MSP_RESULT_ERROR;
3329 break;
3330 #endif
3332 case MSP2_SET_MOTOR_OUTPUT_REORDERING:
3334 const uint8_t arraySize = sbufReadU8(src);
3336 for (unsigned i = 0; i < MAX_SUPPORTED_MOTORS; i++) {
3337 uint8_t value = i;
3339 if (i < arraySize) {
3340 value = sbufReadU8(src);
3343 motorConfigMutable()->dev.motorOutputReordering[i] = value;
3346 break;
3348 #ifdef USE_DSHOT
3349 case MSP2_SEND_DSHOT_COMMAND:
3351 const bool armed = ARMING_FLAG(ARMED);
3353 if (!armed) {
3354 const uint8_t commandType = sbufReadU8(src);
3355 const uint8_t motorIndex = sbufReadU8(src);
3356 const uint8_t commandCount = sbufReadU8(src);
3358 if (DSHOT_CMD_TYPE_BLOCKING == commandType) {
3359 motorDisable();
3362 for (uint8_t i = 0; i < commandCount; i++) {
3363 const uint8_t commandIndex = sbufReadU8(src);
3364 dshotCommandWrite(motorIndex, getMotorCount(), commandIndex, commandType);
3367 if (DSHOT_CMD_TYPE_BLOCKING == commandType) {
3368 motorEnable();
3372 break;
3373 #endif
3375 #ifdef USE_SIMPLIFIED_TUNING
3376 // Added in MSP API 1.44
3377 case MSP_SET_SIMPLIFIED_TUNING:
3379 readSimplifiedPids(currentPidProfile, src);
3380 readSimplifiedDtermFilters(currentPidProfile, src);
3381 readSimplifiedGyroFilters(gyroConfigMutable(), src);
3382 applySimplifiedTuning(currentPidProfile, gyroConfigMutable());
3384 break;
3385 #endif
3387 #ifdef USE_CAMERA_CONTROL
3388 case MSP_CAMERA_CONTROL:
3390 if (ARMING_FLAG(ARMED)) {
3391 return MSP_RESULT_ERROR;
3394 const uint8_t key = sbufReadU8(src);
3395 cameraControlKeyPress(key, 0);
3397 break;
3398 #endif
3400 case MSP_SET_ARMING_DISABLED:
3402 const uint8_t command = sbufReadU8(src);
3403 uint8_t disableRunawayTakeoff = 0;
3404 #ifndef USE_RUNAWAY_TAKEOFF
3405 UNUSED(disableRunawayTakeoff);
3406 #endif
3407 if (sbufBytesRemaining(src)) {
3408 disableRunawayTakeoff = sbufReadU8(src);
3410 if (command) {
3411 mspArmingDisableByDescriptor(srcDesc);
3412 setArmingDisabled(ARMING_DISABLED_MSP);
3413 if (ARMING_FLAG(ARMED)) {
3414 disarm(DISARM_REASON_ARMING_DISABLED);
3416 #ifdef USE_RUNAWAY_TAKEOFF
3417 runawayTakeoffTemporaryDisable(false);
3418 #endif
3419 } else {
3420 mspArmingEnableByDescriptor(srcDesc);
3421 if (mspIsMspArmingEnabled()) {
3422 unsetArmingDisabled(ARMING_DISABLED_MSP);
3423 #ifdef USE_RUNAWAY_TAKEOFF
3424 runawayTakeoffTemporaryDisable(disableRunawayTakeoff);
3425 #endif
3429 break;
3431 #ifdef USE_FLASHFS
3432 case MSP_DATAFLASH_ERASE:
3433 blackboxEraseAll();
3435 break;
3436 #endif
3438 #ifdef USE_GPS
3439 case MSP_SET_RAW_GPS:
3440 gpsSetFixState(sbufReadU8(src));
3441 gpsSol.numSat = sbufReadU8(src);
3442 gpsSol.llh.lat = sbufReadU32(src);
3443 gpsSol.llh.lon = sbufReadU32(src);
3444 gpsSol.llh.altCm = sbufReadU16(src) * 100; // alt changed from 1m to 0.01m per lsb since MSP API 1.39 by RTH. Received MSP altitudes in 1m per lsb have to upscaled.
3445 gpsSol.groundSpeed = sbufReadU16(src);
3446 GPS_update |= GPS_MSP_UPDATE; // MSP data signalisation to GPS functions
3447 break;
3448 #endif // USE_GPS
3449 case MSP_SET_FEATURE_CONFIG:
3450 featureConfigReplace(sbufReadU32(src));
3451 break;
3453 #ifdef USE_BEEPER
3454 case MSP_SET_BEEPER_CONFIG:
3455 beeperConfigMutable()->beeper_off_flags = sbufReadU32(src);
3456 if (sbufBytesRemaining(src) >= 1) {
3457 beeperConfigMutable()->dshotBeaconTone = sbufReadU8(src);
3459 if (sbufBytesRemaining(src) >= 4) {
3460 beeperConfigMutable()->dshotBeaconOffFlags = sbufReadU32(src);
3462 break;
3463 #endif
3465 case MSP_SET_BOARD_ALIGNMENT_CONFIG:
3466 boardAlignmentMutable()->rollDegrees = sbufReadU16(src);
3467 boardAlignmentMutable()->pitchDegrees = sbufReadU16(src);
3468 boardAlignmentMutable()->yawDegrees = sbufReadU16(src);
3469 break;
3471 case MSP_SET_MIXER_CONFIG:
3472 #ifndef USE_QUAD_MIXER_ONLY
3473 mixerConfigMutable()->mixerMode = sbufReadU8(src);
3474 #else
3475 sbufReadU8(src);
3476 #endif
3477 if (sbufBytesRemaining(src) >= 1) {
3478 mixerConfigMutable()->yaw_motors_reversed = sbufReadU8(src);
3480 break;
3482 case MSP_SET_RX_CONFIG:
3483 rxConfigMutable()->serialrx_provider = sbufReadU8(src);
3484 rxConfigMutable()->maxcheck = sbufReadU16(src);
3485 rxConfigMutable()->midrc = sbufReadU16(src);
3486 rxConfigMutable()->mincheck = sbufReadU16(src);
3487 rxConfigMutable()->spektrum_sat_bind = sbufReadU8(src);
3488 if (sbufBytesRemaining(src) >= 4) {
3489 rxConfigMutable()->rx_min_usec = sbufReadU16(src);
3490 rxConfigMutable()->rx_max_usec = sbufReadU16(src);
3492 if (sbufBytesRemaining(src) >= 4) {
3493 sbufReadU8(src); // not required in API 1.44, was rxConfigMutable()->rcInterpolation
3494 sbufReadU8(src); // not required in API 1.44, was rxConfigMutable()->rcInterpolationInterval
3495 rxConfigMutable()->airModeActivateThreshold = (sbufReadU16(src) - 1000) / 10;
3497 if (sbufBytesRemaining(src) >= 6) {
3498 #ifdef USE_RX_SPI
3499 rxSpiConfigMutable()->rx_spi_protocol = sbufReadU8(src);
3500 rxSpiConfigMutable()->rx_spi_id = sbufReadU32(src);
3501 rxSpiConfigMutable()->rx_spi_rf_channel_count = sbufReadU8(src);
3502 #else
3503 sbufReadU8(src);
3504 sbufReadU32(src);
3505 sbufReadU8(src);
3506 #endif
3508 if (sbufBytesRemaining(src) >= 1) {
3509 rxConfigMutable()->fpvCamAngleDegrees = sbufReadU8(src);
3511 if (sbufBytesRemaining(src) >= 6) {
3512 // Added in MSP API 1.40
3513 sbufReadU8(src); // not required in API 1.44, was rxConfigMutable()->rcSmoothingChannels
3514 #if defined(USE_RC_SMOOTHING_FILTER)
3515 sbufReadU8(src); // not required in API 1.44, was rc_smoothing_type
3516 configRebootUpdateCheckU8(&rxConfigMutable()->rc_smoothing_setpoint_cutoff, sbufReadU8(src));
3517 configRebootUpdateCheckU8(&rxConfigMutable()->rc_smoothing_feedforward_cutoff, sbufReadU8(src));
3518 sbufReadU8(src); // not required in API 1.44, was rc_smoothing_input_type
3519 sbufReadU8(src); // not required in API 1.44, was rc_smoothing_derivative_type
3520 #else
3521 sbufReadU8(src);
3522 sbufReadU8(src);
3523 sbufReadU8(src);
3524 sbufReadU8(src);
3525 sbufReadU8(src);
3526 #endif
3528 if (sbufBytesRemaining(src) >= 1) {
3529 // Added in MSP API 1.40
3530 // Kept separate from the section above to work around missing Configurator support in version < 10.4.2
3531 #if defined(USE_USB_CDC_HID)
3532 usbDevConfigMutable()->type = sbufReadU8(src);
3533 #else
3534 sbufReadU8(src);
3535 #endif
3537 if (sbufBytesRemaining(src) >= 1) {
3538 // Added in MSP API 1.42
3539 #if defined(USE_RC_SMOOTHING_FILTER)
3540 // Added extra validation/range constraint for rc_smoothing_auto_factor as a workaround for a bug in
3541 // the 10.6 configurator where it was possible to submit an invalid out-of-range value. We might be
3542 // able to remove the constraint at some point in the future once the affected versions are deprecated
3543 // enough that the risk is low.
3544 configRebootUpdateCheckU8(&rxConfigMutable()->rc_smoothing_auto_factor_rpy, constrain(sbufReadU8(src), RC_SMOOTHING_AUTO_FACTOR_MIN, RC_SMOOTHING_AUTO_FACTOR_MAX));
3545 #else
3546 sbufReadU8(src);
3547 #endif
3549 if (sbufBytesRemaining(src) >= 1) {
3550 // Added in MSP API 1.44
3551 #if defined(USE_RC_SMOOTHING_FILTER)
3552 configRebootUpdateCheckU8(&rxConfigMutable()->rc_smoothing_mode, sbufReadU8(src));
3553 #else
3554 sbufReadU8(src);
3555 #endif
3557 break;
3558 case MSP_SET_FAILSAFE_CONFIG:
3559 failsafeConfigMutable()->failsafe_delay = sbufReadU8(src);
3560 failsafeConfigMutable()->failsafe_off_delay = sbufReadU8(src);
3561 failsafeConfigMutable()->failsafe_throttle = sbufReadU16(src);
3562 failsafeConfigMutable()->failsafe_switch_mode = sbufReadU8(src);
3563 failsafeConfigMutable()->failsafe_throttle_low_delay = sbufReadU16(src);
3564 failsafeConfigMutable()->failsafe_procedure = sbufReadU8(src);
3565 break;
3567 case MSP_SET_RXFAIL_CONFIG:
3568 i = sbufReadU8(src);
3569 if (i < MAX_SUPPORTED_RC_CHANNEL_COUNT) {
3570 rxFailsafeChannelConfigsMutable(i)->mode = sbufReadU8(src);
3571 rxFailsafeChannelConfigsMutable(i)->step = CHANNEL_VALUE_TO_RXFAIL_STEP(sbufReadU16(src));
3572 } else {
3573 return MSP_RESULT_ERROR;
3575 break;
3577 case MSP_SET_RSSI_CONFIG:
3578 rxConfigMutable()->rssi_channel = sbufReadU8(src);
3579 break;
3581 case MSP_SET_RX_MAP:
3582 for (int i = 0; i < RX_MAPPABLE_CHANNEL_COUNT; i++) {
3583 rxConfigMutable()->rcmap[i] = sbufReadU8(src);
3585 break;
3587 case MSP_SET_CF_SERIAL_CONFIG:
3589 uint8_t portConfigSize = sizeof(uint8_t) + sizeof(uint16_t) + (sizeof(uint8_t) * 4);
3591 if (dataSize % portConfigSize != 0) {
3592 return MSP_RESULT_ERROR;
3595 uint8_t remainingPortsInPacket = dataSize / portConfigSize;
3597 while (remainingPortsInPacket--) {
3598 uint8_t identifier = sbufReadU8(src);
3600 serialPortConfig_t *portConfig = serialFindPortConfigurationMutable(identifier);
3602 if (!portConfig) {
3603 return MSP_RESULT_ERROR;
3606 portConfig->identifier = identifier;
3607 portConfig->functionMask = sbufReadU16(src);
3608 portConfig->msp_baudrateIndex = sbufReadU8(src);
3609 portConfig->gps_baudrateIndex = sbufReadU8(src);
3610 portConfig->telemetry_baudrateIndex = sbufReadU8(src);
3611 portConfig->blackbox_baudrateIndex = sbufReadU8(src);
3614 break;
3615 case MSP2_COMMON_SET_SERIAL_CONFIG: {
3616 if (dataSize < 1) {
3617 return MSP_RESULT_ERROR;
3619 unsigned count = sbufReadU8(src);
3620 unsigned portConfigSize = (dataSize - 1) / count;
3621 unsigned expectedPortSize = sizeof(uint8_t) + sizeof(uint32_t) + (sizeof(uint8_t) * 4);
3622 if (portConfigSize < expectedPortSize) {
3623 return MSP_RESULT_ERROR;
3625 for (unsigned ii = 0; ii < count; ii++) {
3626 unsigned start = sbufBytesRemaining(src);
3627 uint8_t identifier = sbufReadU8(src);
3628 serialPortConfig_t *portConfig = serialFindPortConfigurationMutable(identifier);
3630 if (!portConfig) {
3631 return MSP_RESULT_ERROR;
3634 portConfig->identifier = identifier;
3635 portConfig->functionMask = sbufReadU32(src);
3636 portConfig->msp_baudrateIndex = sbufReadU8(src);
3637 portConfig->gps_baudrateIndex = sbufReadU8(src);
3638 portConfig->telemetry_baudrateIndex = sbufReadU8(src);
3639 portConfig->blackbox_baudrateIndex = sbufReadU8(src);
3640 // Skip unknown bytes
3641 while (start - sbufBytesRemaining(src) < portConfigSize && sbufBytesRemaining(src)) {
3642 sbufReadU8(src);
3645 break;
3648 #ifdef USE_LED_STRIP_STATUS_MODE
3649 case MSP_SET_LED_COLORS:
3650 for (int i = 0; i < LED_CONFIGURABLE_COLOR_COUNT; i++) {
3651 hsvColor_t *color = &ledStripStatusModeConfigMutable()->colors[i];
3652 color->h = sbufReadU16(src);
3653 color->s = sbufReadU8(src);
3654 color->v = sbufReadU8(src);
3656 break;
3657 #endif
3659 #ifdef USE_LED_STRIP
3660 case MSP_SET_LED_STRIP_CONFIG:
3662 i = sbufReadU8(src);
3663 if (i >= LED_MAX_STRIP_LENGTH || dataSize != (1 + 4)) {
3664 return MSP_RESULT_ERROR;
3666 #ifdef USE_LED_STRIP_STATUS_MODE
3667 ledConfig_t *ledConfig = &ledStripStatusModeConfigMutable()->ledConfigs[i];
3668 *ledConfig = sbufReadU32(src);
3669 reevaluateLedConfig();
3670 #else
3671 sbufReadU32(src);
3672 #endif
3673 // API 1.41 - selected ledstrip_profile
3674 if (sbufBytesRemaining(src) >= 1) {
3675 ledStripConfigMutable()->ledstrip_profile = sbufReadU8(src);
3678 break;
3679 #endif
3681 #ifdef USE_LED_STRIP_STATUS_MODE
3682 case MSP_SET_LED_STRIP_MODECOLOR:
3684 ledModeIndex_e modeIdx = sbufReadU8(src);
3685 int funIdx = sbufReadU8(src);
3686 int color = sbufReadU8(src);
3688 if (!setModeColor(modeIdx, funIdx, color)) {
3689 return MSP_RESULT_ERROR;
3692 break;
3693 #endif
3695 case MSP_SET_NAME:
3696 memset(pilotConfigMutable()->name, 0, ARRAYLEN(pilotConfig()->name));
3697 for (unsigned int i = 0; i < MIN(MAX_NAME_LENGTH, dataSize); i++) {
3698 pilotConfigMutable()->name[i] = sbufReadU8(src);
3700 #ifdef USE_OSD
3701 osdAnalyzeActiveElements();
3702 #endif
3703 break;
3705 #ifdef USE_RTC_TIME
3706 case MSP_SET_RTC:
3708 // Use seconds and milliseconds to make senders
3709 // easier to implement. Generating a 64 bit value
3710 // might not be trivial in some platforms.
3711 int32_t secs = (int32_t)sbufReadU32(src);
3712 uint16_t millis = sbufReadU16(src);
3713 rtcTime_t t = rtcTimeMake(secs, millis);
3714 rtcSet(&t);
3717 break;
3718 #endif
3720 case MSP_SET_TX_INFO:
3721 setRssiMsp(sbufReadU8(src));
3723 break;
3725 #if defined(USE_BOARD_INFO)
3726 case MSP_SET_BOARD_INFO:
3727 if (!boardInformationIsSet()) {
3728 uint8_t length = sbufReadU8(src);
3729 char boardName[MAX_BOARD_NAME_LENGTH + 1];
3730 sbufReadData(src, boardName, MIN(length, MAX_BOARD_NAME_LENGTH));
3731 if (length > MAX_BOARD_NAME_LENGTH) {
3732 sbufAdvance(src, length - MAX_BOARD_NAME_LENGTH);
3733 length = MAX_BOARD_NAME_LENGTH;
3735 boardName[length] = '\0';
3736 length = sbufReadU8(src);
3737 char manufacturerId[MAX_MANUFACTURER_ID_LENGTH + 1];
3738 sbufReadData(src, manufacturerId, MIN(length, MAX_MANUFACTURER_ID_LENGTH));
3739 if (length > MAX_MANUFACTURER_ID_LENGTH) {
3740 sbufAdvance(src, length - MAX_MANUFACTURER_ID_LENGTH);
3741 length = MAX_MANUFACTURER_ID_LENGTH;
3743 manufacturerId[length] = '\0';
3745 setBoardName(boardName);
3746 setManufacturerId(manufacturerId);
3747 persistBoardInformation();
3748 } else {
3749 return MSP_RESULT_ERROR;
3752 break;
3753 #if defined(USE_SIGNATURE)
3754 case MSP_SET_SIGNATURE:
3755 if (!signatureIsSet()) {
3756 uint8_t signature[SIGNATURE_LENGTH];
3757 sbufReadData(src, signature, SIGNATURE_LENGTH);
3758 setSignature(signature);
3759 persistSignature();
3760 } else {
3761 return MSP_RESULT_ERROR;
3764 break;
3765 #endif
3766 #endif // USE_BOARD_INFO
3767 #if defined(USE_RX_BIND)
3768 case MSP2_BETAFLIGHT_BIND:
3769 if (!startRxBind()) {
3770 return MSP_RESULT_ERROR;
3773 break;
3774 #endif
3775 default:
3776 // we do not know how to handle the (valid) message, indicate error MSP $M!
3777 return MSP_RESULT_ERROR;
3779 return MSP_RESULT_ACK;
3782 static mspResult_e mspCommonProcessInCommand(mspDescriptor_t srcDesc, int16_t cmdMSP, sbuf_t *src, mspPostProcessFnPtr *mspPostProcessFn)
3784 UNUSED(mspPostProcessFn);
3785 const unsigned int dataSize = sbufBytesRemaining(src);
3786 UNUSED(dataSize); // maybe unused due to compiler options
3788 switch (cmdMSP) {
3789 #ifdef USE_TRANSPONDER
3790 case MSP_SET_TRANSPONDER_CONFIG: {
3791 // Backward compatibility to BFC 3.1.1 is lost for this message type
3793 uint8_t provider = sbufReadU8(src);
3794 uint8_t bytesRemaining = dataSize - 1;
3796 if (provider > TRANSPONDER_PROVIDER_COUNT) {
3797 return MSP_RESULT_ERROR;
3800 const uint8_t requirementIndex = provider - 1;
3801 const uint8_t transponderDataSize = transponderRequirements[requirementIndex].dataLength;
3803 transponderConfigMutable()->provider = provider;
3805 if (provider == TRANSPONDER_NONE) {
3806 break;
3809 if (bytesRemaining != transponderDataSize) {
3810 return MSP_RESULT_ERROR;
3813 if (provider != transponderConfig()->provider) {
3814 transponderStopRepeating();
3817 memset(transponderConfigMutable()->data, 0, sizeof(transponderConfig()->data));
3819 for (unsigned int i = 0; i < transponderDataSize; i++) {
3820 transponderConfigMutable()->data[i] = sbufReadU8(src);
3822 transponderUpdateData();
3823 break;
3825 #endif
3827 case MSP_SET_VOLTAGE_METER_CONFIG: {
3828 int8_t id = sbufReadU8(src);
3831 // find and configure an ADC voltage sensor
3833 int8_t voltageSensorADCIndex;
3834 for (voltageSensorADCIndex = 0; voltageSensorADCIndex < MAX_VOLTAGE_SENSOR_ADC; voltageSensorADCIndex++) {
3835 if (id == voltageMeterADCtoIDMap[voltageSensorADCIndex]) {
3836 break;
3840 if (voltageSensorADCIndex < MAX_VOLTAGE_SENSOR_ADC) {
3841 voltageSensorADCConfigMutable(voltageSensorADCIndex)->vbatscale = sbufReadU8(src);
3842 voltageSensorADCConfigMutable(voltageSensorADCIndex)->vbatresdivval = sbufReadU8(src);
3843 voltageSensorADCConfigMutable(voltageSensorADCIndex)->vbatresdivmultiplier = sbufReadU8(src);
3844 } else {
3845 // if we had any other types of voltage sensor to configure, this is where we'd do it.
3846 sbufReadU8(src);
3847 sbufReadU8(src);
3848 sbufReadU8(src);
3850 break;
3853 case MSP_SET_CURRENT_METER_CONFIG: {
3854 int id = sbufReadU8(src);
3856 switch (id) {
3857 case CURRENT_METER_ID_BATTERY_1:
3858 currentSensorADCConfigMutable()->scale = sbufReadU16(src);
3859 currentSensorADCConfigMutable()->offset = sbufReadU16(src);
3860 break;
3861 #ifdef USE_VIRTUAL_CURRENT_METER
3862 case CURRENT_METER_ID_VIRTUAL_1:
3863 currentSensorVirtualConfigMutable()->scale = sbufReadU16(src);
3864 currentSensorVirtualConfigMutable()->offset = sbufReadU16(src);
3865 break;
3866 #endif
3867 default:
3868 sbufReadU16(src);
3869 sbufReadU16(src);
3870 break;
3872 break;
3875 case MSP_SET_BATTERY_CONFIG:
3876 batteryConfigMutable()->vbatmincellvoltage = sbufReadU8(src) * 10; // vbatlevel_warn1 in MWC2.3 GUI
3877 batteryConfigMutable()->vbatmaxcellvoltage = sbufReadU8(src) * 10; // vbatlevel_warn2 in MWC2.3 GUI
3878 batteryConfigMutable()->vbatwarningcellvoltage = sbufReadU8(src) * 10; // vbatlevel when buzzer starts to alert
3879 batteryConfigMutable()->batteryCapacity = sbufReadU16(src);
3880 batteryConfigMutable()->voltageMeterSource = sbufReadU8(src);
3881 batteryConfigMutable()->currentMeterSource = sbufReadU8(src);
3882 if (sbufBytesRemaining(src) >= 6) {
3883 batteryConfigMutable()->vbatmincellvoltage = sbufReadU16(src);
3884 batteryConfigMutable()->vbatmaxcellvoltage = sbufReadU16(src);
3885 batteryConfigMutable()->vbatwarningcellvoltage = sbufReadU16(src);
3887 break;
3889 #if defined(USE_OSD)
3890 case MSP_SET_OSD_CONFIG:
3892 const uint8_t addr = sbufReadU8(src);
3894 if ((int8_t)addr == -1) {
3895 /* Set general OSD settings */
3896 #ifdef USE_MAX7456
3897 vcdProfileMutable()->video_system = sbufReadU8(src);
3898 #else
3899 sbufReadU8(src); // Skip video system
3900 #endif
3901 #if defined(USE_OSD)
3902 osdConfigMutable()->units = sbufReadU8(src);
3904 // Alarms
3905 osdConfigMutable()->rssi_alarm = sbufReadU8(src);
3906 osdConfigMutable()->cap_alarm = sbufReadU16(src);
3907 sbufReadU16(src); // Skip unused (previously fly timer)
3908 osdConfigMutable()->alt_alarm = sbufReadU16(src);
3910 if (sbufBytesRemaining(src) >= 2) {
3911 /* Enabled warnings */
3912 // API < 1.41 supports only the low 16 bits
3913 osdConfigMutable()->enabledWarnings = sbufReadU16(src);
3916 if (sbufBytesRemaining(src) >= 4) {
3917 // 32bit version of enabled warnings (API >= 1.41)
3918 osdConfigMutable()->enabledWarnings = sbufReadU32(src);
3921 if (sbufBytesRemaining(src) >= 1) {
3922 // API >= 1.41
3923 // selected OSD profile
3924 #ifdef USE_OSD_PROFILES
3925 changeOsdProfileIndex(sbufReadU8(src));
3926 #else
3927 sbufReadU8(src);
3928 #endif // USE_OSD_PROFILES
3931 if (sbufBytesRemaining(src) >= 1) {
3932 // API >= 1.41
3933 // OSD stick overlay mode
3935 #ifdef USE_OSD_STICK_OVERLAY
3936 osdConfigMutable()->overlay_radio_mode = sbufReadU8(src);
3937 #else
3938 sbufReadU8(src);
3939 #endif // USE_OSD_STICK_OVERLAY
3943 if (sbufBytesRemaining(src) >= 2) {
3944 // API >= 1.43
3945 // OSD camera frame element width/height
3946 osdConfigMutable()->camera_frame_width = sbufReadU8(src);
3947 osdConfigMutable()->camera_frame_height = sbufReadU8(src);
3949 #endif
3950 } else if ((int8_t)addr == -2) {
3951 #if defined(USE_OSD)
3952 // Timers
3953 uint8_t index = sbufReadU8(src);
3954 if (index > OSD_TIMER_COUNT) {
3955 return MSP_RESULT_ERROR;
3957 osdConfigMutable()->timers[index] = sbufReadU16(src);
3958 #endif
3959 return MSP_RESULT_ERROR;
3960 } else {
3961 #if defined(USE_OSD)
3962 const uint16_t value = sbufReadU16(src);
3964 /* Get screen index, 0 is post flight statistics, 1 and above are in flight OSD screens */
3965 const uint8_t screen = (sbufBytesRemaining(src) >= 1) ? sbufReadU8(src) : 1;
3967 if (screen == 0 && addr < OSD_STAT_COUNT) {
3968 /* Set statistic item enable */
3969 osdStatSetState(addr, (value != 0));
3970 } else if (addr < OSD_ITEM_COUNT) {
3971 /* Set element positions */
3972 osdElementConfigMutable()->item_pos[addr] = value;
3973 osdAnalyzeActiveElements();
3974 } else {
3975 return MSP_RESULT_ERROR;
3977 #else
3978 return MSP_RESULT_ERROR;
3979 #endif
3982 break;
3984 case MSP_OSD_CHAR_WRITE:
3986 osdCharacter_t chr;
3987 size_t osdCharacterBytes;
3988 uint16_t addr;
3989 if (dataSize >= OSD_CHAR_VISIBLE_BYTES + 2) {
3990 if (dataSize >= OSD_CHAR_BYTES + 2) {
3991 // 16 bit address, full char with metadata
3992 addr = sbufReadU16(src);
3993 osdCharacterBytes = OSD_CHAR_BYTES;
3994 } else if (dataSize >= OSD_CHAR_BYTES + 1) {
3995 // 8 bit address, full char with metadata
3996 addr = sbufReadU8(src);
3997 osdCharacterBytes = OSD_CHAR_BYTES;
3998 } else {
3999 // 16 bit character address, only visible char bytes
4000 addr = sbufReadU16(src);
4001 osdCharacterBytes = OSD_CHAR_VISIBLE_BYTES;
4003 } else {
4004 // 8 bit character address, only visible char bytes
4005 addr = sbufReadU8(src);
4006 osdCharacterBytes = OSD_CHAR_VISIBLE_BYTES;
4008 for (unsigned ii = 0; ii < MIN(osdCharacterBytes, sizeof(chr.data)); ii++) {
4009 chr.data[ii] = sbufReadU8(src);
4011 displayPort_t *osdDisplayPort = osdGetDisplayPort(NULL);
4012 if (!osdDisplayPort) {
4013 return MSP_RESULT_ERROR;
4016 if (!displayWriteFontCharacter(osdDisplayPort, addr, &chr)) {
4017 return MSP_RESULT_ERROR;
4020 break;
4021 #endif // OSD
4023 default:
4024 return mspProcessInCommand(srcDesc, cmdMSP, src);
4026 return MSP_RESULT_ACK;
4030 * Returns MSP_RESULT_ACK, MSP_RESULT_ERROR or MSP_RESULT_NO_REPLY
4032 mspResult_e mspFcProcessCommand(mspDescriptor_t srcDesc, mspPacket_t *cmd, mspPacket_t *reply, mspPostProcessFnPtr *mspPostProcessFn)
4034 int ret = MSP_RESULT_ACK;
4035 sbuf_t *dst = &reply->buf;
4036 sbuf_t *src = &cmd->buf;
4037 const int16_t cmdMSP = cmd->cmd;
4038 // initialize reply by default
4039 reply->cmd = cmd->cmd;
4041 if (mspCommonProcessOutCommand(cmdMSP, dst, mspPostProcessFn)) {
4042 ret = MSP_RESULT_ACK;
4043 } else if (mspProcessOutCommand(cmdMSP, dst)) {
4044 ret = MSP_RESULT_ACK;
4045 } else if ((ret = mspFcProcessOutCommandWithArg(srcDesc, cmdMSP, src, dst, mspPostProcessFn)) != MSP_RESULT_CMD_UNKNOWN) {
4046 /* ret */;
4047 } else if (cmdMSP == MSP_SET_PASSTHROUGH) {
4048 mspFcSetPassthroughCommand(dst, src, mspPostProcessFn);
4049 ret = MSP_RESULT_ACK;
4050 #ifdef USE_FLASHFS
4051 } else if (cmdMSP == MSP_DATAFLASH_READ) {
4052 mspFcDataFlashReadCommand(dst, src);
4053 ret = MSP_RESULT_ACK;
4054 #endif
4055 } else {
4056 ret = mspCommonProcessInCommand(srcDesc, cmdMSP, src, mspPostProcessFn);
4058 reply->result = ret;
4059 return ret;
4062 void mspFcProcessReply(mspPacket_t *reply)
4064 sbuf_t *src = &reply->buf;
4065 UNUSED(src); // potentially unused depending on compile options.
4067 switch (reply->cmd) {
4068 case MSP_ANALOG:
4070 uint8_t batteryVoltage = sbufReadU8(src);
4071 uint16_t mAhDrawn = sbufReadU16(src);
4072 uint16_t rssi = sbufReadU16(src);
4073 uint16_t amperage = sbufReadU16(src);
4075 UNUSED(rssi);
4076 UNUSED(batteryVoltage);
4077 UNUSED(amperage);
4078 UNUSED(mAhDrawn);
4080 #ifdef USE_MSP_CURRENT_METER
4081 currentMeterMSPSet(amperage, mAhDrawn);
4082 #endif
4084 break;
4088 void mspInit(void)
4090 initActiveBoxIds();