serial.h 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * @file serial.h
  3. * @brief 串口通信(同步IO方式)
  4. * @author niujiuru
  5. * @date 2014-07-14 created
  6. * @note 2021-04-13 打开串口时允许设置奇偶校检位
  7. * @note 2021-04-23 打开串口时区分开有数据和无数据两种不同状态下的用户回调
  8. * @note 2021-04-25 新增"serial_printf_recv_buffer()"函数, 打印接收缓存区
  9. * @note 2021-04-27 新增"serial_recvThrd_isAlive()"函数, 判断接收线程是否还在
  10. * @note 2021-08-20 新增"serial_get_log_prefix()"函数, 获取日志打印前缀字符串
  11. * @note 2025-10-11 打开串口时新增"__O_CLOEXEC"
  12. */
  13. #ifndef __SERIAL_H__
  14. #define __SERIAL_H__
  15. #ifdef __cplusplus
  16. extern "C"
  17. {
  18. #endif
  19. /* 数据接收处理(用户回调); "wParam"指向打开的串口句柄, "lParm"指向用户数据;
  20. "返回值 < 0"时表示处理失败, 将不再调用该用户回调, "返回值 >= 0"时表示处理成功,
  21. 接收数据空闲时, 延时一段"返回值"时间(ms)后, 继续调用该用户回调 */
  22. typedef int (*PSerialRecvHandler)(unsigned long wParam, unsigned long lParam);
  23. /* 空闲接收处理(用户回调); "wParam"指向打开的串口句柄, "lParm"指向用户数据;
  24. "返回值 < 0"时表示处理失败, 将不再调用该用户回调, "返回值 >= 0"时表示处理成功,
  25. 接收数据空闲时, 延时一段"返回值"时间(ms)后, 继续调用该用户回调 */
  26. typedef int (*PSerialIdleHandler)(unsigned long wParam, unsigned long lParam);
  27. /* 打开串口(8个数据位1个停止位), NULL失败, NOT NULL成功 */
  28. void *serial_open(const char *serialName, int baudrate, const char *parityCheck /* "odd"-奇校检; "even"-偶校检; NULL或其它无效值-无校检 */, \
  29. PSerialRecvHandler pRecvHandler, PSerialIdleHandler pIdleHandler, void *pUserData);
  30. /* 关闭串口 */
  31. void serial_close(void *hSerial, int timeout);
  32. /* 获取日志打印前缀 */
  33. char *serial_get_log_prefix(const void *hSerial);
  34. /* 发送数据, -1失败, >=0发送的字节数 */
  35. int serial_send_data(const void *hSerial, const unsigned char *data, int len);
  36. /* 取得接收缓存区, NULL失败, NOT NULL成功 */
  37. const unsigned char *serial_get_recv_buffer(const void *hSerial);
  38. /* 取得接收缓存区中当前有效数据的字节数, -1失败, 返回值>=0 */
  39. int serial_get_recv_buffer_bytes(const void *hSerial);
  40. /* 清空接收缓存区 */
  41. void serial_clear_recv_buffer(const void *hSerial);
  42. /* 打印接收缓存区 */
  43. void serial_printf_recv_buffer(const void *hSerial, int logLevel);
  44. /* 判断接收线程是否还在 */
  45. bool serial_recvThrd_isAlive(const void *hSerial);
  46. /* 暂停接收线程接收数据 */
  47. void serial_recvThrd_pause(const void *hSerial);
  48. /* 继续接收线程接收数据 */
  49. void serial_recvThrd_resume(const void *hSerial);
  50. #ifdef _DEBUG
  51. /* 向接收缓存中写入数据(一般用于仿真串口输入, 模拟测试时使用) */
  52. void serial_write_recv_buffer(const void *hSerial, const unsigned char *hex, int hexCnt);
  53. #endif
  54. #ifdef __cplusplus
  55. }
  56. #endif
  57. #endif /* __SERIAL_H__ */