pps_sync.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /**
  2. * @file pps_sync.c
  3. * @author zhl
  4. * @brief PPS
  5. * @version 0.1
  6. * @date 2025-11-25
  7. *
  8. * @copyright Copyright (c) 2025
  9. *
  10. */
  11. #define _GNU_SOURCE
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <signal.h>
  15. #include <unistd.h>
  16. #include <fcntl.h>
  17. #include <sys/mman.h>
  18. #include <sched.h>
  19. #include <pthread.h>
  20. #include <time.h>
  21. #include <string.h>
  22. #include <errno.h>
  23. #include <sys/time.h>
  24. #include <sys/timex.h>
  25. #include <stdint.h>
  26. #include <sys/prctl.h>
  27. #include <gps.h>
  28. // ==================== 配置宏定义 ====================
  29. #define DEBUG_PRINT 0
  30. #define PPS_DETAIL_PRINT 0
  31. #define SYNC_DETAIL_PRINT 0
  32. #define STATS_PRINT 0
  33. // 超时和重试配置
  34. #define PPS_READ_TIMEOUT_MS 1200 // PPS读取超时(毫秒)
  35. #define MAX_CONSECUTIVE_ERRORS 5 // 最大连续错误次数
  36. #define SIGNAL_LOST_THRESHOLD 10 // 信号丢失阈值(秒)
  37. // 打印控制宏
  38. #if DEBUG_PRINT
  39. #define DBG_PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__)
  40. #define DBG_PPS(fmt, ...) \
  41. if (PPS_DETAIL_PRINT) \
  42. printf(fmt, ##__VA_ARGS__)
  43. #define DBG_SYNC(fmt, ...) \
  44. if (SYNC_DETAIL_PRINT) \
  45. printf(fmt, ##__VA_ARGS__)
  46. #define DBG_STATS(fmt, ...) \
  47. if (STATS_PRINT) \
  48. printf(fmt, ##__VA_ARGS__)
  49. #define DBG_WARN(fmt, ...) printf("警告: " fmt, ##__VA_ARGS__)
  50. #define DBG_ERROR(fmt, ...) printf("错误: " fmt, ##__VA_ARGS__)
  51. #else
  52. #define DBG_PRINT(fmt, ...) \
  53. do \
  54. { \
  55. } while (0)
  56. #define DBG_PPS(fmt, ...) \
  57. do \
  58. { \
  59. } while (0)
  60. #define DBG_SYNC(fmt, ...) \
  61. do \
  62. { \
  63. } while (0)
  64. #define DBG_STATS(fmt, ...) \
  65. do \
  66. { \
  67. } while (0)
  68. #define DBG_WARN(fmt, ...) \
  69. do \
  70. { \
  71. } while (0)
  72. #define DBG_ERROR(fmt, ...) \
  73. do \
  74. { \
  75. } while (0)
  76. #endif
  77. static volatile sig_atomic_t running = 1;
  78. // 系统状态枚举
  79. typedef enum
  80. {
  81. STATE_NORMAL = 0, // 正常状态
  82. STATE_SIGNAL_WEAK, // 信号弱
  83. STATE_SIGNAL_LOST, // 信号丢失
  84. STATE_RECOVERING, // 恢复中
  85. STATE_ERROR // 错误状态
  86. } system_state_t;
  87. // 性能基准和状态管理
  88. struct performance_benchmark
  89. {
  90. // 计数
  91. int pps_count;
  92. uint64_t last_pps_time;
  93. uint64_t last_success_time;
  94. // 异常处理
  95. system_state_t system_state;
  96. int consecutive_errors;
  97. int signal_lost_count;
  98. uint64_t last_state_change;
  99. };
  100. volatile int64_t shared_gps_time = 0;
  101. volatile int gps_time_valid = 0;
  102. void signal_handler(int sig)
  103. {
  104. running = 0;
  105. DBG_PRINT("收到停止信号,正在退出...\n");
  106. }
  107. // 高精度时间获取
  108. static inline uint64_t get_time_ns(void)
  109. {
  110. struct timespec ts;
  111. clock_gettime(CLOCK_MONOTONIC, &ts);
  112. return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
  113. }
  114. // 显示系统时间
  115. void display_system_time(const char *context)
  116. {
  117. struct timespec ts;
  118. struct tm tm_info;
  119. char time_str[64];
  120. clock_gettime(CLOCK_REALTIME, &ts);
  121. localtime_r(&ts.tv_sec, &tm_info);
  122. strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S", &tm_info);
  123. DBG_PRINT("%s: %s.%09ld\n", context, time_str, ts.tv_nsec);
  124. }
  125. // 状态管理函数
  126. void change_system_state(struct performance_benchmark *bench, system_state_t new_state)
  127. {
  128. if (bench->system_state != new_state)
  129. {
  130. const char *state_names[] = {"正常", "信号弱", "信号丢失", "恢复中", "错误"};
  131. DBG_WARN("系统状态变更: %s -> %s\n",
  132. state_names[bench->system_state], state_names[new_state]);
  133. bench->system_state = new_state;
  134. bench->last_state_change = get_time_ns();
  135. }
  136. }
  137. // 检查信号状态
  138. void check_signal_status(struct performance_benchmark *bench)
  139. {
  140. uint64_t current_time = get_time_ns();
  141. uint64_t time_since_last_pps = (current_time - bench->last_pps_time) / 1000000000ULL; // 转换为秒
  142. if (time_since_last_pps > SIGNAL_LOST_THRESHOLD)
  143. {
  144. if (bench->system_state != STATE_SIGNAL_LOST)
  145. {
  146. change_system_state(bench, STATE_SIGNAL_LOST);
  147. bench->signal_lost_count++;
  148. DBG_WARN("GPS信号丢失! 最后PPS: %lld秒前\n", (long long)time_since_last_pps);
  149. }
  150. }
  151. else if (time_since_last_pps > 3)
  152. {
  153. if (bench->system_state == STATE_NORMAL)
  154. {
  155. change_system_state(bench, STATE_SIGNAL_WEAK);
  156. DBG_WARN("GPS信号弱,最后PPS: %lld秒前\n", (long long)time_since_last_pps);
  157. }
  158. }
  159. else
  160. {
  161. if (bench->system_state != STATE_NORMAL)
  162. {
  163. if (bench->system_state == STATE_SIGNAL_LOST)
  164. {
  165. DBG_PRINT("GPS信号恢复!\n");
  166. }
  167. change_system_state(bench, STATE_NORMAL);
  168. bench->consecutive_errors = 0;
  169. }
  170. }
  171. }
  172. // 带超时的PPS读取
  173. ssize_t read_pps_with_timeout(int fd, void *buf, size_t count, int timeout_ms)
  174. {
  175. fd_set readfds;
  176. struct timeval tv;
  177. int ret;
  178. FD_ZERO(&readfds);
  179. FD_SET(fd, &readfds);
  180. tv.tv_sec = timeout_ms / 1000;
  181. tv.tv_usec = (timeout_ms % 1000) * 1000;
  182. ret = select(fd + 1, &readfds, NULL, NULL, &tv);
  183. if (ret > 0)
  184. {
  185. // 有数据可读
  186. if (FD_ISSET(fd, &readfds))
  187. {
  188. return read(fd, buf, count);
  189. }
  190. }
  191. else if (ret == 0)
  192. {
  193. // 超时
  194. errno = ETIMEDOUT;
  195. return -1;
  196. }
  197. // 错误
  198. return -1;
  199. }
  200. // 考虑时钟偏差的亚秒级时间微调
  201. int calibrated_subsecond_adjust(uint64_t pps_ns, struct performance_benchmark *bench)
  202. {
  203. // 在信号弱或丢失状态下不进行时间调整
  204. if (bench->system_state != STATE_NORMAL)
  205. {
  206. DBG_WARN("信号状态不佳,跳过时间调整\n");
  207. return -1;
  208. }
  209. struct timespec current_ts, new_ts;
  210. int ret;
  211. bool bset = false;
  212. const int correction_value_ns = 500000; // 0.5ms
  213. if (gps_time_valid == 1)
  214. {
  215. new_ts.tv_sec = shared_gps_time + 1; // TODO,是否得加一秒
  216. new_ts.tv_nsec = 0;
  217. gps_time_valid = 0;
  218. }
  219. else
  220. {
  221. return -1;
  222. }
  223. // clock_gettime(CLOCK_REALTIME, &current_ts); //这个是改为获取GPS本身时间 zhl
  224. // DBG_SYNC("当前时间 clock_gettime: %ld.%09ld\n", current_ts.tv_sec, current_ts.tv_nsec);
  225. // ret = clock_settime(CLOCK_REALTIME, &new_ts);
  226. gps_get_time(&current_ts);
  227. if (current_ts.tv_sec == new_ts.tv_sec)
  228. {
  229. if (current_ts.tv_nsec >= correction_value_ns)
  230. {
  231. bset = true;
  232. }
  233. }
  234. else
  235. {
  236. if (abs(new_ts.tv_sec - current_ts.tv_sec) > 1)
  237. {
  238. bset = true;
  239. }
  240. else
  241. {
  242. if (new_ts.tv_sec > current_ts.tv_sec)
  243. {
  244. // 终端时间慢1ms以上
  245. if (NSEC_PER_SEC - current_ts.tv_nsec >= correction_value_ns)
  246. {
  247. bset = true;
  248. }
  249. }
  250. else
  251. {
  252. // 终端时间快1ms以上
  253. if (current_ts.tv_nsec - correction_value_ns >= 0)
  254. {
  255. bset = true;
  256. }
  257. }
  258. }
  259. }
  260. // DBG_SYNC("pps_adjust->gps_set_time:: %ld.%09ld\n", new_ts.tv_sec, new_ts.tv_nsec);
  261. if (bset)
  262. {
  263. gps_set_time(&new_ts); // 写入应用程序全局定时器
  264. rt_printf("gps set time!\r\n");
  265. }
  266. // memset(&new_ts, 0, sizeof(new_ts));
  267. // gps_get_time(&new_ts);
  268. // DBG_SYNC("pps_adjust->gps_get_time: %ld.%09ld\n", new_ts.tv_sec, new_ts.tv_nsec);
  269. return 0;
  270. }
  271. // 智能微调策略(考虑信号状态)
  272. void smart_adjust_strategy(uint64_t pps_ns, uint64_t last_pps_ns,
  273. struct performance_benchmark *bench)
  274. {
  275. // 只在正常状态下进行时间调整
  276. if (bench->system_state != STATE_NORMAL)
  277. {
  278. return;
  279. }
  280. if (bench->pps_count == 2)
  281. {
  282. DBG_SYNC("首次PPS,进行时间微调...\n");
  283. calibrated_subsecond_adjust(pps_ns, bench);
  284. }
  285. else if (bench->pps_count % 1 == 0) // 可调整定期时间微调时间
  286. {
  287. // DBG_SYNC("定期时间微调...\n");
  288. calibrated_subsecond_adjust(pps_ns, bench);
  289. }
  290. }
  291. // PPS数据处理
  292. void process_pps_data(uint64_t pps_ns, uint64_t last_pps_ns,
  293. struct performance_benchmark *bench)
  294. {
  295. bench->last_pps_time = get_time_ns();
  296. bench->last_success_time = bench->last_pps_time;
  297. bench->consecutive_errors = 0;
  298. }
  299. // 处理读取错误
  300. void handle_read_error(struct performance_benchmark *bench)
  301. {
  302. bench->consecutive_errors++;
  303. if (bench->consecutive_errors >= MAX_CONSECUTIVE_ERRORS)
  304. {
  305. DBG_ERROR("连续错误次数过多 (%d次)\n", bench->consecutive_errors);
  306. change_system_state(bench, STATE_ERROR);
  307. }
  308. // 短暂休眠避免忙等待
  309. usleep(100000); // 100ms
  310. }
  311. // 主捕获循环
  312. void pps_capture_main(void *arg)
  313. {
  314. int fd = (int)(long)arg;
  315. uint64_t pps_ns, last_pps_ns = 0;
  316. struct performance_benchmark bench = {0};
  317. // 初始化
  318. bench.last_pps_time = get_time_ns();
  319. bench.system_state = STATE_NORMAL;
  320. DBG_PRINT("开始PPS时钟校准和时间微调...\n");
  321. DBG_PRINT("异常处理已启用: 超时=%dms, 最大错误=%d次\n",
  322. PPS_READ_TIMEOUT_MS, MAX_CONSECUTIVE_ERRORS);
  323. display_system_time("当前系统时间");
  324. prctl(PR_SET_NAME, "pps_capture_thread");
  325. while (running)
  326. {
  327. // 检查信号状态
  328. check_signal_status(&bench);
  329. // 带超时的PPS读取
  330. ssize_t ret = read_pps_with_timeout(fd, &pps_ns, sizeof(pps_ns), PPS_READ_TIMEOUT_MS);
  331. if (ret != sizeof(pps_ns))
  332. {
  333. if (running)
  334. {
  335. if (errno == ETIMEDOUT)
  336. {
  337. if (bench.system_state == STATE_NORMAL && bench.pps_count > 0)
  338. {
  339. DBG_WARN("PPS读取超时\n");
  340. }
  341. }
  342. else if (errno != EINTR)
  343. {
  344. DBG_ERROR("读取错误: code=%d\n", errno);
  345. handle_read_error(&bench);
  346. }
  347. }
  348. continue;
  349. }
  350. // 读取到PPS数据
  351. bench.pps_count++;
  352. if (last_pps_ns != 0)
  353. {
  354. process_pps_data(pps_ns, last_pps_ns, &bench);
  355. smart_adjust_strategy(pps_ns, last_pps_ns, &bench);
  356. }
  357. else
  358. {
  359. DBG_PPS("PPS#%04d | 基准建立 | PPS时间戳: %.9fs\n",
  360. bench.pps_count, pps_ns / 1e9);
  361. }
  362. last_pps_ns = pps_ns;
  363. if (bench.pps_count % 10 == 0)
  364. {
  365. fflush(stdout);
  366. }
  367. }
  368. }
  369. // 设置实时性
  370. void set_realtime_environment(int fd)
  371. {
  372. pthread_attr_t attr;
  373. struct sched_param param;
  374. pthread_t thread;
  375. if (pthread_attr_init(&attr) != 0)
  376. {
  377. perror("pthread_attr_init failed");
  378. return;
  379. }
  380. if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0)
  381. {
  382. perror("pthread_attr_setschedpolicy failed");
  383. goto cleanup;
  384. }
  385. param.sched_priority = 20;
  386. if (pthread_attr_setschedparam(&attr, &param) != 0)
  387. {
  388. perror("pthread_attr_setschedparam failed");
  389. goto cleanup;
  390. }
  391. if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != 0)
  392. {
  393. perror("pthread_attr_setinheritsched failed");
  394. goto cleanup;
  395. }
  396. if (pthread_create(&thread, &attr, pps_capture_main, (void *)(long)fd) != 0)
  397. {
  398. perror("pthread_create failed");
  399. goto cleanup;
  400. }
  401. // 分离线程
  402. pthread_detach(thread);
  403. DBG_PRINT("PPS线程已启动并在后台运行\n");
  404. cleanup:
  405. pthread_attr_destroy(&attr);
  406. }
  407. int pps_init(void)
  408. {
  409. int fd = 0;
  410. DBG_PRINT("初始化PPS设备...");
  411. fd = open("/dev/pps", O_RDONLY);
  412. if (fd < 0)
  413. {
  414. DBG_PRINT(" 初始化PPS失败: %s\n", strerror(errno));
  415. return -1;
  416. }
  417. DBG_PRINT(" 初始化PPS成功\n");
  418. // 设置为非阻塞模式,用于select
  419. int flags = fcntl(fd, F_GETFL, 0);
  420. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  421. set_realtime_environment(fd);
  422. return 0;
  423. }