AP_Radio_bk2425.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. This program is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program. If not, see <http://www.gnu.org/licenses/>.
  12. */
  13. #pragma once
  14. /*
  15. AP_Radio implementation for CC2500 2.4GHz radio.
  16. With thanks to cleanflight and betaflight projects
  17. */
  18. #include "AP_Radio_backend.h"
  19. #if defined(HAL_RCINPUT_WITH_AP_RADIO) && CONFIG_HAL_BOARD_SUBTYPE == HAL_BOARD_SUBTYPE_CHIBIOS_SKYVIPER_F412
  20. #include "hal.h"
  21. #include "telem_structure.h"
  22. #include "driver_bk2425.h"
  23. #define BEKEN_MAX_CHANNELS 16
  24. // Documentation of the expected RSSI values. These are determined by the Cypress chip.
  25. enum {
  26. BK_RSSI_MIN = 0, // Minimum value for RSSI
  27. BK_RSSI_DEFAULT = 16, // The default value for RSSI for chips that do not support it.
  28. BK_RSSI_MAX = 31 // Maximum value for RSSI
  29. };
  30. // This helper struct estimates the times (in microseconds) between packets,
  31. // according to the STM32 clock which may well be 2% different from the STM8 clock.
  32. // For instance it may be 5108 instead of the nominal 5000 microseconds.
  33. struct SyncTiming {
  34. enum { TARGET_DELTA_RX = 5000, // Nominal 5ms between packets is expected
  35. SLOP_DELTA_RX = TARGET_DELTA_RX / 10, // +/- 500us i.e. 10% skew each way is accepted.
  36. DIFF_DELTA_RX = TARGET_DELTA_RX / 100
  37. }; // Two consequetive deltas must be very close together (50us)
  38. uint32_t packet_timer; // Time we last received a valid control packet
  39. uint32_t rx_time_us; // Time we last received a packet
  40. uint32_t tx_time_us; // Time we last finished transmitting a packet
  41. uint32_t delta_rx_time_us; // Time between last rx packets
  42. uint32_t last_delta_rx_time_us; // previous version of the delta
  43. uint32_t sync_time_us; // Estimate of base time in microseconds between packets. 5000 +/- 500
  44. SyncTiming() : // Constructor to setup sensible initial conditions
  45. delta_rx_time_us(TARGET_DELTA_RX),
  46. last_delta_rx_time_us(TARGET_DELTA_RX),
  47. sync_time_us(TARGET_DELTA_RX)
  48. {}
  49. void Rx(uint32_t when); // Adjust the timing based on a new packet
  50. };
  51. // Helper struct for synchronising channels when we change hopping table (e.g. learn of a WiFi channel change).
  52. struct SyncChannel {
  53. enum { countdown_invalid = 0 }; // When countdown is this value, no change is pending
  54. uint8_t channel; // Index within the channel hopping sequence. Corresponds to txChannel on the button board
  55. uint8_t lastchan; // Last requested index, if it is a factory test channel.
  56. uint8_t countdown; // How many packet slots until a pending table change occurs?
  57. uint8_t countdown_chan; // Which channel do we jump to when the table change happens?
  58. uint8_t hopping_current; // Which alternative channels are we on now
  59. uint8_t hopping_wanted; // Which alternative channels will we be on when Tx changes over?
  60. uint8_t hopping_countdown; // How many packet slots until a pending table change occurs?
  61. SyncChannel() : // Constructor to setup sensible initial conditions
  62. channel(0),
  63. lastchan(0),
  64. countdown(countdown_invalid),
  65. countdown_chan(0),
  66. hopping_current(0),
  67. hopping_wanted(0),
  68. hopping_countdown(countdown_invalid)
  69. {}
  70. void SetChannelIfSafe(uint8_t chan); // Check if valid channel index; we have received a packet describing the current channel index
  71. void SetChannel(uint8_t chan) // Already safe. We have received a packet describing the current channel index
  72. {
  73. channel = chan;
  74. }
  75. void SetCountdown(uint8_t cnt, uint8_t nextCh) // We receive a countdown to a non-normal channel change in the future
  76. {
  77. countdown = cnt;
  78. countdown_chan = nextCh;
  79. }
  80. void SetHopping(uint8_t cnt, uint8_t nextHopping) // We receive a countdown to a change in the adaptive table in the future/now
  81. {
  82. hopping_countdown = cnt;
  83. hopping_wanted = nextHopping;
  84. if (cnt == 0) {
  85. hopping_current = nextHopping;
  86. }
  87. }
  88. void NextChannel(void); // Step through the channels normally (taking countdowns into account)
  89. void SafeTable(void); // Give up on this WiFi table as packets have not been received
  90. };
  91. // This helper struct determines which physical channels are better
  92. struct SyncAdaptive {
  93. uint32_t missed[CHANNEL_FCC_HIGH+1]; // Missed
  94. uint32_t rx[CHANNEL_FCC_HIGH+1]; // Received
  95. uint8_t hopping; // Currently wanted hopping state. Send this to the tx.
  96. SyncAdaptive() : // Constructor to setup sensible initial conditions
  97. hopping(0)
  98. {}
  99. void Miss(uint8_t channel);
  100. void Get(uint8_t channel);
  101. void Invalidate()
  102. {
  103. hopping = 0; // e.g. if we have jumped tables
  104. }
  105. };
  106. // Support OTA upload. Assumes that mavlink offsets go from zero upwards contiguously
  107. struct FwUpload {
  108. enum { SZ_BUFFER = 128 }; // Must be a power of two
  109. mavlink_channel_t chan; // Reference for talking to mavlink subsystem
  110. uint8_t counter; // Used to throttle the upload, to prevent starvation of telemetry
  111. enum telem_type fw_type; // Whether we are uploading program code or a test tune
  112. // Data that is reset by reset()
  113. bool need_ack; // When true, we need to talk to mavlink subsystem (ask for more firmware)
  114. uint32_t added; // The number of bytes added to the queue
  115. uint32_t sent; // The number of bytes sent to the tx
  116. uint32_t acked; // The number of bytes acked by the tx
  117. bool rx_ack; // True each time we receive a non-zero ack from the tx
  118. bool rx_reboot; // True when we are in the rebooting process
  119. uint8_t pending_data[SZ_BUFFER]; // Pending data (from mavlink packets) circular buffer
  120. uint8_t pending_head; // Where mavlink packets are added (relative to pending_data[0])
  121. uint8_t pending_tail; // Where DFU packets are taken from (relative to pending_data[0])
  122. uint16_t file_length; // The length of the file, six more than the value stored in the first 16 bit word
  123. uint16_t file_length_round; // file_length rounded up to 0x80
  124. // Helper functions
  125. uint8_t pending_length()
  126. {
  127. return (pending_head - pending_tail) & (SZ_BUFFER-1);
  128. }
  129. uint8_t free_length()
  130. {
  131. return SZ_BUFFER - 1 - pending_length(); // Do not fill in the last byte in the circular buffer
  132. }
  133. void queue(const uint8_t *pSrc, uint8_t len); // Assumes sufficient room has been checked for
  134. void dequeue(uint8_t *pDst, uint8_t len); // Assumes sufficient data has been checked for
  135. void reset()
  136. {
  137. file_length = file_length_round = 0;
  138. added = sent = acked = 0;
  139. pending_head = pending_tail = 0;
  140. rx_reboot = rx_ack = need_ack = false;
  141. }
  142. };
  143. // Main class for receiving (and replying) to Beken radio packets
  144. class AP_Radio_beken : public AP_Radio_backend
  145. {
  146. public:
  147. // Override base class functions
  148. AP_Radio_beken(AP_Radio &radio); // Normal constructore
  149. bool init(void) override; // initialise the radio
  150. bool reset(void) override; // reset the radio
  151. bool send(const uint8_t *pkt, uint16_t len) override; // send a packet
  152. void start_recv_bind(void) override; // start bind process as a receiver
  153. uint32_t last_recv_us(void) override; // return time in microseconds of last received R/C packet
  154. uint8_t num_channels(void) override; // return number of input channels
  155. uint16_t read(uint8_t chan) override; // return current "PWM" (value) of a channel
  156. void handle_data_packet(mavlink_channel_t chan, const mavlink_data96_t &m) override; // handle a data96 mavlink packet for fw upload
  157. void update(void) override; // update status
  158. uint32_t get_tx_version(void) override // get TX fw version
  159. {
  160. // pack date into 16 bits for vendor_id in AUTOPILOT_VERSION
  161. return (uint16_t(tx_date.firmware_year)<<12) + (uint16_t(tx_date.firmware_month)<<8) + tx_date.firmware_day;
  162. }
  163. const AP_Radio::stats &get_stats(void) override; // get radio statistics structure
  164. // Extra public functions
  165. void set_wifi_channel(uint8_t channel) override
  166. {
  167. t_status.wifi_chan = channel; // set the 2.4GHz wifi channel used by companion computer, so it can be avoided
  168. }
  169. private:
  170. // Static functions, for interrupt support
  171. static void irq_handler_thd(void* arg);
  172. static void trigger_irq_radio_event(void);
  173. static void trigger_timeout_event(void *arg);
  174. // Private functions
  175. void radio_init(void);
  176. uint8_t ProcessPacket(const uint8_t* packet, uint8_t rxaddr);
  177. uint8_t ProcessBindPacket(const packetFormatRx * rx);
  178. void BadDroneId(void); // The tx we are listening to wants to talk to another drone
  179. void setChannel(uint8_t channel);
  180. void nextChannel(uint8_t skip);
  181. uint16_t calc_crc(uint8_t *data, uint8_t len);
  182. void irq_handler(uint32_t when);
  183. void irq_timeout(uint32_t when);
  184. void save_bind_info(void);
  185. bool load_bind_info(void);
  186. void UpdateFccScan(void);
  187. bool UpdateTxData(void);
  188. void map_stick_mode(void); // Support mode1,2,3,4 for stick mapping
  189. void update_SRT_telemetry(void);
  190. void check_fw_ack(void);
  191. // Static data, for interrupt support
  192. friend class SyncChannel; // For DebugPrintf support
  193. static AP_Radio_beken *radio_singleton; // Singleton pointer to the Beken radio instance
  194. static thread_t *_irq_handler_ctx;
  195. static virtual_timer_t timeout_vt;
  196. static uint32_t isr_irq_time_us; // Time the Beken IRQ was last triggered, in the handler interrupts (in microseconds)
  197. static uint32_t isr_timeout_time_us; // Time the timeout was last triggered (copied from irq_time_us via irq_when_us) (in microseconds)
  198. static uint32_t next_switch_us; // Time when we next want to switch radio channels (in microseconds)
  199. static uint32_t bind_time_ms; // Rough time in ms (milliseconds) when the last BIND command was received
  200. // Class data
  201. AP_HAL::OwnPtr<AP_HAL::SPIDevice> dev; // Low level support of SPI device
  202. HAL_Semaphore sem; // semaphore between ISR and main thread to protect fwupload
  203. AP_Radio::stats stats; // Radio stats (live) for the current time-period
  204. AP_Radio::stats last_stats; // Radio stats (snapshot) for the previous time-period
  205. uint16_t pwm_channels[BEKEN_MAX_CHANNELS]; // Channel data
  206. uint8_t chan_count; // Number of valid channels
  207. Radio_Beken beken; // The low level class for communicating to the Beken chip
  208. SyncChannel syncch; // Index within the channel hopping sequence. Corresponds to txChannel on the button board
  209. static SyncTiming synctm; // Timing between packets, according to the local clock (not the tx clock).
  210. uint32_t already_bound; // True when we have received packets from a tx after bootup. Prevent auto-binding to something else.
  211. FwUpload fwupload; // Support OTA upload
  212. SyncAdaptive adaptive; // Support adaptive hopping
  213. struct {
  214. uint8_t firmware_year;
  215. uint8_t firmware_month;
  216. uint8_t firmware_day;
  217. } tx_date;
  218. // Bind structure saved to storage
  219. static const uint16_t bind_magic = 0x120a;
  220. struct PACKED bind_info {
  221. uint16_t magic;
  222. uint8_t bindTxId[5]; // The transmission address I last used
  223. };
  224. // Received
  225. struct telem_status t_status; // Keep track of certain data that can be sent as telemetry to the tx.
  226. uint32_t last_pps_ms; // Timestamp of the last PPS (packets per second) calculation, in milliseconds.
  227. uint32_t tx_pps; // Last telemetry PPS received from Tx
  228. uint32_t have_tx_pps; // 0=never received, 1=received at least one, 2=received recently
  229. uint32_t valid_connection; // Take some time before admitting to ardupilot we have a connection
  230. uint32_t telem_send_count; // How many telemetry packets have i sent?
  231. // Parameters
  232. ITX_SPEED spd; // Speed of radio modulation.
  233. uint8_t myDroneId[4]; // CRC of the flight boards UUID, to inform the tx
  234. };
  235. #endif // HAL_RCINPUT_WITH_AP_RADIO