Fix WS2812 led definition
[inav.git] / src / main / io / vtx_smartaudio.c
blob9901db409e28d76ce3cdc0585b7e8beae8c18e02
1 /*
2 * This file is part of Cleanflight and Betaflight.
4 * Cleanflight and Betaflight are free software. You can redistribute
5 * this software and/or modify this software under the terms of the
6 * GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option)
8 * any later version.
10 * Cleanflight and Betaflight are distributed in the hope that they
11 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
12 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 * See the GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this software.
18 * If not, see <http://www.gnu.org/licenses/>.
21 /* Created by jflyper */
23 #include <stdbool.h>
24 #include <stdint.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <math.h>
29 #include "platform.h"
31 #if defined(USE_VTX_SMARTAUDIO) && defined(USE_VTX_CONTROL)
33 #include "build/debug.h"
35 #include "cms/cms.h"
37 #include "common/log.h"
38 #include "common/maths.h"
39 #include "common/printf.h"
40 #include "common/utils.h"
41 #include "common/typeconversion.h"
43 #include "drivers/time.h"
44 #include "drivers/vtx_common.h"
46 #include "fc/settings.h"
48 #include "io/serial.h"
49 #include "io/vtx.h"
50 #include "io/vtx_control.h"
51 #include "io/vtx_smartaudio.h"
52 #include "io/vtx_string.h"
55 // Timing parameters
56 // Note that vtxSAProcess() is normally called at 200ms interval
57 #define SMARTAUDIO_CMD_TIMEOUT 120 // Time until the command is considered lost
58 #define SMARTAUDIO_POLLING_INTERVAL 150 // Minimum time between state polling
59 #define SMARTAUDIO_POLLING_WINDOW 1000 // Time window after command polling for state change
61 static serialPort_t *smartAudioSerialPort = NULL;
63 uint8_t saPowerCount = VTX_SMARTAUDIO_DEFAULT_POWER_COUNT;
64 const char * saPowerNames[VTX_SMARTAUDIO_MAX_POWER_COUNT + 1] = {
65 "----", "25 ", "200 ", "500 ", "800 ", " "
68 // Save powerlevels reported from SA 2.1 devices here
69 char sa21PowerNames[VTX_SMARTAUDIO_MAX_POWER_COUNT][5];
71 static const vtxVTable_t saVTable; // Forward
72 static vtxDevice_t vtxSmartAudio = {
73 .vTable = &saVTable,
74 .capability.bandCount = VTX_SMARTAUDIO_BAND_COUNT,
75 .capability.channelCount = VTX_SMARTAUDIO_CHANNEL_COUNT,
76 .capability.powerCount = VTX_SMARTAUDIO_MAX_POWER_COUNT,
77 .capability.bandNames = (char **)vtx58BandNames,
78 .capability.channelNames = (char **)vtx58ChannelNames,
79 .capability.powerNames = (char**)saPowerNames
82 // SmartAudio command and response codes
83 enum {
84 SA_CMD_NONE = 0x00,
85 SA_CMD_GET_SETTINGS = 0x01,
86 SA_CMD_SET_POWER,
87 SA_CMD_SET_CHAN,
88 SA_CMD_SET_FREQ,
89 SA_CMD_SET_MODE,
90 SA_CMD_GET_SETTINGS_V2 = 0x09, // Response only
91 SA_CMD_GET_SETTINGS_V21 = 0x11,
92 } smartAudioCommand_e;
94 // This is not a good design; can't distinguish command from response this way.
95 #define SACMD(cmd) (((cmd) << 1) | 1)
98 #define SA_IS_PITMODE(n) ((n) & SA_MODE_GET_PITMODE)
99 #define SA_IS_PIRMODE(n) (((n) & SA_MODE_GET_PITMODE) && ((n) & SA_MODE_GET_IN_RANGE_PITMODE))
100 #define SA_IS_PORMODE(n) (((n) & SA_MODE_GET_PITMODE) && ((n) & SA_MODE_GET_OUT_RANGE_PITMODE))
103 // convert between 'saDevice.channel' and band/channel values
104 #define SA_DEVICE_CHVAL_TO_BAND(val) ((val) / (uint8_t)8)
105 #define SA_DEVICE_CHVAL_TO_CHANNEL(val) ((val) % (uint8_t)8)
106 #define SA_BANDCHAN_TO_DEVICE_CHVAL(band, channel) ((band) * (uint8_t)8 + (channel))
109 // Statistical counters, for user side trouble shooting.
111 smartAudioStat_t saStat = {
112 .pktsent = 0,
113 .pktrcvd = 0,
114 .badpre = 0,
115 .badlen = 0,
116 .crc = 0,
117 .ooopresp = 0,
118 .badcode = 0,
121 // Fill table with standard values for SA 1.0 and 2.0
122 saPowerTable_t saPowerTable[VTX_SMARTAUDIO_MAX_POWER_COUNT] = {
123 { 25, 7 },
124 { 200, 16 },
125 { 500, 25 },
126 { 800, 40 },
127 { 0, 0 } // Placeholder
130 // Last received device ('hard') states
132 smartAudioDevice_t saDevice = {
133 .version = SA_UNKNOWN,
134 .channel = SETTING_VTX_CHANNEL_DEFAULT,
135 .power = SETTING_VTX_POWER_DEFAULT,
136 .mode = 0,
137 .freq = 0,
138 .orfreq = 0,
139 .willBootIntoPitMode = false
142 static smartAudioDevice_t saDevicePrev = {
143 .version = 0,
146 // XXX Possible compliance problem here. Need LOCK/UNLOCK menu?
147 static uint8_t saLockMode = SA_MODE_SET_UNLOCK; // saCms variable?
149 // XXX Should be configurable by user?
150 bool saDeferred = true; // saCms variable?
152 // Receive frame reassembly buffer
153 #define SA_MAX_RCVLEN 21
154 static uint8_t sa_rbuf[SA_MAX_RCVLEN+4]; // XXX delete 4 byte guard
157 // CRC8 computations
160 #define POLYGEN 0xd5
162 static uint8_t CRC8(const uint8_t *data, const int8_t len)
164 uint8_t crc = 0; /* start with 0 so first byte can be 'xored' in */
165 uint8_t currByte;
167 for (int i = 0 ; i < len ; i++) {
168 currByte = data[i];
170 crc ^= currByte; /* XOR-in the next input byte */
172 for (int i = 0; i < 8; i++) {
173 if ((crc & 0x80) != 0) {
174 crc = (uint8_t)((crc << 1) ^ POLYGEN);
175 } else {
176 crc <<= 1;
180 return crc;
184 static void saPrintSettings(void)
186 LOG_DEBUG(VTX, "Current status: version: %d", saDevice.version);
187 LOG_DEBUG(VTX, " mode(0x%x): fmode=%s", saDevice.mode, (saDevice.mode & 1) ? "freq" : "chan");
188 LOG_DEBUG(VTX, " pit=%s ", (saDevice.mode & 2) ? "on " : "off");
189 LOG_DEBUG(VTX, " inb=%s", (saDevice.mode & 4) ? "on " : "off");
190 LOG_DEBUG(VTX, " outb=%s", (saDevice.mode & 8) ? "on " : "off");
191 LOG_DEBUG(VTX, " lock=%s", (saDevice.mode & 16) ? "unlocked" : "locked");
192 LOG_DEBUG(VTX, " deferred=%s", (saDevice.mode & 32) ? "on" : "off");
193 LOG_DEBUG(VTX, " channel: %d ", saDevice.channel);
194 LOG_DEBUG(VTX, "freq: %d ", saDevice.freq);
195 LOG_DEBUG(VTX, "power: %d ", saDevice.power);
196 LOG_DEBUG(VTX, "pitfreq: %d ", saDevice.orfreq);
197 LOG_DEBUG(VTX, "BootIntoPitMode: %s", saDevice.willBootIntoPitMode ? "yes" : "no");
200 int saDacToPowerIndex(int dac)
202 for (int idx = saPowerCount - 1 ; idx >= 0 ; idx--) {
203 if (saPowerTable[idx].dbi <= dac) {
204 return idx;
207 return 0;
210 int saDbiToMw(uint16_t dbi) {
212 uint16_t mw = (uint16_t)pow(10.0, dbi / 10.0);
214 if (dbi > 14) {
215 // For powers greater than 25mW round up to a multiple of 50 to match expectations
216 mw = 50 * ((mw + 25) / 50);
219 return mw;
223 // Autobauding
226 #define SMARTBAUD_MIN 4800
227 #define SMARTBAUD_MAX 4950
228 uint16_t sa_smartbaud = SMARTBAUD_MIN;
229 static int sa_adjdir = 1; // -1=going down, 1=going up
230 static int sa_baudstep = 50;
232 static void saAutobaud(void)
234 if (saStat.pktsent < 10) {
235 // Not enough samples collected
236 return;
239 if (((saStat.pktrcvd * 100) / saStat.pktsent) >= 70) {
240 // This is okay
241 saStat.pktsent = 0; // Should be more moderate?
242 saStat.pktrcvd = 0;
243 return;
246 LOG_DEBUG(VTX, "autobaud: adjusting");
248 if ((sa_adjdir == 1) && (sa_smartbaud == SMARTBAUD_MAX)) {
249 sa_adjdir = -1;
250 LOG_DEBUG(VTX, "autobaud: now going down");
251 } else if ((sa_adjdir == -1 && sa_smartbaud == SMARTBAUD_MIN)) {
252 sa_adjdir = 1;
253 LOG_DEBUG(VTX, "autobaud: now going up");
256 sa_smartbaud += sa_baudstep * sa_adjdir;
258 LOG_DEBUG(VTX, "autobaud: %d", sa_smartbaud);
260 smartAudioSerialPort->vTable->serialSetBaudRate(smartAudioSerialPort, sa_smartbaud);
262 saStat.pktsent = 0;
263 saStat.pktrcvd = 0;
266 // Transport level variables
268 static timeUs_t sa_lastTransmissionMs = 0;
269 static uint8_t sa_outstanding = SA_CMD_NONE; // Outstanding command
270 static uint8_t sa_osbuf[32]; // Outstanding comamnd frame for retransmission
271 static int sa_oslen; // And associate length
273 static void saProcessResponse(uint8_t *buf, int len)
275 uint8_t resp = buf[0];
277 if (resp == sa_outstanding) {
278 sa_outstanding = SA_CMD_NONE;
279 } else if ((resp == SA_CMD_GET_SETTINGS_V2 || resp == SA_CMD_GET_SETTINGS_V21) && (sa_outstanding == SA_CMD_GET_SETTINGS)) {
280 sa_outstanding = SA_CMD_NONE;
281 } else {
282 saStat.ooopresp++;
283 LOG_DEBUG(VTX, "processResponse: outstanding %d got %d", sa_outstanding, resp);
286 switch (resp) {
287 case SA_CMD_GET_SETTINGS_V21: // Version 2.1 Get Settings
288 case SA_CMD_GET_SETTINGS_V2: // Version 2 Get Settings
289 case SA_CMD_GET_SETTINGS: // Version 1 Get Settings
290 if (len < 7) {
291 break;
294 // From spec: "Bit 7-3 is holding the Smart audio version where 0 is V1, 1 is V2, 2 is V2.1"
295 // saDevice.version = 0 means unknown, 1 means Smart audio V1, 2 means Smart audio V2 and 3 means Smart audio V2.1
296 saDevice.version = (buf[0] == SA_CMD_GET_SETTINGS) ? 1 : ((buf[0] == SA_CMD_GET_SETTINGS_V2) ? 2 : 3);
297 saDevice.channel = buf[2];
298 uint8_t rawPowerValue = buf[3];
299 saDevice.mode = buf[4];
300 saDevice.freq = (buf[5] << 8) | buf[6];
302 // read pir and por flags to detect if the device will boot into pitmode.
303 // note that "quit pitmode without unsetting the pitmode flag" clears pir and por flags but the device will still boot into pitmode.
304 // therefore we ignore the pir and por flags while the device is not in pitmode
305 // actually, this is the whole reason the variable saDevice.willBootIntoPitMode exists.
306 // otherwise we could use saDevice.mode directly
307 if (saDevice.mode & SA_MODE_GET_PITMODE) {
308 bool newBootMode = (saDevice.mode & SA_MODE_GET_IN_RANGE_PITMODE) || (saDevice.mode & SA_MODE_GET_OUT_RANGE_PITMODE);
309 if (newBootMode != saDevice.willBootIntoPitMode) {
310 LOG_DEBUG(VTX, "saProcessResponse: willBootIntoPitMode is now %s\r\n", newBootMode ? "true" : "false");
312 saDevice.willBootIntoPitMode = newBootMode;
315 if(saDevice.version == SA_2_1) {
316 //read dbm based power levels
317 if(len < 10) { //current power level in dbm field missing or power level length field missing or zero power levels reported
318 LOG_DEBUG(VTX, "processResponse: V2.1 vtx didn't report any power levels\r\n");
319 break;
321 saPowerCount = constrain((int8_t)buf[8], 0, VTX_SMARTAUDIO_MAX_POWER_COUNT);
322 vtxSmartAudio.capability.powerCount = saPowerCount;
323 //SmartAudio seems to report buf[8] + 1 power levels, but one of them is zero.
324 //zero is indeed a valid power level to set the vtx to, but it activates pit mode.
325 //crucially, after sending 0 dbm, the vtx does NOT report its power level to be 0 dbm.
326 //instead, it reports whatever value was set previously and it reports to be in pit mode.
327 //for this reason, zero shouldn't be used as a normal power level in INAV.
328 for (int8_t i = 0; i < saPowerCount; i++ ) {
329 saPowerTable[i].dbi = buf[9 + i + 1]; //+ 1 to skip the first power level, as mentioned above
330 saPowerTable[i].mW = saDbiToMw(saPowerTable[i].dbi);
331 if (i <= VTX_SMARTAUDIO_MAX_POWER_COUNT) {
332 char strbuf[5];
333 itoa(saPowerTable[i].mW, strbuf, 10);
334 strcpy(sa21PowerNames[i], strbuf);
335 saPowerNames[i + 1] = sa21PowerNames[i];
339 LOG_DEBUG(VTX, "processResponse: %d power values: %d, %d, %d, %d\r\n",
340 saPowerCount, saPowerTable[0].dbi, saPowerTable[1].dbi,
341 saPowerTable[2].dbi, saPowerTable[3].dbi);
342 //LOG_DEBUG(VTX, "processResponse: V2.1 received vtx power value %d\r\n",buf[7]);
343 rawPowerValue = buf[7];
345 saDevice.power = 0; //set to unknown power level if the reported one doesnt match any of the known ones
346 LOG_DEBUG(VTX, "processResponse: rawPowerValue is %d, legacy power is %d\r\n", rawPowerValue, buf[3]);
347 for (int8_t i = 0; i < saPowerCount; i++) {
348 if (rawPowerValue == saPowerTable[i].dbi) {
349 saDevice.power = i + 1;
352 } else {
353 saDevice.power = rawPowerValue + 1;
356 DEBUG_SET(DEBUG_SMARTAUDIO, 0, saDevice.version * 100 + saDevice.mode);
357 DEBUG_SET(DEBUG_SMARTAUDIO, 1, saDevice.channel);
358 DEBUG_SET(DEBUG_SMARTAUDIO, 2, saDevice.freq);
359 DEBUG_SET(DEBUG_SMARTAUDIO, 3, saDevice.power);
360 break;
362 case SA_CMD_SET_POWER: // Set Power
363 break;
365 case SA_CMD_SET_CHAN: // Set Channel
366 break;
368 case SA_CMD_SET_FREQ: // Set Frequency
369 if (len < 5) {
370 break;
373 const uint16_t freq = (buf[2] << 8)|buf[3];
375 if (freq & SA_FREQ_GETPIT) {
376 saDevice.orfreq = freq & SA_FREQ_MASK;
377 LOG_DEBUG(VTX, "saProcessResponse: GETPIT freq %d", saDevice.orfreq);
378 } else if (freq & SA_FREQ_SETPIT) {
379 saDevice.orfreq = freq & SA_FREQ_MASK;
380 LOG_DEBUG(VTX, "saProcessResponse: SETPIT freq %d", saDevice.orfreq);
381 } else {
382 saDevice.freq = freq;
383 LOG_DEBUG(VTX, "saProcessResponse: SETFREQ freq %d", freq);
385 break;
387 case SA_CMD_SET_MODE: // Set Mode
388 LOG_DEBUG(VTX, "saProcessResponse: SET_MODE 0x%x, (pir %s, por %s, pitdsbl %s, %s)\r\n",
389 buf[2], (buf[2] & 1) ? "on" : "off", (buf[2] & 2) ? "on" : "off", (buf[3] & 4) ? "on" : "off",
390 (buf[4] & 8) ? "unlocked" : "locked");
391 break;
393 default:
394 saStat.badcode++;
395 return;
398 if (memcmp(&saDevice, &saDevicePrev, sizeof(smartAudioDevice_t))) {
399 // Debug
400 saPrintSettings();
403 saDevicePrev = saDevice;
407 // Datalink
410 static void saReceiveFramer(uint8_t c)
413 static enum saFramerState_e {
414 S_WAITPRE1, // Waiting for preamble 1 (0xAA)
415 S_WAITPRE2, // Waiting for preamble 2 (0x55)
416 S_WAITRESP, // Waiting for response code
417 S_WAITLEN, // Waiting for length
418 S_DATA, // Receiving data
419 S_WAITCRC, // Waiting for CRC
420 } state = S_WAITPRE1;
422 static int len;
423 static int dlen;
425 switch (state) {
426 case S_WAITPRE1:
427 if (c == 0xAA) {
428 state = S_WAITPRE2;
429 } else {
430 state = S_WAITPRE1; // Don't need this (no change)
432 break;
434 case S_WAITPRE2:
435 if (c == 0x55) {
436 state = S_WAITRESP;
437 } else {
438 saStat.badpre++;
439 state = S_WAITPRE1;
441 break;
443 case S_WAITRESP:
444 sa_rbuf[0] = c;
445 state = S_WAITLEN;
446 break;
448 case S_WAITLEN:
449 sa_rbuf[1] = c;
450 len = c;
452 if (len > SA_MAX_RCVLEN - 2) {
453 saStat.badlen++;
454 state = S_WAITPRE1;
455 } else if (len == 0) {
456 state = S_WAITCRC;
457 } else {
458 dlen = 0;
459 state = S_DATA;
461 break;
463 case S_DATA:
464 // XXX Should check buffer overflow (-> saerr_overflow)
465 sa_rbuf[2 + dlen] = c;
466 if (++dlen == len) {
467 state = S_WAITCRC;
469 break;
471 case S_WAITCRC:
472 if (CRC8(sa_rbuf, 2 + len) == c) {
473 // Got a response
474 saProcessResponse(sa_rbuf, len + 2);
475 saStat.pktrcvd++;
476 } else if (sa_rbuf[0] & 1) {
477 // Command echo
478 // XXX There is an exceptional case (V2 response)
479 // XXX Should check crc in the command format?
480 } else {
481 saStat.crc++;
483 state = S_WAITPRE1;
484 break;
488 static void saSendFrame(uint8_t *buf, int len)
490 if ( (vtxConfig()->smartAudioAltSoftSerialMethod &&
491 (smartAudioSerialPort->identifier == SERIAL_PORT_SOFTSERIAL1 || smartAudioSerialPort->identifier == SERIAL_PORT_SOFTSERIAL2))
492 == false) {
493 // TBS SA definition requires that the line is low before frame is sent
494 // (for both soft and hard serial). It can be done by sending first 0x00
495 serialWrite(smartAudioSerialPort, 0x00);
498 for (int i = 0 ; i < len ; i++) {
499 serialWrite(smartAudioSerialPort, buf[i]);
502 // XXX: Workaround for early AKK SAudio-enabled VTX bug,
503 // shouldn't cause any problems with VTX with properly
504 // implemented SAudio.
505 //Update: causes problem with new AKK AIO camera connected to SoftUART
506 if (vtxConfig()->smartAudioEarlyAkkWorkaroundEnable) serialWrite(smartAudioSerialPort, 0x00);
508 sa_lastTransmissionMs = millis();
509 saStat.pktsent++;
513 * Retransmission and command queuing
515 * The transport level support includes retransmission on response timeout
516 * and command queueing.
518 * Resend buffer:
519 * The smartaudio returns response for valid command frames in no less
520 * than 60msec, which we can't wait. So there's a need for a resend buffer.
522 * Command queueing:
523 * The driver autonomously sends GetSettings command for auto-bauding,
524 * asynchronous to user initiated commands; commands issued while another
525 * command is outstanding must be queued for later processing.
526 * The queueing also handles the case in which multiple commands are
527 * required to implement a user level command.
530 // Retransmission
532 static void saResendCmd(void)
534 saSendFrame(sa_osbuf, sa_oslen);
537 static void saSendCmd(uint8_t *buf, int len)
539 for (int i = 0 ; i < len ; i++) {
540 sa_osbuf[i] = buf[i];
543 sa_oslen = len;
544 sa_outstanding = (buf[2] >> 1);
546 saSendFrame(sa_osbuf, sa_oslen);
549 // Command queue management
551 typedef struct saCmdQueue_s {
552 uint8_t *buf;
553 int len;
554 } saCmdQueue_t;
556 #define SA_QSIZE 6 // 1 heartbeat (GetSettings) + 2 commands + 1 slack
557 static saCmdQueue_t sa_queue[SA_QSIZE];
558 static uint8_t sa_qhead = 0;
559 static uint8_t sa_qtail = 0;
561 static bool saQueueEmpty(void)
563 return sa_qhead == sa_qtail;
566 static bool saQueueFull(void)
568 return ((sa_qhead + 1) % SA_QSIZE) == sa_qtail;
571 static void saQueueCmd(uint8_t *buf, int len)
573 if (saQueueFull()) {
574 return;
577 sa_queue[sa_qhead].buf = buf;
578 sa_queue[sa_qhead].len = len;
579 sa_qhead = (sa_qhead + 1) % SA_QSIZE;
582 static void saSendQueue(void)
584 if (saQueueEmpty()) {
585 return;
588 saSendCmd(sa_queue[sa_qtail].buf, sa_queue[sa_qtail].len);
589 sa_qtail = (sa_qtail + 1) % SA_QSIZE;
592 // Individual commands
594 static void saGetSettings(void)
596 static uint8_t bufGetSettings[5] = {0xAA, 0x55, SACMD(SA_CMD_GET_SETTINGS), 0x00, 0x9F};
598 LOG_DEBUG(VTX, "smartAudioGetSettings\r\n");
599 saQueueCmd(bufGetSettings, 5);
602 void saSetFreq(uint16_t freq)
604 static uint8_t buf[7] = { 0xAA, 0x55, SACMD(SA_CMD_SET_FREQ), 2 };
605 static uint8_t switchBuf[7];
607 if (freq & SA_FREQ_GETPIT) {
608 LOG_DEBUG(VTX, "smartAudioSetFreq: GETPIT");
609 } else if (freq & SA_FREQ_SETPIT) {
610 LOG_DEBUG(VTX, "smartAudioSetFreq: SETPIT %d", freq & SA_FREQ_MASK);
611 } else {
612 LOG_DEBUG(VTX, "smartAudioSetFreq: SET %d", freq);
615 buf[4] = (freq >> 8) & 0xff;
616 buf[5] = freq & 0xff;
617 buf[6] = CRC8(buf, 6);
619 // Need to work around apparent SmartAudio bug when going from 'channel'
620 // to 'user-freq' mode, where the set-freq command will fail if the freq
621 // value is unchanged from the previous 'user-freq' mode
622 if ((saDevice.mode & SA_MODE_GET_FREQ_BY_FREQ) == 0 && freq == saDevice.freq) {
623 memcpy(&switchBuf, &buf, sizeof(buf));
624 const uint16_t switchFreq = freq + ((freq == VTX_SMARTAUDIO_MAX_FREQUENCY_MHZ) ? -1 : 1);
625 switchBuf[4] = (switchFreq >> 8);
626 switchBuf[5] = switchFreq & 0xff;
627 switchBuf[6] = CRC8(switchBuf, 6);
629 saQueueCmd(switchBuf, 7);
632 saQueueCmd(buf, 7);
635 void saSetPitFreq(uint16_t freq)
637 saSetFreq(freq | SA_FREQ_SETPIT);
640 static bool saValidateBandAndChannel(uint8_t band, uint8_t channel)
642 return (band >= VTX_SMARTAUDIO_MIN_BAND && band <= VTX_SMARTAUDIO_MAX_BAND &&
643 channel >= VTX_SMARTAUDIO_MIN_CHANNEL && channel <= VTX_SMARTAUDIO_MAX_CHANNEL);
646 void saSetBandAndChannel(uint8_t band, uint8_t channel)
648 static uint8_t buf[6] = { 0xAA, 0x55, SACMD(SA_CMD_SET_CHAN), 1 };
650 buf[4] = SA_BANDCHAN_TO_DEVICE_CHVAL(band, channel);
651 buf[5] = CRC8(buf, 5);
652 LOG_DEBUG(VTX, "vtxSASetBandAndChannel set index band %d channel %d value sent 0x%x\r\n", band, channel, buf[4]);
654 //this will clear saDevice.mode & SA_MODE_GET_FREQ_BY_FREQ
655 saQueueCmd(buf, 6);
658 void saSetMode(int mode)
660 static uint8_t buf[6] = { 0xAA, 0x55, SACMD(SA_CMD_SET_MODE), 1 };
662 buf[4] = (mode & 0x3f) | saLockMode;
663 if (saDevice.version >= SA_2_1 && (mode & SA_MODE_CLR_PITMODE) &&
664 ((mode & SA_MODE_SET_IN_RANGE_PITMODE) || (mode & SA_MODE_SET_OUT_RANGE_PITMODE))) {
665 saDevice.willBootIntoPitMode = true;//quit pitmode without unsetting flag.
666 //the response will just say pit=off but the device will still go into pitmode on reboot.
667 //therefore we have to memorize this change here.
669 LOG_DEBUG(VTX, "saSetMode(0x%x): pir=%s por=%s pitdsbl=%s %s\r\n", mode, (mode & 1) ? "on " : "off", (mode & 2) ? "on " : "off",
670 (mode & 4)? "on " : "off", (mode & 8) ? "locked" : "unlocked");
672 buf[5] = CRC8(buf, 5);
673 saQueueCmd(buf, 6);
676 bool vtxSmartAudioInit(void)
678 serialPortConfig_t *portConfig = findSerialPortConfig(FUNCTION_VTX_SMARTAUDIO);
679 if (portConfig) {
680 portOptions_t portOptions = (vtxConfig()->smartAudioStopBits == 2 ? SERIAL_STOPBITS_2 : SERIAL_STOPBITS_1) | SERIAL_BIDIR_NOPULL;
681 portOptions = portOptions | (vtxConfig()->halfDuplex ? SERIAL_BIDIR | SERIAL_BIDIR_PP : SERIAL_UNIDIR);
682 smartAudioSerialPort = openSerialPort(portConfig->identifier, FUNCTION_VTX_SMARTAUDIO, NULL, NULL, 4800, MODE_RXTX, portOptions);
685 if (!smartAudioSerialPort) {
686 return false;
689 vtxCommonSetDevice(&vtxSmartAudio);
691 return true;
694 #define SA_INITPHASE_START 0
695 #define SA_INITPHASE_WAIT_SETTINGS 1 // SA_CMD_GET_SETTINGS was sent and waiting for reply.
696 #define SA_INITPHASE_WAIT_PITFREQ 2 // SA_FREQ_GETPIT sent and waiting for reply.
697 #define SA_INITPHASE_DONE 3
699 static void vtxSAProcess(vtxDevice_t *vtxDevice, timeUs_t currentTimeUs)
701 UNUSED(vtxDevice);
702 UNUSED(currentTimeUs);
704 static char initPhase = SA_INITPHASE_START;
706 if (smartAudioSerialPort == NULL) {
707 return;
710 while (serialRxBytesWaiting(smartAudioSerialPort) > 0) {
711 uint8_t c = serialRead(smartAudioSerialPort);
712 saReceiveFramer((uint16_t)c);
715 // Re-evaluate baudrate after each frame reception
716 saAutobaud();
718 switch (initPhase) {
719 case SA_INITPHASE_START:
720 saGetSettings();
721 //saSendQueue();
722 initPhase = SA_INITPHASE_WAIT_SETTINGS;
723 break;
725 case SA_INITPHASE_WAIT_SETTINGS:
726 // Don't send SA_FREQ_GETPIT to V1 device; it act as plain SA_CMD_SET_FREQ,
727 // and put the device into user frequency mode with uninitialized freq.
728 if (saDevice.version) {
729 if (saDevice.version == SA_2_0) {
730 saSetFreq(SA_FREQ_GETPIT);
731 initPhase = SA_INITPHASE_WAIT_PITFREQ;
732 } else {
733 initPhase = SA_INITPHASE_DONE;
735 if (saDevice.version >= SA_2_0 ) {
736 //did the device boot up in pit mode on its own?
737 saDevice.willBootIntoPitMode = (saDevice.mode & SA_MODE_GET_PITMODE) ? true : false;
738 LOG_DEBUG(VTX, "sainit: willBootIntoPitMode is %s\r\n", saDevice.willBootIntoPitMode ? "true" : "false");
741 break;
743 case SA_INITPHASE_WAIT_PITFREQ:
744 if (saDevice.orfreq) {
745 initPhase = SA_INITPHASE_DONE;
747 break;
749 case SA_INITPHASE_DONE:
750 break;
753 // Command queue control
755 timeMs_t nowMs = millis(); // Don't substitute with "currentTimeUs / 1000"; sa_lastTransmissionMs is based on millis().
756 static timeMs_t lastCommandSentMs = 0; // Last non-GET_SETTINGS sent
758 if ((sa_outstanding != SA_CMD_NONE) && (nowMs - sa_lastTransmissionMs > SMARTAUDIO_CMD_TIMEOUT)) {
759 // Last command timed out
760 // LOG_DEBUG(VTX, "process: resending 0x%x", sa_outstanding);
761 // XXX Todo: Resend termination and possible offline transition
762 saResendCmd();
763 lastCommandSentMs = nowMs;
764 } else if (!saQueueEmpty()) {
765 // Command pending. Send it.
766 // LOG_DEBUG(VTX, "process: sending queue");
767 saSendQueue();
768 lastCommandSentMs = nowMs;
769 } else if ((nowMs - lastCommandSentMs < SMARTAUDIO_POLLING_WINDOW) && (nowMs - sa_lastTransmissionMs >= SMARTAUDIO_POLLING_INTERVAL)) {
770 //LOG_DEBUG(VTX, "process: sending status change polling");
771 saGetSettings();
772 saSendQueue();
776 // Interface to common VTX API
778 vtxDevType_e vtxSAGetDeviceType(const vtxDevice_t *vtxDevice)
780 UNUSED(vtxDevice);
781 return VTXDEV_SMARTAUDIO;
784 static bool vtxSAIsReady(const vtxDevice_t *vtxDevice)
786 return vtxDevice != NULL && !(saDevice.power == 0);
787 //wait until power reading exists
790 void vtxSASetBandAndChannel(vtxDevice_t *vtxDevice, uint8_t band, uint8_t channel)
792 UNUSED(vtxDevice);
793 if (saValidateBandAndChannel(band, channel)) {
794 saSetBandAndChannel(band - 1, channel - 1);
797 static void vtxSASetPowerByIndex(vtxDevice_t *vtxDevice, uint8_t index)
799 static uint8_t buf[6] = { 0xAA, 0x55, SACMD(SA_CMD_SET_POWER), 1 };
801 if (!vtxSAIsReady(vtxDevice)) {
802 return;
805 if (index == 0) {
806 LOG_DEBUG(VTX, "SmartAudio doesn't support power off");
807 return;
810 if (index > saPowerCount) {
811 LOG_DEBUG(VTX, "Invalid power level");
812 return;
815 LOG_DEBUG(VTX, "saSetPowerByIndex: index %d, value %d\r\n", index, buf[4]);
817 index--;
818 switch (saDevice.version) {
819 case SA_1_0:
820 buf[4] = saPowerTable[index].dbi;
821 break;
822 case SA_2_0:
823 buf[4] = index;
824 break;
825 case SA_2_1:
826 buf[4] = saPowerTable[index].dbi;
827 buf[4] |= 128; //set MSB to indicate set power by dbm
828 break;
829 default:
830 break;
833 buf[5] = CRC8(buf, 5);
834 saQueueCmd(buf, 6);
837 static void vtxSASetPitMode(vtxDevice_t *vtxDevice, uint8_t onoff)
839 if (!vtxSAIsReady(vtxDevice) || saDevice.version < SA_1_0) {
840 return;
843 if (onoff && saDevice.version < SA_2_1) {
844 // Smart Audio prior to V2.1 can not turn pit mode on by software.
845 return;
848 if (saDevice.version >= SA_2_1 && !saDevice.willBootIntoPitMode) {
849 if (onoff) {
850 // enable pitmode using SET_POWER command with 0 dbm.
851 // This enables pitmode without causing the device to boot into pitmode next power-up
852 static uint8_t buf[6] = { 0xAA, 0x55, SACMD(SA_CMD_SET_POWER), 1 };
853 buf[4] = 0 | 128;
854 buf[5] = CRC8(buf, 5);
855 saQueueCmd(buf, 6);
856 LOG_DEBUG(VTX, "vtxSASetPitMode: set power to 0 dbm\r\n");
857 } else {
858 saSetMode(SA_MODE_CLR_PITMODE);
859 LOG_DEBUG(VTX, "vtxSASetPitMode: clear pitmode permanently");
861 return;
864 uint8_t newMode = onoff ? 0 : SA_MODE_CLR_PITMODE;
866 if (saDevice.mode & SA_MODE_GET_OUT_RANGE_PITMODE) {
867 newMode |= SA_MODE_SET_OUT_RANGE_PITMODE;
870 if ((saDevice.mode & SA_MODE_GET_IN_RANGE_PITMODE) || (onoff && newMode == 0)) {
871 // ensure when turning on pit mode that pit mode gets actually enabled
872 newMode |= SA_MODE_SET_IN_RANGE_PITMODE;
874 LOG_DEBUG(VTX, "vtxSASetPitMode %s with stored mode 0x%x por %s, pir %s, newMode 0x%x\r\n", onoff ? "on" : "off", saDevice.mode,
875 (saDevice.mode & SA_MODE_GET_OUT_RANGE_PITMODE) ? "on" : "off",
876 (saDevice.mode & SA_MODE_GET_IN_RANGE_PITMODE) ? "on" : "off" , newMode);
879 saSetMode(newMode);
881 return;
884 static bool vtxSAGetBandAndChannel(const vtxDevice_t *vtxDevice, uint8_t *pBand, uint8_t *pChannel)
886 if (!vtxSAIsReady(vtxDevice)) {
887 return false;
890 // if in user-freq mode then report band as zero
891 *pBand = (saDevice.mode & SA_MODE_GET_FREQ_BY_FREQ) ? 0 :
892 (SA_DEVICE_CHVAL_TO_BAND(saDevice.channel) + 1);
893 *pChannel = SA_DEVICE_CHVAL_TO_CHANNEL(saDevice.channel) + 1;
895 return true;
898 static bool vtxSAGetPowerIndex(const vtxDevice_t *vtxDevice, uint8_t *pIndex)
900 if (!vtxSAIsReady(vtxDevice)) {
901 return false;
904 *pIndex = ((saDevice.version == SA_1_0) ? saDacToPowerIndex(saDevice.power) : saDevice.power);
905 return true;
908 static bool vtxSAGetPitMode(const vtxDevice_t *vtxDevice, uint8_t *pOnOff)
910 if (!(vtxSAIsReady(vtxDevice) && (saDevice.version < SA_2_0))) {
911 return false;
914 *pOnOff = (saDevice.mode & SA_MODE_GET_PITMODE) ? 1 : 0;
915 return true;
918 static bool vtxSAGetFreq(const vtxDevice_t *vtxDevice, uint16_t *pFreq)
920 if (!vtxSAIsReady(vtxDevice)) {
921 return false;
924 // if not in user-freq mode then convert band/chan to frequency
925 *pFreq = (saDevice.mode & SA_MODE_GET_FREQ_BY_FREQ) ? saDevice.freq :
926 vtx58_Bandchan2Freq(SA_DEVICE_CHVAL_TO_BAND(saDevice.channel) + 1,
927 SA_DEVICE_CHVAL_TO_CHANNEL(saDevice.channel) + 1);
928 return true;
931 static bool vtxSAGetPower(const vtxDevice_t *vtxDevice, uint8_t *pIndex, uint16_t *pPowerMw)
933 uint8_t powerIndex;
935 if (!vtxSAGetPowerIndex(vtxDevice, &powerIndex)) {
936 return false;
939 *pIndex = powerIndex;
940 *pPowerMw = (powerIndex > 0) ? saPowerTable[powerIndex - 1].mW : 0;
941 return true;
944 static bool vtxSAGetOsdInfo(const vtxDevice_t *vtxDevice, vtxDeviceOsdInfo_t * pOsdInfo)
946 uint8_t powerIndex;
947 uint16_t powerMw;
948 uint16_t freq;
949 uint8_t band, channel;
951 if (!vtxSAGetBandAndChannel(vtxDevice, &band, &channel)) {
952 return false;
955 if (!vtxSAGetFreq(vtxDevice, &freq)) {
956 return false;
959 if (!vtxSAGetPower(vtxDevice, &powerIndex, &powerMw)) {
960 return false;
963 pOsdInfo->band = band;
964 pOsdInfo->channel = channel;
965 pOsdInfo->frequency = freq;
966 pOsdInfo->powerIndex = powerIndex;
967 pOsdInfo->powerMilliwatt = powerMw;
968 pOsdInfo->bandLetter = vtx58BandNames[band][0];
969 pOsdInfo->bandName = vtx58BandNames[band];
970 pOsdInfo->channelName = vtx58ChannelNames[channel];
971 pOsdInfo->powerIndexLetter = '0' + powerIndex;
972 return true;
975 static const vtxVTable_t saVTable = {
976 .process = vtxSAProcess,
977 .getDeviceType = vtxSAGetDeviceType,
978 .isReady = vtxSAIsReady,
979 .setBandAndChannel = vtxSASetBandAndChannel,
980 .setPowerByIndex = vtxSASetPowerByIndex,
981 .setPitMode = vtxSASetPitMode,
982 .getBandAndChannel = vtxSAGetBandAndChannel,
983 .getPowerIndex = vtxSAGetPowerIndex,
984 .getPitMode = vtxSAGetPitMode,
985 .getFrequency = vtxSAGetFreq,
986 .getPower = vtxSAGetPower,
987 .getOsdInfo = vtxSAGetOsdInfo,
991 #endif // VTX_SMARTAUDIO