AP_GPS_SBP2.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. //
  14. // Swift Navigation SBP GPS driver for ArduPilot.
  15. // Code by Niels Joubert
  16. //
  17. // Swift Binary Protocol format: http://docs.swift-nav.com/
  18. //
  19. #include "AP_GPS.h"
  20. #include "AP_GPS_SBP2.h"
  21. #include <AP_Logger/AP_Logger.h>
  22. #include <GCS_MAVLink/GCS_MAVLink.h>
  23. #include <GCS_MAVLink/GCS.h>
  24. extern const AP_HAL::HAL& hal;
  25. #define SBP_DEBUGGING 0
  26. #define SBP_INFOREPORTING 1
  27. //INVARIANT: We expect SBP to give us a heartbeat in less than 2 seconds.
  28. // This is more lax than the default Piksi settings,
  29. // and we assume the user hasn't reconfigured their Piksi to longer heartbeat intervals
  30. #define SBP_TIMEOUT_HEARTBEAT 2000
  31. #if SBP_DEBUGGING
  32. # define Debug(fmt, args ...) \
  33. do { \
  34. hal.console->printf("%s:%d: " fmt "\n", \
  35. __FUNCTION__, __LINE__, \
  36. ## args); \
  37. hal.scheduler->delay(1); \
  38. } while(0)
  39. #else
  40. # define Debug(fmt, args ...)
  41. #endif
  42. #if SBP_INFOREPORTING
  43. # define Info(fmt, args ...) \
  44. do { \
  45. gcs().send_text(MAV_SEVERITY_INFO, fmt "\n", ## args); \
  46. } while(0)
  47. #else
  48. # define Info(fmt, args ...)
  49. #endif
  50. AP_GPS_SBP2::AP_GPS_SBP2(AP_GPS &_gps, AP_GPS::GPS_State &_state,
  51. AP_HAL::UARTDriver *_port) :
  52. AP_GPS_Backend(_gps, _state, _port)
  53. {
  54. Debug("SBP Driver Initialized");
  55. parser_state.state = sbp_parser_state_t::WAITING;
  56. }
  57. // Process all bytes available from the stream
  58. //
  59. bool
  60. AP_GPS_SBP2::read(void)
  61. {
  62. //Invariant: Calling this function processes *all* data current in the UART buffer.
  63. //
  64. //IMPORTANT NOTICE: This function is NOT CALLED for several seconds
  65. // during arming. That should not cause the driver to die. Process *all* waiting messages
  66. _sbp_process();
  67. return _attempt_state_update();
  68. }
  69. void
  70. AP_GPS_SBP2::inject_data(const uint8_t *data, uint16_t len)
  71. {
  72. if (port->txspace() > len) {
  73. last_injected_data_ms = AP_HAL::millis();
  74. port->write(data, len);
  75. } else {
  76. Debug("PIKSI: Not enough TXSPACE");
  77. }
  78. }
  79. //This attempts to reads all SBP messages from the incoming port.
  80. //Returns true if a new message was read, false if we failed to read a message.
  81. void
  82. AP_GPS_SBP2::_sbp_process()
  83. {
  84. uint32_t nleft = port->available();
  85. while (nleft > 0) {
  86. nleft--;
  87. uint8_t temp = port->read();
  88. uint16_t crc;
  89. //This switch reads one character at a time,
  90. //parsing it into buffers until a full message is dispatched
  91. switch (parser_state.state) {
  92. case sbp_parser_state_t::WAITING:
  93. if (temp == SBP_PREAMBLE) {
  94. parser_state.n_read = 0;
  95. parser_state.state = sbp_parser_state_t::GET_TYPE;
  96. }
  97. break;
  98. case sbp_parser_state_t::GET_TYPE:
  99. *((uint8_t*)&(parser_state.msg_type) + parser_state.n_read) = temp;
  100. parser_state.n_read += 1;
  101. if (parser_state.n_read >= 2) {
  102. parser_state.n_read = 0;
  103. parser_state.state = sbp_parser_state_t::GET_SENDER;
  104. }
  105. break;
  106. case sbp_parser_state_t::GET_SENDER:
  107. *((uint8_t*)&(parser_state.sender_id) + parser_state.n_read) = temp;
  108. parser_state.n_read += 1;
  109. if (parser_state.n_read >= 2) {
  110. parser_state.n_read = 0;
  111. parser_state.state = sbp_parser_state_t::GET_LEN;
  112. }
  113. break;
  114. case sbp_parser_state_t::GET_LEN:
  115. parser_state.msg_len = temp;
  116. parser_state.n_read = 0;
  117. parser_state.state = sbp_parser_state_t::GET_MSG;
  118. break;
  119. case sbp_parser_state_t::GET_MSG:
  120. *((uint8_t*)&(parser_state.msg_buff) + parser_state.n_read) = temp;
  121. parser_state.n_read += 1;
  122. if (parser_state.n_read >= parser_state.msg_len) {
  123. parser_state.n_read = 0;
  124. parser_state.state = sbp_parser_state_t::GET_CRC;
  125. }
  126. break;
  127. case sbp_parser_state_t::GET_CRC:
  128. *((uint8_t*)&(parser_state.crc) + parser_state.n_read) = temp;
  129. parser_state.n_read += 1;
  130. if (parser_state.n_read >= 2) {
  131. parser_state.state = sbp_parser_state_t::WAITING;
  132. crc = crc16_ccitt((uint8_t*)&(parser_state.msg_type), 2, 0);
  133. crc = crc16_ccitt((uint8_t*)&(parser_state.sender_id), 2, crc);
  134. crc = crc16_ccitt(&(parser_state.msg_len), 1, crc);
  135. crc = crc16_ccitt(parser_state.msg_buff, parser_state.msg_len, crc);
  136. if (parser_state.crc == crc) {
  137. _sbp_process_message();
  138. } else {
  139. Debug("CRC Error Occurred!");
  140. crc_error_counter += 1;
  141. }
  142. }
  143. break;
  144. default:
  145. parser_state.state = sbp_parser_state_t::WAITING;
  146. break;
  147. }
  148. }
  149. }
  150. //INVARIANT: A fully received message with correct CRC is currently in parser_state
  151. void
  152. AP_GPS_SBP2::_sbp_process_message() {
  153. //Here, we copy messages into local structs.
  154. switch (parser_state.msg_type) {
  155. case SBP_HEARTBEAT_MSGTYPE:
  156. memcpy(&last_heartbeat, parser_state.msg_buff, sizeof(struct sbp_heartbeat_t));
  157. last_heartbeat_received_ms = AP_HAL::millis();
  158. break;
  159. case SBP_GPS_TIME_MSGTYPE:
  160. memcpy(&last_gps_time, parser_state.msg_buff, sizeof(struct sbp_gps_time_t));
  161. check_new_itow(last_gps_time.tow, parser_state.msg_len);
  162. break;
  163. case SBP_VEL_NED_MSGTYPE:
  164. memcpy(&last_vel_ned, parser_state.msg_buff, sizeof(struct sbp_vel_ned_t));
  165. check_new_itow(last_vel_ned.tow, parser_state.msg_len);
  166. break;
  167. case SBP_POS_LLH_MSGTYPE:
  168. memcpy(&last_pos_llh, parser_state.msg_buff, sizeof(struct sbp_pos_llh_t));
  169. check_new_itow(last_pos_llh.tow, parser_state.msg_len);
  170. break;
  171. case SBP_DOPS_MSGTYPE:
  172. memcpy(&last_dops, parser_state.msg_buff, sizeof(struct sbp_dops_t));
  173. check_new_itow(last_dops.tow, parser_state.msg_len);
  174. break;
  175. case SBP_EXT_EVENT_MSGTYPE:
  176. memcpy(&last_event, parser_state.msg_buff, sizeof(struct sbp_ext_event_t));
  177. check_new_itow(last_event.tow, parser_state.msg_len);
  178. logging_ext_event();
  179. break;
  180. default:
  181. break;
  182. }
  183. // send all messages we receive to log, even if it's an unsupported message,
  184. // so we can do additional post-processing from logs.
  185. // The log mask will be used to adjust or suppress logging
  186. logging_log_raw_sbp(parser_state.msg_type, parser_state.sender_id, parser_state.msg_len, parser_state.msg_buff);
  187. }
  188. int32_t
  189. AP_GPS_SBP2::distMod(int32_t tow1_ms, int32_t tow2_ms, int32_t mod) {
  190. return MIN(abs(tow1_ms - tow2_ms), mod - abs(tow1_ms - tow2_ms));
  191. }
  192. bool
  193. AP_GPS_SBP2::_attempt_state_update()
  194. {
  195. if (last_heartbeat_received_ms == 0)
  196. return false;
  197. uint32_t now = AP_HAL::millis();
  198. if (now - last_heartbeat_received_ms > SBP_TIMEOUT_HEARTBEAT) {
  199. state.status = AP_GPS::NO_FIX;
  200. Info("No Heartbeats from Piksi! Status to NO_FIX.");
  201. return false;
  202. } else if (last_heartbeat.protocol_major != 2) {
  203. state.status = AP_GPS::NO_FIX;
  204. Info("Received a heartbeat from non-SBPv2 device. Current driver only supports SBPv2. Status to NO_FIX.");
  205. return false;
  206. } else if (last_heartbeat.nap_error == 1 ||
  207. last_heartbeat.io_error == 1 ||
  208. last_heartbeat.sys_error == 1) {
  209. state.status = AP_GPS::NO_FIX;
  210. Info("Piksi reported an error. Status to NO_FIX.");
  211. Debug(" ext_antenna: %d", last_heartbeat.ext_antenna);
  212. Debug(" res2: %d", last_heartbeat.res2);
  213. Debug(" protocol_major: %d", last_heartbeat.protocol_major);
  214. Debug(" protocol_minor: %d", last_heartbeat.protocol_minor);
  215. Debug(" res: %d", last_heartbeat.res);
  216. Debug(" nap_error: %d", last_heartbeat.nap_error);
  217. Debug(" io_error: %d", last_heartbeat.io_error);
  218. Debug(" sys_error: %d", last_heartbeat.sys_error);
  219. return false;
  220. } else if (last_pos_llh.tow == last_vel_ned.tow
  221. && (distMod(last_gps_time.tow, last_vel_ned.tow, AP_MSEC_PER_WEEK) < 10000)
  222. && (distMod(last_dops.tow, last_vel_ned.tow, AP_MSEC_PER_WEEK) < 60000)
  223. && (last_vel_ned.tow > last_full_update_tow || (last_gps_time.wn > last_full_update_wn && last_vel_ned.tow < last_full_update_tow))) {
  224. //We have an aligned VEL and LLH, and a recent DOPS and TIME.
  225. //
  226. // Check Flags for Valid Messages
  227. //
  228. if (last_gps_time.flags.time_src == 0 ||
  229. last_vel_ned.flags.vel_mode == 0 ||
  230. last_pos_llh.flags.fix_mode == 0 ||
  231. last_dops.flags.fix_mode == 0) {
  232. Debug("Message Marked as Invalid. NO FIX! Flags: {GPS_TIME: %d, VEL_NED: %d, POS_LLH: %d, DOPS: %d}",
  233. last_gps_time.flags.time_src,
  234. last_vel_ned.flags.vel_mode,
  235. last_pos_llh.flags.fix_mode,
  236. last_dops.flags.fix_mode);
  237. state.status = AP_GPS::NO_FIX;
  238. return false;
  239. }
  240. //
  241. // Update external time and accuracy state
  242. //
  243. state.time_week = last_gps_time.wn;
  244. state.time_week_ms = last_vel_ned.tow;
  245. state.hdop = last_dops.hdop;
  246. state.vdop = last_dops.vdop;
  247. state.last_gps_time_ms = now;
  248. //
  249. // Update velocity state
  250. //
  251. state.velocity[0] = (float)(last_vel_ned.n * 1.0e-3);
  252. state.velocity[1] = (float)(last_vel_ned.e * 1.0e-3);
  253. state.velocity[2] = (float)(last_vel_ned.d * 1.0e-3);
  254. float ground_vector_sq = state.velocity[0]*state.velocity[0] + state.velocity[1]*state.velocity[1];
  255. state.ground_speed = safe_sqrt(ground_vector_sq);
  256. state.ground_course = wrap_360(degrees(atan2f(state.velocity[1], state.velocity[0])));
  257. state.speed_accuracy = safe_sqrt(
  258. powf((float)last_vel_ned.h_accuracy * 1.0e-3f, 2) +
  259. powf((float)last_vel_ned.v_accuracy * 1.0e-3f, 2));
  260. state.horizontal_accuracy = (float) last_pos_llh.h_accuracy * 1.0e-3f;
  261. state.vertical_accuracy = (float) last_pos_llh.v_accuracy * 1.0e-3f;
  262. //
  263. // Set flags appropriately
  264. //
  265. state.have_vertical_velocity = true;
  266. state.have_speed_accuracy = !is_zero(state.speed_accuracy);
  267. state.have_horizontal_accuracy = !is_zero(state.horizontal_accuracy);
  268. state.have_vertical_accuracy = !is_zero(state.vertical_accuracy);
  269. //
  270. // Update position state
  271. //
  272. state.location.lat = (int32_t) (last_pos_llh.lat * (double)1e7);
  273. state.location.lng = (int32_t) (last_pos_llh.lon * (double)1e7);
  274. state.location.alt = (int32_t) (last_pos_llh.height * 100);
  275. state.num_sats = last_pos_llh.n_sats;
  276. switch (last_pos_llh.flags.fix_mode) {
  277. case 1:
  278. state.status = AP_GPS::GPS_OK_FIX_3D;
  279. break;
  280. case 2:
  281. state.status = AP_GPS::GPS_OK_FIX_3D_DGPS;
  282. break;
  283. case 3:
  284. state.status = AP_GPS::GPS_OK_FIX_3D_RTK_FLOAT;
  285. break;
  286. case 4:
  287. state.status = AP_GPS::GPS_OK_FIX_3D_RTK_FIXED;
  288. break;
  289. case 6:
  290. state.status = AP_GPS::GPS_OK_FIX_3D_DGPS;
  291. break;
  292. default:
  293. state.status = AP_GPS::NO_FIX;
  294. break;
  295. }
  296. //
  297. // Update Internal Timing
  298. //
  299. last_full_update_tow = last_vel_ned.tow;
  300. last_full_update_wn = last_gps_time.wn;
  301. return true;
  302. }
  303. return false;
  304. }
  305. bool
  306. AP_GPS_SBP2::_detect(struct SBP2_detect_state &state, uint8_t data)
  307. {
  308. // This switch reads one character at a time, if we find something that
  309. // looks like our preamble we'll try to read the full message length,
  310. // calculating the CRC. If the CRC matches, we have an SBP GPS!
  311. switch (state.state) {
  312. case SBP2_detect_state::WAITING:
  313. if (data == SBP_PREAMBLE) {
  314. state.n_read = 0;
  315. state.crc_so_far = 0;
  316. state.state = SBP2_detect_state::GET_TYPE;
  317. }
  318. break;
  319. case SBP2_detect_state::GET_TYPE:
  320. *((uint8_t*)&(state.msg_type) + state.n_read) = data;
  321. state.crc_so_far = crc16_ccitt(&data, 1, state.crc_so_far);
  322. state.n_read += 1;
  323. if (state.n_read >= 2) {
  324. state.n_read = 0;
  325. state.state = SBP2_detect_state::GET_SENDER;
  326. }
  327. break;
  328. case SBP2_detect_state::GET_SENDER:
  329. state.crc_so_far = crc16_ccitt(&data, 1, state.crc_so_far);
  330. state.n_read += 1;
  331. if (state.n_read >= 2) {
  332. state.n_read = 0;
  333. state.state = SBP2_detect_state::GET_LEN;
  334. }
  335. break;
  336. case SBP2_detect_state::GET_LEN:
  337. state.crc_so_far = crc16_ccitt(&data, 1, state.crc_so_far);
  338. state.msg_len = data;
  339. state.n_read = 0;
  340. state.state = SBP2_detect_state::GET_MSG;
  341. break;
  342. case SBP2_detect_state::GET_MSG:
  343. if (state.msg_type == SBP_HEARTBEAT_MSGTYPE && state.n_read < 4) {
  344. *((uint8_t*)&(state.heartbeat_buff) + state.n_read) = data;
  345. }
  346. state.crc_so_far = crc16_ccitt(&data, 1, state.crc_so_far);
  347. state.n_read += 1;
  348. if (state.n_read >= state.msg_len) {
  349. state.n_read = 0;
  350. state.state = SBP2_detect_state::GET_CRC;
  351. }
  352. break;
  353. case SBP2_detect_state::GET_CRC:
  354. *((uint8_t*)&(state.crc) + state.n_read) = data;
  355. state.n_read += 1;
  356. if (state.n_read >= 2) {
  357. state.state = SBP2_detect_state::WAITING;
  358. if (state.crc == state.crc_so_far
  359. && state.msg_type == SBP_HEARTBEAT_MSGTYPE) {
  360. struct sbp_heartbeat_t* heartbeat = ((struct sbp_heartbeat_t*)state.heartbeat_buff);
  361. return heartbeat->protocol_major == 2;
  362. }
  363. return false;
  364. }
  365. break;
  366. default:
  367. state.state = SBP2_detect_state::WAITING;
  368. break;
  369. }
  370. return false;
  371. }
  372. void
  373. AP_GPS_SBP2::logging_log_full_update()
  374. {
  375. if (!should_log()) {
  376. return;
  377. }
  378. //TODO: Expand with heartbeat info.
  379. //TODO: Get rid of IAR NUM HYPO
  380. struct log_SbpHealth pkt = {
  381. LOG_PACKET_HEADER_INIT(LOG_MSG_SBPHEALTH),
  382. time_us : AP_HAL::micros64(),
  383. crc_error_counter : crc_error_counter,
  384. last_injected_data_ms : last_injected_data_ms,
  385. last_iar_num_hypotheses : 0,
  386. };
  387. AP::logger().WriteBlock(&pkt, sizeof(pkt));
  388. };
  389. void
  390. AP_GPS_SBP2::logging_log_raw_sbp(uint16_t msg_type,
  391. uint16_t sender_id,
  392. uint8_t msg_len,
  393. uint8_t *msg_buff) {
  394. if (!should_log()) {
  395. return;
  396. }
  397. //MASK OUT MESSAGES WE DON'T WANT TO LOG
  398. if (( ((uint16_t) gps._sbp_logmask) & msg_type) == 0) {
  399. return;
  400. }
  401. uint64_t time_us = AP_HAL::micros64();
  402. uint8_t pages = 1;
  403. if (msg_len > 48) {
  404. pages += (msg_len - 48) / 104 + 1;
  405. }
  406. struct log_SbpRAWH pkt = {
  407. LOG_PACKET_HEADER_INIT(LOG_MSG_SBPRAWH),
  408. time_us : time_us,
  409. msg_type : msg_type,
  410. sender_id : sender_id,
  411. index : 1,
  412. pages : pages,
  413. msg_len : msg_len,
  414. };
  415. memcpy(pkt.data, msg_buff, MIN(msg_len, 48));
  416. AP::logger().WriteBlock(&pkt, sizeof(pkt));
  417. for (uint8_t i = 0; i < pages - 1; i++) {
  418. struct log_SbpRAWM pkt2 = {
  419. LOG_PACKET_HEADER_INIT(LOG_MSG_SBPRAWM),
  420. time_us : time_us,
  421. msg_type : msg_type,
  422. sender_id : sender_id,
  423. index : uint8_t(i + 2),
  424. pages : pages,
  425. msg_len : msg_len,
  426. };
  427. memcpy(pkt2.data, &msg_buff[48 + i * 104], MIN(msg_len - (48 + i * 104), 104));
  428. AP::logger().WriteBlock(&pkt2, sizeof(pkt2));
  429. }
  430. };
  431. void
  432. AP_GPS_SBP2::logging_ext_event() {
  433. if (!should_log()) {
  434. return;
  435. }
  436. struct log_SbpEvent pkt = {
  437. LOG_PACKET_HEADER_INIT(LOG_MSG_SBPEVENT),
  438. time_us : AP_HAL::micros64(),
  439. wn : last_event.wn,
  440. tow : last_event.tow,
  441. ns_residual : last_event.ns_residual,
  442. level : last_event.flags.level,
  443. quality : last_event.flags.quality,
  444. };
  445. AP::logger().WriteBlock(&pkt, sizeof(pkt));
  446. };