pps_sync.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. new_ts.tv_sec = shared_gps_time; //TODO,是否得加一秒
  212. new_ts.tv_nsec = 0;
  213. gps_time_valid = 0;
  214. }else{
  215. return -1;
  216. }
  217. // clock_gettime(CLOCK_REALTIME, &current_ts); //这个是改为获取GPS本身时间 zhl
  218. // DBG_SYNC("当前时间 clock_gettime: %ld.%09ld\n", current_ts.tv_sec, current_ts.tv_nsec);
  219. // ret = clock_settime(CLOCK_REALTIME, &new_ts);
  220. // DBG_SYNC("pps_adjust->gps_set_time:: %ld.%09ld\n", new_ts.tv_sec, new_ts.tv_nsec);
  221. gps_set_time(&new_ts); // 写入应用程序全局定时器
  222. // memset(&new_ts, 0, sizeof(new_ts));
  223. // gps_get_time(&new_ts);
  224. // DBG_SYNC("pps_adjust->gps_get_time: %ld.%09ld\n", new_ts.tv_sec, new_ts.tv_nsec);
  225. return 0;
  226. }
  227. // 智能微调策略(考虑信号状态)
  228. void smart_adjust_strategy(uint64_t pps_ns, uint64_t last_pps_ns,
  229. struct performance_benchmark *bench)
  230. {
  231. // 只在正常状态下进行时间调整
  232. if (bench->system_state != STATE_NORMAL)
  233. {
  234. return;
  235. }
  236. if (bench->pps_count == 2)
  237. {
  238. DBG_SYNC("首次PPS,进行时间微调...\n");
  239. calibrated_subsecond_adjust(pps_ns, bench);
  240. }
  241. else if (bench->pps_count % 1 == 0) // 可调整定期时间微调时间
  242. {
  243. // DBG_SYNC("定期时间微调...\n");
  244. calibrated_subsecond_adjust(pps_ns, bench);
  245. }
  246. }
  247. // PPS数据处理
  248. void process_pps_data(uint64_t pps_ns, uint64_t last_pps_ns,
  249. struct performance_benchmark *bench)
  250. {
  251. bench->last_pps_time = get_time_ns();
  252. bench->last_success_time = bench->last_pps_time;
  253. bench->consecutive_errors = 0;
  254. }
  255. // 处理读取错误
  256. void handle_read_error(struct performance_benchmark *bench)
  257. {
  258. bench->consecutive_errors++;
  259. if (bench->consecutive_errors >= MAX_CONSECUTIVE_ERRORS)
  260. {
  261. DBG_ERROR("连续错误次数过多 (%d次)\n", bench->consecutive_errors);
  262. change_system_state(bench, STATE_ERROR);
  263. }
  264. // 短暂休眠避免忙等待
  265. usleep(100000); // 100ms
  266. }
  267. // 主捕获循环
  268. void pps_capture_main(void* arg)
  269. {
  270. int fd = (int)(long)arg;
  271. uint64_t pps_ns, last_pps_ns = 0;
  272. struct performance_benchmark bench = {0};
  273. // 初始化
  274. bench.last_pps_time = get_time_ns();
  275. bench.system_state = STATE_NORMAL;
  276. DBG_PRINT("开始PPS时钟校准和时间微调...\n");
  277. DBG_PRINT("异常处理已启用: 超时=%dms, 最大错误=%d次\n",
  278. PPS_READ_TIMEOUT_MS, MAX_CONSECUTIVE_ERRORS);
  279. display_system_time("当前系统时间");
  280. while (running)
  281. {
  282. // 检查信号状态
  283. check_signal_status(&bench);
  284. // 带超时的PPS读取
  285. ssize_t ret = read_pps_with_timeout(fd, &pps_ns, sizeof(pps_ns), PPS_READ_TIMEOUT_MS);
  286. if (ret != sizeof(pps_ns))
  287. {
  288. if (running)
  289. {
  290. if (errno == ETIMEDOUT)
  291. {
  292. if (bench.system_state == STATE_NORMAL && bench.pps_count > 0)
  293. {
  294. DBG_WARN("PPS读取超时\n");
  295. }
  296. }
  297. else if (errno != EINTR)
  298. {
  299. DBG_ERROR("读取错误: code=%d\n", errno);
  300. handle_read_error(&bench);
  301. }
  302. }
  303. continue;
  304. }
  305. // 读取到PPS数据
  306. bench.pps_count++;
  307. if (last_pps_ns != 0)
  308. {
  309. process_pps_data(pps_ns, last_pps_ns, &bench);
  310. smart_adjust_strategy(pps_ns, last_pps_ns, &bench);
  311. }
  312. else
  313. {
  314. DBG_PPS("PPS#%04d | 基准建立 | PPS时间戳: %.9fs\n",
  315. bench.pps_count, pps_ns / 1e9);
  316. }
  317. last_pps_ns = pps_ns;
  318. if (bench.pps_count % 10 == 0)
  319. {
  320. fflush(stdout);
  321. }
  322. }
  323. }
  324. // 设置实时性
  325. void set_realtime_environment(int fd)
  326. {
  327. pthread_attr_t attr;
  328. struct sched_param param;
  329. pthread_t thread;
  330. if (pthread_attr_init(&attr) != 0) {
  331. perror("pthread_attr_init failed");
  332. return;
  333. }
  334. if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0) {
  335. perror("pthread_attr_setschedpolicy failed");
  336. goto cleanup;
  337. }
  338. param.sched_priority = 20;
  339. if (pthread_attr_setschedparam(&attr, &param) != 0) {
  340. perror("pthread_attr_setschedparam failed");
  341. goto cleanup;
  342. }
  343. if (pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED) != 0) {
  344. perror("pthread_attr_setinheritsched failed");
  345. goto cleanup;
  346. }
  347. if (pthread_create(&thread, &attr, pps_capture_main, (void*)(long)fd) != 0) {
  348. perror("pthread_create failed");
  349. goto cleanup;
  350. }
  351. // 分离线程
  352. pthread_detach(thread);
  353. DBG_PRINT("PPS线程已启动并在后台运行\n");
  354. cleanup:
  355. pthread_attr_destroy(&attr);
  356. }
  357. int pps_init(void)
  358. {
  359. int fd = 0;
  360. DBG_PRINT("初始化PPS设备...");
  361. fd = open("/dev/pps", O_RDONLY);
  362. if (fd < 0)
  363. {
  364. DBG_PRINT(" 初始化PPS失败: %s\n", strerror(errno));
  365. return -1;
  366. }
  367. DBG_PRINT(" 初始化PPS成功\n");
  368. // 设置为非阻塞模式,用于select
  369. int flags = fcntl(fd, F_GETFL, 0);
  370. fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  371. set_realtime_environment(fd);
  372. return 0;
  373. }