pps_sync.c 11 KB

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