[SITL OSX] Fix some of the warnings and add macosx SITL build to workflows (#9063)
[inav.git] / src / main / io / osd.c
blob05e990fca5f6972e52f7f49247791ad63b99d162
1 /*
2 * This file is part of Cleanflight.
4 * Cleanflight is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * Cleanflight is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with Cleanflight. If not, see <http://www.gnu.org/licenses/>.
19 Created by Marcin Baliniak
20 some functions based on MinimOSD
22 OSD-CMS separation by jflyper
25 #include <stdbool.h>
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <ctype.h>
30 #include <math.h>
32 #include "platform.h"
34 #ifdef USE_OSD
36 #include "build/debug.h"
37 #include "build/version.h"
39 #include "cms/cms.h"
40 #include "cms/cms_types.h"
41 #include "cms/cms_menu_osd.h"
43 #include "common/axis.h"
44 #include "common/constants.h"
45 #include "common/filter.h"
46 #include "common/log.h"
47 #include "common/olc.h"
48 #include "common/printf.h"
49 #include "common/string_light.h"
50 #include "common/time.h"
51 #include "common/typeconversion.h"
52 #include "common/utils.h"
54 #include "config/feature.h"
55 #include "config/parameter_group.h"
56 #include "config/parameter_group_ids.h"
58 #include "drivers/display.h"
59 #include "drivers/display_canvas.h"
60 #include "drivers/display_font_metadata.h"
61 #include "drivers/osd_symbols.h"
62 #include "drivers/time.h"
63 #include "drivers/vtx_common.h"
65 #include "io/flashfs.h"
66 #include "io/gps.h"
67 #include "io/osd.h"
68 #include "io/osd_common.h"
69 #include "io/osd_hud.h"
70 #include "io/osd_utils.h"
71 #include "io/displayport_msp_bf_compat.h"
72 #include "io/vtx.h"
73 #include "io/vtx_string.h"
75 #include "fc/config.h"
76 #include "fc/controlrate_profile.h"
77 #include "fc/fc_core.h"
78 #include "fc/fc_tasks.h"
79 #include "fc/rc_adjustments.h"
80 #include "fc/rc_controls.h"
81 #include "fc/rc_modes.h"
82 #include "fc/runtime_config.h"
83 #include "fc/settings.h"
85 #include "flight/imu.h"
86 #include "flight/mixer.h"
87 #include "flight/pid.h"
88 #include "flight/power_limits.h"
89 #include "flight/rth_estimator.h"
90 #include "flight/servos.h"
91 #include "flight/wind_estimator.h"
93 #include "navigation/navigation.h"
94 #include "navigation/navigation_private.h"
96 #include "rx/rx.h"
97 #include "rx/msp_override.h"
99 #include "sensors/acceleration.h"
100 #include "sensors/battery.h"
101 #include "sensors/boardalignment.h"
102 #include "sensors/diagnostics.h"
103 #include "sensors/sensors.h"
104 #include "sensors/pitotmeter.h"
105 #include "sensors/temperature.h"
106 #include "sensors/esc_sensor.h"
107 #include "sensors/rangefinder.h"
109 #include "programming/logic_condition.h"
110 #include "programming/global_variables.h"
112 #ifdef USE_HARDWARE_REVISION_DETECTION
113 #include "hardware_revision.h"
114 #endif
116 #define VIDEO_BUFFER_CHARS_PAL 480
117 #define VIDEO_BUFFER_CHARS_HDZERO 900
118 #define VIDEO_BUFFER_CHARS_DJIWTF 1320
120 #define GFORCE_FILTER_TC 0.2
122 #define OSD_STATS_SINGLE_PAGE_MIN_ROWS 18
123 #define IS_HI(X) (rxGetChannelValue(X) > 1750)
124 #define IS_LO(X) (rxGetChannelValue(X) < 1250)
125 #define IS_MID(X) (rxGetChannelValue(X) > 1250 && rxGetChannelValue(X) < 1750)
127 #define OSD_RESUME_UPDATES_STICK_COMMAND (checkStickPosition(THR_HI) || checkStickPosition(PIT_HI))
128 #define STATS_PAGE2 (checkStickPosition(ROL_HI))
129 #define STATS_PAGE1 (checkStickPosition(ROL_LO))
131 #define SPLASH_SCREEN_DISPLAY_TIME 4000 // ms
132 #define ARMED_SCREEN_DISPLAY_TIME 1500 // ms
133 #define STATS_SCREEN_DISPLAY_TIME 60000 // ms
135 #define EFFICIENCY_UPDATE_INTERVAL (5 * 1000)
137 // Adjust OSD_MESSAGE's default position when
138 // changing OSD_MESSAGE_LENGTH
139 #define OSD_MESSAGE_LENGTH 28
140 #define OSD_ALTERNATING_CHOICES(ms, num_choices) ((millis() / ms) % num_choices)
141 #define _CONST_STR_SIZE(s) ((sizeof(s)/sizeof(s[0]))-1) // -1 to avoid counting final '\0'
142 // Wrap all string constants intenteded for display as messages with
143 // this macro to ensure compile time length validation.
144 #define OSD_MESSAGE_STR(x) ({ \
145 STATIC_ASSERT(_CONST_STR_SIZE(x) <= OSD_MESSAGE_LENGTH, message_string_ ## __COUNTER__ ## _too_long); \
146 x; \
149 #define OSD_CHR_IS_NUM(c) (c >= '0' && c <= '9')
151 #define OSD_CENTER_LEN(x) ((osdDisplayPort->cols - x) / 2)
152 #define OSD_CENTER_S(s) OSD_CENTER_LEN(strlen(s))
154 #define OSD_MIN_FONT_VERSION 3
156 static timeMs_t notify_settings_saved = 0;
157 static bool savingSettings = false;
159 static unsigned currentLayout = 0;
160 static int layoutOverride = -1;
161 static bool hasExtendedFont = false; // Wether the font supports characters > 256
162 static timeMs_t layoutOverrideUntil = 0;
163 static pt1Filter_t GForceFilter, GForceFilterAxis[XYZ_AXIS_COUNT];
164 static float GForce, GForceAxis[XYZ_AXIS_COUNT];
166 typedef struct statistic_s {
167 uint16_t max_speed;
168 uint16_t max_3D_speed;
169 uint16_t max_air_speed;
170 uint16_t min_voltage; // /100
171 int16_t max_current;
172 int32_t max_power;
173 int16_t min_rssi;
174 int16_t min_lq; // for CRSF
175 int16_t min_rssi_dbm; // for CRSF
176 int32_t max_altitude;
177 uint32_t max_distance;
178 } statistic_t;
180 static statistic_t stats;
182 static timeUs_t resumeRefreshAt = 0;
183 static bool refreshWaitForResumeCmdRelease;
185 static bool fullRedraw = false;
187 static uint8_t armState;
189 typedef struct osdMapData_s {
190 uint32_t scale;
191 char referenceSymbol;
192 } osdMapData_t;
194 static osdMapData_t osdMapData;
196 static displayPort_t *osdDisplayPort;
197 static bool osdDisplayIsReady = false;
198 #if defined(USE_CANVAS)
199 static displayCanvas_t osdCanvas;
200 static bool osdDisplayHasCanvas;
201 #else
202 #define osdDisplayHasCanvas false
203 #endif
205 #define AH_MAX_PITCH_DEFAULT 20 // Specify default maximum AHI pitch value displayed (degrees)
207 PG_REGISTER_WITH_RESET_TEMPLATE(osdConfig_t, osdConfig, PG_OSD_CONFIG, 8);
208 PG_REGISTER_WITH_RESET_FN(osdLayoutsConfig_t, osdLayoutsConfig, PG_OSD_LAYOUTS_CONFIG, 1);
210 void osdStartedSaveProcess(void) {
211 savingSettings = true;
214 void osdShowEEPROMSavedNotification(void) {
215 savingSettings = false;
216 notify_settings_saved = millis() + 5000;
221 bool osdDisplayIsPAL(void)
223 return displayScreenSize(osdDisplayPort) == VIDEO_BUFFER_CHARS_PAL;
226 bool osdDisplayIsHD(void)
228 if (displayScreenSize(osdDisplayPort) >= VIDEO_BUFFER_CHARS_HDZERO)
230 return true;
232 return false;
238 * Aligns text to the left side. Adds spaces at the end to keep string length unchanged.
240 static void osdLeftAlignString(char *buff)
242 uint8_t sp = 0, ch = 0;
243 uint8_t len = strlen(buff);
244 while (buff[sp] == ' ') sp++;
245 for (ch = 0; ch < (len - sp); ch++) buff[ch] = buff[ch + sp];
246 for (sp = ch; sp < len; sp++) buff[sp] = ' ';
250 * This is a simplified distance conversion code that does not use any scaling
251 * but is fully compatible with the DJI G2 MSP Displayport OSD implementation.
252 * (Based on osdSimpleAltitudeSymbol() implementation)
254 /* void osdSimpleDistanceSymbol(char *buff, int32_t dist) {
256 int32_t convertedDistance;
257 char suffix;
259 switch ((osd_unit_e)osdConfig()->units) {
260 case OSD_UNIT_UK:
261 FALLTHROUGH;
262 case OSD_UNIT_GA:
263 FALLTHROUGH;
264 case OSD_UNIT_IMPERIAL:
265 convertedDistance = CENTIMETERS_TO_FEET(dist);
266 suffix = SYM_ALT_FT;
267 break;
268 case OSD_UNIT_METRIC_MPH:
269 FALLTHROUGH;
270 case OSD_UNIT_METRIC:
271 convertedDistance = CENTIMETERS_TO_METERS(dist);
272 suffix = SYM_ALT_M; // Intentionally use the altitude symbol, as the distance symbol is not defined in BFCOMPAT mode
273 break;
276 tfp_sprintf(buff, "%5d", (int) convertedDistance); // 5 digits, allowing up to 99999 meters/feet, which should be plenty for 99.9% of use cases
277 buff[5] = suffix;
278 buff[6] = '\0';
279 } */
282 * Converts distance into a string based on the current unit system
283 * prefixed by a a symbol to indicate the unit used.
284 * @param dist Distance in centimeters
286 static void osdFormatDistanceSymbol(char *buff, int32_t dist, uint8_t decimals)
288 uint8_t digits = 3U; // Total number of digits (including decimal point)
289 uint8_t sym_index = 3U; // Position (index) at buffer of units symbol
290 uint8_t symbol_m = SYM_DIST_M;
291 uint8_t symbol_km = SYM_DIST_KM;
292 uint8_t symbol_ft = SYM_DIST_FT;
293 uint8_t symbol_mi = SYM_DIST_MI;
294 uint8_t symbol_nm = SYM_DIST_NM;
296 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it and change the values
297 if (isBfCompatibleVideoSystem(osdConfig())) {
298 // Add one digit so up no switch to scaled decimal occurs above 99
299 digits = 4U;
300 sym_index = 4U;
301 // Use altitude symbols on purpose, as it seems distance symbols are not defined in BFCOMPAT mode
302 symbol_m = SYM_ALT_M;
303 symbol_km = SYM_ALT_KM;
304 symbol_ft = SYM_ALT_FT;
305 symbol_mi = SYM_MI;
306 symbol_nm = SYM_MI;
308 #endif
310 switch ((osd_unit_e)osdConfig()->units) {
311 case OSD_UNIT_UK:
312 FALLTHROUGH;
313 case OSD_UNIT_IMPERIAL:
314 if (osdFormatCentiNumber(buff, CENTIMETERS_TO_CENTIFEET(dist), FEET_PER_MILE, decimals, 3, digits)) {
315 buff[sym_index] = symbol_mi;
316 } else {
317 buff[sym_index] = symbol_ft;
319 buff[sym_index + 1] = '\0';
320 break;
321 case OSD_UNIT_METRIC_MPH:
322 FALLTHROUGH;
323 case OSD_UNIT_METRIC:
324 if (osdFormatCentiNumber(buff, dist, METERS_PER_KILOMETER, decimals, 3, digits)) {
325 buff[sym_index] = symbol_km;
326 } else {
327 buff[sym_index] = symbol_m;
329 buff[sym_index + 1] = '\0';
330 break;
331 case OSD_UNIT_GA:
332 if (osdFormatCentiNumber(buff, CENTIMETERS_TO_CENTIFEET(dist), (uint32_t)FEET_PER_NAUTICALMILE, decimals, 3, digits)) {
333 buff[sym_index] = symbol_nm;
334 } else {
335 buff[sym_index] = symbol_ft;
337 buff[sym_index + 1] = '\0';
338 break;
343 * Converts distance into a string based on the current unit system.
344 * @param dist Distance in centimeters
346 static void osdFormatDistanceStr(char *buff, int32_t dist)
348 int32_t centifeet;
349 switch ((osd_unit_e)osdConfig()->units) {
350 case OSD_UNIT_UK:
351 FALLTHROUGH;
352 case OSD_UNIT_IMPERIAL:
353 centifeet = CENTIMETERS_TO_CENTIFEET(dist);
354 if (abs(centifeet) < FEET_PER_MILE * 100 / 2) {
355 // Show feet when dist < 0.5mi
356 tfp_sprintf(buff, "%d%c", (int)(centifeet / 100), SYM_FT);
357 } else {
358 // Show miles when dist >= 0.5mi
359 tfp_sprintf(buff, "%d.%02d%c", (int)(centifeet / (100*FEET_PER_MILE)),
360 (abs(centifeet) % (100 * FEET_PER_MILE)) / FEET_PER_MILE, SYM_MI);
362 break;
363 case OSD_UNIT_METRIC_MPH:
364 FALLTHROUGH;
365 case OSD_UNIT_METRIC:
366 if (abs(dist) < METERS_PER_KILOMETER * 100) {
367 // Show meters when dist < 1km
368 tfp_sprintf(buff, "%d%c", (int)(dist / 100), SYM_M);
369 } else {
370 // Show kilometers when dist >= 1km
371 tfp_sprintf(buff, "%d.%02d%c", (int)(dist / (100*METERS_PER_KILOMETER)),
372 (abs(dist) % (100 * METERS_PER_KILOMETER)) / METERS_PER_KILOMETER, SYM_KM);
374 break;
375 case OSD_UNIT_GA:
376 centifeet = CENTIMETERS_TO_CENTIFEET(dist);
377 if (abs(centifeet) < 100000) {
378 // Show feet when dist < 1000ft
379 tfp_sprintf(buff, "%d%c", (int)(centifeet / 100), SYM_FT);
380 } else {
381 // Show nautical miles when dist >= 1000ft
382 tfp_sprintf(buff, "%d.%02d%c", (int)(centifeet / (100 * FEET_PER_NAUTICALMILE)),
383 (int)((abs(centifeet) % (int)(100 * FEET_PER_NAUTICALMILE)) / FEET_PER_NAUTICALMILE), SYM_NM);
385 break;
390 * Converts velocity based on the current unit system (kmh or mph).
391 * @param alt Raw velocity (i.e. as taken from gpsSol.groundSpeed in centimeters/second)
393 static int32_t osdConvertVelocityToUnit(int32_t vel)
395 switch ((osd_unit_e)osdConfig()->units) {
396 case OSD_UNIT_UK:
397 FALLTHROUGH;
398 case OSD_UNIT_METRIC_MPH:
399 FALLTHROUGH;
400 case OSD_UNIT_IMPERIAL:
401 return CMSEC_TO_CENTIMPH(vel) / 100; // Convert to mph
402 case OSD_UNIT_METRIC:
403 return CMSEC_TO_CENTIKPH(vel) / 100; // Convert to kmh
404 case OSD_UNIT_GA:
405 return CMSEC_TO_CENTIKNOTS(vel) / 100; // Convert to Knots
407 // Unreachable
408 return -1;
412 * Converts velocity into a string based on the current unit system.
413 * @param vel Raw velocity (i.e. as taken from gpsSol.groundSpeed in centimeters/seconds)
414 * @param _3D is a 3D velocity
415 * @param _max is a maximum velocity
417 void osdFormatVelocityStr(char* buff, int32_t vel, bool _3D, bool _max)
419 switch ((osd_unit_e)osdConfig()->units) {
420 case OSD_UNIT_UK:
421 FALLTHROUGH;
422 case OSD_UNIT_METRIC_MPH:
423 FALLTHROUGH;
424 case OSD_UNIT_IMPERIAL:
425 if (_max) {
426 tfp_sprintf(buff, "%c%3d%c", SYM_MAX, (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_MPH : SYM_MPH));
427 } else {
428 tfp_sprintf(buff, "%3d%c", (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_MPH : SYM_MPH));
430 break;
431 case OSD_UNIT_METRIC:
432 if (_max) {
433 tfp_sprintf(buff, "%c%3d%c", SYM_MAX, (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KMH : SYM_KMH));
434 } else {
435 tfp_sprintf(buff, "%3d%c", (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KMH : SYM_KMH));
437 break;
438 case OSD_UNIT_GA:
439 if (_max) {
440 tfp_sprintf(buff, "%c%3d%c", SYM_MAX, (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KT : SYM_KT));
441 } else {
442 tfp_sprintf(buff, "%3d%c", (int)osdConvertVelocityToUnit(vel), (_3D ? SYM_3D_KT : SYM_KT));
444 break;
449 * Returns the average velocity. This always uses stats, so can be called as an OSD element later if wanted, to show a real time average
451 static void osdGenerateAverageVelocityStr(char* buff) {
452 uint32_t cmPerSec = getTotalTravelDistance() / getFlightTime();
453 osdFormatVelocityStr(buff, cmPerSec, false, false);
457 * Converts wind speed into a string based on the current unit system, using
458 * always 3 digits and an additional character for the unit at the right. buff
459 * is null terminated.
460 * @param ws Raw wind speed in cm/s
462 #ifdef USE_WIND_ESTIMATOR
463 static void osdFormatWindSpeedStr(char *buff, int32_t ws, bool isValid)
465 int32_t centivalue;
466 char suffix;
467 switch (osdConfig()->units) {
468 case OSD_UNIT_UK:
469 FALLTHROUGH;
470 case OSD_UNIT_METRIC_MPH:
471 FALLTHROUGH;
472 case OSD_UNIT_IMPERIAL:
473 centivalue = CMSEC_TO_CENTIMPH(ws);
474 suffix = SYM_MPH;
475 break;
476 case OSD_UNIT_GA:
477 centivalue = CMSEC_TO_CENTIKNOTS(ws);
478 suffix = SYM_KT;
479 break;
480 default:
481 case OSD_UNIT_METRIC:
482 centivalue = CMSEC_TO_CENTIKPH(ws);
483 suffix = SYM_KMH;
484 break;
487 osdFormatCentiNumber(buff, centivalue, 0, 2, 0, 3);
489 if (!isValid && ((millis() / 1000) % 4 < 2))
490 suffix = '*';
492 buff[3] = suffix;
493 buff[4] = '\0';
495 #endif
498 * This is a simplified altitude conversion code that does not use any scaling
499 * but is fully compatible with the DJI G2 MSP Displayport OSD implementation.
501 /* void osdSimpleAltitudeSymbol(char *buff, int32_t alt) {
503 int32_t convertedAltutude = 0;
504 char suffix = '\0';
506 switch ((osd_unit_e)osdConfig()->units) {
507 case OSD_UNIT_UK:
508 FALLTHROUGH;
509 case OSD_UNIT_GA:
510 FALLTHROUGH;
511 case OSD_UNIT_IMPERIAL:
512 convertedAltutude = CENTIMETERS_TO_FEET(alt);
513 suffix = SYM_ALT_FT;
514 break;
515 case OSD_UNIT_METRIC_MPH:
516 FALLTHROUGH;
517 case OSD_UNIT_METRIC:
518 convertedAltutude = CENTIMETERS_TO_METERS(alt);
519 suffix = SYM_ALT_M;
520 break;
523 tfp_sprintf(buff, "%4d", (int) convertedAltutude);
524 buff[4] = suffix;
525 buff[5] = '\0';
526 } */
529 * Converts altitude into a string based on the current unit system
530 * prefixed by a a symbol to indicate the unit used.
531 * @param alt Raw altitude/distance (i.e. as taken from baro.BaroAlt in centimeters)
533 void osdFormatAltitudeSymbol(char *buff, int32_t alt)
535 uint8_t digits = 4U;
536 uint8_t symbolIndex = 4U;
537 uint8_t symbolKFt = SYM_ALT_KFT;
539 if (alt >= 0) {
540 digits = 3U;
541 buff[0] = ' ';
544 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it and change the values
545 if (isBfCompatibleVideoSystem(osdConfig())) {
546 digits++;
547 symbolIndex++;
548 symbolKFt = SYM_ALT_FT;
550 #endif
552 switch ((osd_unit_e)osdConfig()->units) {
553 case OSD_UNIT_UK:
554 FALLTHROUGH;
555 case OSD_UNIT_GA:
556 FALLTHROUGH;
557 case OSD_UNIT_IMPERIAL:
558 if (osdFormatCentiNumber(buff + 4 - digits, CENTIMETERS_TO_CENTIFEET(alt), 1000, 0, 2, digits)) {
559 // Scaled to kft
560 buff[symbolIndex++] = symbolKFt;
561 } else {
562 // Formatted in feet
563 buff[symbolIndex++] = SYM_ALT_FT;
565 buff[symbolIndex] = '\0';
566 break;
567 case OSD_UNIT_METRIC_MPH:
568 FALLTHROUGH;
569 case OSD_UNIT_METRIC:
570 // alt is alredy in cm
571 if (osdFormatCentiNumber(buff + 4 - digits, alt, 1000, 0, 2, digits)) {
572 // Scaled to km
573 buff[symbolIndex++] = SYM_ALT_KM;
574 } else {
575 // Formatted in m
576 buff[symbolIndex++] = SYM_ALT_M;
578 buff[symbolIndex] = '\0';
579 break;
584 * Converts altitude into a string based on the current unit system.
585 * @param alt Raw altitude/distance (i.e. as taken from baro.BaroAlt in centimeters)
587 static void osdFormatAltitudeStr(char *buff, int32_t alt)
589 int32_t value;
590 switch ((osd_unit_e)osdConfig()->units) {
591 case OSD_UNIT_UK:
592 FALLTHROUGH;
593 case OSD_UNIT_GA:
594 FALLTHROUGH;
595 case OSD_UNIT_IMPERIAL:
596 value = CENTIMETERS_TO_FEET(alt);
597 tfp_sprintf(buff, "%d%c", (int)value, SYM_FT);
598 break;
599 case OSD_UNIT_METRIC_MPH:
600 FALLTHROUGH;
601 case OSD_UNIT_METRIC:
602 value = CENTIMETERS_TO_METERS(alt);
603 tfp_sprintf(buff, "%d%c", (int)value, SYM_M);
604 break;
608 static void osdFormatTime(char *buff, uint32_t seconds, char sym_m, char sym_h)
610 uint32_t value = seconds;
611 char sym = sym_m;
612 // Maximum value we can show in minutes is 99 minutes and 59 seconds
613 if (seconds > (99 * 60) + 59) {
614 sym = sym_h;
615 value = seconds / 60;
617 buff[0] = sym;
618 tfp_sprintf(buff + 1, "%02d:%02d", (int)(value / 60), (int)(value % 60));
621 static inline void osdFormatOnTime(char *buff)
623 osdFormatTime(buff, micros() / 1000000, SYM_ON_M, SYM_ON_H);
626 static inline void osdFormatFlyTime(char *buff, textAttributes_t *attr)
628 uint32_t seconds = getFlightTime();
629 osdFormatTime(buff, seconds, SYM_FLY_M, SYM_FLY_H);
630 if (attr && osdConfig()->time_alarm > 0) {
631 if (seconds / 60 >= osdConfig()->time_alarm && ARMING_FLAG(ARMED)) {
632 TEXT_ATTRIBUTES_ADD_BLINK(*attr);
637 /**
638 * Trim whitespace from string.
639 * Used in Stats screen on lines with multiple values.
641 char *osdFormatTrimWhiteSpace(char *buff)
643 char *end;
645 // Trim leading spaces
646 while(isspace((unsigned char)*buff)) buff++;
648 // All spaces?
649 if(*buff == 0)
650 return buff;
652 // Trim trailing spaces
653 end = buff + strlen(buff) - 1;
654 while(end > buff && isspace((unsigned char)*end)) end--;
656 // Write new null terminator character
657 end[1] = '\0';
659 return buff;
663 * Converts RSSI into a % value used by the OSD.
665 static uint16_t osdConvertRSSI(void)
667 // change range to [0, 99]
668 return constrain(getRSSI() * 100 / RSSI_MAX_VALUE, 0, 99);
671 static uint16_t osdGetCrsfLQ(void)
673 int16_t statsLQ = rxLinkStatistics.uplinkLQ;
674 int16_t scaledLQ = scaleRange(constrain(statsLQ, 0, 100), 0, 100, 170, 300);
675 int16_t displayedLQ = 0;
676 switch (osdConfig()->crsf_lq_format) {
677 case OSD_CRSF_LQ_TYPE1:
678 displayedLQ = statsLQ;
679 break;
680 case OSD_CRSF_LQ_TYPE2:
681 displayedLQ = statsLQ;
682 break;
683 case OSD_CRSF_LQ_TYPE3:
684 displayedLQ = rxLinkStatistics.rfMode >= 2 ? scaledLQ : statsLQ;
685 break;
687 return displayedLQ;
690 static int16_t osdGetCrsfdBm(void)
692 return rxLinkStatistics.uplinkRSSI;
695 * Displays a temperature postfixed with a symbol depending on the current unit system
696 * @param label to display
697 * @param valid true if measurement is valid
698 * @param temperature in deciDegrees Celcius
700 static void osdDisplayTemperature(uint8_t elemPosX, uint8_t elemPosY, uint16_t symbol, const char *label, bool valid, int16_t temperature, int16_t alarm_min, int16_t alarm_max)
702 char buff[TEMPERATURE_LABEL_LEN + 2 < 6 ? 6 : TEMPERATURE_LABEL_LEN + 2];
703 textAttributes_t elemAttr = valid ? TEXT_ATTRIBUTES_NONE : _TEXT_ATTRIBUTES_BLINK_BIT;
704 uint8_t valueXOffset = 0;
706 if (symbol) {
707 buff[0] = symbol;
708 buff[1] = '\0';
709 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
710 valueXOffset = 1;
712 #ifdef USE_TEMPERATURE_SENSOR
713 else if (label[0] != '\0') {
714 uint8_t label_len = strnlen(label, TEMPERATURE_LABEL_LEN);
715 memcpy(buff, label, label_len);
716 memset(buff + label_len, ' ', TEMPERATURE_LABEL_LEN + 1 - label_len);
717 buff[5] = '\0';
718 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
719 valueXOffset = osdConfig()->temp_label_align == OSD_ALIGN_LEFT ? 5 : label_len + 1;
721 #else
722 UNUSED(label);
723 #endif
725 if (valid) {
727 if ((temperature <= alarm_min) || (temperature >= alarm_max)) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
728 if (osdConfig()->units == OSD_UNIT_IMPERIAL) temperature = temperature * 9 / 5.0f + 320;
729 tfp_sprintf(buff, "%3d", temperature / 10);
731 } else
732 strcpy(buff, "---");
734 buff[3] = osdConfig()->units == OSD_UNIT_IMPERIAL ? SYM_TEMP_F : SYM_TEMP_C;
735 buff[4] = '\0';
737 displayWriteWithAttr(osdDisplayPort, elemPosX + valueXOffset, elemPosY, buff, elemAttr);
740 #ifdef USE_TEMPERATURE_SENSOR
741 static void osdDisplayTemperatureSensor(uint8_t elemPosX, uint8_t elemPosY, uint8_t sensorIndex)
743 int16_t temperature;
744 const bool valid = getSensorTemperature(sensorIndex, &temperature);
745 const tempSensorConfig_t *sensorConfig = tempSensorConfig(sensorIndex);
746 uint16_t symbol = sensorConfig->osdSymbol ? SYM_TEMP_SENSOR_FIRST + sensorConfig->osdSymbol - 1 : 0;
747 osdDisplayTemperature(elemPosX, elemPosY, symbol, sensorConfig->label, valid, temperature, sensorConfig->alarm_min, sensorConfig->alarm_max);
749 #endif
751 static void osdFormatCoordinate(char *buff, char sym, int32_t val)
753 // up to 4 for number + 1 for the symbol + null terminator + fill the rest with decimals
754 const int coordinateLength = osdConfig()->coordinate_digits + 1;
756 buff[0] = sym;
757 int32_t integerPart = val / GPS_DEGREES_DIVIDER;
758 // Latitude maximum integer width is 3 (-90) while
759 // longitude maximum integer width is 4 (-180).
760 int integerDigits = tfp_sprintf(buff + 1, (integerPart == 0 && val < 0) ? "-%d" : "%d", (int)integerPart);
761 // We can show up to 7 digits in decimalPart.
762 int32_t decimalPart = abs(val % (int)GPS_DEGREES_DIVIDER);
763 STATIC_ASSERT(GPS_DEGREES_DIVIDER == 1e7, adjust_max_decimal_digits);
764 int decimalDigits;
765 bool bfcompat = false; // Assume BFCOMPAT mode is no enabled
767 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it
768 if(isBfCompatibleVideoSystem(osdConfig())) {
769 bfcompat = true;
771 #endif
773 if (!bfcompat) {
774 decimalDigits = tfp_sprintf(buff + 1 + integerDigits, "%07d", (int)decimalPart);
775 // Embbed the decimal separator
776 buff[1 + integerDigits - 1] += SYM_ZERO_HALF_TRAILING_DOT - '0';
777 buff[1 + integerDigits] += SYM_ZERO_HALF_LEADING_DOT - '0';
778 } else {
779 // BFCOMPAT mode enabled
780 decimalDigits = tfp_sprintf(buff + 1 + integerDigits, ".%06d", (int)decimalPart);
782 // Fill up to coordinateLength with zeros
783 int total = 1 + integerDigits + decimalDigits;
784 while(total < coordinateLength) {
785 buff[total] = '0';
786 total++;
788 buff[coordinateLength] = '\0';
791 static void osdFormatCraftName(char *buff)
793 if (strlen(systemConfig()->craftName) == 0)
794 strcpy(buff, "CRAFT_NAME");
795 else {
796 for (int i = 0; i < MAX_NAME_LENGTH; i++) {
797 buff[i] = sl_toupper((unsigned char)systemConfig()->craftName[i]);
798 if (systemConfig()->craftName[i] == 0)
799 break;
804 void osdFormatPilotName(char *buff)
806 if (strlen(systemConfig()->pilotName) == 0)
807 strcpy(buff, "PILOT_NAME");
808 else {
809 for (int i = 0; i < MAX_NAME_LENGTH; i++) {
810 buff[i] = sl_toupper((unsigned char)systemConfig()->pilotName[i]);
811 if (systemConfig()->pilotName[i] == 0)
812 break;
817 static const char * osdArmingDisabledReasonMessage(void)
819 const char *message = NULL;
820 char messageBuf[MAX(SETTING_MAX_NAME_LENGTH, OSD_MESSAGE_LENGTH+1)];
822 switch (isArmingDisabledReason()) {
823 case ARMING_DISABLED_FAILSAFE_SYSTEM:
824 // See handling of FAILSAFE_RX_LOSS_MONITORING in failsafe.c
825 if (failsafePhase() == FAILSAFE_RX_LOSS_MONITORING) {
826 if (failsafeIsReceivingRxData()) {
827 // If we're not using sticks, it means the ARM switch
828 // hasn't been off since entering FAILSAFE_RX_LOSS_MONITORING
829 // yet
830 return OSD_MESSAGE_STR(OSD_MSG_TURN_ARM_SW_OFF);
832 // Not receiving RX data
833 return OSD_MESSAGE_STR(OSD_MSG_RC_RX_LINK_LOST);
835 return OSD_MESSAGE_STR(OSD_MSG_DISABLED_BY_FS);
836 case ARMING_DISABLED_NOT_LEVEL:
837 return OSD_MESSAGE_STR(OSD_MSG_AIRCRAFT_UNLEVEL);
838 case ARMING_DISABLED_SENSORS_CALIBRATING:
839 return OSD_MESSAGE_STR(OSD_MSG_SENSORS_CAL);
840 case ARMING_DISABLED_SYSTEM_OVERLOADED:
841 return OSD_MESSAGE_STR(OSD_MSG_SYS_OVERLOADED);
842 case ARMING_DISABLED_NAVIGATION_UNSAFE:
843 // Check the exact reason
844 switch (navigationIsBlockingArming(NULL)) {
845 char buf[6];
846 case NAV_ARMING_BLOCKER_NONE:
847 break;
848 case NAV_ARMING_BLOCKER_MISSING_GPS_FIX:
849 return OSD_MESSAGE_STR(OSD_MSG_WAITING_GPS_FIX);
850 case NAV_ARMING_BLOCKER_NAV_IS_ALREADY_ACTIVE:
851 return OSD_MESSAGE_STR(OSD_MSG_DISABLE_NAV_FIRST);
852 case NAV_ARMING_BLOCKER_FIRST_WAYPOINT_TOO_FAR:
853 osdFormatDistanceSymbol(buf, distanceToFirstWP(), 0);
854 tfp_sprintf(messageBuf, "FIRST WP TOO FAR (%s)", buf);
855 return message = messageBuf;
856 case NAV_ARMING_BLOCKER_JUMP_WAYPOINT_ERROR:
857 return OSD_MESSAGE_STR(OSD_MSG_JUMP_WP_MISCONFIG);
859 break;
860 case ARMING_DISABLED_COMPASS_NOT_CALIBRATED:
861 return OSD_MESSAGE_STR(OSD_MSG_MAG_NOT_CAL);
862 case ARMING_DISABLED_ACCELEROMETER_NOT_CALIBRATED:
863 return OSD_MESSAGE_STR(OSD_MSG_ACC_NOT_CAL);
864 case ARMING_DISABLED_ARM_SWITCH:
865 return OSD_MESSAGE_STR(OSD_MSG_DISARM_1ST);
866 case ARMING_DISABLED_HARDWARE_FAILURE:
868 if (!HW_SENSOR_IS_HEALTHY(getHwGyroStatus())) {
869 return OSD_MESSAGE_STR(OSD_MSG_GYRO_FAILURE);
871 if (!HW_SENSOR_IS_HEALTHY(getHwAccelerometerStatus())) {
872 return OSD_MESSAGE_STR(OSD_MSG_ACC_FAIL);
874 if (!HW_SENSOR_IS_HEALTHY(getHwCompassStatus())) {
875 return OSD_MESSAGE_STR(OSD_MSG_MAG_FAIL);
877 if (!HW_SENSOR_IS_HEALTHY(getHwBarometerStatus())) {
878 return OSD_MESSAGE_STR(OSD_MSG_BARO_FAIL);
880 if (!HW_SENSOR_IS_HEALTHY(getHwGPSStatus())) {
881 return OSD_MESSAGE_STR(OSD_MSG_GPS_FAIL);
883 if (!HW_SENSOR_IS_HEALTHY(getHwRangefinderStatus())) {
884 return OSD_MESSAGE_STR(OSD_MSG_RANGEFINDER_FAIL);
886 if (!HW_SENSOR_IS_HEALTHY(getHwPitotmeterStatus())) {
887 return OSD_MESSAGE_STR(OSD_MSG_PITOT_FAIL);
890 return OSD_MESSAGE_STR(OSD_MSG_HW_FAIL);
891 case ARMING_DISABLED_BOXFAILSAFE:
892 return OSD_MESSAGE_STR(OSD_MSG_FS_EN);
893 case ARMING_DISABLED_BOXKILLSWITCH:
894 return OSD_MESSAGE_STR(OSD_MSG_KILL_SW_EN);
895 case ARMING_DISABLED_RC_LINK:
896 return OSD_MESSAGE_STR(OSD_MSG_NO_RC_LINK);
897 case ARMING_DISABLED_THROTTLE:
898 return OSD_MESSAGE_STR(OSD_MSG_THROTTLE_NOT_LOW);
899 case ARMING_DISABLED_ROLLPITCH_NOT_CENTERED:
900 return OSD_MESSAGE_STR(OSD_MSG_ROLLPITCH_OFFCENTER);
901 case ARMING_DISABLED_SERVO_AUTOTRIM:
902 return OSD_MESSAGE_STR(OSD_MSG_AUTOTRIM_ACTIVE);
903 case ARMING_DISABLED_OOM:
904 return OSD_MESSAGE_STR(OSD_MSG_NOT_ENOUGH_MEMORY);
905 case ARMING_DISABLED_INVALID_SETTING:
906 return OSD_MESSAGE_STR(OSD_MSG_INVALID_SETTING);
907 case ARMING_DISABLED_CLI:
908 return OSD_MESSAGE_STR(OSD_MSG_CLI_ACTIVE);
909 case ARMING_DISABLED_PWM_OUTPUT_ERROR:
910 return OSD_MESSAGE_STR(OSD_MSG_PWM_INIT_ERROR);
911 case ARMING_DISABLED_NO_PREARM:
912 return OSD_MESSAGE_STR(OSD_MSG_NO_PREARM);
913 case ARMING_DISABLED_DSHOT_BEEPER:
914 return OSD_MESSAGE_STR(OSD_MSG_DSHOT_BEEPER);
915 // Cases without message
916 case ARMING_DISABLED_LANDING_DETECTED:
917 FALLTHROUGH;
918 case ARMING_DISABLED_CMS_MENU:
919 FALLTHROUGH;
920 case ARMING_DISABLED_OSD_MENU:
921 FALLTHROUGH;
922 case ARMING_DISABLED_ALL_FLAGS:
923 FALLTHROUGH;
924 case ARMED:
925 FALLTHROUGH;
926 case SIMULATOR_MODE_HITL:
927 FALLTHROUGH;
928 case SIMULATOR_MODE_SITL:
929 FALLTHROUGH;
930 case WAS_EVER_ARMED:
931 break;
933 return NULL;
936 static const char * osdFailsafePhaseMessage(void)
938 // See failsafe.h for each phase explanation
939 switch (failsafePhase()) {
940 case FAILSAFE_RETURN_TO_HOME:
941 // XXX: Keep this in sync with OSD_FLYMODE.
942 return OSD_MESSAGE_STR(OSD_MSG_RTH_FS);
943 case FAILSAFE_LANDING:
944 // This should be considered an emergengy landing
945 return OSD_MESSAGE_STR(OSD_MSG_EMERG_LANDING_FS);
946 case FAILSAFE_RX_LOSS_MONITORING:
947 // Only reachable from FAILSAFE_LANDED, which performs
948 // a disarm. Since aircraft has been disarmed, we no
949 // longer show failsafe details.
950 FALLTHROUGH;
951 case FAILSAFE_LANDED:
952 // Very brief, disarms and transitions into
953 // FAILSAFE_RX_LOSS_MONITORING. Note that it prevents
954 // further rearming via ARMING_DISABLED_FAILSAFE_SYSTEM,
955 // so we'll show the user how to re-arm in when
956 // that flag is the reason to prevent arming.
957 FALLTHROUGH;
958 case FAILSAFE_RX_LOSS_IDLE:
959 // This only happens when user has chosen NONE as FS
960 // procedure. The recovery messages should be enough.
961 FALLTHROUGH;
962 case FAILSAFE_IDLE:
963 // Failsafe not active
964 FALLTHROUGH;
965 case FAILSAFE_RX_LOSS_DETECTED:
966 // Very brief, changes to FAILSAFE_RX_LOSS_RECOVERED
967 // or the FS procedure immediately.
968 FALLTHROUGH;
969 case FAILSAFE_RX_LOSS_RECOVERED:
970 // Exiting failsafe
971 break;
973 return NULL;
976 static const char * osdFailsafeInfoMessage(void)
978 if (failsafeIsReceivingRxData()) {
979 // User must move sticks to exit FS mode
980 return OSD_MESSAGE_STR(OSD_MSG_MOVE_EXIT_FS);
982 return OSD_MESSAGE_STR(OSD_MSG_RC_RX_LINK_LOST);
984 #if defined(USE_SAFE_HOME)
985 static const char * divertingToSafehomeMessage(void)
987 if (NAV_Status.state != MW_NAV_STATE_HOVER_ABOVE_HOME && safehome_applied) {
988 return OSD_MESSAGE_STR(OSD_MSG_DIVERT_SAFEHOME);
990 return NULL;
992 #endif
994 static const char * navigationStateMessage(void)
996 switch (NAV_Status.state) {
997 case MW_NAV_STATE_NONE:
998 break;
999 case MW_NAV_STATE_RTH_START:
1000 return OSD_MESSAGE_STR(OSD_MSG_STARTING_RTH);
1001 case MW_NAV_STATE_RTH_CLIMB:
1002 return OSD_MESSAGE_STR(OSD_MSG_RTH_CLIMB);
1003 case MW_NAV_STATE_RTH_ENROUTE:
1004 if (posControl.flags.rthTrackbackActive) {
1005 return OSD_MESSAGE_STR(OSD_MSG_RTH_TRACKBACK);
1006 } else {
1007 return OSD_MESSAGE_STR(OSD_MSG_HEADING_HOME);
1009 case MW_NAV_STATE_HOLD_INFINIT:
1010 // Used by HOLD flight modes. No information to add.
1011 break;
1012 case MW_NAV_STATE_HOLD_TIMED:
1013 // "HOLDING WP FOR xx S" Countdown added in osdGetSystemMessage
1014 break;
1015 case MW_NAV_STATE_WP_ENROUTE:
1016 // "TO WP" + WP countdown added in osdGetSystemMessage
1017 break;
1018 case MW_NAV_STATE_PROCESS_NEXT:
1019 return OSD_MESSAGE_STR(OSD_MSG_PREPARE_NEXT_WP);
1020 case MW_NAV_STATE_DO_JUMP:
1021 // Not used
1022 break;
1023 case MW_NAV_STATE_LAND_START:
1024 // Not used
1025 break;
1026 case MW_NAV_STATE_EMERGENCY_LANDING:
1027 return OSD_MESSAGE_STR(OSD_MSG_EMERG_LANDING);
1028 case MW_NAV_STATE_LAND_IN_PROGRESS:
1029 return OSD_MESSAGE_STR(OSD_MSG_LANDING);
1030 case MW_NAV_STATE_HOVER_ABOVE_HOME:
1031 if (STATE(FIXED_WING_LEGACY)) {
1032 #if defined(USE_SAFE_HOME)
1033 if (safehome_applied) {
1034 return OSD_MESSAGE_STR(OSD_MSG_LOITERING_SAFEHOME);
1036 #endif
1037 return OSD_MESSAGE_STR(OSD_MSG_LOITERING_HOME);
1039 return OSD_MESSAGE_STR(OSD_MSG_HOVERING);
1040 case MW_NAV_STATE_LANDED:
1041 return OSD_MESSAGE_STR(OSD_MSG_LANDED);
1042 case MW_NAV_STATE_LAND_SETTLE:
1043 return OSD_MESSAGE_STR(OSD_MSG_PREPARING_LAND);
1044 case MW_NAV_STATE_LAND_START_DESCENT:
1045 // Not used
1046 break;
1048 return NULL;
1051 static void osdFormatMessage(char *buff, size_t size, const char *message, bool isCenteredText)
1053 // String is always filled with Blanks
1054 memset(buff, SYM_BLANK, size);
1055 if (message) {
1056 size_t messageLength = strlen(message);
1057 int rem = isCenteredText ? MAX(0, (int)size - (int)messageLength) : 0;
1058 strncpy(buff + rem / 2, message, MIN((int)size - rem / 2, (int)messageLength));
1060 // Ensure buff is zero terminated
1061 buff[size] = '\0';
1065 * Draws the battery symbol filled in accordingly to the
1066 * battery voltage to buff[0].
1068 static void osdFormatBatteryChargeSymbol(char *buff)
1070 uint8_t p = calculateBatteryPercentage();
1071 p = (100 - p) / 16.6;
1072 buff[0] = SYM_BATT_FULL + p;
1075 static void osdUpdateBatteryCapacityOrVoltageTextAttributes(textAttributes_t *attr)
1077 const batteryState_e batteryState = getBatteryState();
1079 if (batteryState == BATTERY_WARNING || batteryState == BATTERY_CRITICAL) {
1080 TEXT_ATTRIBUTES_ADD_BLINK(*attr);
1084 void osdCrosshairPosition(uint8_t *x, uint8_t *y)
1086 *x = osdDisplayPort->cols / 2;
1087 *y = osdDisplayPort->rows / 2;
1088 *y -= osdConfig()->horizon_offset; // positive horizon_offset moves the HUD up, negative moves down
1092 * Check if this OSD layout is using scaled or unscaled throttle.
1093 * If both are used, it will default to scaled.
1095 bool osdUsingScaledThrottle(void)
1097 bool usingScaledThrottle = OSD_VISIBLE(osdLayoutsConfig()->item_pos[currentLayout][OSD_SCALED_THROTTLE_POS]);
1098 bool usingRCThrottle = OSD_VISIBLE(osdLayoutsConfig()->item_pos[currentLayout][OSD_THROTTLE_POS]);
1100 if (!usingScaledThrottle && !usingRCThrottle)
1101 usingScaledThrottle = true;
1103 return usingScaledThrottle;
1107 * Formats throttle position prefixed by its symbol.
1108 * Shows unscaled or scaled (output to motor) throttle percentage
1110 static void osdFormatThrottlePosition(char *buff, bool useScaled, textAttributes_t *elemAttr)
1112 if (useScaled) {
1113 buff[0] = SYM_SCALE;
1114 } else {
1115 buff[0] = SYM_BLANK;
1117 buff[1] = SYM_THR;
1118 if (navigationIsControllingThrottle()) {
1119 buff[0] = SYM_AUTO_THR0;
1120 buff[1] = SYM_AUTO_THR1;
1121 if (isFixedWingAutoThrottleManuallyIncreased()) {
1122 TEXT_ATTRIBUTES_ADD_BLINK(*elemAttr);
1124 useScaled = true;
1126 #ifdef USE_POWER_LIMITS
1127 if (powerLimiterIsLimiting()) {
1128 TEXT_ATTRIBUTES_ADD_BLINK(*elemAttr);
1130 #endif
1131 tfp_sprintf(buff + 2, "%3d", getThrottlePercent(useScaled));
1135 * Formats gvars prefixed by its number (0-indexed). If autoThr
1137 static void osdFormatGVar(char *buff, uint8_t index)
1139 buff[0] = 'G';
1140 buff[1] = '0'+index;
1141 buff[2] = ':';
1142 #ifdef USE_PROGRAMMING_FRAMEWORK
1143 osdFormatCentiNumber(buff + 3, (int32_t)gvGet(index)*(int32_t)100, 1, 0, 0, 5);
1144 #endif
1147 #if defined(USE_ESC_SENSOR)
1148 static void osdFormatRpm(char *buff, uint32_t rpm)
1150 buff[0] = SYM_RPM;
1151 if (rpm) {
1152 if ( digitCount(rpm) > osdConfig()->esc_rpm_precision) {
1153 uint8_t rpmMaxDecimals = (osdConfig()->esc_rpm_precision - 3);
1154 osdFormatCentiNumber(buff + 1, rpm / 10, 0, rpmMaxDecimals, rpmMaxDecimals, osdConfig()->esc_rpm_precision-1);
1155 buff[osdConfig()->esc_rpm_precision] = 'K';
1156 buff[osdConfig()->esc_rpm_precision+1] = '\0';
1158 else {
1159 switch(osdConfig()->esc_rpm_precision) {
1160 case 6:
1161 tfp_sprintf(buff + 1, "%6lu", rpm);
1162 break;
1163 case 5:
1164 tfp_sprintf(buff + 1, "%5lu", rpm);
1165 break;
1166 case 4:
1167 tfp_sprintf(buff + 1, "%4lu", rpm);
1168 break;
1169 case 3:
1170 default:
1171 tfp_sprintf(buff + 1, "%3lu", rpm);
1172 break;
1178 else {
1179 uint8_t buffPos = 1;
1180 while (buffPos <=( osdConfig()->esc_rpm_precision)) {
1181 strcpy(buff + buffPos++, "-");
1185 #endif
1187 int32_t osdGetAltitude(void)
1189 return getEstimatedActualPosition(Z);
1192 static inline int32_t osdGetAltitudeMsl(void)
1194 return getEstimatedActualPosition(Z)+GPS_home.alt;
1197 uint16_t osdGetRemainingGlideTime(void) {
1198 float value = getEstimatedActualVelocity(Z);
1199 static pt1Filter_t glideTimeFilterState;
1200 const timeMs_t curTimeMs = millis();
1201 static timeMs_t glideTimeUpdatedMs;
1203 value = pt1FilterApply4(&glideTimeFilterState, isnormal(value) ? value : 0, 0.5, MS2S(curTimeMs - glideTimeUpdatedMs));
1204 glideTimeUpdatedMs = curTimeMs;
1206 if (value < 0) {
1207 value = osdGetAltitude() / abs((int)value);
1208 } else {
1209 value = 0;
1212 return (uint16_t)roundf(value);
1215 static bool osdIsHeadingValid(void)
1217 return isImuHeadingValid();
1220 int16_t osdGetHeading(void)
1222 return attitude.values.yaw;
1225 int16_t osdGetPanServoOffset(void)
1227 int8_t servoIndex = osdConfig()->pan_servo_index;
1228 int16_t servoPosition = servo[servoIndex];
1229 int16_t servoMiddle = servoParams(servoIndex)->middle;
1230 return (int16_t)CENTIDEGREES_TO_DEGREES((servoPosition - servoMiddle) * osdConfig()->pan_servo_pwm2centideg);
1233 // Returns a heading angle in degrees normalized to [0, 360).
1234 int osdGetHeadingAngle(int angle)
1236 while (angle < 0) {
1237 angle += 360;
1239 while (angle >= 360) {
1240 angle -= 360;
1242 return angle;
1245 #if defined(USE_GPS)
1247 /* Draws a map with the given symbol in the center and given point of interest
1248 * defined by its distance in meters and direction in degrees.
1249 * referenceHeading indicates the up direction in the map, in degrees, while
1250 * referenceSym (if non-zero) is drawn at the upper right corner below a small
1251 * arrow to indicate the map reference to the user. The drawn argument is an
1252 * in-out used to store the last position where the craft was drawn to avoid
1253 * erasing all screen on each redraw.
1255 static void osdDrawMap(int referenceHeading, uint16_t referenceSym, uint16_t centerSym,
1256 uint32_t poiDistance, int16_t poiDirection, uint16_t poiSymbol,
1257 uint16_t *drawn, uint32_t *usedScale)
1259 // TODO: These need to be tested with several setups. We might
1260 // need to make them configurable.
1261 const int hMargin = 5;
1262 const int vMargin = 3;
1264 // TODO: Get this from the display driver?
1265 const int charWidth = 12;
1266 const int charHeight = 18;
1268 uint8_t minX = hMargin;
1269 uint8_t maxX = osdDisplayPort->cols - 1 - hMargin;
1270 uint8_t minY = vMargin;
1271 uint8_t maxY = osdDisplayPort->rows - 1 - vMargin;
1272 uint8_t midX = osdDisplayPort->cols / 2;
1273 uint8_t midY = osdDisplayPort->rows / 2;
1275 // Fixed marks
1276 displayWriteChar(osdDisplayPort, midX, midY, centerSym);
1278 // First, erase the previous drawing.
1279 if (OSD_VISIBLE(*drawn)) {
1280 displayWriteChar(osdDisplayPort, OSD_X(*drawn), OSD_Y(*drawn), SYM_BLANK);
1281 *drawn = 0;
1284 uint32_t initialScale;
1285 const unsigned scaleMultiplier = 2;
1286 // We try to reduce the scale when the POI will be around half the distance
1287 // between the center and the closers map edge, to avoid too much jumping
1288 const int scaleReductionMultiplier = MIN(midX - hMargin, midY - vMargin) / 2;
1290 switch (osdConfig()->units) {
1291 case OSD_UNIT_UK:
1292 FALLTHROUGH;
1293 case OSD_UNIT_IMPERIAL:
1294 initialScale = 16; // 16m ~= 0.01miles
1295 break;
1296 case OSD_UNIT_GA:
1297 initialScale = 18; // 18m ~= 0.01 nautical miles
1298 break;
1299 default:
1300 case OSD_UNIT_METRIC_MPH:
1301 FALLTHROUGH;
1302 case OSD_UNIT_METRIC:
1303 initialScale = 10; // 10m as initial scale
1304 break;
1307 // Try to keep the same scale when getting closer until we draw over the center point
1308 uint32_t scale = initialScale;
1309 if (*usedScale) {
1310 scale = *usedScale;
1311 if (scale > initialScale && poiDistance < *usedScale * scaleReductionMultiplier) {
1312 scale /= scaleMultiplier;
1316 if (STATE(GPS_FIX)) {
1318 int directionToPoi = osdGetHeadingAngle(poiDirection - referenceHeading);
1319 float poiAngle = DEGREES_TO_RADIANS(directionToPoi);
1320 float poiSin = sin_approx(poiAngle);
1321 float poiCos = cos_approx(poiAngle);
1323 // Now start looking for a valid scale that lets us draw everything
1324 int ii;
1325 for (ii = 0; ii < 50; ii++) {
1326 // Calculate location of the aircraft in map
1327 int points = poiDistance / ((float)scale / charHeight);
1329 float pointsX = points * poiSin;
1330 int poiX = midX - roundf(pointsX / charWidth);
1331 if (poiX < minX || poiX > maxX) {
1332 scale *= scaleMultiplier;
1333 continue;
1336 float pointsY = points * poiCos;
1337 int poiY = midY + roundf(pointsY / charHeight);
1338 if (poiY < minY || poiY > maxY) {
1339 scale *= scaleMultiplier;
1340 continue;
1343 if (poiX == midX && poiY == midY) {
1344 // We're over the map center symbol, so we would be drawing
1345 // over it even if we increased the scale. Alternate between
1346 // drawing the center symbol or drawing the POI.
1347 if (centerSym != SYM_BLANK && OSD_ALTERNATING_CHOICES(1000, 2) == 0) {
1348 break;
1350 } else {
1352 uint16_t c;
1353 if (displayReadCharWithAttr(osdDisplayPort, poiX, poiY, &c, NULL) && c != SYM_BLANK) {
1354 // Something else written here, increase scale. If the display doesn't support reading
1355 // back characters, we assume there's nothing.
1357 // If we're close to the center, decrease scale. Otherwise increase it.
1358 uint8_t centerDeltaX = (maxX - minX) / (scaleMultiplier * 2);
1359 uint8_t centerDeltaY = (maxY - minY) / (scaleMultiplier * 2);
1360 if (poiX >= midX - centerDeltaX && poiX <= midX + centerDeltaX &&
1361 poiY >= midY - centerDeltaY && poiY <= midY + centerDeltaY &&
1362 scale > scaleMultiplier) {
1364 scale /= scaleMultiplier;
1365 } else {
1366 scale *= scaleMultiplier;
1368 continue;
1372 // Draw the point on the map
1373 if (poiSymbol == SYM_ARROW_UP) {
1374 // Drawing aircraft, rotate
1375 int mapHeading = osdGetHeadingAngle(DECIDEGREES_TO_DEGREES(osdGetHeading()) - referenceHeading);
1376 poiSymbol += mapHeading * 2 / 45;
1378 displayWriteChar(osdDisplayPort, poiX, poiY, poiSymbol);
1380 // Update saved location
1381 *drawn = OSD_POS(poiX, poiY) | OSD_VISIBLE_FLAG;
1382 break;
1386 *usedScale = scale;
1388 // Update global map data for scale and reference
1389 osdMapData.scale = scale;
1390 osdMapData.referenceSymbol = referenceSym;
1393 /* Draws a map with the home in the center and the craft moving around.
1394 * See osdDrawMap() for reference.
1396 static void osdDrawHomeMap(int referenceHeading, uint8_t referenceSym, uint16_t *drawn, uint32_t *usedScale)
1398 osdDrawMap(referenceHeading, referenceSym, SYM_HOME, GPS_distanceToHome, GPS_directionToHome, SYM_ARROW_UP, drawn, usedScale);
1401 /* Draws a map with the aircraft in the center and the home moving around.
1402 * See osdDrawMap() for reference.
1404 static void osdDrawRadar(uint16_t *drawn, uint32_t *usedScale)
1406 int16_t reference = DECIDEGREES_TO_DEGREES(osdGetHeading());
1407 int16_t poiDirection = osdGetHeadingAngle(GPS_directionToHome + 180);
1408 osdDrawMap(reference, 0, SYM_ARROW_UP, GPS_distanceToHome, poiDirection, SYM_HOME, drawn, usedScale);
1411 static uint16_t crc_accumulate(uint8_t data, uint16_t crcAccum)
1413 uint8_t tmp;
1414 tmp = data ^ (uint8_t)(crcAccum & 0xff);
1415 tmp ^= (tmp << 4);
1416 crcAccum = (crcAccum >> 8) ^ (tmp << 8) ^ (tmp << 3) ^ (tmp >> 4);
1417 return crcAccum;
1421 static void osdDisplayTelemetry(void)
1423 uint32_t trk_data;
1424 uint16_t trk_crc = 0;
1425 char trk_buffer[31];
1426 static int16_t trk_elevation = 127;
1427 static uint16_t trk_bearing = 0;
1429 if (ARMING_FLAG(ARMED)) {
1430 if (STATE(GPS_FIX)){
1431 if (GPS_distanceToHome > 5) {
1432 trk_bearing = GPS_directionToHome;
1433 trk_bearing += 360 + 180;
1434 trk_bearing %= 360;
1435 int32_t alt = CENTIMETERS_TO_METERS(osdGetAltitude());
1436 float at = atan2(alt, GPS_distanceToHome);
1437 trk_elevation = at * 57.2957795f; // 57.2957795 = 1 rad
1438 trk_elevation += 37; // because elevation in telemetry should be from -37 to 90
1439 if (trk_elevation < 0) {
1440 trk_elevation = 0;
1445 else{
1446 trk_elevation = 127;
1447 trk_bearing = 0;
1450 trk_data = 0; // bit 0 - packet type 0 = bearing/elevation, 1 = 2 byte data packet
1451 trk_data = trk_data | (uint32_t)(0x7F & trk_elevation) << 1; // bits 1-7 - elevation angle to target. NOTE number is abused. constrained value of -37 to 90 sent as 0 to 127.
1452 trk_data = trk_data | (uint32_t)trk_bearing << 8; // bits 8-17 - bearing angle to target. 0 = true north. 0 to 360
1453 trk_crc = crc_accumulate(0xFF & trk_data, trk_crc); // CRC First Byte bits 0-7
1454 trk_crc = crc_accumulate(0xFF & trk_bearing, trk_crc); // CRC Second Byte bits 8-15
1455 trk_crc = crc_accumulate(trk_bearing >> 8, trk_crc); // CRC Third Byte bits 16-17
1456 trk_data = trk_data | (uint32_t)trk_crc << 17; // bits 18-29 CRC & 0x3FFFF
1458 for (uint8_t t_ctr = 0; t_ctr < 30; t_ctr++) { // Prepare screen buffer and write data line.
1459 if (trk_data & (uint32_t)1 << t_ctr){
1460 trk_buffer[29 - t_ctr] = SYM_TELEMETRY_0;
1462 else{
1463 trk_buffer[29 - t_ctr] = SYM_TELEMETRY_1;
1466 trk_buffer[30] = 0;
1467 displayWrite(osdDisplayPort, 0, 0, trk_buffer);
1468 if (osdConfig()->telemetry>1){
1469 displayWrite(osdDisplayPort, 0, 3, trk_buffer); // Test display because normal telemetry line is not visible
1472 #endif
1474 static void osdFormatPidControllerOutput(char *buff, const char *label, const pidController_t *pidController, uint8_t scale, bool showDecimal) {
1475 strcpy(buff, label);
1476 for (uint8_t i = strlen(label); i < 5; ++i) buff[i] = ' ';
1477 uint8_t decimals = showDecimal ? 1 : 0;
1478 osdFormatCentiNumber(buff + 5, pidController->proportional * scale, 0, decimals, 0, 4);
1479 buff[9] = ' ';
1480 osdFormatCentiNumber(buff + 10, pidController->integrator * scale, 0, decimals, 0, 4);
1481 buff[14] = ' ';
1482 osdFormatCentiNumber(buff + 15, pidController->derivative * scale, 0, decimals, 0, 4);
1483 buff[19] = ' ';
1484 osdFormatCentiNumber(buff + 20, pidController->output_constrained * scale, 0, decimals, 0, 4);
1485 buff[24] = '\0';
1488 static void osdDisplayBatteryVoltage(uint8_t elemPosX, uint8_t elemPosY, uint16_t voltage, uint8_t digits, uint8_t decimals)
1490 char buff[7];
1491 textAttributes_t elemAttr = TEXT_ATTRIBUTES_NONE;
1493 osdFormatBatteryChargeSymbol(buff);
1494 buff[1] = '\0';
1495 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1496 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
1498 elemAttr = TEXT_ATTRIBUTES_NONE;
1499 digits = MIN(digits, 5);
1500 osdFormatCentiNumber(buff, voltage, 0, decimals, 0, digits);
1501 buff[digits] = SYM_VOLT;
1502 buff[digits+1] = '\0';
1503 const batteryState_e batteryVoltageState = checkBatteryVoltageState();
1504 if (batteryVoltageState == BATTERY_CRITICAL || batteryVoltageState == BATTERY_WARNING) {
1505 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1507 displayWriteWithAttr(osdDisplayPort, elemPosX + 1, elemPosY, buff, elemAttr);
1510 static void osdDisplayFlightPIDValues(uint8_t elemPosX, uint8_t elemPosY, const char *str, pidIndex_e pidIndex, adjustmentFunction_e adjFuncP, adjustmentFunction_e adjFuncI, adjustmentFunction_e adjFuncD, adjustmentFunction_e adjFuncFF)
1512 textAttributes_t elemAttr;
1513 char buff[4];
1515 const pid8_t *pid = &pidBank()->pid[pidIndex];
1516 pidType_e pidType = pidIndexGetType(pidIndex);
1518 displayWrite(osdDisplayPort, elemPosX, elemPosY, str);
1520 if (pidType == PID_TYPE_NONE) {
1521 // PID is not used in this configuration. Draw dashes.
1522 // XXX: Keep this in sync with the %3d format and spacing used below
1523 displayWrite(osdDisplayPort, elemPosX + 6, elemPosY, "- - - -");
1524 return;
1527 elemAttr = TEXT_ATTRIBUTES_NONE;
1528 tfp_sprintf(buff, "%3d", pid->P);
1529 if ((isAdjustmentFunctionSelected(adjFuncP)) || (((adjFuncP == ADJUSTMENT_ROLL_P) || (adjFuncP == ADJUSTMENT_PITCH_P)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_P))))
1530 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1531 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
1533 elemAttr = TEXT_ATTRIBUTES_NONE;
1534 tfp_sprintf(buff, "%3d", pid->I);
1535 if ((isAdjustmentFunctionSelected(adjFuncI)) || (((adjFuncI == ADJUSTMENT_ROLL_I) || (adjFuncI == ADJUSTMENT_PITCH_I)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_I))))
1536 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1537 displayWriteWithAttr(osdDisplayPort, elemPosX + 8, elemPosY, buff, elemAttr);
1539 elemAttr = TEXT_ATTRIBUTES_NONE;
1540 tfp_sprintf(buff, "%3d", pid->D);
1541 if ((isAdjustmentFunctionSelected(adjFuncD)) || (((adjFuncD == ADJUSTMENT_ROLL_D) || (adjFuncD == ADJUSTMENT_PITCH_D)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_D))))
1542 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1543 displayWriteWithAttr(osdDisplayPort, elemPosX + 12, elemPosY, buff, elemAttr);
1545 elemAttr = TEXT_ATTRIBUTES_NONE;
1546 tfp_sprintf(buff, "%3d", pid->FF);
1547 if ((isAdjustmentFunctionSelected(adjFuncFF)) || (((adjFuncFF == ADJUSTMENT_ROLL_FF) || (adjFuncFF == ADJUSTMENT_PITCH_FF)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_FF))))
1548 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1549 displayWriteWithAttr(osdDisplayPort, elemPosX + 16, elemPosY, buff, elemAttr);
1552 static void osdDisplayNavPIDValues(uint8_t elemPosX, uint8_t elemPosY, const char *str, pidIndex_e pidIndex, adjustmentFunction_e adjFuncP, adjustmentFunction_e adjFuncI, adjustmentFunction_e adjFuncD)
1554 textAttributes_t elemAttr;
1555 char buff[4];
1557 const pid8_t *pid = &pidBank()->pid[pidIndex];
1558 pidType_e pidType = pidIndexGetType(pidIndex);
1560 displayWrite(osdDisplayPort, elemPosX, elemPosY, str);
1562 if (pidType == PID_TYPE_NONE) {
1563 // PID is not used in this configuration. Draw dashes.
1564 // XXX: Keep this in sync with the %3d format and spacing used below
1565 displayWrite(osdDisplayPort, elemPosX + 6, elemPosY, "- - -");
1566 return;
1569 elemAttr = TEXT_ATTRIBUTES_NONE;
1570 tfp_sprintf(buff, "%3d", pid->P);
1571 if ((isAdjustmentFunctionSelected(adjFuncP)) || (((adjFuncP == ADJUSTMENT_ROLL_P) || (adjFuncP == ADJUSTMENT_PITCH_P)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_P))))
1572 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1573 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
1575 elemAttr = TEXT_ATTRIBUTES_NONE;
1576 tfp_sprintf(buff, "%3d", pid->I);
1577 if ((isAdjustmentFunctionSelected(adjFuncI)) || (((adjFuncI == ADJUSTMENT_ROLL_I) || (adjFuncI == ADJUSTMENT_PITCH_I)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_I))))
1578 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1579 displayWriteWithAttr(osdDisplayPort, elemPosX + 8, elemPosY, buff, elemAttr);
1581 elemAttr = TEXT_ATTRIBUTES_NONE;
1582 tfp_sprintf(buff, "%3d", pidType == PID_TYPE_PIFF ? pid->FF : pid->D);
1583 if ((isAdjustmentFunctionSelected(adjFuncD)) || (((adjFuncD == ADJUSTMENT_ROLL_D) || (adjFuncD == ADJUSTMENT_PITCH_D)) && (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_D))))
1584 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1585 displayWriteWithAttr(osdDisplayPort, elemPosX + 12, elemPosY, buff, elemAttr);
1588 static void osdDisplayAdjustableDecimalValue(uint8_t elemPosX, uint8_t elemPosY, const char *str, const uint8_t valueOffset, const float value, const uint8_t valueLength, const uint8_t maxDecimals, adjustmentFunction_e adjFunc) {
1589 char buff[8];
1590 textAttributes_t elemAttr;
1591 displayWrite(osdDisplayPort, elemPosX, elemPosY, str);
1593 elemAttr = TEXT_ATTRIBUTES_NONE;
1594 osdFormatCentiNumber(buff, value * 100, 0, maxDecimals, 0, MIN(valueLength, 8));
1595 if (isAdjustmentFunctionSelected(adjFunc))
1596 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1597 displayWriteWithAttr(osdDisplayPort, elemPosX + strlen(str) + 1 + valueOffset, elemPosY, buff, elemAttr);
1600 int8_t getGeoWaypointNumber(int8_t waypointIndex)
1602 static int8_t lastWaypointIndex = 1;
1603 static int8_t geoWaypointIndex;
1605 if (waypointIndex != lastWaypointIndex) {
1606 lastWaypointIndex = geoWaypointIndex = waypointIndex;
1607 for (uint8_t i = posControl.startWpIndex; i <= waypointIndex; i++) {
1608 if (posControl.waypointList[i].action == NAV_WP_ACTION_SET_POI ||
1609 posControl.waypointList[i].action == NAV_WP_ACTION_SET_HEAD ||
1610 posControl.waypointList[i].action == NAV_WP_ACTION_JUMP) {
1611 geoWaypointIndex -= 1;
1616 return geoWaypointIndex - posControl.startWpIndex + 1;
1619 void osdDisplaySwitchIndicator(const char *swName, int rcValue, char *buff) {
1620 int8_t ptr = 0;
1622 if (osdConfig()->osd_switch_indicators_align_left) {
1623 for (ptr = 0; ptr < constrain(strlen(swName), 0, OSD_SWITCH_INDICATOR_NAME_LENGTH); ptr++) {
1624 buff[ptr] = swName[ptr];
1627 if ( rcValue < 1333) {
1628 buff[ptr++] = SYM_SWITCH_INDICATOR_LOW;
1629 } else if ( rcValue > 1666) {
1630 buff[ptr++] = SYM_SWITCH_INDICATOR_HIGH;
1631 } else {
1632 buff[ptr++] = SYM_SWITCH_INDICATOR_MID;
1634 } else {
1635 if ( rcValue < 1333) {
1636 buff[ptr++] = SYM_SWITCH_INDICATOR_LOW;
1637 } else if ( rcValue > 1666) {
1638 buff[ptr++] = SYM_SWITCH_INDICATOR_HIGH;
1639 } else {
1640 buff[ptr++] = SYM_SWITCH_INDICATOR_MID;
1643 for (ptr = 1; ptr < constrain(strlen(swName), 0, OSD_SWITCH_INDICATOR_NAME_LENGTH) + 1; ptr++) {
1644 buff[ptr] = swName[ptr-1];
1647 ptr++;
1650 buff[ptr] = '\0';
1653 static bool osdDrawSingleElement(uint8_t item)
1655 uint16_t pos = osdLayoutsConfig()->item_pos[currentLayout][item];
1656 if (!OSD_VISIBLE(pos)) {
1657 return false;
1659 uint8_t elemPosX = OSD_X(pos);
1660 uint8_t elemPosY = OSD_Y(pos);
1661 textAttributes_t elemAttr = TEXT_ATTRIBUTES_NONE;
1662 char buff[32] = {0};
1664 switch (item) {
1665 case OSD_RSSI_VALUE:
1667 uint16_t osdRssi = osdConvertRSSI();
1668 buff[0] = SYM_RSSI;
1669 tfp_sprintf(buff + 1, "%2d", osdRssi);
1670 if (osdRssi < osdConfig()->rssi_alarm) {
1671 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1673 break;
1676 case OSD_MAIN_BATT_VOLTAGE: {
1677 uint8_t base_digits = 2U;
1678 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it
1679 if(isBfCompatibleVideoSystem(osdConfig())) {
1680 base_digits = 3U; // Add extra digit to account for decimal point taking an extra character space
1682 #endif
1683 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatteryRawVoltage(), base_digits + osdConfig()->main_voltage_decimals, osdConfig()->main_voltage_decimals);
1684 return true;
1687 case OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE: {
1688 uint8_t base_digits = 2U;
1689 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it
1690 if(isBfCompatibleVideoSystem(osdConfig())) {
1691 base_digits = 3U; // Add extra digit to account for decimal point taking an extra character space
1693 #endif
1694 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatterySagCompensatedVoltage(), base_digits + osdConfig()->main_voltage_decimals, osdConfig()->main_voltage_decimals);
1695 return true;
1698 case OSD_CURRENT_DRAW: {
1699 osdFormatCentiNumber(buff, getAmperage(), 0, 2, 0, 3);
1700 buff[3] = SYM_AMP;
1701 buff[4] = '\0';
1703 uint8_t current_alarm = osdConfig()->current_alarm;
1704 if ((current_alarm > 0) && ((getAmperage() / 100.0f) > current_alarm)) {
1705 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1707 break;
1710 case OSD_MAH_DRAWN: {
1711 uint8_t mah_digits = osdConfig()->mAh_used_precision; // Initialize to config value
1712 bool bfcompat = false; // Assume BFCOMPAT is off
1714 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it
1715 if (isBfCompatibleVideoSystem(osdConfig())) {
1716 bfcompat = true;
1718 #endif
1720 if (bfcompat) {
1721 //BFcompat is unable to work with scaled values and it only has mAh symbol to work with
1722 tfp_sprintf(buff, "%5d", (int)getMAhDrawn()); // Use 5 digits to allow 10Ah+ packs
1723 buff[5] = SYM_MAH;
1724 buff[6] = '\0';
1725 } else {
1726 if (osdFormatCentiNumber(buff, getMAhDrawn() * 100, 1000, 0, (mah_digits - 2), mah_digits)) {
1727 // Shown in Ah
1728 buff[mah_digits] = SYM_AH;
1729 } else {
1730 // Shown in mAh
1731 buff[mah_digits] = SYM_MAH;
1733 buff[mah_digits + 1] = '\0';
1736 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1737 break;
1740 case OSD_WH_DRAWN:
1741 osdFormatCentiNumber(buff, getMWhDrawn() / 10, 0, 2, 0, 3);
1742 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1743 buff[3] = SYM_WH;
1744 buff[4] = '\0';
1745 break;
1747 case OSD_BATTERY_REMAINING_CAPACITY:
1749 if (currentBatteryProfile->capacity.value == 0)
1750 tfp_sprintf(buff, " NA");
1751 else if (!batteryWasFullWhenPluggedIn())
1752 tfp_sprintf(buff, " NF");
1753 else if (currentBatteryProfile->capacity.unit == BAT_CAPACITY_UNIT_MAH)
1754 tfp_sprintf(buff, "%4lu", (unsigned long)getBatteryRemainingCapacity());
1755 else // currentBatteryProfile->capacity.unit == BAT_CAPACITY_UNIT_MWH
1756 osdFormatCentiNumber(buff + 1, getBatteryRemainingCapacity() / 10, 0, 2, 0, 3);
1758 buff[4] = currentBatteryProfile->capacity.unit == BAT_CAPACITY_UNIT_MAH ? SYM_MAH : SYM_WH;
1759 buff[5] = '\0';
1761 if (batteryUsesCapacityThresholds()) {
1762 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1765 break;
1767 case OSD_BATTERY_REMAINING_PERCENT:
1768 osdFormatBatteryChargeSymbol(buff);
1769 tfp_sprintf(buff + 1, "%3d%%", calculateBatteryPercentage());
1770 osdUpdateBatteryCapacityOrVoltageTextAttributes(&elemAttr);
1771 break;
1773 case OSD_POWER_SUPPLY_IMPEDANCE:
1774 if (isPowerSupplyImpedanceValid())
1775 tfp_sprintf(buff, "%3d", getPowerSupplyImpedance());
1776 else
1777 strcpy(buff, "---");
1778 buff[3] = SYM_MILLIOHM;
1779 buff[4] = '\0';
1780 break;
1782 #ifdef USE_GPS
1783 case OSD_GPS_SATS:
1784 buff[0] = SYM_SAT_L;
1785 buff[1] = SYM_SAT_R;
1786 tfp_sprintf(buff + 2, "%2d", gpsSol.numSat);
1787 if (!STATE(GPS_FIX)) {
1788 if (getHwGPSStatus() == HW_SENSOR_UNAVAILABLE || getHwGPSStatus() == HW_SENSOR_UNHEALTHY) {
1789 strcpy(buff + 2, "X!");
1791 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1793 break;
1795 case OSD_GPS_SPEED:
1796 osdFormatVelocityStr(buff, gpsSol.groundSpeed, false, false);
1797 break;
1799 case OSD_GPS_MAX_SPEED:
1800 osdFormatVelocityStr(buff, stats.max_speed, false, true);
1801 break;
1803 case OSD_3D_SPEED:
1804 osdFormatVelocityStr(buff, osdGet3DSpeed(), true, false);
1805 break;
1807 case OSD_3D_MAX_SPEED:
1808 osdFormatVelocityStr(buff, stats.max_3D_speed, true, true);
1809 break;
1811 case OSD_GLIDESLOPE:
1813 float horizontalSpeed = gpsSol.groundSpeed;
1814 float sinkRate = -getEstimatedActualVelocity(Z);
1815 static pt1Filter_t gsFilterState;
1816 const timeMs_t currentTimeMs = millis();
1817 static timeMs_t gsUpdatedTimeMs;
1818 float glideSlope = horizontalSpeed / sinkRate;
1819 glideSlope = pt1FilterApply4(&gsFilterState, isnormal(glideSlope) ? glideSlope : 200, 0.5, MS2S(currentTimeMs - gsUpdatedTimeMs));
1820 gsUpdatedTimeMs = currentTimeMs;
1822 buff[0] = SYM_GLIDESLOPE;
1823 if (glideSlope > 0.0f && glideSlope < 100.0f) {
1824 osdFormatCentiNumber(buff + 1, glideSlope * 100.0f, 0, 2, 0, 3);
1825 } else {
1826 buff[1] = buff[2] = buff[3] = '-';
1828 buff[4] = '\0';
1829 break;
1832 case OSD_GPS_LAT:
1833 osdFormatCoordinate(buff, SYM_LAT, gpsSol.llh.lat);
1834 break;
1836 case OSD_GPS_LON:
1837 osdFormatCoordinate(buff, SYM_LON, gpsSol.llh.lon);
1838 break;
1840 case OSD_HOME_DIR:
1842 if (STATE(GPS_FIX) && STATE(GPS_FIX_HOME) && isImuHeadingValid()) {
1843 if (GPS_distanceToHome < (navConfig()->general.min_rth_distance / 100) ) {
1844 displayWriteChar(osdDisplayPort, elemPosX, elemPosY, SYM_HOME_NEAR);
1846 else
1848 int16_t panHomeDirOffset = 0;
1849 if (!(osdConfig()->pan_servo_pwm2centideg == 0)){
1850 panHomeDirOffset = osdGetPanServoOffset();
1852 int16_t flightDirection = STATE(AIRPLANE) ? CENTIDEGREES_TO_DEGREES(posControl.actualState.cog) : DECIDEGREES_TO_DEGREES(osdGetHeading());
1853 int homeDirection = GPS_directionToHome - flightDirection + panHomeDirOffset;
1854 osdDrawDirArrow(osdDisplayPort, osdGetDisplayPortCanvas(), OSD_DRAW_POINT_GRID(elemPosX, elemPosY), homeDirection);
1856 } else {
1857 // No home or no fix or unknown heading, blink.
1858 // If we're unarmed, show the arrow pointing up so users can see the arrow
1859 // while configuring the OSD. If we're armed, show a '-' indicating that
1860 // we don't know the direction to home.
1861 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1862 displayWriteCharWithAttr(osdDisplayPort, elemPosX, elemPosY, ARMING_FLAG(ARMED) ? '-' : SYM_ARROW_UP, elemAttr);
1864 return true;
1867 case OSD_HOME_HEADING_ERROR:
1869 buff[0] = SYM_HOME;
1870 buff[1] = SYM_HEADING;
1872 if (isImuHeadingValid() && navigationPositionEstimateIsHealthy()) {
1873 int16_t h = lrintf(CENTIDEGREES_TO_DEGREES((float)wrap_18000(DEGREES_TO_CENTIDEGREES((int32_t)GPS_directionToHome) - (STATE(AIRPLANE) ? posControl.actualState.cog : DECIDEGREES_TO_CENTIDEGREES((int32_t)osdGetHeading())))));
1874 tfp_sprintf(buff + 2, "%4d", h);
1875 } else {
1876 strcpy(buff + 2, "----");
1879 buff[6] = SYM_DEGREES;
1880 buff[7] = '\0';
1881 break;
1884 case OSD_HOME_DIST:
1886 buff[0] = SYM_HOME;
1887 uint32_t distance_to_home_cm = GPS_distanceToHome * 100;
1888 osdFormatDistanceSymbol(&buff[1], distance_to_home_cm, 0);
1890 uint16_t dist_alarm = osdConfig()->dist_alarm;
1891 if (dist_alarm > 0 && GPS_distanceToHome > dist_alarm) {
1892 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
1895 break;
1897 case OSD_TRIP_DIST:
1898 buff[0] = SYM_TOTAL;
1899 osdFormatDistanceSymbol(buff + 1, getTotalTravelDistance(), 0);
1900 break;
1902 case OSD_GROUND_COURSE:
1904 buff[0] = SYM_GROUND_COURSE;
1905 if (osdIsHeadingValid()) {
1906 tfp_sprintf(&buff[1], "%3d", (int16_t)CENTIDEGREES_TO_DEGREES(posControl.actualState.cog));
1907 } else {
1908 buff[1] = buff[2] = buff[3] = '-';
1910 buff[4] = SYM_DEGREES;
1911 buff[5] = '\0';
1912 break;
1915 case OSD_COURSE_HOLD_ERROR:
1917 if (ARMING_FLAG(ARMED) && !FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) {
1918 displayWrite(osdDisplayPort, elemPosX, elemPosY, " ");
1919 return true;
1922 buff[0] = SYM_HEADING;
1924 if ((!ARMING_FLAG(ARMED)) || (FLIGHT_MODE(NAV_COURSE_HOLD_MODE) && isAdjustingPosition())) {
1925 buff[1] = buff[2] = buff[3] = '-';
1926 } else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) {
1927 int16_t herr = lrintf(CENTIDEGREES_TO_DEGREES((float)navigationGetHeadingError()));
1928 if (ABS(herr) > 99)
1929 strcpy(buff + 1, ">99");
1930 else
1931 tfp_sprintf(buff + 1, "%3d", herr);
1934 buff[4] = SYM_DEGREES;
1935 buff[5] = '\0';
1936 break;
1939 case OSD_COURSE_HOLD_ADJUSTMENT:
1941 int16_t heading_adjust = lrintf(CENTIDEGREES_TO_DEGREES((float)getCruiseHeadingAdjustment()));
1943 if (ARMING_FLAG(ARMED) && ((!FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) || !(isAdjustingPosition() || isAdjustingHeading() || (heading_adjust != 0)))) {
1944 displayWrite(osdDisplayPort, elemPosX, elemPosY, " ");
1945 return true;
1948 buff[0] = SYM_HEADING;
1950 if (!ARMING_FLAG(ARMED)) {
1951 buff[1] = buff[2] = buff[3] = buff[4] = '-';
1952 } else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE)) {
1953 tfp_sprintf(buff + 1, "%4d", heading_adjust);
1956 buff[5] = SYM_DEGREES;
1957 buff[6] = '\0';
1958 break;
1961 case OSD_CROSS_TRACK_ERROR:
1963 if (isWaypointNavTrackingActive()) {
1964 buff[0] = SYM_CROSS_TRACK_ERROR;
1965 osdFormatDistanceSymbol(buff + 1, navigationGetCrossTrackError(), 0);
1966 } else {
1967 displayWrite(osdDisplayPort, elemPosX, elemPosY, " ");
1968 return true;
1970 break;
1973 case OSD_GPS_HDOP:
1975 buff[0] = SYM_HDP_L;
1976 buff[1] = SYM_HDP_R;
1977 int32_t centiHDOP = 100 * gpsSol.hdop / HDOP_SCALE;
1978 uint8_t digits = 2U;
1979 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it and change the values
1980 if (isBfCompatibleVideoSystem(osdConfig())) {
1981 digits = 3U;
1983 #endif
1984 osdFormatCentiNumber(&buff[2], centiHDOP, 0, 1, 0, digits);
1985 break;
1988 case OSD_MAP_NORTH:
1990 static uint16_t drawn = 0;
1991 static uint32_t scale = 0;
1992 osdDrawHomeMap(0, 'N', &drawn, &scale);
1993 return true;
1995 case OSD_MAP_TAKEOFF:
1997 static uint16_t drawn = 0;
1998 static uint32_t scale = 0;
1999 osdDrawHomeMap(CENTIDEGREES_TO_DEGREES(navigationGetHomeHeading()), 'T', &drawn, &scale);
2000 return true;
2002 case OSD_RADAR:
2004 static uint16_t drawn = 0;
2005 static uint32_t scale = 0;
2006 osdDrawRadar(&drawn, &scale);
2007 return true;
2009 #endif // GPS
2011 case OSD_ALTITUDE:
2013 int32_t alt = osdGetAltitude();
2014 osdFormatAltitudeSymbol(buff, alt);
2016 uint16_t alt_alarm = osdConfig()->alt_alarm;
2017 uint16_t neg_alt_alarm = osdConfig()->neg_alt_alarm;
2018 if ((alt_alarm > 0 && CENTIMETERS_TO_METERS(alt) > alt_alarm) ||
2019 (neg_alt_alarm > 0 && alt < 0 && -CENTIMETERS_TO_METERS(alt) > neg_alt_alarm)) {
2021 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2023 break;
2026 case OSD_ALTITUDE_MSL:
2028 int32_t alt = osdGetAltitudeMsl();
2029 osdFormatAltitudeSymbol(buff, alt);
2030 break;
2033 #ifdef USE_RANGEFINDER
2034 case OSD_RANGEFINDER:
2036 int32_t range = rangefinderGetLatestRawAltitude();
2037 if (range < 0) {
2038 buff[0] = '-';
2039 buff[1] = '-';
2040 buff[2] = '-';
2041 } else {
2042 osdFormatDistanceSymbol(buff, range, 1);
2045 break;
2046 #endif
2048 case OSD_ONTIME:
2050 osdFormatOnTime(buff);
2051 break;
2054 case OSD_FLYTIME:
2056 osdFormatFlyTime(buff, &elemAttr);
2057 break;
2060 case OSD_ONTIME_FLYTIME:
2062 if (ARMING_FLAG(ARMED)) {
2063 osdFormatFlyTime(buff, &elemAttr);
2064 } else {
2065 osdFormatOnTime(buff);
2067 break;
2070 case OSD_REMAINING_FLIGHT_TIME_BEFORE_RTH:
2072 /*static int32_t updatedTimeSeconds = 0;*/
2073 static int32_t timeSeconds = -1;
2074 #if defined(USE_ADC) && defined(USE_GPS)
2075 static timeUs_t updatedTimestamp = 0;
2076 timeUs_t currentTimeUs = micros();
2077 if (cmpTimeUs(currentTimeUs, updatedTimestamp) >= MS2US(1000)) {
2078 #ifdef USE_WIND_ESTIMATOR
2079 timeSeconds = calculateRemainingFlightTimeBeforeRTH(osdConfig()->estimations_wind_compensation);
2080 #else
2081 timeSeconds = calculateRemainingFlightTimeBeforeRTH(false);
2082 #endif
2083 updatedTimestamp = currentTimeUs;
2085 #endif
2086 if ((!ARMING_FLAG(ARMED)) || (timeSeconds == -1)) {
2087 buff[0] = SYM_FLIGHT_MINS_REMAINING;
2088 strcpy(buff + 1, "--:--");
2089 #if defined(USE_ADC) && defined(USE_GPS)
2090 updatedTimestamp = 0;
2091 #endif
2092 } else if (timeSeconds == -2) {
2093 // Wind is too strong to come back with cruise throttle
2094 buff[0] = SYM_FLIGHT_MINS_REMAINING;
2095 buff[1] = buff[2] = buff[4] = buff[5] = SYM_WIND_HORIZONTAL;
2096 buff[3] = ':';
2097 buff[6] = '\0';
2098 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2099 } else {
2100 osdFormatTime(buff, timeSeconds, SYM_FLIGHT_MINS_REMAINING, SYM_FLIGHT_HOURS_REMAINING);
2101 if (timeSeconds == 0)
2102 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2105 break;
2107 case OSD_REMAINING_DISTANCE_BEFORE_RTH:;
2108 static int32_t distanceMeters = -1;
2109 #if defined(USE_ADC) && defined(USE_GPS)
2110 static timeUs_t updatedTimestamp = 0;
2111 timeUs_t currentTimeUs = micros();
2112 if (cmpTimeUs(currentTimeUs, updatedTimestamp) >= MS2US(1000)) {
2113 #ifdef USE_WIND_ESTIMATOR
2114 distanceMeters = calculateRemainingDistanceBeforeRTH(osdConfig()->estimations_wind_compensation);
2115 #else
2116 distanceMeters = calculateRemainingDistanceBeforeRTH(false);
2117 #endif
2118 updatedTimestamp = currentTimeUs;
2120 #endif
2121 //buff[0] = SYM_TRIP_DIST;
2122 displayWriteChar(osdDisplayPort, elemPosX, elemPosY, SYM_FLIGHT_DIST_REMAINING);
2123 if ((!ARMING_FLAG(ARMED)) || (distanceMeters == -1)) {
2124 buff[4] = SYM_BLANK;
2125 buff[5] = '\0';
2126 strcpy(buff + 1, "---");
2127 } else if (distanceMeters == -2) {
2128 // Wind is too strong to come back with cruise throttle
2129 buff[1] = buff[2] = buff[3] = SYM_WIND_HORIZONTAL;
2130 switch ((osd_unit_e)osdConfig()->units){
2131 case OSD_UNIT_UK:
2132 FALLTHROUGH;
2133 case OSD_UNIT_IMPERIAL:
2134 buff[4] = SYM_DIST_MI;
2135 break;
2136 case OSD_UNIT_METRIC_MPH:
2137 FALLTHROUGH;
2138 case OSD_UNIT_METRIC:
2139 buff[4] = SYM_DIST_KM;
2140 break;
2141 case OSD_UNIT_GA:
2142 buff[4] = SYM_DIST_NM;
2143 break;
2145 buff[5] = '\0';
2146 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2147 } else {
2148 osdFormatDistanceSymbol(buff + 1, distanceMeters * 100, 0);
2149 if (distanceMeters == 0)
2150 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2152 break;
2154 case OSD_FLYMODE:
2156 char *p = "ACRO";
2158 if (FLIGHT_MODE(FAILSAFE_MODE))
2159 p = "!FS!";
2160 else if (FLIGHT_MODE(MANUAL_MODE))
2161 p = "MANU";
2162 else if (FLIGHT_MODE(TURTLE_MODE))
2163 p = "TURT";
2164 else if (FLIGHT_MODE(NAV_RTH_MODE))
2165 p = isWaypointMissionRTHActive() ? "WRTH" : "RTH ";
2166 else if (FLIGHT_MODE(NAV_POSHOLD_MODE) && STATE(AIRPLANE))
2167 p = "LOTR";
2168 else if (FLIGHT_MODE(NAV_POSHOLD_MODE))
2169 p = "HOLD";
2170 else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE) && FLIGHT_MODE(NAV_ALTHOLD_MODE))
2171 p = "CRUZ";
2172 else if (FLIGHT_MODE(NAV_COURSE_HOLD_MODE))
2173 p = "CRSH";
2174 else if (FLIGHT_MODE(NAV_WP_MODE))
2175 p = " WP ";
2176 else if (FLIGHT_MODE(NAV_ALTHOLD_MODE) && navigationRequiresAngleMode()) {
2177 // If navigationRequiresAngleMode() returns false when ALTHOLD is active,
2178 // it means it can be combined with ANGLE, HORIZON, ACRO, etc...
2179 // and its display is handled by OSD_MESSAGES rather than OSD_FLYMODE.
2180 p = " AH ";
2182 else if (FLIGHT_MODE(ANGLE_MODE))
2183 p = "ANGL";
2184 else if (FLIGHT_MODE(HORIZON_MODE))
2185 p = "HOR ";
2187 displayWrite(osdDisplayPort, elemPosX, elemPosY, p);
2188 return true;
2191 case OSD_CRAFT_NAME:
2192 osdFormatCraftName(buff);
2193 break;
2195 case OSD_PILOT_NAME:
2196 osdFormatPilotName(buff);
2197 break;
2199 case OSD_THROTTLE_POS:
2201 osdFormatThrottlePosition(buff, false, &elemAttr);
2202 break;
2205 case OSD_VTX_CHANNEL:
2207 vtxDeviceOsdInfo_t osdInfo;
2208 vtxCommonGetOsdInfo(vtxCommonDevice(), &osdInfo);
2210 tfp_sprintf(buff, "CH:%c%s:", osdInfo.bandLetter, osdInfo.channelName);
2211 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2213 tfp_sprintf(buff, "%c", osdInfo.powerIndexLetter);
2214 if (isAdjustmentFunctionSelected(ADJUSTMENT_VTX_POWER_LEVEL)) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2215 displayWriteWithAttr(osdDisplayPort, elemPosX + 6, elemPosY, buff, elemAttr);
2216 return true;
2218 break;
2220 case OSD_VTX_POWER:
2222 vtxDeviceOsdInfo_t osdInfo;
2223 vtxCommonGetOsdInfo(vtxCommonDevice(), &osdInfo);
2225 tfp_sprintf(buff, "%c", SYM_VTX_POWER);
2226 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2228 tfp_sprintf(buff, "%c", osdInfo.powerIndexLetter);
2229 if (isAdjustmentFunctionSelected(ADJUSTMENT_VTX_POWER_LEVEL)) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2230 displayWriteWithAttr(osdDisplayPort, elemPosX+1, elemPosY, buff, elemAttr);
2231 return true;
2234 #if defined(USE_SERIALRX_CRSF)
2235 case OSD_CRSF_RSSI_DBM:
2237 int16_t rssi = rxLinkStatistics.uplinkRSSI;
2238 buff[0] = (rxLinkStatistics.activeAntenna == 0) ? SYM_RSSI : SYM_2RSS; // Separate symbols for each antenna
2239 if (rssi <= -100) {
2240 tfp_sprintf(buff + 1, "%4d%c", rssi, SYM_DBM);
2241 } else {
2242 tfp_sprintf(buff + 1, "%3d%c%c", rssi, SYM_DBM, ' ');
2244 if (!failsafeIsReceivingRxData()){
2245 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2246 } else if (osdConfig()->rssi_dbm_alarm && rssi < osdConfig()->rssi_dbm_alarm) {
2247 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2249 break;
2251 case OSD_CRSF_LQ:
2253 buff[0] = SYM_LQ;
2254 int16_t statsLQ = rxLinkStatistics.uplinkLQ;
2255 int16_t scaledLQ = scaleRange(constrain(statsLQ, 0, 100), 0, 100, 170, 300);
2256 switch (osdConfig()->crsf_lq_format) {
2257 case OSD_CRSF_LQ_TYPE1:
2258 if (!failsafeIsReceivingRxData()) {
2259 tfp_sprintf(buff+1, "%3d", 0);
2260 } else {
2261 tfp_sprintf(buff+1, "%3d", rxLinkStatistics.uplinkLQ);
2263 break;
2264 case OSD_CRSF_LQ_TYPE2:
2265 if (!failsafeIsReceivingRxData()) {
2266 tfp_sprintf(buff+1, "%s:%3d", " ", 0);
2267 } else {
2268 tfp_sprintf(buff+1, "%d:%3d", rxLinkStatistics.rfMode, rxLinkStatistics.uplinkLQ);
2270 break;
2271 case OSD_CRSF_LQ_TYPE3:
2272 if (!failsafeIsReceivingRxData()) {
2273 tfp_sprintf(buff+1, "%3d", 0);
2274 } else {
2275 tfp_sprintf(buff+1, "%3d", rxLinkStatistics.rfMode >= 2 ? scaledLQ : rxLinkStatistics.uplinkLQ);
2277 break;
2279 if (!failsafeIsReceivingRxData()) {
2280 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2281 } else if (rxLinkStatistics.uplinkLQ < osdConfig()->link_quality_alarm) {
2282 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2284 break;
2287 case OSD_CRSF_SNR_DB:
2289 static pt1Filter_t snrFilterState;
2290 static timeMs_t snrUpdated = 0;
2291 int8_t snrFiltered = pt1FilterApply4(&snrFilterState, rxLinkStatistics.uplinkSNR, 0.5f, MS2S(millis() - snrUpdated));
2292 snrUpdated = millis();
2294 const char* showsnr = "-20";
2295 const char* hidesnr = " ";
2296 if (snrFiltered > osdConfig()->snr_alarm) {
2297 if (cmsInMenu) {
2298 buff[0] = SYM_SNR;
2299 tfp_sprintf(buff + 1, "%s%c", showsnr, SYM_DB);
2300 } else {
2301 buff[0] = SYM_BLANK;
2302 tfp_sprintf(buff + 1, "%s%c", hidesnr, SYM_BLANK);
2304 } else if (snrFiltered <= osdConfig()->snr_alarm) {
2305 buff[0] = SYM_SNR;
2306 if (snrFiltered <= -10) {
2307 tfp_sprintf(buff + 1, "%3d%c", snrFiltered, SYM_DB);
2308 } else {
2309 tfp_sprintf(buff + 1, "%2d%c%c", snrFiltered, SYM_DB, ' ');
2312 break;
2315 case OSD_CRSF_TX_POWER:
2317 if (!failsafeIsReceivingRxData())
2318 tfp_sprintf(buff, "%s%c", " ", SYM_BLANK);
2319 else
2320 tfp_sprintf(buff, "%4d%c", rxLinkStatistics.uplinkTXPower, SYM_MW);
2321 break;
2323 #endif
2325 case OSD_CROSSHAIRS: // Hud is a sub-element of the crosshair
2327 osdCrosshairPosition(&elemPosX, &elemPosY);
2328 osdHudDrawCrosshair(osdGetDisplayPortCanvas(), elemPosX, elemPosY);
2330 if (osdConfig()->hud_homing && STATE(GPS_FIX) && STATE(GPS_FIX_HOME) && isImuHeadingValid()) {
2331 osdHudDrawHoming(elemPosX, elemPosY);
2334 if (STATE(GPS_FIX) && isImuHeadingValid()) {
2336 if (osdConfig()->hud_homepoint || osdConfig()->hud_radar_disp > 0 || osdConfig()->hud_wp_disp > 0) {
2337 osdHudClear();
2340 // -------- POI : Home point
2342 if (osdConfig()->hud_homepoint) { // Display the home point (H)
2343 osdHudDrawPoi(GPS_distanceToHome, GPS_directionToHome, -osdGetAltitude() / 100, 0, SYM_HOME, 0 , 0);
2346 // -------- POI : Nearby aircrafts from ESP32 radar
2348 if (osdConfig()->hud_radar_disp > 0) { // Display the POI from the radar
2349 for (uint8_t i = 0; i < osdConfig()->hud_radar_disp; i++) {
2350 if (radar_pois[i].gps.lat != 0 && radar_pois[i].gps.lon != 0 && radar_pois[i].state < 2) { // state 2 means POI has been lost and must be skipped
2351 fpVector3_t poi;
2352 geoConvertGeodeticToLocal(&poi, &posControl.gpsOrigin, &radar_pois[i].gps, GEO_ALT_RELATIVE);
2353 radar_pois[i].distance = calculateDistanceToDestination(&poi) / 100; // In meters
2355 if (radar_pois[i].distance >= osdConfig()->hud_radar_range_min && radar_pois[i].distance <= osdConfig()->hud_radar_range_max) {
2356 radar_pois[i].direction = calculateBearingToDestination(&poi) / 100; // In °
2357 radar_pois[i].altitude = (radar_pois[i].gps.alt - osdGetAltitudeMsl()) / 100;
2358 osdHudDrawPoi(radar_pois[i].distance, osdGetHeadingAngle(radar_pois[i].direction), radar_pois[i].altitude, 1, 65 + i, radar_pois[i].heading, radar_pois[i].lq);
2364 // -------- POI : Next waypoints from navigation
2366 if (osdConfig()->hud_wp_disp > 0 && posControl.waypointListValid && posControl.waypointCount > 0) { // Display the next waypoints
2367 gpsLocation_t wp2;
2368 int j;
2370 for (int i = osdConfig()->hud_wp_disp - 1; i >= 0 ; i--) { // Display in reverse order so the next WP is always written on top
2371 j = posControl.activeWaypointIndex + i;
2372 if (j > posControl.startWpIndex + posControl.waypointCount - 1) { // limit to max WP index for mission
2373 break;
2375 if (posControl.waypointList[j].lat != 0 && posControl.waypointList[j].lon != 0) {
2376 wp2.lat = posControl.waypointList[j].lat;
2377 wp2.lon = posControl.waypointList[j].lon;
2378 wp2.alt = posControl.waypointList[j].alt;
2379 fpVector3_t poi;
2380 geoConvertGeodeticToLocal(&poi, &posControl.gpsOrigin, &wp2, waypointMissionAltConvMode(posControl.waypointList[j].p3));
2381 int32_t altConvModeAltitude = waypointMissionAltConvMode(posControl.waypointList[j].p3) == GEO_ALT_ABSOLUTE ? osdGetAltitudeMsl() : osdGetAltitude();
2382 j = getGeoWaypointNumber(j);
2383 while (j > 9) j -= 10; // Only the last digit displayed if WP>=10, no room for more (48 = ascii 0)
2384 osdHudDrawPoi(calculateDistanceToDestination(&poi) / 100, osdGetHeadingAngle(calculateBearingToDestination(&poi) / 100), (posControl.waypointList[j].alt - altConvModeAltitude)/ 100, 2, SYM_WAYPOINT, 48 + j, i);
2390 return true;
2391 break;
2393 case OSD_ATTITUDE_ROLL:
2394 buff[0] = SYM_ROLL_LEVEL;
2395 if (ABS(attitude.values.roll) >= 1)
2396 buff[0] += (attitude.values.roll < 0 ? -1 : 1);
2397 osdFormatCentiNumber(buff + 1, DECIDEGREES_TO_CENTIDEGREES(ABS(attitude.values.roll)), 0, 1, 0, 3);
2398 break;
2400 case OSD_ATTITUDE_PITCH:
2401 if (ABS(attitude.values.pitch) < 1)
2402 buff[0] = 'P';
2403 else if (attitude.values.pitch > 0)
2404 buff[0] = SYM_PITCH_DOWN;
2405 else if (attitude.values.pitch < 0)
2406 buff[0] = SYM_PITCH_UP;
2407 osdFormatCentiNumber(buff + 1, DECIDEGREES_TO_CENTIDEGREES(ABS(attitude.values.pitch)), 0, 1, 0, 3);
2408 break;
2410 case OSD_ARTIFICIAL_HORIZON:
2412 float rollAngle = DECIDEGREES_TO_RADIANS(attitude.values.roll);
2413 float pitchAngle = DECIDEGREES_TO_RADIANS(attitude.values.pitch);
2415 pitchAngle -= osdConfig()->ahi_camera_uptilt_comp ? DEGREES_TO_RADIANS(osdConfig()->camera_uptilt) : 0;
2416 pitchAngle += DEGREES_TO_RADIANS(getFixedWingLevelTrim());
2417 if (osdConfig()->ahi_reverse_roll) {
2418 rollAngle = -rollAngle;
2420 osdDrawArtificialHorizon(osdDisplayPort, osdGetDisplayPortCanvas(),
2421 OSD_DRAW_POINT_GRID(elemPosX, elemPosY), rollAngle, pitchAngle);
2422 osdDrawSingleElement(OSD_HORIZON_SIDEBARS);
2423 osdDrawSingleElement(OSD_CROSSHAIRS);
2425 return true;
2428 case OSD_HORIZON_SIDEBARS:
2430 osdDrawSidebars(osdDisplayPort, osdGetDisplayPortCanvas());
2431 return true;
2434 #if defined(USE_BARO) || defined(USE_GPS)
2435 case OSD_VARIO:
2437 float zvel = getEstimatedActualVelocity(Z);
2438 osdDrawVario(osdDisplayPort, osdGetDisplayPortCanvas(), OSD_DRAW_POINT_GRID(elemPosX, elemPosY), zvel);
2439 return true;
2442 case OSD_VARIO_NUM:
2444 int16_t value = getEstimatedActualVelocity(Z);
2445 char sym;
2446 switch ((osd_unit_e)osdConfig()->units) {
2447 case OSD_UNIT_UK:
2448 FALLTHROUGH;
2449 case OSD_UNIT_IMPERIAL:
2450 // Convert to centifeet/s
2451 value = CENTIMETERS_TO_CENTIFEET(value);
2452 sym = SYM_FTS;
2453 break;
2454 case OSD_UNIT_GA:
2455 // Convert to centi-100feet/min
2456 value = CENTIMETERS_TO_FEET(value * 60);
2457 sym = SYM_100FTM;
2458 break;
2459 default:
2460 case OSD_UNIT_METRIC_MPH:
2461 FALLTHROUGH;
2462 case OSD_UNIT_METRIC:
2463 // Already in cm/s
2464 sym = SYM_MS;
2465 break;
2468 osdFormatCentiNumber(buff, value, 0, 1, 0, 3);
2469 buff[3] = sym;
2470 buff[4] = '\0';
2471 break;
2473 case OSD_CLIMB_EFFICIENCY:
2475 // amperage is in centi amps (10mA), vertical speed is in cms/s. We want
2476 // Ah/dist only to show when vertical speed > 1m/s.
2477 static pt1Filter_t veFilterState;
2478 static timeUs_t vEfficiencyUpdated = 0;
2479 int32_t value = 0;
2480 timeUs_t currentTimeUs = micros();
2481 timeDelta_t vEfficiencyTimeDelta = cmpTimeUs(currentTimeUs, vEfficiencyUpdated);
2482 if (getEstimatedActualVelocity(Z) > 0) {
2483 if (vEfficiencyTimeDelta >= EFFICIENCY_UPDATE_INTERVAL) {
2484 // Centiamps (kept for osdFormatCentiNumber) / m/s - Will appear as A / m/s in OSD
2485 value = pt1FilterApply4(&veFilterState, (float)getAmperage() / (getEstimatedActualVelocity(Z) / 100.0f), 1, US2S(vEfficiencyTimeDelta));
2487 vEfficiencyUpdated = currentTimeUs;
2488 } else {
2489 value = veFilterState.state;
2492 bool efficiencyValid = (value > 0) && (getEstimatedActualVelocity(Z) > 100);
2493 switch (osdConfig()->units) {
2494 case OSD_UNIT_UK:
2495 FALLTHROUGH;
2496 case OSD_UNIT_GA:
2497 FALLTHROUGH;
2498 case OSD_UNIT_IMPERIAL:
2499 // mAh/foot
2500 if (efficiencyValid) {
2501 osdFormatCentiNumber(buff, (value * METERS_PER_FOOT), 1, 2, 2, 3);
2502 tfp_sprintf(buff, "%s%c%c", buff, SYM_AH_V_FT_0, SYM_AH_V_FT_1);
2503 } else {
2504 buff[0] = buff[1] = buff[2] = '-';
2505 buff[3] = SYM_AH_V_FT_0;
2506 buff[4] = SYM_AH_V_FT_1;
2507 buff[5] = '\0';
2509 break;
2510 case OSD_UNIT_METRIC_MPH:
2511 FALLTHROUGH;
2512 case OSD_UNIT_METRIC:
2513 // mAh/metre
2514 if (efficiencyValid) {
2515 osdFormatCentiNumber(buff, value, 1, 2, 2, 3);
2516 tfp_sprintf(buff, "%s%c%c", buff, SYM_AH_V_M_0, SYM_AH_V_M_1);
2517 } else {
2518 buff[0] = buff[1] = buff[2] = '-';
2519 buff[3] = SYM_AH_V_M_0;
2520 buff[4] = SYM_AH_V_M_1;
2521 buff[5] = '\0';
2523 break;
2525 break;
2527 case OSD_GLIDE_TIME_REMAINING:
2529 uint16_t glideTime = osdGetRemainingGlideTime();
2530 buff[0] = SYM_GLIDE_MINS;
2531 if (glideTime > 0) {
2532 // Maximum value we can show in minutes is 99 minutes and 59 seconds. It is extremely unlikely that glide
2533 // time will be longer than 99 minutes. If it is, it will show 99:^^
2534 if (glideTime > (99 * 60) + 59) {
2535 tfp_sprintf(buff + 1, "%02d:", (int)(glideTime / 60));
2536 buff[4] = SYM_DIRECTION;
2537 buff[5] = SYM_DIRECTION;
2538 } else {
2539 tfp_sprintf(buff + 1, "%02d:%02d", (int)(glideTime / 60), (int)(glideTime % 60));
2541 } else {
2542 tfp_sprintf(buff + 1, "%s", "--:--");
2544 buff[6] = '\0';
2545 break;
2547 case OSD_GLIDE_RANGE:
2549 uint16_t glideSeconds = osdGetRemainingGlideTime();
2550 buff[0] = SYM_GLIDE_DIST;
2551 if (glideSeconds > 0) {
2552 uint32_t glideRangeCM = glideSeconds * gpsSol.groundSpeed;
2553 osdFormatDistanceSymbol(buff + 1, glideRangeCM, 0);
2554 } else {
2555 tfp_sprintf(buff + 1, "%s%c", "---", SYM_BLANK);
2556 buff[5] = '\0';
2558 break;
2560 #endif
2562 case OSD_SWITCH_INDICATOR_0:
2563 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator0_name, rxGetChannelValue(osdConfig()->osd_switch_indicator0_channel - 1), buff);
2564 break;
2566 case OSD_SWITCH_INDICATOR_1:
2567 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator1_name, rxGetChannelValue(osdConfig()->osd_switch_indicator1_channel - 1), buff);
2568 break;
2570 case OSD_SWITCH_INDICATOR_2:
2571 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator2_name, rxGetChannelValue(osdConfig()->osd_switch_indicator2_channel - 1), buff);
2572 break;
2574 case OSD_SWITCH_INDICATOR_3:
2575 osdDisplaySwitchIndicator(osdConfig()->osd_switch_indicator3_name, rxGetChannelValue(osdConfig()->osd_switch_indicator3_channel - 1), buff);
2576 break;
2578 case OSD_PAN_SERVO_CENTRED:
2580 int16_t panOffset = osdGetPanServoOffset();
2581 const timeMs_t panServoTimeNow = millis();
2582 static timeMs_t panServoTimeOffCentre = 0;
2584 if (panOffset < 0) {
2585 if (osdConfig()->pan_servo_offcentre_warning != 0 && panOffset >= -osdConfig()->pan_servo_offcentre_warning) {
2586 if (panServoTimeOffCentre == 0) {
2587 panServoTimeOffCentre = panServoTimeNow;
2588 } else if (panServoTimeNow >= (panServoTimeOffCentre + 10000 )) {
2589 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2591 } else {
2592 panServoTimeOffCentre = 0;
2595 if (osdConfig()->pan_servo_indicator_show_degrees) {
2596 tfp_sprintf(buff, "%3d%c", -panOffset, SYM_DEGREES);
2597 displayWriteWithAttr(osdDisplayPort, elemPosX+1, elemPosY, buff, elemAttr);
2599 displayWriteCharWithAttr(osdDisplayPort, elemPosX, elemPosY, SYM_SERVO_PAN_IS_OFFSET_R, elemAttr);
2600 } else if (panOffset > 0) {
2601 if (osdConfig()->pan_servo_offcentre_warning != 0 && panOffset <= osdConfig()->pan_servo_offcentre_warning) {
2602 if (panServoTimeOffCentre == 0) {
2603 panServoTimeOffCentre = panServoTimeNow;
2604 } else if (panServoTimeNow >= (panServoTimeOffCentre + 10000 )) {
2605 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2607 } else {
2608 panServoTimeOffCentre = 0;
2611 if (osdConfig()->pan_servo_indicator_show_degrees) {
2612 tfp_sprintf(buff, "%3d%c", panOffset, SYM_DEGREES);
2613 displayWriteWithAttr(osdDisplayPort, elemPosX+1, elemPosY, buff, elemAttr);
2615 displayWriteCharWithAttr(osdDisplayPort, elemPosX, elemPosY, SYM_SERVO_PAN_IS_OFFSET_L, elemAttr);
2616 } else {
2617 panServoTimeOffCentre = 0;
2619 if (osdConfig()->pan_servo_indicator_show_degrees) {
2620 tfp_sprintf(buff, "%3d%c", panOffset, SYM_DEGREES);
2621 displayWriteWithAttr(osdDisplayPort, elemPosX+1, elemPosY, buff, elemAttr);
2623 displayWriteChar(osdDisplayPort, elemPosX, elemPosY, SYM_SERVO_PAN_IS_CENTRED);
2626 return true;
2628 break;
2630 case OSD_ACTIVE_PROFILE:
2631 tfp_sprintf(buff, "%c%u", SYM_PROFILE, (getConfigProfile() + 1));
2632 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2633 break;
2635 case OSD_ROLL_PIDS:
2636 osdDisplayFlightPIDValues(elemPosX, elemPosY, "ROL", PID_ROLL, ADJUSTMENT_ROLL_P, ADJUSTMENT_ROLL_I, ADJUSTMENT_ROLL_D, ADJUSTMENT_ROLL_FF);
2637 return true;
2639 case OSD_PITCH_PIDS:
2640 osdDisplayFlightPIDValues(elemPosX, elemPosY, "PIT", PID_PITCH, ADJUSTMENT_PITCH_P, ADJUSTMENT_PITCH_I, ADJUSTMENT_PITCH_D, ADJUSTMENT_PITCH_FF);
2641 return true;
2643 case OSD_YAW_PIDS:
2644 osdDisplayFlightPIDValues(elemPosX, elemPosY, "YAW", PID_YAW, ADJUSTMENT_YAW_P, ADJUSTMENT_YAW_I, ADJUSTMENT_YAW_D, ADJUSTMENT_YAW_FF);
2645 return true;
2647 case OSD_LEVEL_PIDS:
2648 osdDisplayNavPIDValues(elemPosX, elemPosY, "LEV", PID_LEVEL, ADJUSTMENT_LEVEL_P, ADJUSTMENT_LEVEL_I, ADJUSTMENT_LEVEL_D);
2649 return true;
2651 case OSD_POS_XY_PIDS:
2652 osdDisplayNavPIDValues(elemPosX, elemPosY, "PXY", PID_POS_XY, ADJUSTMENT_POS_XY_P, ADJUSTMENT_POS_XY_I, ADJUSTMENT_POS_XY_D);
2653 return true;
2655 case OSD_POS_Z_PIDS:
2656 osdDisplayNavPIDValues(elemPosX, elemPosY, "PZ", PID_POS_Z, ADJUSTMENT_POS_Z_P, ADJUSTMENT_POS_Z_I, ADJUSTMENT_POS_Z_D);
2657 return true;
2659 case OSD_VEL_XY_PIDS:
2660 osdDisplayNavPIDValues(elemPosX, elemPosY, "VXY", PID_VEL_XY, ADJUSTMENT_VEL_XY_P, ADJUSTMENT_VEL_XY_I, ADJUSTMENT_VEL_XY_D);
2661 return true;
2663 case OSD_VEL_Z_PIDS:
2664 osdDisplayNavPIDValues(elemPosX, elemPosY, "VZ", PID_VEL_Z, ADJUSTMENT_VEL_Z_P, ADJUSTMENT_VEL_Z_I, ADJUSTMENT_VEL_Z_D);
2665 return true;
2667 case OSD_HEADING_P:
2668 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "HP", 0, pidBank()->pid[PID_HEADING].P, 3, 0, ADJUSTMENT_HEADING_P);
2669 return true;
2671 case OSD_BOARD_ALIGN_ROLL:
2672 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "AR", 0, DECIDEGREES_TO_DEGREES((float)boardAlignment()->rollDeciDegrees), 4, 1, ADJUSTMENT_ROLL_BOARD_ALIGNMENT);
2673 return true;
2675 case OSD_BOARD_ALIGN_PITCH:
2676 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "AP", 0, DECIDEGREES_TO_DEGREES((float)boardAlignment()->pitchDeciDegrees), 4, 1, ADJUSTMENT_PITCH_BOARD_ALIGNMENT);
2677 return true;
2679 case OSD_RC_EXPO:
2680 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "EXP", 0, currentControlRateProfile->stabilized.rcExpo8, 3, 0, ADJUSTMENT_RC_EXPO);
2681 return true;
2683 case OSD_RC_YAW_EXPO:
2684 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "YEX", 0, currentControlRateProfile->stabilized.rcYawExpo8, 3, 0, ADJUSTMENT_RC_YAW_EXPO);
2685 return true;
2687 case OSD_THROTTLE_EXPO:
2688 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "TEX", 0, currentControlRateProfile->throttle.rcExpo8, 3, 0, ADJUSTMENT_THROTTLE_EXPO);
2689 return true;
2691 case OSD_PITCH_RATE:
2692 displayWrite(osdDisplayPort, elemPosX, elemPosY, "SPR");
2694 elemAttr = TEXT_ATTRIBUTES_NONE;
2695 tfp_sprintf(buff, "%3d", currentControlRateProfile->stabilized.rates[FD_PITCH]);
2696 if (isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_RATE))
2697 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2698 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2699 return true;
2701 case OSD_ROLL_RATE:
2702 displayWrite(osdDisplayPort, elemPosX, elemPosY, "SRR");
2704 elemAttr = TEXT_ATTRIBUTES_NONE;
2705 tfp_sprintf(buff, "%3d", currentControlRateProfile->stabilized.rates[FD_ROLL]);
2706 if (isAdjustmentFunctionSelected(ADJUSTMENT_ROLL_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_PITCH_ROLL_RATE))
2707 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2708 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2709 return true;
2711 case OSD_YAW_RATE:
2712 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "SYR", 0, currentControlRateProfile->stabilized.rates[FD_YAW], 3, 0, ADJUSTMENT_YAW_RATE);
2713 return true;
2715 case OSD_MANUAL_RC_EXPO:
2716 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "MEX", 0, currentControlRateProfile->manual.rcExpo8, 3, 0, ADJUSTMENT_MANUAL_RC_EXPO);
2717 return true;
2719 case OSD_MANUAL_RC_YAW_EXPO:
2720 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "MYX", 0, currentControlRateProfile->manual.rcYawExpo8, 3, 0, ADJUSTMENT_MANUAL_RC_YAW_EXPO);
2721 return true;
2723 case OSD_MANUAL_PITCH_RATE:
2724 displayWrite(osdDisplayPort, elemPosX, elemPosY, "MPR");
2726 elemAttr = TEXT_ATTRIBUTES_NONE;
2727 tfp_sprintf(buff, "%3d", currentControlRateProfile->manual.rates[FD_PITCH]);
2728 if (isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_PITCH_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_PITCH_ROLL_RATE))
2729 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2730 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2731 return true;
2733 case OSD_MANUAL_ROLL_RATE:
2734 displayWrite(osdDisplayPort, elemPosX, elemPosY, "MRR");
2736 elemAttr = TEXT_ATTRIBUTES_NONE;
2737 tfp_sprintf(buff, "%3d", currentControlRateProfile->manual.rates[FD_ROLL]);
2738 if (isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_ROLL_RATE) || isAdjustmentFunctionSelected(ADJUSTMENT_MANUAL_PITCH_ROLL_RATE))
2739 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2740 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY, buff, elemAttr);
2741 return true;
2743 case OSD_MANUAL_YAW_RATE:
2744 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "MYR", 0, currentControlRateProfile->stabilized.rates[FD_YAW], 3, 0, ADJUSTMENT_YAW_RATE);
2745 return true;
2747 case OSD_NAV_FW_CRUISE_THR:
2748 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "CRZ", 0, currentBatteryProfile->nav.fw.cruise_throttle, 4, 0, ADJUSTMENT_NAV_FW_CRUISE_THR);
2749 return true;
2751 case OSD_NAV_FW_PITCH2THR:
2752 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "P2T", 0, currentBatteryProfile->nav.fw.pitch_to_throttle, 3, 0, ADJUSTMENT_NAV_FW_PITCH2THR);
2753 return true;
2755 case OSD_FW_MIN_THROTTLE_DOWN_PITCH_ANGLE:
2756 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "0TP", 0, (float)navConfig()->fw.minThrottleDownPitchAngle / 10, 3, 1, ADJUSTMENT_FW_MIN_THROTTLE_DOWN_PITCH_ANGLE);
2757 return true;
2759 case OSD_FW_ALT_PID_OUTPUTS:
2761 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2762 osdFormatPidControllerOutput(buff, "PZO", &nav_pids->fw_alt, 10, true); // display requested pitch degrees
2763 break;
2766 case OSD_FW_POS_PID_OUTPUTS:
2768 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers(); // display requested roll degrees
2769 osdFormatPidControllerOutput(buff, "PXYO", &nav_pids->fw_nav, 1, true);
2770 break;
2773 case OSD_MC_VEL_Z_PID_OUTPUTS:
2775 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2776 osdFormatPidControllerOutput(buff, "VZO", &nav_pids->vel[Z], 100, false); // display throttle adjustment µs
2777 break;
2780 case OSD_MC_VEL_X_PID_OUTPUTS:
2782 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2783 osdFormatPidControllerOutput(buff, "VXO", &nav_pids->vel[X], 100, false); // display requested acceleration cm/s^2
2784 break;
2787 case OSD_MC_VEL_Y_PID_OUTPUTS:
2789 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2790 osdFormatPidControllerOutput(buff, "VYO", &nav_pids->vel[Y], 100, false); // display requested acceleration cm/s^2
2791 break;
2794 case OSD_MC_POS_XYZ_P_OUTPUTS:
2796 const navigationPIDControllers_t *nav_pids = getNavigationPIDControllers();
2797 strcpy(buff, "POSO ");
2798 // display requested velocity cm/s
2799 tfp_sprintf(buff + 5, "%4d", (int)lrintf(nav_pids->pos[X].output_constrained * 100));
2800 buff[9] = ' ';
2801 tfp_sprintf(buff + 10, "%4d", (int)lrintf(nav_pids->pos[Y].output_constrained * 100));
2802 buff[14] = ' ';
2803 tfp_sprintf(buff + 15, "%4d", (int)lrintf(nav_pids->pos[Z].output_constrained * 100));
2804 buff[19] = '\0';
2805 break;
2808 case OSD_POWER:
2810 bool kiloWatt = osdFormatCentiNumber(buff, getPower(), 1000, 2, 2, 3);
2811 buff[3] = kiloWatt ? SYM_KILOWATT : SYM_WATT;
2812 buff[4] = '\0';
2814 uint8_t current_alarm = osdConfig()->current_alarm;
2815 if ((current_alarm > 0) && ((getAmperage() / 100.0f) > current_alarm)) {
2816 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2818 break;
2821 case OSD_AIR_SPEED:
2823 #ifdef USE_PITOT
2824 buff[0] = SYM_AIR;
2826 if (pitotIsHealthy())
2828 const float airspeed_estimate = getAirspeedEstimate();
2829 osdFormatVelocityStr(buff + 1, airspeed_estimate, false, false);
2830 if ((osdConfig()->airspeed_alarm_min != 0 && airspeed_estimate < osdConfig()->airspeed_alarm_min) ||
2831 (osdConfig()->airspeed_alarm_max != 0 && airspeed_estimate > osdConfig()->airspeed_alarm_max)) {
2832 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2835 else
2837 strcpy(buff + 1, " X!");
2838 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
2840 #else
2841 return false;
2842 #endif
2843 break;
2846 case OSD_AIR_MAX_SPEED:
2848 #ifdef USE_PITOT
2849 buff[0] = SYM_MAX;
2850 buff[1] = SYM_AIR;
2851 osdFormatVelocityStr(buff + 2, stats.max_air_speed, false, false);
2852 #else
2853 return false;
2854 #endif
2855 break;
2858 case OSD_RTC_TIME:
2860 // RTC not configured will show 00:00
2861 dateTime_t dateTime;
2862 rtcGetDateTimeLocal(&dateTime);
2863 buff[0] = SYM_CLOCK;
2864 tfp_sprintf(buff + 1, "%02u:%02u:%02u", dateTime.hours, dateTime.minutes, dateTime.seconds);
2865 break;
2868 case OSD_MESSAGES:
2870 elemAttr = osdGetSystemMessage(buff, OSD_MESSAGE_LENGTH, true);
2871 break;
2874 case OSD_VERSION:
2876 tfp_sprintf(buff, "INAV %s", FC_VERSION_STRING);
2877 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
2878 break;
2881 case OSD_MAIN_BATT_CELL_VOLTAGE:
2883 uint8_t base_digits = 3U;
2884 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it
2885 if(isBfCompatibleVideoSystem(osdConfig())) {
2886 base_digits = 4U; // Add extra digit to account for decimal point taking an extra character space
2888 #endif
2889 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatteryRawAverageCellVoltage(), base_digits, 2);
2890 return true;
2893 case OSD_MAIN_BATT_SAG_COMPENSATED_CELL_VOLTAGE:
2895 uint8_t base_digits = 3U;
2896 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it
2897 if(isBfCompatibleVideoSystem(osdConfig())) {
2898 base_digits = 4U; // Add extra digit to account for decimal point taking an extra character space
2900 #endif
2901 osdDisplayBatteryVoltage(elemPosX, elemPosY, getBatterySagCompensatedAverageCellVoltage(), base_digits, 2);
2902 return true;
2905 case OSD_SCALED_THROTTLE_POS:
2907 osdFormatThrottlePosition(buff, true, &elemAttr);
2908 break;
2911 case OSD_HEADING:
2913 buff[0] = SYM_HEADING;
2914 if (osdIsHeadingValid()) {
2915 int16_t h = DECIDEGREES_TO_DEGREES(osdGetHeading());
2916 if (h < 0) {
2917 h += 360;
2919 tfp_sprintf(&buff[1], "%3d", h);
2920 } else {
2921 buff[1] = buff[2] = buff[3] = '-';
2923 buff[4] = SYM_DEGREES;
2924 buff[5] = '\0';
2925 break;
2928 case OSD_HEADING_GRAPH:
2930 if (osdIsHeadingValid()) {
2931 osdDrawHeadingGraph(osdDisplayPort, osdGetDisplayPortCanvas(), OSD_DRAW_POINT_GRID(elemPosX, elemPosY), osdGetHeading());
2932 return true;
2933 } else {
2934 buff[0] = buff[2] = buff[4] = buff[6] = buff[8] = SYM_HEADING_LINE;
2935 buff[1] = buff[3] = buff[5] = buff[7] = SYM_HEADING_DIVIDED_LINE;
2936 buff[OSD_HEADING_GRAPH_WIDTH] = '\0';
2938 break;
2941 case OSD_EFFICIENCY_MAH_PER_KM:
2943 // amperage is in centi amps, speed is in cms/s. We want
2944 // mah/km. Only show when ground speed > 1m/s.
2945 static pt1Filter_t eFilterState;
2946 static timeUs_t efficiencyUpdated = 0;
2947 int32_t value = 0;
2948 bool moreThanAh = false;
2949 timeUs_t currentTimeUs = micros();
2950 timeDelta_t efficiencyTimeDelta = cmpTimeUs(currentTimeUs, efficiencyUpdated);
2951 uint8_t digits = 3U;
2952 #ifndef DISABLE_MSP_BF_COMPAT // IF BFCOMPAT is not supported, there's no need to check for it and change the values
2953 if (isBfCompatibleVideoSystem(osdConfig())) {
2954 // Increase number of digits so values above 99 don't get scaled by osdFormatCentiNumber
2955 digits = 4U;
2957 #endif
2958 if (STATE(GPS_FIX) && gpsSol.groundSpeed > 0) {
2959 if (efficiencyTimeDelta >= EFFICIENCY_UPDATE_INTERVAL) {
2960 value = pt1FilterApply4(&eFilterState, ((float)getAmperage() / gpsSol.groundSpeed) / 0.0036f,
2961 1, US2S(efficiencyTimeDelta));
2963 efficiencyUpdated = currentTimeUs;
2964 } else {
2965 value = eFilterState.state;
2968 bool efficiencyValid = (value > 0) && (gpsSol.groundSpeed > 100);
2969 switch (osdConfig()->units) {
2970 case OSD_UNIT_UK:
2971 FALLTHROUGH;
2972 case OSD_UNIT_IMPERIAL:
2973 moreThanAh = osdFormatCentiNumber(buff, value * METERS_PER_MILE / 10, 1000, 0, 2, digits);
2974 if (!moreThanAh) {
2975 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_MI_0, SYM_MAH_MI_1);
2976 } else {
2977 tfp_sprintf(buff, "%s%c", buff, SYM_AH_MI);
2979 if (!efficiencyValid) {
2980 buff[0] = buff[1] = buff[2] = buff[3] = '-';
2981 buff[digits] = SYM_MAH_MI_0; // This will overwrite the "-" at buff[3] if not in BFCOMPAT mode
2982 buff[digits + 1] = SYM_MAH_MI_1;
2983 buff[digits + 2] = '\0';
2985 break;
2986 case OSD_UNIT_GA:
2987 moreThanAh = osdFormatCentiNumber(buff, value * METERS_PER_NAUTICALMILE / 10, 1000, 0, 2, digits);
2988 if (!moreThanAh) {
2989 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_NM_0, SYM_MAH_NM_1);
2990 } else {
2991 tfp_sprintf(buff, "%s%c", buff, SYM_AH_NM);
2993 if (!efficiencyValid) {
2994 buff[0] = buff[1] = buff[2] = buff[3] = '-';
2995 buff[digits] = SYM_MAH_NM_0;
2996 buff[digits + 1] = SYM_MAH_NM_1;
2997 buff[digits + 2] = '\0';
2999 break;
3000 case OSD_UNIT_METRIC_MPH:
3001 FALLTHROUGH;
3002 case OSD_UNIT_METRIC:
3003 moreThanAh = osdFormatCentiNumber(buff, value * 100, 1000, 0, 2, digits);
3004 if (!moreThanAh) {
3005 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_KM_0, SYM_MAH_KM_1);
3006 } else {
3007 tfp_sprintf(buff, "%s%c", buff, SYM_AH_KM);
3009 if (!efficiencyValid) {
3010 buff[0] = buff[1] = buff[2] = buff[3] = '-';
3011 buff[digits] = SYM_MAH_KM_0;
3012 buff[digits + 1] = SYM_MAH_KM_1;
3013 buff[digits + 2] = '\0';
3015 break;
3017 break;
3020 case OSD_EFFICIENCY_WH_PER_KM:
3022 // amperage is in centi amps, speed is in cms/s. We want
3023 // mWh/km. Only show when ground speed > 1m/s.
3024 static pt1Filter_t eFilterState;
3025 static timeUs_t efficiencyUpdated = 0;
3026 int32_t value = 0;
3027 timeUs_t currentTimeUs = micros();
3028 timeDelta_t efficiencyTimeDelta = cmpTimeUs(currentTimeUs, efficiencyUpdated);
3029 if (STATE(GPS_FIX) && gpsSol.groundSpeed > 0) {
3030 if (efficiencyTimeDelta >= EFFICIENCY_UPDATE_INTERVAL) {
3031 value = pt1FilterApply4(&eFilterState, ((float)getPower() / gpsSol.groundSpeed) / 0.0036f,
3032 1, US2S(efficiencyTimeDelta));
3034 efficiencyUpdated = currentTimeUs;
3035 } else {
3036 value = eFilterState.state;
3039 bool efficiencyValid = (value > 0) && (gpsSol.groundSpeed > 100);
3040 switch (osdConfig()->units) {
3041 case OSD_UNIT_UK:
3042 FALLTHROUGH;
3043 case OSD_UNIT_IMPERIAL:
3044 osdFormatCentiNumber(buff, value * METERS_PER_MILE / 10000, 0, 2, 0, 3);
3045 buff[3] = SYM_WH_MI;
3046 break;
3047 case OSD_UNIT_GA:
3048 osdFormatCentiNumber(buff, value * METERS_PER_NAUTICALMILE / 10000, 0, 2, 0, 3);
3049 buff[3] = SYM_WH_NM;
3050 break;
3051 case OSD_UNIT_METRIC_MPH:
3052 FALLTHROUGH;
3053 case OSD_UNIT_METRIC:
3054 osdFormatCentiNumber(buff, value / 10, 0, 2, 0, 3);
3055 buff[3] = SYM_WH_KM;
3056 break;
3058 buff[4] = '\0';
3059 if (!efficiencyValid) {
3060 buff[0] = buff[1] = buff[2] = '-';
3062 break;
3065 case OSD_GFORCE:
3067 buff[0] = SYM_GFORCE;
3068 osdFormatCentiNumber(buff + 1, GForce, 0, 2, 0, 3);
3069 if (GForce > osdConfig()->gforce_alarm * 100) {
3070 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3072 break;
3075 case OSD_GFORCE_X:
3076 case OSD_GFORCE_Y:
3077 case OSD_GFORCE_Z:
3079 float GForceValue = GForceAxis[item - OSD_GFORCE_X];
3080 buff[0] = SYM_GFORCE_X + item - OSD_GFORCE_X;
3081 osdFormatCentiNumber(buff + 1, GForceValue, 0, 2, 0, 4);
3082 if ((GForceValue < osdConfig()->gforce_axis_alarm_min * 100) || (GForceValue > osdConfig()->gforce_axis_alarm_max * 100)) {
3083 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3085 break;
3087 case OSD_DEBUG:
3090 * Longest representable string is -2147483648 does not fit in the screen.
3091 * Only 7 digits for negative and 8 digits for positive values allowed
3093 for (uint8_t bufferIndex = 0; bufferIndex < DEBUG32_VALUE_COUNT; ++elemPosY, bufferIndex += 2) {
3094 tfp_sprintf(
3095 buff,
3096 "[%u]=%8ld [%u]=%8ld",
3097 bufferIndex,
3098 (long)constrain(debug[bufferIndex], -9999999, 99999999),
3099 bufferIndex+1,
3100 (long)constrain(debug[bufferIndex+1], -9999999, 99999999)
3102 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
3104 break;
3107 case OSD_IMU_TEMPERATURE:
3109 int16_t temperature;
3110 const bool valid = getIMUTemperature(&temperature);
3111 osdDisplayTemperature(elemPosX, elemPosY, SYM_IMU_TEMP, NULL, valid, temperature, osdConfig()->imu_temp_alarm_min, osdConfig()->imu_temp_alarm_max);
3112 return true;
3115 case OSD_BARO_TEMPERATURE:
3117 int16_t temperature;
3118 const bool valid = getBaroTemperature(&temperature);
3119 osdDisplayTemperature(elemPosX, elemPosY, SYM_BARO_TEMP, NULL, valid, temperature, osdConfig()->imu_temp_alarm_min, osdConfig()->imu_temp_alarm_max);
3120 return true;
3123 #ifdef USE_TEMPERATURE_SENSOR
3124 case OSD_TEMP_SENSOR_0_TEMPERATURE:
3125 case OSD_TEMP_SENSOR_1_TEMPERATURE:
3126 case OSD_TEMP_SENSOR_2_TEMPERATURE:
3127 case OSD_TEMP_SENSOR_3_TEMPERATURE:
3128 case OSD_TEMP_SENSOR_4_TEMPERATURE:
3129 case OSD_TEMP_SENSOR_5_TEMPERATURE:
3130 case OSD_TEMP_SENSOR_6_TEMPERATURE:
3131 case OSD_TEMP_SENSOR_7_TEMPERATURE:
3133 osdDisplayTemperatureSensor(elemPosX, elemPosY, item - OSD_TEMP_SENSOR_0_TEMPERATURE);
3134 return true;
3136 #endif /* ifdef USE_TEMPERATURE_SENSOR */
3138 case OSD_WIND_SPEED_HORIZONTAL:
3139 #ifdef USE_WIND_ESTIMATOR
3141 bool valid = isEstimatedWindSpeedValid();
3142 float horizontalWindSpeed;
3143 uint16_t angle;
3144 horizontalWindSpeed = getEstimatedHorizontalWindSpeed(&angle);
3145 int16_t windDirection = osdGetHeadingAngle( CENTIDEGREES_TO_DEGREES((int)angle) - DECIDEGREES_TO_DEGREES(attitude.values.yaw) + 22);
3146 buff[0] = SYM_WIND_HORIZONTAL;
3147 buff[1] = SYM_DIRECTION + (windDirection*2 / 90);
3148 osdFormatWindSpeedStr(buff + 2, horizontalWindSpeed, valid);
3149 break;
3151 #else
3152 return false;
3153 #endif
3155 case OSD_WIND_SPEED_VERTICAL:
3156 #ifdef USE_WIND_ESTIMATOR
3158 buff[0] = SYM_WIND_VERTICAL;
3159 buff[1] = SYM_BLANK;
3160 bool valid = isEstimatedWindSpeedValid();
3161 float verticalWindSpeed;
3162 verticalWindSpeed = -getEstimatedWindSpeed(Z); //from NED to NEU
3163 if (verticalWindSpeed < 0) {
3164 buff[1] = SYM_AH_DIRECTION_DOWN;
3165 verticalWindSpeed = -verticalWindSpeed;
3166 } else {
3167 buff[1] = SYM_AH_DIRECTION_UP;
3169 osdFormatWindSpeedStr(buff + 2, verticalWindSpeed, valid);
3170 break;
3172 #else
3173 return false;
3174 #endif
3176 case OSD_PLUS_CODE:
3178 STATIC_ASSERT(GPS_DEGREES_DIVIDER == OLC_DEG_MULTIPLIER, invalid_olc_deg_multiplier);
3179 int digits = osdConfig()->plus_code_digits;
3180 int digitsRemoved = osdConfig()->plus_code_short * 2;
3181 if (STATE(GPS_FIX)) {
3182 olc_encode(gpsSol.llh.lat, gpsSol.llh.lon, digits, buff, sizeof(buff));
3183 } else {
3184 // +codes with > 8 digits have a + at the 9th digit
3185 // and we only support 10 and up.
3186 memset(buff, '-', digits + 1);
3187 buff[8] = '+';
3188 buff[digits + 1] = '\0';
3190 // Optionally trim digits from the left
3191 memmove(buff, buff+digitsRemoved, strlen(buff) + digitsRemoved);
3192 buff[digits + 1 - digitsRemoved] = '\0';
3193 break;
3196 case OSD_AZIMUTH:
3199 buff[0] = SYM_AZIMUTH;
3200 if (osdIsHeadingValid()) {
3201 int16_t h = GPS_directionToHome;
3202 if (h < 0) {
3203 h += 360;
3205 if (h >= 180)
3206 h = h - 180;
3207 else
3208 h = h + 180;
3210 tfp_sprintf(&buff[1], "%3d", h);
3211 } else {
3212 buff[1] = buff[2] = buff[3] = '-';
3214 buff[4] = SYM_DEGREES;
3215 buff[5] = '\0';
3216 break;
3219 case OSD_MAP_SCALE:
3221 float scaleToUnit;
3222 int scaleUnitDivisor;
3223 char symUnscaled;
3224 char symScaled;
3225 int maxDecimals;
3227 switch (osdConfig()->units) {
3228 case OSD_UNIT_UK:
3229 FALLTHROUGH;
3230 case OSD_UNIT_IMPERIAL:
3231 scaleToUnit = 100 / 1609.3440f; // scale to 0.01mi for osdFormatCentiNumber()
3232 scaleUnitDivisor = 0;
3233 symUnscaled = SYM_MI;
3234 symScaled = SYM_MI;
3235 maxDecimals = 2;
3236 break;
3237 case OSD_UNIT_GA:
3238 scaleToUnit = 100 / 1852.0010f; // scale to 0.01mi for osdFormatCentiNumber()
3239 scaleUnitDivisor = 0;
3240 symUnscaled = SYM_NM;
3241 symScaled = SYM_NM;
3242 maxDecimals = 2;
3243 break;
3244 default:
3245 case OSD_UNIT_METRIC_MPH:
3246 FALLTHROUGH;
3247 case OSD_UNIT_METRIC:
3248 scaleToUnit = 100; // scale to cm for osdFormatCentiNumber()
3249 scaleUnitDivisor = 1000; // Convert to km when scale gets bigger than 999m
3250 symUnscaled = SYM_M;
3251 symScaled = SYM_KM;
3252 maxDecimals = 0;
3253 break;
3255 buff[0] = SYM_SCALE;
3256 if (osdMapData.scale > 0) {
3257 bool scaled = osdFormatCentiNumber(&buff[1], osdMapData.scale * scaleToUnit, scaleUnitDivisor, maxDecimals, 2, 3);
3258 buff[4] = scaled ? symScaled : symUnscaled;
3259 // Make sure this is cleared if the map stops being drawn
3260 osdMapData.scale = 0;
3261 } else {
3262 memset(&buff[1], '-', 4);
3264 buff[5] = '\0';
3265 break;
3267 case OSD_MAP_REFERENCE:
3269 char referenceSymbol;
3270 if (osdMapData.referenceSymbol) {
3271 referenceSymbol = osdMapData.referenceSymbol;
3272 // Make sure this is cleared if the map stops being drawn
3273 osdMapData.referenceSymbol = 0;
3274 } else {
3275 referenceSymbol = '-';
3277 displayWriteChar(osdDisplayPort, elemPosX, elemPosY, SYM_DIRECTION);
3278 displayWriteChar(osdDisplayPort, elemPosX, elemPosY + 1, referenceSymbol);
3279 return true;
3282 case OSD_GVAR_0:
3284 osdFormatGVar(buff, 0);
3285 break;
3287 case OSD_GVAR_1:
3289 osdFormatGVar(buff, 1);
3290 break;
3292 case OSD_GVAR_2:
3294 osdFormatGVar(buff, 2);
3295 break;
3297 case OSD_GVAR_3:
3299 osdFormatGVar(buff, 3);
3300 break;
3303 #if defined(USE_RX_MSP) && defined(USE_MSP_RC_OVERRIDE)
3304 case OSD_RC_SOURCE:
3306 const char *source_text = IS_RC_MODE_ACTIVE(BOXMSPRCOVERRIDE) && !mspOverrideIsInFailsafe() ? "MSP" : "STD";
3307 if (IS_RC_MODE_ACTIVE(BOXMSPRCOVERRIDE) && mspOverrideIsInFailsafe()) TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3308 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, source_text, elemAttr);
3309 return true;
3311 #endif
3313 #if defined(USE_ESC_SENSOR)
3314 case OSD_ESC_RPM:
3316 escSensorData_t * escSensor = escSensorGetData();
3317 if (escSensor && escSensor->dataAge <= ESC_DATA_MAX_AGE) {
3318 osdFormatRpm(buff, escSensor->rpm);
3320 else {
3321 osdFormatRpm(buff, 0);
3323 break;
3325 case OSD_ESC_TEMPERATURE:
3327 escSensorData_t * escSensor = escSensorGetData();
3328 bool escTemperatureValid = escSensor && escSensor->dataAge <= ESC_DATA_MAX_AGE;
3329 osdDisplayTemperature(elemPosX, elemPosY, SYM_ESC_TEMP, NULL, escTemperatureValid, (escSensor->temperature)*10, osdConfig()->esc_temp_alarm_min, osdConfig()->esc_temp_alarm_max);
3330 return true;
3332 #endif
3333 case OSD_TPA:
3335 char buff[4];
3336 textAttributes_t attr;
3338 displayWrite(osdDisplayPort, elemPosX, elemPosY, "TPA");
3339 attr = TEXT_ATTRIBUTES_NONE;
3340 tfp_sprintf(buff, "%3d", currentControlRateProfile->throttle.dynPID);
3341 if (isAdjustmentFunctionSelected(ADJUSTMENT_TPA)) {
3342 TEXT_ATTRIBUTES_ADD_BLINK(attr);
3344 displayWriteWithAttr(osdDisplayPort, elemPosX + 5, elemPosY, buff, attr);
3346 displayWrite(osdDisplayPort, elemPosX, elemPosY + 1, "BP");
3347 attr = TEXT_ATTRIBUTES_NONE;
3348 tfp_sprintf(buff, "%4d", currentControlRateProfile->throttle.pa_breakpoint);
3349 if (isAdjustmentFunctionSelected(ADJUSTMENT_TPA_BREAKPOINT)) {
3350 TEXT_ATTRIBUTES_ADD_BLINK(attr);
3352 displayWriteWithAttr(osdDisplayPort, elemPosX + 4, elemPosY + 1, buff, attr);
3354 return true;
3356 case OSD_TPA_TIME_CONSTANT:
3358 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "TPA TC", 0, currentControlRateProfile->throttle.fixedWingTauMs, 4, 0, ADJUSTMENT_FW_TPA_TIME_CONSTANT);
3359 return true;
3361 case OSD_FW_LEVEL_TRIM:
3363 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "LEVEL", 0, getFixedWingLevelTrim(), 3, 1, ADJUSTMENT_FW_LEVEL_TRIM);
3364 return true;
3367 case OSD_NAV_FW_CONTROL_SMOOTHNESS:
3369 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "CTL S", 0, navConfig()->fw.control_smoothness, 1, 0, ADJUSTMENT_NAV_FW_CONTROL_SMOOTHNESS);
3370 return true;
3372 #ifdef USE_MULTI_MISSION
3373 case OSD_NAV_WP_MULTI_MISSION_INDEX:
3375 osdDisplayAdjustableDecimalValue(elemPosX, elemPosY, "WP NO", 0, navConfig()->general.waypoint_multi_mission_index, 1, 0, ADJUSTMENT_NAV_WP_MULTI_MISSION_INDEX);
3376 return true;
3378 #endif
3379 case OSD_MISSION:
3381 if (IS_RC_MODE_ACTIVE(BOXPLANWPMISSION)) {
3382 char buf[5];
3383 switch (posControl.wpMissionPlannerStatus) {
3384 case WP_PLAN_WAIT:
3385 strcpy(buf, "WAIT");
3386 break;
3387 case WP_PLAN_SAVE:
3388 strcpy(buf, "SAVE");
3389 break;
3390 case WP_PLAN_OK:
3391 strcpy(buf, " OK ");
3392 break;
3393 case WP_PLAN_FULL:
3394 strcpy(buf, "FULL");
3396 tfp_sprintf(buff, "%s>%2uWP", buf, posControl.wpPlannerActiveWPIndex);
3397 } else if (posControl.wpPlannerActiveWPIndex){
3398 tfp_sprintf(buff, "PLAN>%2uWP", posControl.waypointCount); // mission planner mision active
3400 #ifdef USE_MULTI_MISSION
3401 else {
3402 if (ARMING_FLAG(ARMED) && !(IS_RC_MODE_ACTIVE(BOXCHANGEMISSION) && posControl.multiMissionCount > 1)){
3403 // Limit field size when Armed, only show selected mission
3404 tfp_sprintf(buff, "M%u ", posControl.loadedMultiMissionIndex);
3405 } else if (posControl.multiMissionCount) {
3406 if (navConfig()->general.waypoint_multi_mission_index != posControl.loadedMultiMissionIndex) {
3407 tfp_sprintf(buff, "M%u/%u>LOAD", navConfig()->general.waypoint_multi_mission_index, posControl.multiMissionCount);
3408 } else {
3409 if (posControl.waypointListValid && posControl.waypointCount > 0) {
3410 tfp_sprintf(buff, "M%u/%u>%2uWP", posControl.loadedMultiMissionIndex, posControl.multiMissionCount, posControl.waypointCount);
3411 } else {
3412 tfp_sprintf(buff, "M0/%u> 0WP", posControl.multiMissionCount);
3415 } else { // no multi mission loaded - show active WP count from other source
3416 tfp_sprintf(buff, "WP CNT>%2u", posControl.waypointCount);
3419 #endif
3420 displayWrite(osdDisplayPort, elemPosX, elemPosY, buff);
3421 return true;
3424 #ifdef USE_POWER_LIMITS
3425 case OSD_PLIMIT_REMAINING_BURST_TIME:
3426 osdFormatCentiNumber(buff, powerLimiterGetRemainingBurstTime() * 100, 0, 1, 0, 3);
3427 buff[3] = 'S';
3428 buff[4] = '\0';
3429 break;
3431 case OSD_PLIMIT_ACTIVE_CURRENT_LIMIT:
3432 if (currentBatteryProfile->powerLimits.continuousCurrent) {
3433 osdFormatCentiNumber(buff, powerLimiterGetActiveCurrentLimit(), 0, 2, 0, 3);
3434 buff[3] = SYM_AMP;
3435 buff[4] = '\0';
3437 if (powerLimiterIsLimitingCurrent()) {
3438 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3441 break;
3443 #ifdef USE_ADC
3444 case OSD_PLIMIT_ACTIVE_POWER_LIMIT:
3446 if (currentBatteryProfile->powerLimits.continuousPower) {
3447 bool kiloWatt = osdFormatCentiNumber(buff, powerLimiterGetActivePowerLimit(), 1000, 2, 2, 3);
3448 buff[3] = kiloWatt ? SYM_KILOWATT : SYM_WATT;
3449 buff[4] = '\0';
3451 if (powerLimiterIsLimitingPower()) {
3452 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
3455 break;
3457 #endif // USE_ADC
3458 #endif // USE_POWER_LIMITS
3460 default:
3461 return false;
3464 displayWriteWithAttr(osdDisplayPort, elemPosX, elemPosY, buff, elemAttr);
3465 return true;
3468 uint8_t osdIncElementIndex(uint8_t elementIndex)
3470 ++elementIndex;
3472 if (elementIndex == OSD_ARTIFICIAL_HORIZON) { // always drawn last so skip
3473 elementIndex++;
3476 #ifndef USE_TEMPERATURE_SENSOR
3477 if (elementIndex == OSD_TEMP_SENSOR_0_TEMPERATURE) {
3478 elementIndex = OSD_ALTITUDE_MSL;
3480 #endif
3482 if (!(feature(FEATURE_VBAT) && feature(FEATURE_CURRENT_METER))) {
3483 if (elementIndex == OSD_POWER) {
3484 elementIndex = OSD_GPS_LON;
3486 if (elementIndex == OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE) {
3487 elementIndex = OSD_LEVEL_PIDS;
3489 #ifdef USE_POWER_LIMITS
3490 if (elementIndex == OSD_PLIMIT_REMAINING_BURST_TIME) {
3491 elementIndex = OSD_GLIDESLOPE;
3493 #endif
3496 #ifndef USE_POWER_LIMITS
3497 if (elementIndex == OSD_PLIMIT_REMAINING_BURST_TIME) {
3498 elementIndex = OSD_GLIDESLOPE;
3500 #endif
3502 if (!feature(FEATURE_CURRENT_METER)) {
3503 if (elementIndex == OSD_CURRENT_DRAW) {
3504 elementIndex = OSD_GPS_SPEED;
3506 if (elementIndex == OSD_EFFICIENCY_MAH_PER_KM) {
3507 elementIndex = OSD_BATTERY_REMAINING_PERCENT;
3509 if (elementIndex == OSD_EFFICIENCY_WH_PER_KM) {
3510 elementIndex = OSD_TRIP_DIST;
3512 if (elementIndex == OSD_REMAINING_FLIGHT_TIME_BEFORE_RTH) {
3513 elementIndex = OSD_HOME_HEADING_ERROR;
3515 if (elementIndex == OSD_CLIMB_EFFICIENCY) {
3516 elementIndex = OSD_NAV_WP_MULTI_MISSION_INDEX;
3520 if (!STATE(ESC_SENSOR_ENABLED)) {
3521 if (elementIndex == OSD_ESC_RPM) {
3522 elementIndex = OSD_AZIMUTH;
3526 if (!feature(FEATURE_GPS)) {
3527 if (elementIndex == OSD_GPS_HDOP || elementIndex == OSD_TRIP_DIST || elementIndex == OSD_3D_SPEED || elementIndex == OSD_MISSION ||
3528 elementIndex == OSD_AZIMUTH || elementIndex == OSD_BATTERY_REMAINING_CAPACITY || elementIndex == OSD_EFFICIENCY_MAH_PER_KM) {
3529 elementIndex++;
3531 if (elementIndex == OSD_HEADING_GRAPH && !sensors(SENSOR_MAG)) {
3532 elementIndex = feature(FEATURE_CURRENT_METER) ? OSD_WH_DRAWN : OSD_BATTERY_REMAINING_PERCENT;
3534 if (elementIndex == OSD_EFFICIENCY_WH_PER_KM) {
3535 elementIndex = OSD_ATTITUDE_PITCH;
3537 if (elementIndex == OSD_GPS_SPEED) {
3538 elementIndex = OSD_ALTITUDE;
3540 if (elementIndex == OSD_GPS_LON) {
3541 elementIndex = sensors(SENSOR_MAG) ? OSD_HEADING : OSD_VARIO;
3543 if (elementIndex == OSD_MAP_NORTH) {
3544 elementIndex = feature(FEATURE_CURRENT_METER) ? OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE : OSD_LEVEL_PIDS;
3546 if (elementIndex == OSD_PLUS_CODE) {
3547 elementIndex = OSD_GFORCE;
3549 if (elementIndex == OSD_GLIDESLOPE) {
3550 elementIndex = OSD_AIR_MAX_SPEED;
3552 if (elementIndex == OSD_GLIDE_RANGE) {
3553 elementIndex = feature(FEATURE_CURRENT_METER) ? OSD_CLIMB_EFFICIENCY : OSD_ITEM_COUNT;
3555 if (elementIndex == OSD_NAV_WP_MULTI_MISSION_INDEX) {
3556 elementIndex = OSD_ITEM_COUNT;
3560 if (!sensors(SENSOR_ACC)) {
3561 if (elementIndex == OSD_CROSSHAIRS) {
3562 elementIndex = OSD_ONTIME;
3564 if (elementIndex == OSD_GFORCE) {
3565 elementIndex = OSD_RC_SOURCE;
3569 if (elementIndex == OSD_ITEM_COUNT) {
3570 elementIndex = 0;
3572 return elementIndex;
3575 void osdDrawNextElement(void)
3577 static uint8_t elementIndex = 0;
3578 // Flag for end of loop, also prevents infinite loop when no elements are enabled
3579 uint8_t index = elementIndex;
3580 do {
3581 elementIndex = osdIncElementIndex(elementIndex);
3582 } while (!osdDrawSingleElement(elementIndex) && index != elementIndex);
3584 // Draw artificial horizon + tracking telemtry last
3585 osdDrawSingleElement(OSD_ARTIFICIAL_HORIZON);
3586 if (osdConfig()->telemetry>0){
3587 osdDisplayTelemetry();
3591 PG_RESET_TEMPLATE(osdConfig_t, osdConfig,
3592 .rssi_alarm = SETTING_OSD_RSSI_ALARM_DEFAULT,
3593 .time_alarm = SETTING_OSD_TIME_ALARM_DEFAULT,
3594 .alt_alarm = SETTING_OSD_ALT_ALARM_DEFAULT,
3595 .dist_alarm = SETTING_OSD_DIST_ALARM_DEFAULT,
3596 .neg_alt_alarm = SETTING_OSD_NEG_ALT_ALARM_DEFAULT,
3597 .current_alarm = SETTING_OSD_CURRENT_ALARM_DEFAULT,
3598 .imu_temp_alarm_min = SETTING_OSD_IMU_TEMP_ALARM_MIN_DEFAULT,
3599 .imu_temp_alarm_max = SETTING_OSD_IMU_TEMP_ALARM_MAX_DEFAULT,
3600 .esc_temp_alarm_min = SETTING_OSD_ESC_TEMP_ALARM_MIN_DEFAULT,
3601 .esc_temp_alarm_max = SETTING_OSD_ESC_TEMP_ALARM_MAX_DEFAULT,
3602 .gforce_alarm = SETTING_OSD_GFORCE_ALARM_DEFAULT,
3603 .gforce_axis_alarm_min = SETTING_OSD_GFORCE_AXIS_ALARM_MIN_DEFAULT,
3604 .gforce_axis_alarm_max = SETTING_OSD_GFORCE_AXIS_ALARM_MAX_DEFAULT,
3605 #ifdef USE_BARO
3606 .baro_temp_alarm_min = SETTING_OSD_BARO_TEMP_ALARM_MIN_DEFAULT,
3607 .baro_temp_alarm_max = SETTING_OSD_BARO_TEMP_ALARM_MAX_DEFAULT,
3608 #endif
3609 #ifdef USE_SERIALRX_CRSF
3610 .snr_alarm = SETTING_OSD_SNR_ALARM_DEFAULT,
3611 .crsf_lq_format = SETTING_OSD_CRSF_LQ_FORMAT_DEFAULT,
3612 .link_quality_alarm = SETTING_OSD_LINK_QUALITY_ALARM_DEFAULT,
3613 .rssi_dbm_alarm = SETTING_OSD_RSSI_DBM_ALARM_DEFAULT,
3614 .rssi_dbm_max = SETTING_OSD_RSSI_DBM_MAX_DEFAULT,
3615 .rssi_dbm_min = SETTING_OSD_RSSI_DBM_MIN_DEFAULT,
3616 #endif
3617 #ifdef USE_TEMPERATURE_SENSOR
3618 .temp_label_align = SETTING_OSD_TEMP_LABEL_ALIGN_DEFAULT,
3619 #endif
3620 #ifdef USE_PITOT
3621 .airspeed_alarm_min = SETTING_OSD_AIRSPEED_ALARM_MIN_DEFAULT,
3622 .airspeed_alarm_max = SETTING_OSD_AIRSPEED_ALARM_MAX_DEFAULT,
3623 #endif
3625 .video_system = SETTING_OSD_VIDEO_SYSTEM_DEFAULT,
3626 .row_shiftdown = SETTING_OSD_ROW_SHIFTDOWN_DEFAULT,
3627 .msp_displayport_fullframe_interval = SETTING_OSD_MSP_DISPLAYPORT_FULLFRAME_INTERVAL_DEFAULT,
3629 .ahi_reverse_roll = SETTING_OSD_AHI_REVERSE_ROLL_DEFAULT,
3630 .ahi_max_pitch = SETTING_OSD_AHI_MAX_PITCH_DEFAULT,
3631 .crosshairs_style = SETTING_OSD_CROSSHAIRS_STYLE_DEFAULT,
3632 .horizon_offset = SETTING_OSD_HORIZON_OFFSET_DEFAULT,
3633 .camera_uptilt = SETTING_OSD_CAMERA_UPTILT_DEFAULT,
3634 .ahi_camera_uptilt_comp = SETTING_OSD_AHI_CAMERA_UPTILT_COMP_DEFAULT,
3635 .camera_fov_h = SETTING_OSD_CAMERA_FOV_H_DEFAULT,
3636 .camera_fov_v = SETTING_OSD_CAMERA_FOV_V_DEFAULT,
3637 .hud_margin_h = SETTING_OSD_HUD_MARGIN_H_DEFAULT,
3638 .hud_margin_v = SETTING_OSD_HUD_MARGIN_V_DEFAULT,
3639 .hud_homing = SETTING_OSD_HUD_HOMING_DEFAULT,
3640 .hud_homepoint = SETTING_OSD_HUD_HOMEPOINT_DEFAULT,
3641 .hud_radar_disp = SETTING_OSD_HUD_RADAR_DISP_DEFAULT,
3642 .hud_radar_range_min = SETTING_OSD_HUD_RADAR_RANGE_MIN_DEFAULT,
3643 .hud_radar_range_max = SETTING_OSD_HUD_RADAR_RANGE_MAX_DEFAULT,
3644 .hud_radar_alt_difference_display_time = SETTING_OSD_HUD_RADAR_ALT_DIFFERENCE_DISPLAY_TIME_DEFAULT,
3645 .hud_radar_distance_display_time = SETTING_OSD_HUD_RADAR_DISTANCE_DISPLAY_TIME_DEFAULT,
3646 .hud_wp_disp = SETTING_OSD_HUD_WP_DISP_DEFAULT,
3647 .left_sidebar_scroll = SETTING_OSD_LEFT_SIDEBAR_SCROLL_DEFAULT,
3648 .right_sidebar_scroll = SETTING_OSD_RIGHT_SIDEBAR_SCROLL_DEFAULT,
3649 .sidebar_scroll_arrows = SETTING_OSD_SIDEBAR_SCROLL_ARROWS_DEFAULT,
3650 .sidebar_horizontal_offset = SETTING_OSD_SIDEBAR_HORIZONTAL_OFFSET_DEFAULT,
3651 .left_sidebar_scroll_step = SETTING_OSD_LEFT_SIDEBAR_SCROLL_STEP_DEFAULT,
3652 .right_sidebar_scroll_step = SETTING_OSD_RIGHT_SIDEBAR_SCROLL_STEP_DEFAULT,
3653 .sidebar_height = SETTING_OSD_SIDEBAR_HEIGHT_DEFAULT,
3654 .ahi_pitch_interval = SETTING_OSD_AHI_PITCH_INTERVAL_DEFAULT,
3655 .osd_home_position_arm_screen = SETTING_OSD_HOME_POSITION_ARM_SCREEN_DEFAULT,
3656 .pan_servo_index = SETTING_OSD_PAN_SERVO_INDEX_DEFAULT,
3657 .pan_servo_pwm2centideg = SETTING_OSD_PAN_SERVO_PWM2CENTIDEG_DEFAULT,
3658 .pan_servo_offcentre_warning = SETTING_OSD_PAN_SERVO_OFFCENTRE_WARNING_DEFAULT,
3659 .pan_servo_indicator_show_degrees = SETTING_OSD_PAN_SERVO_INDICATOR_SHOW_DEGREES_DEFAULT,
3660 .esc_rpm_precision = SETTING_OSD_ESC_RPM_PRECISION_DEFAULT,
3661 .mAh_used_precision = SETTING_OSD_MAH_USED_PRECISION_DEFAULT,
3662 .osd_switch_indicator0_name = SETTING_OSD_SWITCH_INDICATOR_ZERO_NAME_DEFAULT,
3663 .osd_switch_indicator0_channel = SETTING_OSD_SWITCH_INDICATOR_ZERO_CHANNEL_DEFAULT,
3664 .osd_switch_indicator1_name = SETTING_OSD_SWITCH_INDICATOR_ONE_NAME_DEFAULT,
3665 .osd_switch_indicator1_channel = SETTING_OSD_SWITCH_INDICATOR_ONE_CHANNEL_DEFAULT,
3666 .osd_switch_indicator2_name = SETTING_OSD_SWITCH_INDICATOR_TWO_NAME_DEFAULT,
3667 .osd_switch_indicator2_channel = SETTING_OSD_SWITCH_INDICATOR_TWO_CHANNEL_DEFAULT,
3668 .osd_switch_indicator3_name = SETTING_OSD_SWITCH_INDICATOR_THREE_NAME_DEFAULT,
3669 .osd_switch_indicator3_channel = SETTING_OSD_SWITCH_INDICATOR_THREE_CHANNEL_DEFAULT,
3670 .osd_switch_indicators_align_left = SETTING_OSD_SWITCH_INDICATORS_ALIGN_LEFT_DEFAULT,
3671 .system_msg_display_time = SETTING_OSD_SYSTEM_MSG_DISPLAY_TIME_DEFAULT,
3672 .units = SETTING_OSD_UNITS_DEFAULT,
3673 .main_voltage_decimals = SETTING_OSD_MAIN_VOLTAGE_DECIMALS_DEFAULT,
3675 #ifdef USE_WIND_ESTIMATOR
3676 .estimations_wind_compensation = SETTING_OSD_ESTIMATIONS_WIND_COMPENSATION_DEFAULT,
3677 #endif
3679 .coordinate_digits = SETTING_OSD_COORDINATE_DIGITS_DEFAULT,
3681 .osd_failsafe_switch_layout = SETTING_OSD_FAILSAFE_SWITCH_LAYOUT_DEFAULT,
3683 .plus_code_digits = SETTING_OSD_PLUS_CODE_DIGITS_DEFAULT,
3684 .plus_code_short = SETTING_OSD_PLUS_CODE_SHORT_DEFAULT,
3686 .ahi_width = SETTING_OSD_AHI_WIDTH_DEFAULT,
3687 .ahi_height = SETTING_OSD_AHI_HEIGHT_DEFAULT,
3688 .ahi_vertical_offset = SETTING_OSD_AHI_VERTICAL_OFFSET_DEFAULT,
3689 .ahi_bordered = SETTING_OSD_AHI_BORDERED_DEFAULT,
3690 .ahi_style = SETTING_OSD_AHI_STYLE_DEFAULT,
3692 .force_grid = SETTING_OSD_FORCE_GRID_DEFAULT,
3694 .stats_energy_unit = SETTING_OSD_STATS_ENERGY_UNIT_DEFAULT,
3695 .stats_min_voltage_unit = SETTING_OSD_STATS_MIN_VOLTAGE_UNIT_DEFAULT,
3696 .stats_page_auto_swap_time = SETTING_OSD_STATS_PAGE_AUTO_SWAP_TIME_DEFAULT
3699 void pgResetFn_osdLayoutsConfig(osdLayoutsConfig_t *osdLayoutsConfig)
3701 osdLayoutsConfig->item_pos[0][OSD_ALTITUDE] = OSD_POS(1, 0) | OSD_VISIBLE_FLAG;
3702 osdLayoutsConfig->item_pos[0][OSD_MAIN_BATT_VOLTAGE] = OSD_POS(12, 0) | OSD_VISIBLE_FLAG;
3703 osdLayoutsConfig->item_pos[0][OSD_SAG_COMPENSATED_MAIN_BATT_VOLTAGE] = OSD_POS(12, 1);
3705 osdLayoutsConfig->item_pos[0][OSD_RSSI_VALUE] = OSD_POS(23, 0) | OSD_VISIBLE_FLAG;
3706 //line 2
3707 osdLayoutsConfig->item_pos[0][OSD_HOME_DIST] = OSD_POS(1, 1);
3708 osdLayoutsConfig->item_pos[0][OSD_TRIP_DIST] = OSD_POS(1, 2);
3709 osdLayoutsConfig->item_pos[0][OSD_MAIN_BATT_CELL_VOLTAGE] = OSD_POS(12, 1);
3710 osdLayoutsConfig->item_pos[0][OSD_MAIN_BATT_SAG_COMPENSATED_CELL_VOLTAGE] = OSD_POS(12, 1);
3711 osdLayoutsConfig->item_pos[0][OSD_GPS_SPEED] = OSD_POS(23, 1);
3712 osdLayoutsConfig->item_pos[0][OSD_3D_SPEED] = OSD_POS(23, 1);
3713 osdLayoutsConfig->item_pos[0][OSD_GLIDESLOPE] = OSD_POS(23, 2);
3715 osdLayoutsConfig->item_pos[0][OSD_THROTTLE_POS] = OSD_POS(1, 2) | OSD_VISIBLE_FLAG;
3716 osdLayoutsConfig->item_pos[0][OSD_SCALED_THROTTLE_POS] = OSD_POS(6, 2);
3717 osdLayoutsConfig->item_pos[0][OSD_HEADING] = OSD_POS(12, 2);
3718 osdLayoutsConfig->item_pos[0][OSD_GROUND_COURSE] = OSD_POS(12, 3);
3719 osdLayoutsConfig->item_pos[0][OSD_COURSE_HOLD_ERROR] = OSD_POS(12, 2);
3720 osdLayoutsConfig->item_pos[0][OSD_COURSE_HOLD_ADJUSTMENT] = OSD_POS(12, 2);
3721 osdLayoutsConfig->item_pos[0][OSD_CROSS_TRACK_ERROR] = OSD_POS(12, 3);
3722 osdLayoutsConfig->item_pos[0][OSD_HEADING_GRAPH] = OSD_POS(18, 2);
3723 osdLayoutsConfig->item_pos[0][OSD_CURRENT_DRAW] = OSD_POS(2, 3) | OSD_VISIBLE_FLAG;
3724 osdLayoutsConfig->item_pos[0][OSD_MAH_DRAWN] = OSD_POS(1, 4) | OSD_VISIBLE_FLAG;
3725 osdLayoutsConfig->item_pos[0][OSD_WH_DRAWN] = OSD_POS(1, 5);
3726 osdLayoutsConfig->item_pos[0][OSD_BATTERY_REMAINING_CAPACITY] = OSD_POS(1, 6);
3727 osdLayoutsConfig->item_pos[0][OSD_BATTERY_REMAINING_PERCENT] = OSD_POS(1, 7);
3728 osdLayoutsConfig->item_pos[0][OSD_POWER_SUPPLY_IMPEDANCE] = OSD_POS(1, 8);
3730 osdLayoutsConfig->item_pos[0][OSD_EFFICIENCY_MAH_PER_KM] = OSD_POS(1, 5);
3731 osdLayoutsConfig->item_pos[0][OSD_EFFICIENCY_WH_PER_KM] = OSD_POS(1, 5);
3733 osdLayoutsConfig->item_pos[0][OSD_ATTITUDE_ROLL] = OSD_POS(1, 7);
3734 osdLayoutsConfig->item_pos[0][OSD_ATTITUDE_PITCH] = OSD_POS(1, 8);
3736 // avoid OSD_VARIO under OSD_CROSSHAIRS
3737 osdLayoutsConfig->item_pos[0][OSD_VARIO] = OSD_POS(23, 5);
3738 // OSD_VARIO_NUM at the right of OSD_VARIO
3739 osdLayoutsConfig->item_pos[0][OSD_VARIO_NUM] = OSD_POS(24, 7);
3740 osdLayoutsConfig->item_pos[0][OSD_HOME_DIR] = OSD_POS(14, 11);
3741 osdLayoutsConfig->item_pos[0][OSD_ARTIFICIAL_HORIZON] = OSD_POS(8, 6);
3742 osdLayoutsConfig->item_pos[0][OSD_HORIZON_SIDEBARS] = OSD_POS(8, 6);
3744 osdLayoutsConfig->item_pos[0][OSD_CRAFT_NAME] = OSD_POS(20, 2);
3745 osdLayoutsConfig->item_pos[0][OSD_PILOT_NAME] = OSD_POS(20, 3);
3746 osdLayoutsConfig->item_pos[0][OSD_VTX_CHANNEL] = OSD_POS(8, 6);
3748 #ifdef USE_SERIALRX_CRSF
3749 osdLayoutsConfig->item_pos[0][OSD_CRSF_RSSI_DBM] = OSD_POS(23, 12);
3750 osdLayoutsConfig->item_pos[0][OSD_CRSF_LQ] = OSD_POS(23, 11);
3751 osdLayoutsConfig->item_pos[0][OSD_CRSF_SNR_DB] = OSD_POS(24, 9);
3752 osdLayoutsConfig->item_pos[0][OSD_CRSF_TX_POWER] = OSD_POS(24, 10);
3753 #endif
3755 osdLayoutsConfig->item_pos[0][OSD_ONTIME] = OSD_POS(23, 8);
3756 osdLayoutsConfig->item_pos[0][OSD_FLYTIME] = OSD_POS(23, 9);
3757 osdLayoutsConfig->item_pos[0][OSD_ONTIME_FLYTIME] = OSD_POS(23, 11) | OSD_VISIBLE_FLAG;
3758 osdLayoutsConfig->item_pos[0][OSD_RTC_TIME] = OSD_POS(23, 12);
3759 osdLayoutsConfig->item_pos[0][OSD_REMAINING_FLIGHT_TIME_BEFORE_RTH] = OSD_POS(23, 7);
3760 osdLayoutsConfig->item_pos[0][OSD_REMAINING_DISTANCE_BEFORE_RTH] = OSD_POS(23, 6);
3762 osdLayoutsConfig->item_pos[0][OSD_MISSION] = OSD_POS(0, 10);
3763 osdLayoutsConfig->item_pos[0][OSD_GPS_SATS] = OSD_POS(0, 11) | OSD_VISIBLE_FLAG;
3764 osdLayoutsConfig->item_pos[0][OSD_GPS_HDOP] = OSD_POS(0, 10);
3766 osdLayoutsConfig->item_pos[0][OSD_GPS_LAT] = OSD_POS(0, 12);
3767 // Put this on top of the latitude, since it's very unlikely
3768 // that users will want to use both at the same time.
3769 osdLayoutsConfig->item_pos[0][OSD_PLUS_CODE] = OSD_POS(0, 12);
3770 osdLayoutsConfig->item_pos[0][OSD_FLYMODE] = OSD_POS(13, 12) | OSD_VISIBLE_FLAG;
3771 osdLayoutsConfig->item_pos[0][OSD_GPS_LON] = OSD_POS(18, 12);
3773 osdLayoutsConfig->item_pos[0][OSD_AZIMUTH] = OSD_POS(2, 12);
3775 osdLayoutsConfig->item_pos[0][OSD_ROLL_PIDS] = OSD_POS(2, 10);
3776 osdLayoutsConfig->item_pos[0][OSD_PITCH_PIDS] = OSD_POS(2, 11);
3777 osdLayoutsConfig->item_pos[0][OSD_YAW_PIDS] = OSD_POS(2, 12);
3778 osdLayoutsConfig->item_pos[0][OSD_LEVEL_PIDS] = OSD_POS(2, 12);
3779 osdLayoutsConfig->item_pos[0][OSD_POS_XY_PIDS] = OSD_POS(2, 12);
3780 osdLayoutsConfig->item_pos[0][OSD_POS_Z_PIDS] = OSD_POS(2, 12);
3781 osdLayoutsConfig->item_pos[0][OSD_VEL_XY_PIDS] = OSD_POS(2, 12);
3782 osdLayoutsConfig->item_pos[0][OSD_VEL_Z_PIDS] = OSD_POS(2, 12);
3783 osdLayoutsConfig->item_pos[0][OSD_HEADING_P] = OSD_POS(2, 12);
3784 osdLayoutsConfig->item_pos[0][OSD_BOARD_ALIGN_ROLL] = OSD_POS(2, 10);
3785 osdLayoutsConfig->item_pos[0][OSD_BOARD_ALIGN_PITCH] = OSD_POS(2, 11);
3786 osdLayoutsConfig->item_pos[0][OSD_RC_EXPO] = OSD_POS(2, 12);
3787 osdLayoutsConfig->item_pos[0][OSD_RC_YAW_EXPO] = OSD_POS(2, 12);
3788 osdLayoutsConfig->item_pos[0][OSD_THROTTLE_EXPO] = OSD_POS(2, 12);
3789 osdLayoutsConfig->item_pos[0][OSD_PITCH_RATE] = OSD_POS(2, 12);
3790 osdLayoutsConfig->item_pos[0][OSD_ROLL_RATE] = OSD_POS(2, 12);
3791 osdLayoutsConfig->item_pos[0][OSD_YAW_RATE] = OSD_POS(2, 12);
3792 osdLayoutsConfig->item_pos[0][OSD_MANUAL_RC_EXPO] = OSD_POS(2, 12);
3793 osdLayoutsConfig->item_pos[0][OSD_MANUAL_RC_YAW_EXPO] = OSD_POS(2, 12);
3794 osdLayoutsConfig->item_pos[0][OSD_MANUAL_PITCH_RATE] = OSD_POS(2, 12);
3795 osdLayoutsConfig->item_pos[0][OSD_MANUAL_ROLL_RATE] = OSD_POS(2, 12);
3796 osdLayoutsConfig->item_pos[0][OSD_MANUAL_YAW_RATE] = OSD_POS(2, 12);
3797 osdLayoutsConfig->item_pos[0][OSD_NAV_FW_CRUISE_THR] = OSD_POS(2, 12);
3798 osdLayoutsConfig->item_pos[0][OSD_NAV_FW_PITCH2THR] = OSD_POS(2, 12);
3799 osdLayoutsConfig->item_pos[0][OSD_FW_MIN_THROTTLE_DOWN_PITCH_ANGLE] = OSD_POS(2, 12);
3800 osdLayoutsConfig->item_pos[0][OSD_FW_ALT_PID_OUTPUTS] = OSD_POS(2, 12);
3801 osdLayoutsConfig->item_pos[0][OSD_FW_POS_PID_OUTPUTS] = OSD_POS(2, 12);
3802 osdLayoutsConfig->item_pos[0][OSD_MC_VEL_X_PID_OUTPUTS] = OSD_POS(2, 12);
3803 osdLayoutsConfig->item_pos[0][OSD_MC_VEL_Y_PID_OUTPUTS] = OSD_POS(2, 12);
3804 osdLayoutsConfig->item_pos[0][OSD_MC_VEL_Z_PID_OUTPUTS] = OSD_POS(2, 12);
3805 osdLayoutsConfig->item_pos[0][OSD_MC_POS_XYZ_P_OUTPUTS] = OSD_POS(2, 12);
3807 osdLayoutsConfig->item_pos[0][OSD_POWER] = OSD_POS(15, 1);
3809 osdLayoutsConfig->item_pos[0][OSD_IMU_TEMPERATURE] = OSD_POS(19, 2);
3810 osdLayoutsConfig->item_pos[0][OSD_BARO_TEMPERATURE] = OSD_POS(19, 3);
3811 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_0_TEMPERATURE] = OSD_POS(19, 4);
3812 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_1_TEMPERATURE] = OSD_POS(19, 5);
3813 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_2_TEMPERATURE] = OSD_POS(19, 6);
3814 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_3_TEMPERATURE] = OSD_POS(19, 7);
3815 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_4_TEMPERATURE] = OSD_POS(19, 8);
3816 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_5_TEMPERATURE] = OSD_POS(19, 9);
3817 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_6_TEMPERATURE] = OSD_POS(19, 10);
3818 osdLayoutsConfig->item_pos[0][OSD_TEMP_SENSOR_7_TEMPERATURE] = OSD_POS(19, 11);
3820 osdLayoutsConfig->item_pos[0][OSD_AIR_SPEED] = OSD_POS(3, 5);
3821 osdLayoutsConfig->item_pos[0][OSD_WIND_SPEED_HORIZONTAL] = OSD_POS(3, 6);
3822 osdLayoutsConfig->item_pos[0][OSD_WIND_SPEED_VERTICAL] = OSD_POS(3, 7);
3824 osdLayoutsConfig->item_pos[0][OSD_GFORCE] = OSD_POS(12, 4);
3825 osdLayoutsConfig->item_pos[0][OSD_GFORCE_X] = OSD_POS(12, 5);
3826 osdLayoutsConfig->item_pos[0][OSD_GFORCE_Y] = OSD_POS(12, 6);
3827 osdLayoutsConfig->item_pos[0][OSD_GFORCE_Z] = OSD_POS(12, 7);
3829 osdLayoutsConfig->item_pos[0][OSD_VTX_POWER] = OSD_POS(3, 5);
3831 osdLayoutsConfig->item_pos[0][OSD_GVAR_0] = OSD_POS(1, 1);
3832 osdLayoutsConfig->item_pos[0][OSD_GVAR_1] = OSD_POS(1, 2);
3833 osdLayoutsConfig->item_pos[0][OSD_GVAR_2] = OSD_POS(1, 3);
3834 osdLayoutsConfig->item_pos[0][OSD_GVAR_3] = OSD_POS(1, 4);
3836 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_0] = OSD_POS(2, 7);
3837 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_1] = OSD_POS(2, 8);
3838 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_2] = OSD_POS(2, 9);
3839 osdLayoutsConfig->item_pos[0][OSD_SWITCH_INDICATOR_3] = OSD_POS(2, 10);
3841 #if defined(USE_ESC_SENSOR)
3842 osdLayoutsConfig->item_pos[0][OSD_ESC_RPM] = OSD_POS(1, 2);
3843 osdLayoutsConfig->item_pos[0][OSD_ESC_TEMPERATURE] = OSD_POS(1, 3);
3844 #endif
3846 #if defined(USE_RX_MSP) && defined(USE_MSP_RC_OVERRIDE)
3847 osdLayoutsConfig->item_pos[0][OSD_RC_SOURCE] = OSD_POS(3, 4);
3848 #endif
3850 #ifdef USE_POWER_LIMITS
3851 osdLayoutsConfig->item_pos[0][OSD_PLIMIT_REMAINING_BURST_TIME] = OSD_POS(3, 4);
3852 osdLayoutsConfig->item_pos[0][OSD_PLIMIT_ACTIVE_CURRENT_LIMIT] = OSD_POS(3, 5);
3853 osdLayoutsConfig->item_pos[0][OSD_PLIMIT_ACTIVE_POWER_LIMIT] = OSD_POS(3, 6);
3854 #endif
3856 // Under OSD_FLYMODE. TODO: Might not be visible on NTSC?
3857 osdLayoutsConfig->item_pos[0][OSD_MESSAGES] = OSD_POS(1, 13) | OSD_VISIBLE_FLAG;
3859 for (unsigned ii = 1; ii < OSD_LAYOUT_COUNT; ii++) {
3860 for (unsigned jj = 0; jj < ARRAYLEN(osdLayoutsConfig->item_pos[0]); jj++) {
3861 osdLayoutsConfig->item_pos[ii][jj] = osdLayoutsConfig->item_pos[0][jj] & ~OSD_VISIBLE_FLAG;
3866 static void osdSetNextRefreshIn(uint32_t timeMs) {
3867 resumeRefreshAt = micros() + timeMs * 1000;
3868 refreshWaitForResumeCmdRelease = true;
3871 static void osdCompleteAsyncInitialization(void)
3873 if (!displayIsReady(osdDisplayPort)) {
3874 // Update the display.
3875 // XXX: Rename displayDrawScreen() and associated functions
3876 // to displayUpdate()
3877 displayDrawScreen(osdDisplayPort);
3878 return;
3881 osdDisplayIsReady = true;
3883 #if defined(USE_CANVAS)
3884 if (osdConfig()->force_grid) {
3885 osdDisplayHasCanvas = false;
3886 } else {
3887 osdDisplayHasCanvas = displayGetCanvas(&osdCanvas, osdDisplayPort);
3889 #endif
3891 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
3892 displayClearScreen(osdDisplayPort);
3894 uint8_t y = 1;
3895 displayFontMetadata_t metadata;
3896 bool fontHasMetadata = displayGetFontMetadata(&metadata, osdDisplayPort);
3897 LOG_DEBUG(OSD, "Font metadata version %s: %u (%u chars)",
3898 fontHasMetadata ? "Y" : "N", metadata.version, metadata.charCount);
3900 if (fontHasMetadata && metadata.charCount > 256) {
3901 hasExtendedFont = true;
3902 unsigned logo_c = SYM_LOGO_START;
3903 unsigned logo_x = OSD_CENTER_LEN(SYM_LOGO_WIDTH);
3904 for (unsigned ii = 0; ii < SYM_LOGO_HEIGHT; ii++) {
3905 for (unsigned jj = 0; jj < SYM_LOGO_WIDTH; jj++) {
3906 displayWriteChar(osdDisplayPort, logo_x + jj, y, logo_c++);
3908 y++;
3910 y++;
3911 } else if (!fontHasMetadata) {
3912 const char *m = "INVALID FONT";
3913 displayWrite(osdDisplayPort, OSD_CENTER_S(m), 3, m);
3914 y = 4;
3917 if (fontHasMetadata && metadata.version < OSD_MIN_FONT_VERSION) {
3918 const char *m = "INVALID FONT VERSION";
3919 displayWrite(osdDisplayPort, OSD_CENTER_S(m), y++, m);
3922 char string_buffer[30];
3923 tfp_sprintf(string_buffer, "INAV VERSION: %s", FC_VERSION_STRING);
3924 uint8_t xPos = osdDisplayIsHD() ? 15 : 5;
3925 displayWrite(osdDisplayPort, xPos, y++, string_buffer);
3926 #ifdef USE_CMS
3927 displayWrite(osdDisplayPort, xPos+2, y++, CMS_STARTUP_HELP_TEXT1);
3928 displayWrite(osdDisplayPort, xPos+6, y++, CMS_STARTUP_HELP_TEXT2);
3929 displayWrite(osdDisplayPort, xPos+6, y++, CMS_STARTUP_HELP_TEXT3);
3930 #endif
3931 #ifdef USE_STATS
3934 uint8_t statNameX = osdDisplayIsHD() ? 14 : 4;
3935 uint8_t statValueX = osdDisplayIsHD() ? 34 : 24;
3937 if (statsConfig()->stats_enabled) {
3938 displayWrite(osdDisplayPort, statNameX, ++y, "ODOMETER:");
3939 switch (osdConfig()->units) {
3940 case OSD_UNIT_UK:
3941 FALLTHROUGH;
3942 case OSD_UNIT_IMPERIAL:
3943 tfp_sprintf(string_buffer, "%5d", (int)(statsConfig()->stats_total_dist / METERS_PER_MILE));
3944 string_buffer[5] = SYM_MI;
3945 break;
3946 default:
3947 case OSD_UNIT_GA:
3948 tfp_sprintf(string_buffer, "%5d", (int)(statsConfig()->stats_total_dist / METERS_PER_NAUTICALMILE));
3949 string_buffer[5] = SYM_NM;
3950 break;
3951 case OSD_UNIT_METRIC_MPH:
3952 FALLTHROUGH;
3953 case OSD_UNIT_METRIC:
3954 tfp_sprintf(string_buffer, "%5d", (int)(statsConfig()->stats_total_dist / METERS_PER_KILOMETER));
3955 string_buffer[5] = SYM_KM;
3956 break;
3958 string_buffer[6] = '\0';
3959 displayWrite(osdDisplayPort, statValueX-5, y, string_buffer);
3961 displayWrite(osdDisplayPort, statNameX, ++y, "TOTAL TIME:");
3962 uint32_t tot_mins = statsConfig()->stats_total_time / 60;
3963 tfp_sprintf(string_buffer, "%2d:%02dHM", (int)(tot_mins / 60), (int)(tot_mins % 60));
3964 displayWrite(osdDisplayPort, statValueX-5, y, string_buffer);
3966 #ifdef USE_ADC
3967 if (feature(FEATURE_VBAT) && feature(FEATURE_CURRENT_METER)) {
3968 displayWrite(osdDisplayPort, statNameX, ++y, "TOTAL ENERGY:");
3969 osdFormatCentiNumber(string_buffer, statsConfig()->stats_total_energy / 10, 0, 2, 0, 4);
3970 strcat(string_buffer, "\xAB"); // SYM_WH
3971 displayWrite(osdDisplayPort, statValueX-4, y, string_buffer);
3973 displayWrite(osdDisplayPort, statNameX, ++y, "AVG EFFICIENCY:");
3974 if (statsConfig()->stats_total_dist) {
3975 uint32_t avg_efficiency = statsConfig()->stats_total_energy / (statsConfig()->stats_total_dist / METERS_PER_KILOMETER); // mWh/km
3976 switch (osdConfig()->units) {
3977 case OSD_UNIT_UK:
3978 FALLTHROUGH;
3979 case OSD_UNIT_IMPERIAL:
3980 osdFormatCentiNumber(string_buffer, avg_efficiency / 10, 0, 2, 0, 3);
3981 string_buffer[3] = SYM_WH_MI;
3982 break;
3983 case OSD_UNIT_GA:
3984 osdFormatCentiNumber(string_buffer, avg_efficiency / 10, 0, 2, 0, 3);
3985 string_buffer[3] = SYM_WH_NM;
3986 break;
3987 default:
3988 case OSD_UNIT_METRIC_MPH:
3989 FALLTHROUGH;
3990 case OSD_UNIT_METRIC:
3991 osdFormatCentiNumber(string_buffer, avg_efficiency / 10000 * METERS_PER_MILE, 0, 2, 0, 3);
3992 string_buffer[3] = SYM_WH_KM;
3993 break;
3995 } else {
3996 string_buffer[0] = string_buffer[1] = string_buffer[2] = '-';
3998 string_buffer[4] = '\0';
3999 displayWrite(osdDisplayPort, statValueX-3, y, string_buffer);
4001 #endif // USE_ADC
4003 #endif
4005 displayCommitTransaction(osdDisplayPort);
4006 displayResync(osdDisplayPort);
4007 osdSetNextRefreshIn(SPLASH_SCREEN_DISPLAY_TIME);
4010 void osdInit(displayPort_t *osdDisplayPortToUse)
4012 if (!osdDisplayPortToUse)
4013 return;
4015 BUILD_BUG_ON(OSD_POS_MAX != OSD_POS(63,63));
4017 osdDisplayPort = osdDisplayPortToUse;
4019 #ifdef USE_CMS
4020 cmsDisplayPortRegister(osdDisplayPort);
4021 #endif
4023 armState = ARMING_FLAG(ARMED);
4024 osdCompleteAsyncInitialization();
4027 static void osdResetStats(void)
4029 stats.max_current = 0;
4030 stats.max_power = 0;
4031 stats.max_speed = 0;
4032 stats.max_3D_speed = 0;
4033 stats.max_air_speed = 0;
4034 stats.min_voltage = 5000;
4035 stats.min_rssi = 99;
4036 stats.min_lq = 300;
4037 stats.min_rssi_dbm = 0;
4038 stats.max_altitude = 0;
4041 static void osdUpdateStats(void)
4043 int32_t value;
4045 if (feature(FEATURE_GPS)) {
4046 value = osdGet3DSpeed();
4047 const float airspeed_estimate = getAirspeedEstimate();
4049 if (stats.max_3D_speed < value)
4050 stats.max_3D_speed = value;
4052 if (stats.max_speed < gpsSol.groundSpeed)
4053 stats.max_speed = gpsSol.groundSpeed;
4055 if (stats.max_air_speed < airspeed_estimate)
4056 stats.max_air_speed = airspeed_estimate;
4058 if (stats.max_distance < GPS_distanceToHome)
4059 stats.max_distance = GPS_distanceToHome;
4062 value = getBatteryVoltage();
4063 if (stats.min_voltage > value)
4064 stats.min_voltage = value;
4066 value = abs(getAmperage());
4067 if (stats.max_current < value)
4068 stats.max_current = value;
4070 value = labs(getPower());
4071 if (stats.max_power < value)
4072 stats.max_power = value;
4074 value = osdConvertRSSI();
4075 if (stats.min_rssi > value)
4076 stats.min_rssi = value;
4078 value = osdGetCrsfLQ();
4079 if (stats.min_lq > value)
4080 stats.min_lq = value;
4082 if (!failsafeIsReceivingRxData())
4083 stats.min_lq = 0;
4085 value = osdGetCrsfdBm();
4086 if (stats.min_rssi_dbm > value)
4087 stats.min_rssi_dbm = value;
4089 stats.max_altitude = MAX(stats.max_altitude, osdGetAltitude());
4092 static void osdShowStats(bool isSinglePageStatsCompatible, uint8_t page)
4094 const char * disarmReasonStr[DISARM_REASON_COUNT] = { "UNKNOWN", "TIMEOUT", "STICKS", "SWITCH", "SWITCH", "KILLSW", "FAILSAFE", "NAV SYS", "LANDING"};
4095 uint8_t top = 1; // Start one line down leaving space at the top of the screen.
4096 size_t multiValueLengthOffset = 0;
4098 const uint8_t statNameX = osdDisplayIsHD() ? 11 : 1;
4099 const uint8_t statValuesX = osdDisplayIsHD() ? 30 : 20;
4100 char buff[10];
4102 if (page > 1)
4103 page = 0;
4105 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
4106 displayClearScreen(osdDisplayPort);
4108 if (isSinglePageStatsCompatible) {
4109 displayWrite(osdDisplayPort, statNameX, top++, "--- STATS ---");
4110 } else if (page == 0) {
4111 displayWrite(osdDisplayPort, statNameX, top++, "--- STATS --- 1/2 ->");
4112 } else if (page == 1) {
4113 displayWrite(osdDisplayPort, statNameX, top++, "--- STATS --- <- 2/2");
4116 if (isSinglePageStatsCompatible || page == 0) {
4117 if (feature(FEATURE_GPS)) {
4118 if (isSinglePageStatsCompatible) {
4119 displayWrite(osdDisplayPort, statNameX, top, "MAX/AVG SPEED :");
4120 osdFormatVelocityStr(buff, stats.max_3D_speed, true, false);
4121 osdLeftAlignString(buff);
4122 strcat(osdFormatTrimWhiteSpace(buff),"/");
4123 multiValueLengthOffset = strlen(buff);
4124 displayWrite(osdDisplayPort, statValuesX, top, buff);
4125 osdGenerateAverageVelocityStr(buff);
4126 osdLeftAlignString(buff);
4127 displayWrite(osdDisplayPort, statValuesX + multiValueLengthOffset, top++, buff);
4128 } else {
4129 displayWrite(osdDisplayPort, statNameX, top, "MAX SPEED :");
4130 osdFormatVelocityStr(buff, stats.max_3D_speed, true, false);
4131 osdLeftAlignString(buff);
4132 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4134 displayWrite(osdDisplayPort, statNameX, top, "AVG SPEED :");
4135 osdGenerateAverageVelocityStr(buff);
4136 osdLeftAlignString(buff);
4137 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4140 displayWrite(osdDisplayPort, statNameX, top, "MAX DISTANCE :");
4141 osdFormatDistanceStr(buff, stats.max_distance*100);
4142 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4144 displayWrite(osdDisplayPort, statNameX, top, "TRAVELED DISTANCE:");
4145 osdFormatDistanceStr(buff, getTotalTravelDistance());
4146 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4149 displayWrite(osdDisplayPort, statNameX, top, "MAX ALTITUDE :");
4150 osdFormatAltitudeStr(buff, stats.max_altitude);
4151 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4153 switch (rxConfig()->serialrx_provider) {
4154 case SERIALRX_CRSF:
4155 if (isSinglePageStatsCompatible) {
4156 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI %/DBM :");
4157 itoa(stats.min_rssi, buff, 10);
4158 osdLeftAlignString(buff);
4159 strcat(osdFormatTrimWhiteSpace(buff), "%/");
4160 multiValueLengthOffset = strlen(buff);
4161 displayWrite(osdDisplayPort, statValuesX, top, buff);
4162 itoa(stats.min_rssi_dbm, buff, 10);
4163 tfp_sprintf(buff, "%s%c", buff, SYM_DBM);
4164 osdLeftAlignString(buff);
4165 displayWrite(osdDisplayPort, statValuesX + multiValueLengthOffset, top++, buff);
4166 } else {
4167 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI % :");
4168 itoa(stats.min_rssi, buff, 10);
4169 strcat(buff, "%");
4170 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4172 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI DBM :");
4173 itoa(stats.min_rssi_dbm, buff, 10);
4174 tfp_sprintf(buff, "%s%c", buff, SYM_DBM);
4175 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4178 displayWrite(osdDisplayPort, statNameX, top, "MIN LQ :");
4179 itoa(stats.min_lq, buff, 10);
4180 strcat(buff, "%");
4181 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4182 break;
4183 default:
4184 displayWrite(osdDisplayPort, statNameX, top, "MIN RSSI :");
4185 itoa(stats.min_rssi, buff, 10);
4186 strcat(buff, "%");
4187 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4190 displayWrite(osdDisplayPort, statNameX, top, "FLY TIME :");
4191 uint16_t flySeconds = getFlightTime();
4192 uint16_t flyMinutes = flySeconds / 60;
4193 flySeconds %= 60;
4194 uint16_t flyHours = flyMinutes / 60;
4195 flyMinutes %= 60;
4196 tfp_sprintf(buff, "%02u:%02u:%02u", flyHours, flyMinutes, flySeconds);
4197 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4199 displayWrite(osdDisplayPort, statNameX, top, "DISARMED BY :");
4200 displayWrite(osdDisplayPort, statValuesX, top++, disarmReasonStr[getDisarmReason()]);
4203 if (isSinglePageStatsCompatible || page == 1) {
4204 if (osdConfig()->stats_min_voltage_unit == OSD_STATS_MIN_VOLTAGE_UNIT_BATTERY) {
4205 displayWrite(osdDisplayPort, statNameX, top, "MIN BATTERY VOLT :");
4206 osdFormatCentiNumber(buff, stats.min_voltage, 0, osdConfig()->main_voltage_decimals, 0, osdConfig()->main_voltage_decimals + 2);
4207 } else {
4208 displayWrite(osdDisplayPort, statNameX, top, "MIN CELL VOLTAGE :");
4209 osdFormatCentiNumber(buff, stats.min_voltage/getBatteryCellCount(), 0, 2, 0, 3);
4211 tfp_sprintf(buff, "%s%c", buff, SYM_VOLT);
4212 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4214 if (feature(FEATURE_CURRENT_METER)) {
4215 displayWrite(osdDisplayPort, statNameX, top, "MAX CURRENT :");
4216 osdFormatCentiNumber(buff, stats.max_current, 0, 2, 0, 3);
4217 tfp_sprintf(buff, "%s%c", buff, SYM_AMP);
4218 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4220 displayWrite(osdDisplayPort, statNameX, top, "MAX POWER :");
4221 bool kiloWatt = osdFormatCentiNumber(buff, stats.max_power, 1000, 2, 2, 3);
4222 buff[3] = kiloWatt ? SYM_KILOWATT : SYM_WATT;
4223 buff[4] = '\0';
4224 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4226 displayWrite(osdDisplayPort, statNameX, top, "USED CAPACITY :");
4227 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
4228 tfp_sprintf(buff, "%d%c", (int)getMAhDrawn(), SYM_MAH);
4229 } else {
4230 osdFormatCentiNumber(buff, getMWhDrawn() / 10, 0, 2, 0, 3);
4231 tfp_sprintf(buff, "%s%c", buff, SYM_WH);
4233 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4235 int32_t totalDistance = getTotalTravelDistance();
4236 bool moreThanAh = false;
4237 bool efficiencyValid = totalDistance >= 10000;
4238 if (feature(FEATURE_GPS)) {
4239 displayWrite(osdDisplayPort, statNameX, top, "AVG EFFICIENCY :");
4240 switch (osdConfig()->units) {
4241 case OSD_UNIT_UK:
4242 FALLTHROUGH;
4243 case OSD_UNIT_IMPERIAL:
4244 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
4245 moreThanAh = osdFormatCentiNumber(buff, (int32_t)(getMAhDrawn() * 10000.0f * METERS_PER_MILE / totalDistance), 1000, 0, 2, 3);
4246 if (!moreThanAh) {
4247 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_MI_0, SYM_MAH_MI_1);
4248 } else {
4249 tfp_sprintf(buff, "%s%c", buff, SYM_AH_MI);
4251 if (!efficiencyValid) {
4252 buff[0] = buff[1] = buff[2] = '-';
4253 buff[3] = SYM_MAH_MI_0;
4254 buff[4] = SYM_MAH_MI_1;
4255 buff[5] = '\0';
4257 } else {
4258 osdFormatCentiNumber(buff, (int32_t)(getMWhDrawn() * 10.0f * METERS_PER_MILE / totalDistance), 0, 2, 0, 3);
4259 tfp_sprintf(buff, "%s%c", buff, SYM_WH_MI);
4260 if (!efficiencyValid) {
4261 buff[0] = buff[1] = buff[2] = '-';
4264 break;
4265 case OSD_UNIT_GA:
4266 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
4267 moreThanAh = osdFormatCentiNumber(buff, (int32_t)(getMAhDrawn() * 10000.0f * METERS_PER_NAUTICALMILE / totalDistance), 1000, 0, 2, 3);
4268 if (!moreThanAh) {
4269 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_NM_0, SYM_MAH_NM_1);
4270 } else {
4271 tfp_sprintf(buff, "%s%c", buff, SYM_AH_NM);
4273 if (!efficiencyValid) {
4274 buff[0] = buff[1] = buff[2] = '-';
4275 buff[3] = SYM_MAH_NM_0;
4276 buff[4] = SYM_MAH_NM_1;
4277 buff[5] = '\0';
4279 } else {
4280 osdFormatCentiNumber(buff, (int32_t)(getMWhDrawn() * 10.0f * METERS_PER_NAUTICALMILE / totalDistance), 0, 2, 0, 3);
4281 tfp_sprintf(buff, "%s%c", buff, SYM_WH_NM);
4282 if (!efficiencyValid) {
4283 buff[0] = buff[1] = buff[2] = '-';
4286 break;
4287 case OSD_UNIT_METRIC_MPH:
4288 FALLTHROUGH;
4289 case OSD_UNIT_METRIC:
4290 if (osdConfig()->stats_energy_unit == OSD_STATS_ENERGY_UNIT_MAH) {
4291 moreThanAh = osdFormatCentiNumber(buff, (int32_t)(getMAhDrawn() * 10000000.0f / totalDistance), 1000, 0, 2, 3);
4292 if (!moreThanAh) {
4293 tfp_sprintf(buff, "%s%c%c", buff, SYM_MAH_KM_0, SYM_MAH_KM_1);
4294 } else {
4295 tfp_sprintf(buff, "%s%c", buff, SYM_AH_KM);
4297 if (!efficiencyValid) {
4298 buff[0] = buff[1] = buff[2] = '-';
4299 buff[3] = SYM_MAH_KM_0;
4300 buff[4] = SYM_MAH_KM_1;
4301 buff[5] = '\0';
4303 } else {
4304 osdFormatCentiNumber(buff, (int32_t)(getMWhDrawn() * 10000.0f / totalDistance), 0, 2, 0, 3);
4305 tfp_sprintf(buff, "%s%c", buff, SYM_WH_KM);
4306 if (!efficiencyValid) {
4307 buff[0] = buff[1] = buff[2] = '-';
4310 break;
4312 osdLeftAlignString(buff);
4313 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4317 const float max_gforce = accGetMeasuredMaxG();
4318 displayWrite(osdDisplayPort, statNameX, top, "MAX G-FORCE :");
4319 osdFormatCentiNumber(buff, max_gforce * 100, 0, 2, 0, 3);
4320 displayWrite(osdDisplayPort, statValuesX, top++, buff);
4322 const acc_extremes_t *acc_extremes = accGetMeasuredExtremes();
4323 const float acc_extremes_min = acc_extremes[Z].min;
4324 const float acc_extremes_max = acc_extremes[Z].max;
4325 displayWrite(osdDisplayPort, statNameX, top, "MIN/MAX Z G-FORCE:");
4326 osdFormatCentiNumber(buff, acc_extremes_min * 100, 0, 2, 0, 4);
4327 osdLeftAlignString(buff);
4328 strcat(osdFormatTrimWhiteSpace(buff),"/");
4329 multiValueLengthOffset = strlen(buff);
4330 displayWrite(osdDisplayPort, statValuesX, top, buff);
4331 osdFormatCentiNumber(buff, acc_extremes_max * 100, 0, 2, 0, 3);
4332 osdLeftAlignString(buff);
4333 displayWrite(osdDisplayPort, statValuesX + multiValueLengthOffset, top++, buff);
4336 if (savingSettings == true) {
4337 displayWrite(osdDisplayPort, statNameX, top++, OSD_MESSAGE_STR(OSD_MSG_SAVING_SETTNGS));
4338 } else if (notify_settings_saved > 0) {
4339 if (millis() > notify_settings_saved) {
4340 notify_settings_saved = 0;
4341 } else {
4342 displayWrite(osdDisplayPort, statNameX, top++, OSD_MESSAGE_STR(OSD_MSG_SETTINGS_SAVED));
4346 displayCommitTransaction(osdDisplayPort);
4349 // called when motors armed
4350 static void osdShowArmed(void)
4352 dateTime_t dt;
4353 char buf[MAX(32, FORMATTED_DATE_TIME_BUFSIZE)];
4354 char craftNameBuf[MAX_NAME_LENGTH];
4355 char versionBuf[30];
4356 char *date;
4357 char *time;
4358 // We need 12 visible rows, start row never < first fully visible row 1
4359 uint8_t y = osdDisplayPort->rows > 13 ? (osdDisplayPort->rows - 12) / 2 : 1;
4361 displayClearScreen(osdDisplayPort);
4362 strcpy(buf, "ARMED");
4363 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4364 y += 2;
4366 if (strlen(systemConfig()->craftName) > 0) {
4367 osdFormatCraftName(craftNameBuf);
4368 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(systemConfig()->craftName)) / 2, y, craftNameBuf );
4369 y += 1;
4371 if (posControl.waypointListValid && posControl.waypointCount > 0) {
4372 #ifdef USE_MULTI_MISSION
4373 tfp_sprintf(buf, "MISSION %u/%u (%u WP)", posControl.loadedMultiMissionIndex, posControl.multiMissionCount, posControl.waypointCount);
4374 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4375 #else
4376 strcpy(buf, "*MISSION LOADED*");
4377 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4378 #endif
4380 y += 1;
4382 #if defined(USE_GPS)
4383 if (feature(FEATURE_GPS)) {
4384 if (STATE(GPS_FIX_HOME)) {
4385 if (osdConfig()->osd_home_position_arm_screen){
4386 osdFormatCoordinate(buf, SYM_LAT, GPS_home.lat);
4387 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4388 osdFormatCoordinate(buf, SYM_LON, GPS_home.lon);
4389 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y + 1, buf);
4390 int digits = osdConfig()->plus_code_digits;
4391 olc_encode(GPS_home.lat, GPS_home.lon, digits, buf, sizeof(buf));
4392 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y + 2, buf);
4394 y += 4;
4395 #if defined (USE_SAFE_HOME)
4396 if (safehome_distance) { // safehome found during arming
4397 if (navConfig()->general.flags.safehome_usage_mode == SAFEHOME_USAGE_OFF) {
4398 strcpy(buf, "SAFEHOME FOUND; MODE OFF");
4399 } else {
4400 char buf2[12]; // format the distance first
4401 osdFormatDistanceStr(buf2, safehome_distance);
4402 tfp_sprintf(buf, "%c - %s -> SAFEHOME %u", SYM_HOME, buf2, safehome_index);
4404 textAttributes_t elemAttr = _TEXT_ATTRIBUTES_BLINK_BIT;
4405 // write this message above the ARMED message to make it obvious
4406 displayWriteWithAttr(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y - 8, buf, elemAttr);
4408 #endif
4409 } else {
4410 strcpy(buf, "!NO HOME POSITION!");
4411 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(buf)) / 2, y, buf);
4412 y += 1;
4415 #endif
4417 if (rtcGetDateTime(&dt)) {
4418 dateTimeFormatLocal(buf, &dt);
4419 dateTimeSplitFormatted(buf, &date, &time);
4421 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(date)) / 2, y, date);
4422 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(time)) / 2, y + 1, time);
4423 y += 3;
4426 tfp_sprintf(versionBuf, "INAV VERSION: %s", FC_VERSION_STRING);
4427 displayWrite(osdDisplayPort, (osdDisplayPort->cols - strlen(versionBuf)) / 2, y, versionBuf);
4430 static void osdFilterData(timeUs_t currentTimeUs) {
4431 static timeUs_t lastRefresh = 0;
4432 float refresh_dT = US2S(cmpTimeUs(currentTimeUs, lastRefresh));
4434 GForce = fast_fsqrtf(vectorNormSquared(&imuMeasuredAccelBF)) / GRAVITY_MSS;
4435 for (uint8_t axis = 0; axis < XYZ_AXIS_COUNT; ++axis) GForceAxis[axis] = imuMeasuredAccelBF.v[axis] / GRAVITY_MSS;
4437 if (lastRefresh) {
4438 GForce = pt1FilterApply3(&GForceFilter, GForce, refresh_dT);
4439 for (uint8_t axis = 0; axis < XYZ_AXIS_COUNT; ++axis) pt1FilterApply3(GForceFilterAxis + axis, GForceAxis[axis], refresh_dT);
4440 } else {
4441 pt1FilterInitRC(&GForceFilter, GFORCE_FILTER_TC, 0);
4442 pt1FilterReset(&GForceFilter, GForce);
4444 for (uint8_t axis = 0; axis < XYZ_AXIS_COUNT; ++axis) {
4445 pt1FilterInitRC(GForceFilterAxis + axis, GFORCE_FILTER_TC, 0);
4446 pt1FilterReset(GForceFilterAxis + axis, GForceAxis[axis]);
4450 lastRefresh = currentTimeUs;
4453 // Detect when the user is holding the roll stick to the right
4454 static bool osdIsPageUpStickCommandHeld(void)
4456 static int pageUpHoldCount = 1;
4458 bool keyHeld = false;
4460 if (IS_HI(ROLL)) {
4461 keyHeld = true;
4464 if (!keyHeld) {
4465 pageUpHoldCount = 1;
4466 } else {
4467 ++pageUpHoldCount;
4470 if (pageUpHoldCount > 20) {
4471 pageUpHoldCount = 1;
4472 return true;
4475 return false;
4478 // Detect when the user is holding the roll stick to the left
4479 static bool osdIsPageDownStickCommandHeld(void)
4481 static int pageDownHoldCount = 1;
4483 bool keyHeld = false;
4484 if (IS_LO(ROLL)) {
4485 keyHeld = true;
4488 if (!keyHeld) {
4489 pageDownHoldCount = 1;
4490 } else {
4491 ++pageDownHoldCount;
4494 if (pageDownHoldCount > 20) {
4495 pageDownHoldCount = 1;
4496 return true;
4499 return false;
4502 static void osdRefresh(timeUs_t currentTimeUs)
4504 osdFilterData(currentTimeUs);
4506 #ifdef USE_CMS
4507 if (IS_RC_MODE_ACTIVE(BOXOSD) && (!cmsInMenu) && !(osdConfig()->osd_failsafe_switch_layout && FLIGHT_MODE(FAILSAFE_MODE))) {
4508 #else
4509 if (IS_RC_MODE_ACTIVE(BOXOSD) && !(osdConfig()->osd_failsafe_switch_layout && FLIGHT_MODE(FAILSAFE_MODE))) {
4510 #endif
4511 displayClearScreen(osdDisplayPort);
4512 armState = ARMING_FLAG(ARMED);
4513 return;
4516 bool statsSinglePageCompatible = (osdDisplayPort->rows >= OSD_STATS_SINGLE_PAGE_MIN_ROWS);
4517 static uint8_t statsCurrentPage = 0;
4518 static bool statsDisplayed = false;
4519 static bool statsAutoPagingEnabled = true;
4521 // Detect arm/disarm
4522 if (armState != ARMING_FLAG(ARMED)) {
4523 if (ARMING_FLAG(ARMED)) {
4524 // Display the "Arming" screen
4525 statsDisplayed = false;
4526 osdResetStats();
4527 osdShowArmed();
4528 uint32_t delay = ARMED_SCREEN_DISPLAY_TIME;
4529 #if defined(USE_SAFE_HOME)
4530 if (safehome_distance)
4531 delay *= 3;
4532 #endif
4533 osdSetNextRefreshIn(delay);
4534 } else {
4535 // Display the "Stats" screen
4536 statsDisplayed = true;
4537 statsCurrentPage = 0;
4538 statsAutoPagingEnabled = osdConfig()->stats_page_auto_swap_time > 0 ? true : false;
4539 osdShowStats(statsSinglePageCompatible, statsCurrentPage);
4540 osdSetNextRefreshIn(STATS_SCREEN_DISPLAY_TIME);
4543 armState = ARMING_FLAG(ARMED);
4546 // This block is entered when we're showing the "Splash", "Armed" or "Stats" screens
4547 if (resumeRefreshAt) {
4549 // Handle events only when the "Stats" screen is being displayed.
4550 if (statsDisplayed) {
4552 // Manual paging stick commands are only applicable to multi-page stats.
4553 // ******************************
4554 // For single-page stats, this effectively disables the ability to cancel the
4555 // automatic paging/updates with the stick commands. So unless stats_page_auto_swap_time
4556 // is set to 0 or greater than 4 (saved settings display interval is 5 seconds), then
4557 // "Saved Settings" should display if it is active within the refresh interval.
4558 // ******************************
4559 // With multi-page stats, "Saved Settings" could also be missed if the user
4560 // has canceled automatic paging using the stick commands, because that is only
4561 // updated when osdShowStats() is called. So, in that case, they would only see
4562 // the "Saved Settings" message if they happen to manually change pages using the
4563 // stick commands within the interval the message is displayed.
4564 bool manualPageUpRequested = false;
4565 bool manualPageDownRequested = false;
4566 if (!statsSinglePageCompatible) {
4567 // These methods ensure the paging stick commands are held for a brief period
4568 // Otherwise it can result in a race condition where the stats are
4569 // updated too quickly and can result in partial blanks, etc.
4570 if (osdIsPageUpStickCommandHeld()) {
4571 manualPageUpRequested = true;
4572 statsAutoPagingEnabled = false;
4573 } else if (osdIsPageDownStickCommandHeld()) {
4574 manualPageDownRequested = true;
4575 statsAutoPagingEnabled = false;
4579 if (statsAutoPagingEnabled) {
4580 // Alternate screens for multi-page stats.
4581 // Also, refreshes screen at swap interval for single-page stats.
4582 if (OSD_ALTERNATING_CHOICES((osdConfig()->stats_page_auto_swap_time * 1000), 2)) {
4583 if (statsCurrentPage == 0) {
4584 osdShowStats(statsSinglePageCompatible, statsCurrentPage);
4585 statsCurrentPage = 1;
4587 } else {
4588 if (statsCurrentPage == 1) {
4589 osdShowStats(statsSinglePageCompatible, statsCurrentPage);
4590 statsCurrentPage = 0;
4593 } else {
4594 // Process manual page change events for multi-page stats.
4595 if (manualPageUpRequested) {
4596 osdShowStats(statsSinglePageCompatible, 1);
4597 statsCurrentPage = 1;
4598 } else if (manualPageDownRequested) {
4599 osdShowStats(statsSinglePageCompatible, 0);
4600 statsCurrentPage = 0;
4605 // Handle events when either "Splash", "Armed" or "Stats" screens are displayed.
4606 if ((currentTimeUs > resumeRefreshAt) || OSD_RESUME_UPDATES_STICK_COMMAND) {
4607 // Time elapsed or canceled by stick commands.
4608 // Exit to normal OSD operation.
4609 displayClearScreen(osdDisplayPort);
4610 resumeRefreshAt = 0;
4611 statsDisplayed = false;
4612 } else {
4613 // Continue "Splash", "Armed" or "Stats" screens.
4614 displayHeartbeat(osdDisplayPort);
4617 return;
4620 #ifdef USE_CMS
4621 if (!displayIsGrabbed(osdDisplayPort)) {
4622 displayBeginTransaction(osdDisplayPort, DISPLAY_TRANSACTION_OPT_RESET_DRAWING);
4623 if (fullRedraw) {
4624 displayClearScreen(osdDisplayPort);
4625 fullRedraw = false;
4627 osdDrawNextElement();
4628 displayHeartbeat(osdDisplayPort);
4629 displayCommitTransaction(osdDisplayPort);
4630 #ifdef OSD_CALLS_CMS
4631 } else {
4632 cmsUpdate(currentTimeUs);
4633 #endif
4635 #endif
4639 * Called periodically by the scheduler
4641 void osdUpdate(timeUs_t currentTimeUs)
4643 static uint32_t counter = 0;
4645 // don't touch buffers if DMA transaction is in progress
4646 if (displayIsTransferInProgress(osdDisplayPort)) {
4647 return;
4650 if (!osdDisplayIsReady) {
4651 osdCompleteAsyncInitialization();
4652 return;
4655 #if defined(OSD_ALTERNATE_LAYOUT_COUNT) && OSD_ALTERNATE_LAYOUT_COUNT > 0
4656 // Check if the layout has changed. Higher numbered
4657 // boxes take priority.
4658 unsigned activeLayout;
4659 if (layoutOverride >= 0) {
4660 activeLayout = layoutOverride;
4661 // Check for timed override, it will go into effect on
4662 // the next OSD iteration
4663 if (layoutOverrideUntil > 0 && millis() > layoutOverrideUntil) {
4664 layoutOverrideUntil = 0;
4665 layoutOverride = -1;
4667 } else if (osdConfig()->osd_failsafe_switch_layout && FLIGHT_MODE(FAILSAFE_MODE)) {
4668 activeLayout = 0;
4669 } else {
4670 #if OSD_ALTERNATE_LAYOUT_COUNT > 2
4671 if (IS_RC_MODE_ACTIVE(BOXOSDALT3))
4672 activeLayout = 3;
4673 else
4674 #endif
4675 #if OSD_ALTERNATE_LAYOUT_COUNT > 1
4676 if (IS_RC_MODE_ACTIVE(BOXOSDALT2))
4677 activeLayout = 2;
4678 else
4679 #endif
4680 if (IS_RC_MODE_ACTIVE(BOXOSDALT1))
4681 activeLayout = 1;
4682 else
4683 #ifdef USE_PROGRAMMING_FRAMEWORK
4684 if (LOGIC_CONDITION_GLOBAL_FLAG(LOGIC_CONDITION_GLOBAL_FLAG_OVERRIDE_OSD_LAYOUT))
4685 activeLayout = constrain(logicConditionValuesByType[LOGIC_CONDITION_SET_OSD_LAYOUT], 0, OSD_ALTERNATE_LAYOUT_COUNT);
4686 else
4687 #endif
4688 activeLayout = 0;
4690 if (currentLayout != activeLayout) {
4691 currentLayout = activeLayout;
4692 osdStartFullRedraw();
4694 #endif
4696 #define DRAW_FREQ_DENOM 4
4697 #define STATS_FREQ_DENOM 50
4698 counter++;
4700 if ((counter % STATS_FREQ_DENOM) == 0) {
4701 osdUpdateStats();
4704 if ((counter % DRAW_FREQ_DENOM) == 0) {
4705 // redraw values in buffer
4706 osdRefresh(currentTimeUs);
4707 } else {
4708 // rest of time redraw screen
4709 displayDrawScreen(osdDisplayPort);
4712 #ifdef USE_CMS
4713 // do not allow ARM if we are in menu
4714 if (displayIsGrabbed(osdDisplayPort)) {
4715 ENABLE_ARMING_FLAG(ARMING_DISABLED_OSD_MENU);
4716 } else {
4717 DISABLE_ARMING_FLAG(ARMING_DISABLED_OSD_MENU);
4719 #endif
4722 void osdStartFullRedraw(void)
4724 fullRedraw = true;
4727 void osdOverrideLayout(int layout, timeMs_t duration)
4729 layoutOverride = constrain(layout, -1, ARRAYLEN(osdLayoutsConfig()->item_pos) - 1);
4730 if (layoutOverride >= 0 && duration > 0) {
4731 layoutOverrideUntil = millis() + duration;
4732 } else {
4733 layoutOverrideUntil = 0;
4737 int osdGetActiveLayout(bool *overridden)
4739 if (overridden) {
4740 *overridden = layoutOverride >= 0;
4742 return currentLayout;
4745 bool osdItemIsFixed(osd_items_e item)
4747 return item == OSD_CROSSHAIRS ||
4748 item == OSD_ARTIFICIAL_HORIZON ||
4749 item == OSD_HORIZON_SIDEBARS;
4752 displayPort_t *osdGetDisplayPort(void)
4754 return osdDisplayPort;
4757 displayCanvas_t *osdGetDisplayPortCanvas(void)
4759 #if defined(USE_CANVAS)
4760 if (osdDisplayHasCanvas) {
4761 return &osdCanvas;
4763 #endif
4764 return NULL;
4767 timeMs_t systemMessageCycleTime(unsigned messageCount, const char **messages){
4768 uint8_t i = 0;
4769 float factor = 1.0f;
4770 while (i < messageCount) {
4771 if ((float)strlen(messages[i]) / 15.0f > factor) {
4772 factor = (float)strlen(messages[i]) / 15.0f;
4774 i++;
4776 return osdConfig()->system_msg_display_time * factor;
4779 textAttributes_t osdGetSystemMessage(char *buff, size_t buff_size, bool isCenteredText)
4781 textAttributes_t elemAttr = TEXT_ATTRIBUTES_NONE;
4783 if (buff != NULL) {
4784 const char *message = NULL;
4785 char messageBuf[MAX(SETTING_MAX_NAME_LENGTH, OSD_MESSAGE_LENGTH+1)];
4786 // We might have up to 5 messages to show.
4787 const char *messages[5];
4788 unsigned messageCount = 0;
4789 const char *failsafeInfoMessage = NULL;
4790 const char *invertedInfoMessage = NULL;
4792 if (ARMING_FLAG(ARMED)) {
4793 if (FLIGHT_MODE(FAILSAFE_MODE) || FLIGHT_MODE(NAV_RTH_MODE) || FLIGHT_MODE(NAV_WP_MODE) || navigationIsExecutingAnEmergencyLanding()) {
4794 if (isWaypointMissionRTHActive()) {
4795 // if RTH activated whilst WP mode selected, remind pilot to cancel WP mode to exit RTH
4796 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_WP_RTH_CANCEL);
4798 if (navGetCurrentStateFlags() & NAV_AUTO_WP_DONE) {
4799 messages[messageCount++] = STATE(LANDING_DETECTED) ? OSD_MESSAGE_STR(OSD_MSG_WP_LANDED) : OSD_MESSAGE_STR(OSD_MSG_WP_FINISHED);
4800 } else if (NAV_Status.state == MW_NAV_STATE_WP_ENROUTE) {
4801 // Countdown display for remaining Waypoints
4802 char buf[6];
4803 osdFormatDistanceSymbol(buf, posControl.wpDistance, 0);
4804 tfp_sprintf(messageBuf, "TO WP %u/%u (%s)", getGeoWaypointNumber(posControl.activeWaypointIndex), posControl.geoWaypointCount, buf);
4805 messages[messageCount++] = messageBuf;
4806 } else if (NAV_Status.state == MW_NAV_STATE_HOLD_TIMED) {
4807 if (navConfig()->general.waypoint_enforce_altitude && !posControl.wpAltitudeReached) {
4808 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_ADJUSTING_WP_ALT);
4809 } else {
4810 // WP hold time countdown in seconds
4811 timeMs_t currentTime = millis();
4812 int holdTimeRemaining = posControl.waypointList[posControl.activeWaypointIndex].p1 - (int)(MS2S(currentTime - posControl.wpReachedTime));
4813 holdTimeRemaining = holdTimeRemaining >= 0 ? holdTimeRemaining : 0;
4815 tfp_sprintf(messageBuf, "HOLDING WP FOR %2u S", holdTimeRemaining);
4817 messages[messageCount++] = messageBuf;
4819 } else {
4820 const char *navStateMessage = navigationStateMessage();
4821 if (navStateMessage) {
4822 messages[messageCount++] = navStateMessage;
4825 #if defined(USE_SAFE_HOME)
4826 const char *safehomeMessage = divertingToSafehomeMessage();
4827 if (safehomeMessage) {
4828 messages[messageCount++] = safehomeMessage;
4830 #endif
4831 if (FLIGHT_MODE(FAILSAFE_MODE)) {
4832 // In FS mode while being armed too
4833 const char *failsafePhaseMessage = osdFailsafePhaseMessage();
4834 failsafeInfoMessage = osdFailsafeInfoMessage();
4836 if (failsafePhaseMessage) {
4837 messages[messageCount++] = failsafePhaseMessage;
4839 if (failsafeInfoMessage) {
4840 messages[messageCount++] = failsafeInfoMessage;
4843 } else { /* messages shown only when Failsafe, WP, RTH or Emergency Landing not active */
4844 if (STATE(FIXED_WING_LEGACY) && (navGetCurrentStateFlags() & NAV_CTL_LAUNCH)) {
4845 messages[messageCount++] = navConfig()->fw.launch_manual_throttle ? OSD_MESSAGE_STR(OSD_MSG_AUTOLAUNCH_MANUAL) :
4846 OSD_MESSAGE_STR(OSD_MSG_AUTOLAUNCH);
4847 const char *launchStateMessage = fixedWingLaunchStateMessage();
4848 if (launchStateMessage) {
4849 messages[messageCount++] = launchStateMessage;
4851 } else {
4852 if (FLIGHT_MODE(NAV_ALTHOLD_MODE) && !navigationRequiresAngleMode()) {
4853 // ALTHOLD might be enabled alongside ANGLE/HORIZON/ACRO
4854 // when it doesn't require ANGLE mode (required only in FW
4855 // right now). If if requires ANGLE, its display is handled
4856 // by OSD_FLYMODE.
4857 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_ALTITUDE_HOLD);
4859 if (IS_RC_MODE_ACTIVE(BOXAUTOTRIM) && !feature(FEATURE_FW_AUTOTRIM)) {
4860 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOTRIM);
4862 if (IS_RC_MODE_ACTIVE(BOXAUTOTUNE)) {
4863 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOTUNE);
4864 if (FLIGHT_MODE(MANUAL_MODE)) {
4865 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOTUNE_ACRO);
4868 if (IS_RC_MODE_ACTIVE(BOXAUTOLEVEL) && (FLIGHT_MODE(ANGLE_MODE) || FLIGHT_MODE(HORIZON_MODE) || (navigationRequiresAngleMode() && !navigationIsControllingAltitude()))) {
4869 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_AUTOLEVEL);
4871 if (FLIGHT_MODE(HEADFREE_MODE)) {
4872 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_HEADFREE);
4874 if (FLIGHT_MODE(SOARING_MODE)) {
4875 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_NAV_SOARING);
4877 if (posControl.flags.wpMissionPlannerActive) {
4878 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_MISSION_PLANNER);
4880 if (STATE(LANDING_DETECTED)) {
4881 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_LANDED);
4885 } else if (ARMING_FLAG(ARMING_DISABLED_ALL_FLAGS)) {
4886 unsigned invalidIndex;
4888 // Check if we're unable to arm for some reason
4889 if (ARMING_FLAG(ARMING_DISABLED_INVALID_SETTING) && !settingsValidate(&invalidIndex)) {
4891 const setting_t *setting = settingGet(invalidIndex);
4892 settingGetName(setting, messageBuf);
4893 for (int ii = 0; messageBuf[ii]; ii++) {
4894 messageBuf[ii] = sl_toupper(messageBuf[ii]);
4896 invertedInfoMessage = messageBuf;
4897 messages[messageCount++] = invertedInfoMessage;
4899 invertedInfoMessage = OSD_MESSAGE_STR(OSD_MSG_INVALID_SETTING);
4900 messages[messageCount++] = invertedInfoMessage;
4902 } else {
4904 invertedInfoMessage = OSD_MESSAGE_STR(OSD_MSG_UNABLE_ARM);
4905 messages[messageCount++] = invertedInfoMessage;
4907 // Show the reason for not arming
4908 messages[messageCount++] = osdArmingDisabledReasonMessage();
4911 } else if (!ARMING_FLAG(ARMED)) {
4912 if (isWaypointListValid()) {
4913 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_WP_MISSION_LOADED);
4917 /* Messages that are shown regardless of Arming state */
4919 if (savingSettings == true) {
4920 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_SAVING_SETTNGS);
4921 } else if (notify_settings_saved > 0) {
4922 if (millis() > notify_settings_saved) {
4923 notify_settings_saved = 0;
4924 } else {
4925 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_SETTINGS_SAVED);
4929 #ifdef USE_DEV_TOOLS
4930 if (systemConfig()->groundTestMode) {
4931 messages[messageCount++] = OSD_MESSAGE_STR(OSD_MSG_GRD_TEST_MODE);
4933 #endif
4935 if (messageCount > 0) {
4936 message = messages[OSD_ALTERNATING_CHOICES(systemMessageCycleTime(messageCount, messages), messageCount)];
4937 if (message == failsafeInfoMessage) {
4938 // failsafeInfoMessage is not useful for recovering
4939 // a lost model, but might help avoiding a crash.
4940 // Blink to grab user attention.
4941 TEXT_ATTRIBUTES_ADD_BLINK(elemAttr);
4942 } else if (message == invertedInfoMessage) {
4943 TEXT_ATTRIBUTES_ADD_INVERTED(elemAttr);
4945 // We're shoing either failsafePhaseMessage or
4946 // navStateMessage. Don't BLINK here since
4947 // having this text available might be crucial
4948 // during a lost aircraft recovery and blinking
4949 // will cause it to be missing from some frames.
4952 osdFormatMessage(buff, buff_size, message, isCenteredText);
4954 return elemAttr;
4957 #endif // OSD