Linux libusb "TIMEOUT -116" libusb_send返回值为-116 error解决方法

本文针对Linux环境下使用libusb库时遇到的usb_read_bulk()函数出现timeout error的问题,提供了一套从设备配置、指令确认、传输方式到硬件检查的四步骤解决方案,旨在帮助开发者有效排查并解决USB通讯故障。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Linux下libusb开发遇到如下问题

在Linux下用libusb进行usb_write_bulk()函数调用时,但usb_read_bulk()函数却会出现:

libusb0-dll:[_usb_reap_async] timeout error 的错误提示 返回值为-116 接收不到usb传来的数据

此问题原因有很多种,需一一分析!

解决方法

第一步:排除设备配置错误

检查usb设备的配置模式、接口设置、传输方式等参数使用是否正确,如不确定,可多试试其他模式参数。在此,我推荐一款软件usbtreeview来查看usb设备的详细参数!

若第一步过后,问题还没解决,可采取第二步

第二步:确定发送的指令是否正确,并确定usb设备会产生响应数据

确定发送的指令是否正确,并确定usb设备会产生响应数据。在此,我推荐一款抓包软件Bus Hound来查看usb设备和电脑的交互数据,确定usb设备是否有数据传送过来。

若第二步过后,问题还没解决,可采取第三步

第三步:使用异步的方法进行USB的批量传输

异步的方法进行USB的批量传输,比如使用usb_reap_async_nocancel()函数进行数据传输。

或 采用开辟专用线程,并将usb_read_bulk()函数中的超时参数设置为:-1(即无限等待)。

若第三步过后,问题还没解决,可采取第四步

第四步:检查USB设备

检查硬件设备,确保usb设备程序没有问题,usb设备的元器件没有问题,usb数据传输线没有问题,usb插口重新插入一下...以确保usb设备硬件没有问题。

若第四步过后,问题还没解决,那就继续去别处找找原因吧...

参考链接

https://blog.youkuaiyun.com/karizhang/article/details/51829079

https://blog.youkuaiyun.com/nolatin/article/details/27094299

https://bbs.youkuaiyun.com/topics/392043088?list=lz

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <libusb-1.0/libusb.h> #include <thread> #include <iostream> #include <fstream> #include <iomanip> #include <ctime> #include <sstream> #include <vector> #include <atomic> #include <chrono> #include <pthread.h> #include "CircularBuffer.h" #include <spdlog/spdlog.h> #include <spdlog/sinks/basic_file_sink.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unordered_map> #include <string> #include <array> #include <regex> #include <sys/stat.h> #include <arpa/inet.h> #include "cyusb.h" #define SERVER_IP "192.168.1.103" std::string win_ip_str = "192.168.1.104"; const char *WIN_IP = win_ip_str.c_str(); #define SERVER_PORT 8892 #define WIN_PORT 8893 #define TCP_BUFFER_SIZE 1024 // ======================== 常量定义 ======================== #define VENDOR_ID 0x04b4 #define PRODUCT_ID 0x00f1 #define ENDPOINT_IN 0x81 #define ENDPOINT_OUT 0x01 #define BAND_SIZE 200 #define QUEUE_SIZE 26 #define TRANSFER_LEN (1024 * 16 * 3) #define OUT_BUF_LEN (4096 * 1) #define FRAME_SIZE (4096 * 201) #define LINE_SIZE (4096 * 1) #define CIRCULAR_BUF_CAPACITY (4096 * 201 * 1000) // ======================== UDP发数 ======================== #define UDP_BUF_SIZE (OUT_BUF_LEN * 5) char udpBuf[UDP_BUF_SIZE]; int udpBufUsed = 0; // ======================== 指令映射表 ======================== std::unordered_map<std::string, std::array<uint8_t, 8>> commandMap = { {"SET_FPS_1", {0x92, 0xAC, 0x02, 0x92, 0xD1, 0x43, 0x00, 0x00}}, {"SET_FPS_2", {0x92, 0xAC, 0x02, 0x92, 0xD2, 0x40, 0x00, 0x00}}, {"SET_FPS_3", {0x92, 0xAC, 0x02, 0x92, 0xD3, 0x41, 0x00, 0x00}}, {"SET_FPS_4", {0x92, 0xAC, 0x02, 0x92, 0xD4, 0x46, 0x00, 0x00}}, {"SET_FPS_5", {0x92, 0xAC, 0x02, 0x92, 0xD5, 0x47, 0x00, 0x00}}, {"SET_FPS_6", {0x92, 0xAC, 0x02, 0x92, 0xD6, 0x44, 0x00, 0x00}}, {"SET_FPS_7", {0x92, 0xAC, 0x02, 0x92, 0xD7, 0x45, 0x00, 0x00}}, {"SET_FPS_8", {0x92, 0xAC, 0x02, 0x92, 0xD8, 0x4A, 0x00, 0x00}}, {"SET_FPS_9", {0x92, 0xAC, 0x02, 0x92, 0xD9, 0x4B, 0x00, 0x00}}, {"SET_FPS_10", {0x92, 0xAC, 0x02, 0x92, 0xDA, 0x48, 0x00, 0x00}}, {"SET_TIME_1", {0x92, 0xAC, 0x02, 0x92, 0xA1, 0x33, 0x00, 0x00}}, {"SET_TIME_2", {0x92, 0xAC, 0x02, 0x92, 0xA2, 0x30, 0x00, 0x00}}, {"SET_TIME_3", {0x92, 0xAC, 0x02, 0x92, 0xA3, 0x31, 0x00, 0x00}}, {"SET_TIME_4", {0x92, 0xAC, 0x02, 0x92, 0xA4, 0x36, 0x00, 0x00}}, {"SET_TIME_5", {0x92, 0xAC, 0x02, 0x92, 0xA5, 0x37, 0x00, 0x00}}, {"SET_TIME_6", {0x92, 0xAC, 0x02, 0x92, 0xA6, 0x34, 0x00, 0x00}}, {"SET_TIME_7", {0x92, 0xAC, 0x02, 0x92, 0xA7, 0x35, 0x00, 0x00}}, {"SET_TIME_8", {0x92, 0xAC, 0x02, 0x92, 0xA8, 0x3A, 0x00, 0x00}}, {"SET_TIME_9", {0x92, 0xAC, 0x02, 0x92, 0xA9, 0x3B, 0x00, 0x00}}, {"SET_TIME_10", {0x92, 0xAC, 0x02, 0x92, 0xAA, 0x38, 0x00, 0x00}}, {"SET_TIME_11", {0x92, 0xAC, 0x02, 0x92, 0xAB, 0x39, 0x00, 0x00}}, {"SET_TIME_12", {0x92, 0xAC, 0x02, 0x92, 0xAC, 0x3E, 0x00, 0x00}}, {"SET_TIME_13", {0x92, 0xAC, 0x02, 0x92, 0xAD, 0x3F, 0x00, 0x00}}, {"SET_TIME_14", {0x92, 0xAC, 0x02, 0x92, 0xAE, 0x3C, 0x00, 0x00}}, {"SET_TIME_15", {0x92, 0xAC, 0x02, 0x92, 0xAF, 0x3D, 0x00, 0x00}}, {"SET_START_IMG", {0x92, 0xAC, 0x02, 0x92, 0xE3, 0x71, 0x00, 0x00}}, {"SET_END_IMG", {0x92, 0xAC, 0x02, 0x92, 0xE4, 0x76, 0x00, 0x00}}, {"SET_REAL", {0x92, 0xAC, 0x02, 0x92, 0xE1, 0x73, 0x00, 0x00}}, {"SET_MOCK", {0x92, 0xAC, 0x02, 0x92, 0xE2, 0x70, 0x00, 0x00}}, {"SET_MASTER", {0x92, 0xAC, 0x02, 0x92, 0xF1, 0x63, 0x00, 0x00}}, {"SET_SLAVE", {0x92, 0xAC, 0x02, 0x92, 0xF2, 0x60, 0x00, 0x00}}, {"SET_GAIN_1", {0x92, 0xAC, 0x02, 0x92, 0xC1, 0x53, 0x00, 0x00}}, {"SET_GAIN_2", {0x92, 0xAC, 0x02, 0x92, 0xC2, 0x50, 0x00, 0x00}}, {"SET_GAIN_3", {0x92, 0xAC, 0x02, 0x92, 0xC3, 0x51, 0x00, 0x00}}}; // ======================== 全局变量 ======================== CircularBuffer _circular_buf; CircularBuffer _circular_buf_write; std::atomic<bool> run(true); std::atomic<bool> isUsbWorking(false); std::atomic<bool> open(true); // 在全局作用域添加线程变量声明 std::thread work_thread_proc; std::thread work_thread_recv; std::thread work_thread_write; libusb_device_handle *handle = nullptr; // 添加全局 USB 设备句柄 // 存数 std::ofstream g_saveFile_dat; std::ofstream g_saveFile_aux; std::ofstream g_saveFile_hdr; std::string dir = "/media/myssd/data/"; std::atomic<bool> isSaveDat(false); // 全局变量声明 int frame_count = 0; // 实际写入的帧数 uint32_t last_picNO = 0xFFFFFFFF; // 上一帧号 bool is_frame_valid = false; // 当前帧是否有效 uint32_t last_aux_picNO = 0xFFFFFFFF; // 上一个aux包帧号 uint32_t last_lineNO = -1; std::atomic<bool> isNO1(false); // RGB FLAG int rFlag = 192; int gFlag = 80; int bFlag = 32; // 修复链接错误:全局变量只在此处定义和初始化一次 std::atomic<bool> isCalcMean(false); std::atomic<bool> meanReady(false); std::vector<uint16_t> dark_mean(BAND_SIZE *(LINE_SIZE / 2), 0); // 每行的像素个数是 LINE_SIZE / 2 std::vector<bool> band_got(BAND_SIZE, false); // 发送一帧波段数据到Win端 void send_udp_to_win(const char *buf, size_t len, const char *win_ip, int win_port) { int sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) return; struct sockaddr_in dst; memset(&dst, 0, sizeof(dst)); dst.sin_family = AF_INET; dst.sin_port = htons(win_port); inet_pton(AF_INET, win_ip, &dst.sin_addr); sendto(sock, buf, len, 0, (struct sockaddr *)&dst, sizeof(dst)); close(sock); } // =========== USB 设备初始化函数 =========== bool init_usb_device(libusb_device_handle *&handle) { int rc = libusb_init(NULL); if (rc < 0) { spdlog::error("libusb_init failed: {}", libusb_error_name(rc)); return false; } // 打开指定设备 handle = libusb_open_device_with_vid_pid(NULL, VENDOR_ID, PRODUCT_ID); if (!handle) { spdlog::error("Device not found"); libusb_exit(NULL); return false; } // 声明接口 rc = libusb_claim_interface(handle, 0); if (rc != 0) { spdlog::error("Failed to claim interface: {}", libusb_error_name(rc)); libusb_close(handle); libusb_exit(NULL); return false; } // 清除端点 halt 状态 rc = libusb_clear_halt(handle, ENDPOINT_IN); if (rc != 0) { spdlog::error("Failed to clear halt on ENDPOINT_IN: {}", libusb_error_name(rc)); } rc = libusb_clear_halt(handle, ENDPOINT_OUT); if (rc != 0) { spdlog::error("Failed to clear halt on ENDPOINT_OUT: {}", libusb_error_name(rc)); } // 设置配置 rc = libusb_set_configuration(handle, 1); if (rc != 0) { spdlog::error("Failed to set configuration: {}", libusb_error_name(rc)); } // 设置接口 rc = libusb_set_interface_alt_setting(handle, 0, 0); if (rc != 0) { spdlog::error("Failed to set interface alt setting: {}", libusb_error_name(rc)); } spdlog::info("USB device initialized successfully"); isUsbWorking = true; return true; } // =========== USB 重启函数 =========== bool restart_usb_device() { spdlog::info("Attempting to restart USB device..."); // 先清理现有连接 if (handle) { libusb_release_interface(handle, 0); libusb_close(handle); handle = nullptr; } // 等待一小段时间 std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 复用初始化函数 return init_usb_device(handle); } // =========== 清理 USB 设备函数 =========== void cleanup_usb_device(libusb_device_handle *handle) { if (handle) { libusb_release_interface(handle, 0); libusb_close(handle); } libusb_exit(NULL); isUsbWorking = false; } // =========== USB 异步回调上下文结构体 =========== struct usb_ctx { libusb_device_handle *handle; unsigned char *buffer; struct libusb_transfer *transfer; int idx; // 槽索引 }; // =========== USB 异步回调函数 =========== void transfer_callback(struct libusb_transfer *transfer) { usb_ctx *ctx = (usb_ctx *)transfer->user_data; if (transfer->status == LIBUSB_TRANSFER_COMPLETED && transfer->actual_length > 0) { if (_circular_buf.CanWrite(transfer->actual_length)) { _circular_buf.BlockWrite((const char *)transfer->buffer, transfer->actual_length); } else { spdlog::warn("Circular Buffer is full"); } } else { spdlog::error("USB Transfer error, status: {}", transfer->status); } // 如果还在运行,再次提交该槽的 transfer if (open.load()) { int r = libusb_submit_transfer(transfer); if (r != 0) { spdlog::error("Failed to resubmit transfer: {}", libusb_error_name(r)); } } } // ===========USB 同步发送指令 =========== bool send_usb_command(libusb_device_handle *handle, unsigned char endpoint, const unsigned char *cmd, int length, unsigned timeout_ms = 5000) { // 1. 检查 handle 是否有效 if (handle == nullptr) { spdlog::error("USB handle is null!"); return false; } // 2. 检查 endpoint 是否为合法端点(一般为0x01~0x0F或0x81~0x8F,具体看你的设备描述符) if ((endpoint & 0xF0) != 0x00 && (endpoint & 0xF0) != 0x80) { spdlog::error("USB endpoint 0x{:02X} is invalid!", endpoint); return false; } // 3. 检查 cmd 和 length if (cmd == nullptr || length <= 0) { spdlog::error("USB command buffer is null or length <= 0!"); return false; } int transferred = 0; int rc = libusb_bulk_transfer(handle, endpoint, (unsigned char *)cmd, length, &transferred, timeout_ms); if (rc != 0 || transferred != length) { spdlog::error("USB Failed to send command, code={}, ({}), transferred={}", rc, libusb_error_name(rc), transferred); return false; } return true; } // =========== USB异步采集线程 =========== void _run_recv_async() { int retry_count = 0; const int MAX_RETRIES = 3; // 最大重试次数 while (retry_count < MAX_RETRIES) { // 检查 USB 设备状态和句柄 if (!isUsbWorking || !handle) { spdlog::error("USB device is not working or handle is invalid, attempt {}/{}", retry_count + 1, MAX_RETRIES); if (!restart_usb_device()) { retry_count++; continue; } } // 检查端点是否有效 if (ENDPOINT_IN == 0 || ENDPOINT_OUT == 0) { spdlog::error("Invalid endpoint values: IN={}, OUT={}", ENDPOINT_IN, ENDPOINT_OUT); if (!restart_usb_device()) { retry_count++; continue; } } // 发送控制命令 unsigned char cmd0[8] = {0x92, 0xAC, 0x02, 0x92, 0xE3, 0x71, 0x00, 0x00}; if (!send_usb_command(handle, ENDPOINT_OUT, cmd0, sizeof(cmd0))) { spdlog::error("Failed to send control command, attempt {}/{}", retry_count + 1, MAX_RETRIES); if (!restart_usb_device()) { retry_count++; continue; } } // 如果所有检查都通过,跳出重试循环 break; } // 如果重试次数用完仍然失败 if (retry_count >= MAX_RETRIES) { spdlog::error("Failed to initialize USB device after {} attempts", MAX_RETRIES); return; } // ==== 异步收数流水线 ==== std::vector<usb_ctx *> ctxs(QUEUE_SIZE, nullptr); for (int i = 0; i < QUEUE_SIZE; ++i) { ctxs[i] = new usb_ctx(); ctxs[i]->handle = handle; ctxs[i]->idx = i; ctxs[i]->buffer = new unsigned char[TRANSFER_LEN]; ctxs[i]->transfer = libusb_alloc_transfer(0); libusb_fill_bulk_transfer( ctxs[i]->transfer, handle, ENDPOINT_IN, ctxs[i]->buffer, TRANSFER_LEN, transfer_callback, ctxs[i], // user_data 5000 // timeout ms ); int ret = libusb_submit_transfer(ctxs[i]->transfer); if (ret < 0) { std::cerr << "submit_transfer failed: " << libusb_error_name(ret) << std::endl; // open = false; break; } } // 主循环,每秒统计一次速率 timeval tv = {0, 5000}; // 5ms一次 auto last_tp = std::chrono::steady_clock::now(); uint64_t last_bytes = 0; while (open.load()) { libusb_handle_events_timeout(NULL, &tv); } // 停止后取消所有transfer for (int i = 0; i < QUEUE_SIZE; ++i) { if (ctxs[i] && ctxs[i]->transfer) { libusb_cancel_transfer(ctxs[i]->transfer); } } libusb_handle_events_completed(NULL, NULL); // cleanup: for (int i = 0; i < QUEUE_SIZE; ++i) { if (!ctxs[i]) continue; if (ctxs[i]->transfer) libusb_free_transfer(ctxs[i]->transfer); if (ctxs[i]->buffer) delete[] ctxs[i]->buffer; delete ctxs[i]; } // libusb_release_interface(handle, 0); // libusb_close(handle); // libusb_exit(NULL); } // =========== 数据处理线程 =========== void _run_proc() { char *outBuf = new char[OUT_BUF_LEN]; memset(outBuf, 0, OUT_BUF_LEN); bool find_head = true; std::vector<char> zeroLine(LINE_SIZE, 0); while (open) { if (!_circular_buf.CanRead(OUT_BUF_LEN)) { usleep(50000); continue; } if (find_head) { _circular_buf.BlockRead(outBuf, OUT_BUF_LEN); } // 对齐帧头 if ((unsigned char)outBuf[0] != 0x0E || (unsigned char)outBuf[1] != 0xB9 || (unsigned char)outBuf[2] != 0x0E || (unsigned char)outBuf[3] != 0xB9) { find_head = false; memmove(outBuf, outBuf + 1, OUT_BUF_LEN - 1); _circular_buf.BlockRead(outBuf + OUT_BUF_LEN - 1, 1); continue; } find_head = true; if ((unsigned char)outBuf[7] == 0x12) // 图像数据 { uint32_t a = 0xFF & ((unsigned char)outBuf[8]); uint32_t b = 0xFF & ((unsigned char)outBuf[9]); uint32_t c = 0xFF & ((unsigned char)outBuf[10]); uint32_t d = 0xFF & ((unsigned char)outBuf[11]); uint32_t e = 0xFF & ((unsigned char)outBuf[12]); uint32_t f = 0xFF & ((unsigned char)outBuf[13]); uint32_t picNO = (a << 24) | (b << 16) | (c << 8) | (d); int lineNO = (e << 8) | f; // ====== 采集暗帧 ====== if (isCalcMean && !meanReady) { if (lineNO - 1 >= 0 && lineNO - 1 < BAND_SIZE) { // 这里需要根据每行像素的字节数修改,将每个像素作为 2 字节来处理 for (int j = 0; j < LINE_SIZE / 2; ++j) { // 每个像素由 2 字节组成,读取时按小端格式组合 unsigned short pixel_value = (static_cast<unsigned char>(outBuf[j * 2 + 1]) << 8) | static_cast<unsigned char>(outBuf[j * 2]); // 将每个像素值存储到 dark_mean 中 dark_mean[(lineNO - 1) * (LINE_SIZE / 2) + j] = pixel_value; // 这里注意使用 LINE_SIZE / 2 } // 统计已采集的波段数 band_got[lineNO - 1] = true; int got_count = 0; for (int i = 0; i < BAND_SIZE; ++i) { if (band_got[i]) ++got_count; } if (got_count == BAND_SIZE) { meanReady = true; isCalcMean = false; spdlog::info("Dark frame captured as mean."); // 保存暗数据到 txt 文件 // 获取当前时间并格式化为字符串 auto now = std::chrono::system_clock::now(); std::time_t now_time_t = std::chrono::system_clock::to_time_t(now); std::tm now_tm = *std::localtime(&now_time_t); // 格式化时间为字符串(例如 "2025-06-25_12-30-45.txt") std::ostringstream filename_stream; filename_stream << std::put_time(&now_tm, "%Y-%m-%d_%H-%M-%S"); std::string filename = "/media/myssd/data/dark_mean_" + filename_stream.str() + ".txt"; std::ofstream ofs(filename); if (ofs.is_open()) { for (int band = 0; band < BAND_SIZE; ++band) { for (int j = 0; j < LINE_SIZE / 2; ++j) { ofs << " " << dark_mean[band * (LINE_SIZE / 2) + j]; // 每个波段的像素 } ofs << std::endl; } ofs.close(); spdlog::info("Dark frame saved to /media/myssd/data/dark_mean.txt"); } else { spdlog::error("Failed to open /media/myssd/data/dark_mean.txt for writing!"); } } } } // ========== 仅对 rFlag/gFlag/bFlag 波段做暗场扣除并UDP发送 ========== if (lineNO == rFlag || lineNO == gFlag || lineNO == bFlag) { if (meanReady) { // 暗场已采集完成,做实时扣除 std::vector<char> corrected(OUT_BUF_LEN); // 存放扣除暗场后的数据 int band_idx = lineNO; // 当前行的波段号 for (int j = 0; j < LINE_SIZE / 2; ++j) { // 如果 j 在 0 到 9 之间,原样输出 if (j < 10) { // 直接将原始像素值复制到 corrected 数组中,不进行暗场扣除 corrected[j * 2] = outBuf[j * 2]; // 低字节 corrected[j * 2 + 1] = outBuf[j * 2 + 1]; // 高字节 } else { // 获取原始像素值,2 字节合并(小端格式) unsigned short pixel_value = (static_cast<unsigned char>(outBuf[j * 2 + 1]) << 8) | static_cast<unsigned char>(outBuf[j * 2]); // 获取暗场值(dark_mean 使用小端存储,因此读取时无需额外处理) unsigned short dark_value = dark_mean[band_idx * (LINE_SIZE / 2) + j]; // 扣除暗场值,确保结果在合法范围内 int corrected_pixel = pixel_value - dark_value; if (corrected_pixel < 0) corrected_pixel = 0; if (corrected_pixel > 65535) corrected_pixel = 65535; // 存储修正后的值,分为高字节和低字节(小端格式) corrected[j * 2] = corrected_pixel & 0xFF; // 低字节 corrected[j * 2 + 1] = (corrected_pixel >> 8) & 0xFF; // 高字节 } } // 发送扣除暗场后的数据 // spdlog::info("UDP发送波段 {},已做暗场扣除", lineNO); send_udp_to_win(corrected.data(), OUT_BUF_LEN, WIN_IP, WIN_PORT); } else { // 暗场未采集完成,直接发送原始数据 send_udp_to_win(outBuf, OUT_BUF_LEN, WIN_IP, WIN_PORT); } } // ========== 仅对 rFlag/gFlag/bFlag 波段做暗场扣除并UDP发送 END ========== uint32_t now_lineNO = (picNO - 1) * BAND_SIZE + lineNO; int lostline = now_lineNO - last_lineNO - 1; if (lostline != 0) { spdlog::warn("loasLine {}, now_lineNO {},last_lineNO {},picNO {},lineNO {}", lostline, now_lineNO, last_lineNO, picNO, lineNO); } if (isSaveDat) { // 这里就是要保证从第一行开始存 if (isNO1) { // 如果在保存,先把丢失的0 补充一下,再存当前的数据 if (lostline != 0) { for (uint32_t i = 0; i < lostline; ++i) { // 把这里换成压如新缓存 // g_saveFile_dat.write(zeroLine.data(), OUT_BUF_LEN); if (_circular_buf_write.CanWrite(OUT_BUF_LEN)) // 如果 circular buffer 可以容纳数据 { _circular_buf_write.BlockWrite(zeroLine.data(), OUT_BUF_LEN); } else { std::cout << "_circular_buf_write Buffer is full" << std::endl; } } spdlog::warn("帧 {} 丢行,补 {} 行,丢失区间: {} / {}", picNO, lostline, last_lineNO + 1, now_lineNO - 1); } // 把这里换成压如新缓存 // g_saveFile_dat.write(outBuf, OUT_BUF_LEN); if (_circular_buf_write.CanWrite(OUT_BUF_LEN)) // 如果 circular buffer 可以容纳数据 { _circular_buf_write.BlockWrite(outBuf, OUT_BUF_LEN); } else { std::cout << "_circular_buf_write Buffer is full" << std::endl; } } } last_lineNO = now_lineNO; } else if ((unsigned char)outBuf[7] == 0x11) // 辅助包 { uint32_t a = 0xFF & ((unsigned char)outBuf[8]); uint32_t b = 0xFF & ((unsigned char)outBuf[9]); uint32_t c = 0xFF & ((unsigned char)outBuf[10]); uint32_t d = 0xFF & ((unsigned char)outBuf[11]); uint32_t picNO = (a << 24) | (b << 16) | (c << 8) | (d); static uint32_t last_aux_picNO = 0xFFFFFFFF; std::vector<char> zeroLine(OUT_BUF_LEN, 0); // 判断帧号是否连续 if (last_aux_picNO != 0xFFFFFFFF && picNO != last_aux_picNO + 1) { uint32_t lost = picNO - last_aux_picNO - 1; if (lost > 0) { if (isSaveDat) { for (uint32_t i = 0; i < lost; ++i) g_saveFile_aux.write(zeroLine.data(), OUT_BUF_LEN); } spdlog::warn("辅助包帧号丢失,补 {} 个帧头,丢失区间: {} ~ {}", lost, last_aux_picNO + 1, picNO - 1); } } if (isSaveDat) { g_saveFile_aux.write(outBuf, OUT_BUF_LEN); isNO1 = true; frame_count++; } last_aux_picNO = picNO; } else { spdlog::warn("outBuf[7] is not right"); } } delete[] outBuf; } // =========== 数据保存线程 =========== void _run_write() { char *outBuf = new char[OUT_BUF_LEN]; memset(outBuf, 0, OUT_BUF_LEN); // 从新缓存里取数存入文件 while (run) { if (!_circular_buf_write.CanRead(4096 * 1)) { usleep(50000); continue; } _circular_buf_write.BlockRead(outBuf, 4096 * 1); g_saveFile_dat.write(outBuf, 4096 * 1); } delete[] outBuf; } // =========== 设置线程优先级 =========== void set_thread_priority(std::thread &t, int priority) { pthread_t native_handle = t.native_handle(); struct sched_param param; param.sched_priority = priority; if (pthread_setschedparam(native_handle, SCHED_FIFO, &param) != 0) { std::cerr << "Failed to set thread priority." << std::endl; } } // =========== 开始成像 =========== void start_get_img() { open = true; // 先检查并处理现有线程 if (work_thread_proc.joinable()) { work_thread_proc.join(); } if (work_thread_recv.joinable()) { work_thread_recv.join(); } if (work_thread_write.joinable()) { work_thread_write.join(); } // 检查 USB 设备状态 if (!isUsbWorking) { spdlog::error("USB device is not working"); return; } // 然后创建新线程 work_thread_proc = std::thread(_run_proc); usleep(50000); work_thread_recv = std::thread(_run_recv_async); usleep(50000); work_thread_recv = std::thread(_run_write); set_thread_priority(work_thread_recv, 99); spdlog::info("START GET IMG"); } // =========== 开始落数 =========== void write_envi_hdr(int lines) { g_saveFile_hdr << "ENVI\n"; g_saveFile_hdr << "samples = 2048\n"; g_saveFile_hdr << "lines = " << lines -1 << "\n"; g_saveFile_hdr << "bands = 200\n"; g_saveFile_hdr << "header offset = 0\n"; g_saveFile_hdr << "file type = ENVI Standard\n"; g_saveFile_hdr << "data type = 12\n"; g_saveFile_hdr << "interleave = bil\n"; g_saveFile_hdr << "byte order = 0\n"; g_saveFile_hdr.close(); // spdlog::info("ENVI hdr file written: {}", hdr_path); } void create_dir_if_not_exists(const std::string &dir) { struct stat st; if (stat(dir.c_str(), &st) != 0) { mkdir(dir.c_str(), 0755); } } void start_save_dat(const std::string &path) { // 重置全局统计和状态变量 frame_count = 0; last_picNO = 0xFFFFFFFF; last_lineNO = -1; is_frame_valid = false; last_aux_picNO = 0xFFFFFFFF; last_lineNO = -1; isNO1 = false; // 去除后缀,得到子目录名 std::string baseName = std::regex_replace(path, std::regex("\\.[^.]*$"), ""); std::string subDir = dir + baseName + "/"; create_dir_if_not_exists(subDir); // 关闭之前的文件(如果有) if (g_saveFile_dat.is_open()) g_saveFile_dat.close(); if (g_saveFile_aux.is_open()) g_saveFile_aux.close(); if (g_saveFile_hdr.is_open()) g_saveFile_hdr.close(); std::string fullPath_dat = subDir + baseName + ".dat"; std::string fullPath_aux = subDir + baseName + ".aux"; std::string fullPath_hdr = subDir + baseName + ".hdr"; // 打开新文件 g_saveFile_dat.open(fullPath_dat, std::ios::out | std::ios::binary); g_saveFile_aux.open(fullPath_aux, std::ios::out | std::ios::binary); g_saveFile_hdr.open(fullPath_hdr, std::ios::out | std::ios::binary); if (!g_saveFile_dat.is_open() || !g_saveFile_aux.is_open() || !g_saveFile_hdr.is_open()) { spdlog::error("Failed to open file(s): {}, {}, {}", fullPath_dat, fullPath_aux, fullPath_hdr); isSaveDat = false; return; } isSaveDat = true; spdlog::info("START SAVE DAT, path: {}", fullPath_dat); spdlog::info("START SAVE AUX, path: {}", fullPath_aux); spdlog::info("START SAVE HDR, path: {}", fullPath_hdr); } // =========== 结束落数 =========== void end_save_dat() { isSaveDat = false; write_envi_hdr(frame_count); if (g_saveFile_dat.is_open()) g_saveFile_dat.close(); if (g_saveFile_aux.is_open()) g_saveFile_aux.close(); if (g_saveFile_hdr.is_open()) g_saveFile_hdr.close(); spdlog::info("All save files closed."); } // =========== 结束成像 =========== void end_get_img() { // 如果正在落数,先结束落数 if (isSaveDat) end_save_dat(); usleep(50000); unsigned char cmd0[8] = {0x92, 0xAC, 0x02, 0x92, 0xE4, 0x76, 0x00, 0x00}; send_usb_command(handle, ENDPOINT_OUT, cmd0, sizeof(cmd0)); // usleep(200000); open = false; if (work_thread_recv.joinable()) work_thread_recv.join(); if (work_thread_proc.joinable()) work_thread_proc.join(); spdlog::info("END GET IMG"); } // =========== 主程序入口 =========== int main() { // 初始化相机线程和环形buffer _circular_buf.Initialize(CIRCULAR_BUF_CAPACITY); _circular_buf_write.Initialize(CIRCULAR_BUF_CAPACITY); run = true; // 创建日志器 auto logger = spdlog::get("vis_logger"); if (!logger) { logger = spdlog::basic_logger_mt("vis_logger", "/root/VisServer-YB26/build/server_log.txt"); } spdlog::set_default_logger(logger); spdlog::set_level(spdlog::level::info); // 只记录info及以上级别日志 spdlog::flush_on(spdlog::level::info); // 每条 info 日志都立即写入文件 // 初始化 USB 设备 if (!init_usb_device(handle)) { spdlog::error("Failed to initialize USB device"); return -1; } else { spdlog::info("USB device initialized successfully"); } // socket int server_fd, client_fd; struct sockaddr_in server_addr, client_addr; socklen_t sin_size; char buffer[TCP_BUFFER_SIZE]; // 创建socket server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd == -1) { spdlog::error("socket error: {}", strerror(errno)); return -1; } // 设置 SO_REUSEADDR,避免端口占用导致 bind 失败 int opt = 1; if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) { spdlog::error("setsockopt error: {}", strerror(errno)); close(server_fd); return -1; } // 设置服务器地址结构 memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; // 监听所有IP server_addr.sin_port = htons(SERVER_PORT); // 绑定 if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { spdlog::error("bind error: {}", strerror(errno)); close(server_fd); return -1; } // 监听 if (listen(server_fd, 5) < 0) { spdlog::error("listen error: {}", strerror(errno)); close(server_fd); spdlog::shutdown(); // 确保日志资源释放 return -1; } spdlog::info("Server listening on port {}...", SERVER_PORT); while (run) { sin_size = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &sin_size); if (client_fd < 0) { spdlog::error("accept error: {}", strerror(errno)); continue; } ssize_t recv_len = recv(client_fd, buffer, sizeof(buffer) - 1, 0); if (recv_len == 8) // 确保收到8字节 { // 格式化为十六进制字符串 std::ostringstream oss; oss << "Received cmd: "; for (int i = 0; i < 8; ++i) { oss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << (static_cast<unsigned int>(static_cast<unsigned char>(buffer[i]))) << " "; } spdlog::info(oss.str()); } else { // 变长字符串 std::string recvStr(buffer, recv_len); spdlog::info("Received string: {}", recvStr); // 查找指令映射表 auto it = commandMap.find(recvStr); if (it != commandMap.end()) { // 找到对应指令,处理8字节命令 const auto &cmd = it->second; std::ostringstream oss; for (int i = 0; i < 8; ++i) { oss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << (int)cmd[i] << " "; } spdlog::info("指令名: {}, 指令内容: {}", recvStr, oss.str()); send_usb_command(handle, ENDPOINT_OUT, cmd.data(), cmd.size()); } if (recvStr.find("START_IMAGE") == 0) { spdlog::info("START_IMAGE"); start_get_img(); } if (recvStr.find("END_IMAGE") == 0) { spdlog::info("END_IMAGE"); end_get_img(); } if (recvStr.find("START SAVE DAT PATH =") == 0) { // 解析路径 size_t pos1 = recvStr.find('='); size_t pos2 = recvStr.rfind(';'); if (pos1 != std::string::npos && pos2 != std::string::npos && pos2 > pos1) { std::string path = recvStr.substr(pos1 + 1, pos2 - pos1 - 1); // 去除前后空格 path.erase(0, path.find_first_not_of(" \t")); path.erase(path.find_last_not_of(" \t") + 1); spdlog::info("Parsed save path: {}", path); start_save_dat(path); } } if (recvStr.find("STOP SAVE DAT") == 0) { spdlog::info("STOP SAVE DAT"); end_save_dat(); } if (recvStr.rfind("UPLOAD_TXT ", 0) == 0) { std::string filename = recvStr.substr(strlen("UPLOAD_TXT ")); // 去掉收尾空格/回车换行 filename.erase(filename.find_last_not_of(" \r\n") + 1); // 路径合法性检查,只允许 /mnt/temp/ 开头 if (filename.find("/media/myssd/data/calibration/") != 0) { spdlog::error("拒绝非法路径: {}", filename); close(client_fd); continue; } std::ofstream ofs(filename, std::ios::binary); if (!ofs) { spdlog::error("无法打开 {} 进行写入!", filename); close(client_fd); continue; } // 继续读socket内容直到断开,把所有内容写入txt ssize_t chunk; while ((chunk = recv(client_fd, buffer, sizeof(buffer), 0)) > 0) { ofs.write(buffer, chunk); } ofs.close(); spdlog::info("TXT文件已保存到: {}", filename); close(client_fd); continue; } if (recvStr.find("SET_RGB_FLAG_") == 0) { spdlog::info("SET_RGB_FLAG"); std::string params = recvStr.substr(strlen("SET_RGB_FLAG_")); // 分割字符串 size_t pos1 = params.find('_'); size_t pos2 = params.rfind('_'); if (pos1 != std::string::npos && pos2 != std::string::npos && pos1 != pos2) { try { rFlag = std::stoi(params.substr(0, pos1)); gFlag = std::stoi(params.substr(pos1 + 1, pos2 - pos1 - 1)); bFlag = std::stoi(params.substr(pos2 + 1)); spdlog::info("RGB flags: R={}, G={}, B={}", rFlag, gFlag, bFlag); } catch (const std::exception &e) { spdlog::error("RGB参数解析失败: {}", e.what()); } } else { spdlog::error("RGB参数格式错误: {}", params); } } if (recvStr.find("SET_LOCAL_IP_") == 0) { spdlog::info("SET_LOCAL_IP"); std::string ip = recvStr.substr(strlen("SET_LOCAL_IP_")); // 或 13 win_ip_str = ip; WIN_IP = win_ip_str.c_str(); spdlog::info("WIN_IP set to: {}", WIN_IP); } if (recvStr.find("CALC_MEAN") == 0) { spdlog::info("CALC_MEAN"); if (!isCalcMean) { // 只有没在采集时才允许启动 isCalcMean = true; // 启动采集 meanReady = false; // 标记为未完成 std::fill(band_got.begin(), band_got.end(), false); } else { spdlog::info("CALC_MEAN ignored: already collecting dark frame."); } } if (recvStr.find("CLOSE_MEAN") == 0) { spdlog::info("CLOSE_MEAN"); if (!isCalcMean) { meanReady = false; // 标记为未完成 } else { spdlog::info("CLOSE_MEAN no"); } } if (recvStr.find("QUIT") == 0) { spdlog::info("QUIT"); break; } } close(client_fd); usleep(100000); // 100ms空转 } close(server_fd); run = false; std::cout << "Program end." << std::endl; }帮我检查下
最新发布
07-08
//以下为串口通讯方式的控制程序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <errno.h> #define FINGERPRINT_STARTCODE 0xEF01 //起始码 #define FINGERPRINT_COMMANDPACKET 0x01 //指令包 #define FINGERPRINT_DATA_PACKET 0x02 //数据包 #define FINGERPRINT_ACKPACKET 0x07 //应答包 #define FINGERPRINT_ENDDATAPACKET 0x08 //结束数据包 #define FINGERPRINT_TIMEOUT 1000 //超时时间 int fd = -1; //串口文件描述符 void serialInit(char *port) //串口初始化 { struct termios options; fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { perror("open"); return; } tcgetattr(fd, &options); options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; options.c_iflag = IGNPAR | ICRNL; options.c_oflag = 0; options.c_lflag = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &options); } int serialSend(unsigned char *data, int len) //串口发送数据 { int ret = -1; ret = write(fd, data, len); if (ret < 0) { perror("write"); return -1; } return ret; } int serialRecv(unsigned char *data, int len) //串口接收数据 { int ret = -1; fd_set readfds; struct timeval timeout; FD_ZERO(&readfds); FD_SET(fd, &readfds); timeout.tv_sec = 0; timeout.tv_usec = FINGERPRINT_TIMEOUT; ret = select(fd + 1, &readfds, NULL, NULL, &timeout); if (ret == -1) { perror("select"); return -1; } else if (ret == 0) { printf("select timeout\n"); return -1; } else { ret = read(fd, data, len); if (ret < 0) { perror("read"); return -1; } return ret; } } int fingerprintVerify() //指纹验证 { unsigned char cmd[12] = {0}; //指令 unsigned char recvBuf[12] = {0}; //接收缓存 int ret = -1; //返回值 int i = 0; //计数器 int sum = 0; //校验和 cmd[0] = (FINGERPRINT_STARTCODE >> 8) & 0xff; //起始码高位 cmd[1] = FINGERPRINT_STARTCODE & 0xff; //起始码低位 cmd[2] = 0x00; //设备地址 cmd[3] = 0x03; //数据长度 cmd[4] = FINGERPRINT_COMMANDPACKET; //指令类型 cmd[5] = 0x01; //指令代码 cmd[6] = 0x00; //参数1 cmd[7] = 0x00; //参数2 sum = cmd[4] + cmd[5] + cmd[6] + cmd[7]; //计算校验和 cmd[8] = (sum >> 8) & 0xff; //校验和高位 cmd[9] = sum & 0xff; //校验和低位 cmd[10] = (FINGERPRINT_ENDDATAPACKET >> 8) & 0xff; //结束码高位 cmd[11] = FINGERPRINT_ENDDATAPACKET & 0xff; //结束码低位 ret = serialSend(cmd, sizeof(cmd)); //发送指令 if (ret < 0) { printf("serial send failed\n"); return -1; } ret = serialRecv(recvBuf, sizeof(recvBuf)); //接收应答 if (ret < 0) { printf("serial recv failed\n"); return -1; } if (recvBuf[0] != ((FINGERPRINT_STARTCODE >> 8) & 0xff) || recvBuf[1] != (FINGERPRINT_STARTCODE & 0xff)) //判断起始码 { printf("start code error\n"); return -1; } if (recvBuf[4] != FINGERPRINT_ACKPACKET) //判断是否为应答包 { printf("not ack packet\n"); return -1; } if (recvBuf[5] != 0x01) //判断指令代码 { printf("verification failed\n"); return -1; } return 0; } int main() { serialInit("/dev/ttyUSB0"); //初始化串口 if (fingerprintVerify() == 0) //指纹验证 { printf("verification succeed\n"); } else { printf("verification failed\n"); } close(fd); //关闭串口 return 0; } //以下为USB通讯方式的控制程序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libusb-1.0/libusb.h> #define FINGERPRINT_STARTCODE 0xEF01 //起始码 #define FINGERPRINT_COMMANDPACKET 0x01 //指令包 #define FINGERPRINT_DATA_PACKET 0x02 //数据包 #define FINGERPRINT_ACKPACKET 0x07 //应答包 #define FINGERPRINT_ENDDATAPACKET 0x08 //结束数据包 #define FINGERPRINT_TIMEOUT 1000 //超时时间 libusb_device_handle *dev_handle = NULL; //USB设备句柄 int usbInit() //USB初始化 { int ret = -1; libusb_init(NULL); dev_handle = libusb_open_device_with_vid_pid(NULL, 0x0403, 0x6001); //根据设备的VID和PID打开设备 if (dev_handle == NULL) { printf("open device failed\n"); libusb_exit(NULL); return -1; } ret = libusb_claim_interface(dev_handle, 0); //申请接口0 if (ret < 0) { printf("claim interface failed\n"); libusb_close(dev_handle); libusb_exit(NULL); return -1; } return 0; } int usbSend(unsigned char *data, int len) //USB发送数据 { int ret = -1; ret = libusb_bulk_transfer(dev_handle, 0x02, data, len, &len, FINGERPRINT_TIMEOUT); //使用bulk传输方式发送数据 if (ret < 0) { printf("send data failed\n"); return -1; } return len; } int usbRecv(unsigned char *data, int len) //USB接收数据 { int ret = -1; ret = libusb_bulk_transfer(dev_handle, 0x81, data, len, &len, FINGERPRINT_TIMEOUT); //使用bulk传输方式接收数据 if (ret < 0) { printf("recv data failed\n"); return -1; } return len; } int fingerprintVerify() //指纹验证 { unsigned char cmd[12] = {0}; //指令 unsigned char recvBuf[12] = {0}; //接收缓存 int ret = -1; //返回值 int i = 0; //计数器 int sum = 0; //校验和 cmd[0] = (FINGERPRINT_STARTCODE >> 8) & 0xff; //起始码高位 cmd[1] = FINGERPRINT_STARTCODE & 0xff; //起始码低位 cmd[2] = 0x00; //设备地址 cmd[3] = 0x03; //数据长度 cmd[4] = FINGERPRINT_COMMANDPACKET; //指令类型 cmd[5] = 0x01; //指令代码 cmd[6] = 0x00; //参数1 cmd[7] = 0x00; //参数2 sum = cmd[4] + cmd[5] + cmd[6] + cmd[7]; //计算校验和 cmd[8] = (sum >> 8) & 0xff; //校验和高位 cmd[9] = sum & 0xff; //校验和低位 cmd[10] = (FINGERPRINT_ENDDATAPACKET >> 8) & 0xff; //结束码高位 cmd[11] = FINGERPRINT_ENDDATAPACKET & 0xff; //结束码低位 ret = usbSend(cmd, sizeof(cmd)); //发送指令 if (ret < 0) { printf("usb send failed\n"); return -1; } ret = usbRecv(recvBuf, sizeof(recvBuf)); //接收应答 if (ret < 0) { printf("usb recv failed\n"); return -1; } if (recvBuf[0] != ((FINGERPRINT_STARTCODE >> 8) & 0xff) || recvBuf[1] != (FINGERPRINT_STARTCODE & 0xff)) //判断起始码 { printf("start code error\n"); return -1; } if (recvBuf[4] != FINGERPRINT_ACKPACKET) //判断是否为应答包 { printf("not ack packet\n"); return -1; } if (recvBuf[5] != 0x01) //判断指令代码 { printf("verification failed\n"); return -1; } return 0; } int main() { usbInit(); //初始化USB if (fingerprintVerify() == 0) //指纹验证 { printf("verification succeed\n"); } else { printf("verification failed\n"); } libusb_release_interface(dev_handle, 0); //释放接口0 libusb_close(dev_handle); //关闭设备 libusb_exit(NULL); //退出libusb return 0; } //以下为TTL通讯方式的控制程序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wiringPi.h> #define FINGERPRINT_STARTCODE 0xEF01 //起始码 #define FINGERPRINT_COMMANDPACKET 0x01 //指令包 #define FINGERPRINT_DATA_PACKET 0x02 //数据包 #define FINGERPRINT_ACKPACKET 0x07 //应答包 #define FINGERPRINT_ENDDATAPACKET 0x08 //结束数据包 #define FINGERPRINT_TIMEOUT 1000 //超时时间 const int PIN_TXD = 15; //发送引脚 const int PIN_RXD = 16; //接收引脚 void ttlInit() //TTL初始化 { wiringPiSetup(); pinMode(PIN_TXD, OUTPUT); pinMode(PIN_RXD, INPUT); } int ttlSend(unsigned char *data, int len) //TTL发送数据 { int i = 0; int j = 0; int sum = 0; digitalWrite(PIN_TXD, LOW); delay(10); for (i = 0; i < len; i++) //循环发送每个字节 { for (j = 0; j < 8; j++) //循环发送每个位 { digitalWrite(PIN_TXD, (data[i] >> j) & 0x01); //发送数据位 delayMicroseconds(100); } digitalWrite(PIN_TXD, HIGH); //发送停止位 delayMicroseconds(100); } return len; } int ttlRecv(unsigned char *data, int len) //TTL接收数据 { int i = 0; int j = 0; int ret = -1; int sum = 0; for (i = 0; i < len; i++) //循环接收每个字节 { for (j = 0; j < 8; j++) //循环接收每个位 { while (digitalRead(PIN_RXD) == LOW); //等待接收到起始位 delayMicroseconds(50); data[i] |= digitalRead(PIN_RXD) << j; //接收数据位 } while (digitalRead(PIN_RXD) == HIGH); //等待接收到停止位 delayMicroseconds(50); } return len; } int fingerprintVerify() //指纹验证 { unsigned char cmd[12] = {0}; //指令 unsigned char recvBuf[12] = {0}; //接收缓存 int ret = -1; //返回值 int i = 0; //计数器 int sum = 0; //校验和 cmd[0] = (FINGERPRINT_STARTCODE >> 8) & 0xff; //起始码高位 cmd[1] = FINGERPRINT_STARTCODE & 0xff; //起始码低位 cmd[2] = 0x00; //设备地址 cmd[3] = 0x03; //数据长度 cmd[4] = FINGERPRINT_COMMANDPACKET; //指令类型 cmd[5] = 0x01; //指令代码 cmd[6] = 0x00; //参数1 cmd[7] = 0x00; //参数2 sum = cmd[4] + cmd[5] + cmd[6] + cmd[7]; //计算校验和 cmd[8] = (sum >> 8) & 0xff; //校验和高位 cmd[9] = sum & 0xff; //校验和低位 cmd[10] = (FINGERPRINT_ENDDATAPACKET >> 8) & 0xff; //结束码高位 cmd[11] = FINGERPRINT_ENDDATAPACKET & 0xff; //结束码低位 ret = ttlSend(cmd, sizeof(cmd)); //发送指令 if (ret < 0) { printf("ttl send failed\n"); return -1; } ret = ttlRecv(recvBuf, sizeof(recvBuf)); //接收应答 if (ret < 0) { printf("ttl recv failed\n"); return -1; } if (recvBuf[0] != ((FINGERPRINT_STARTCODE >> 8) & 0xff) || recvBuf[1] != (FINGERPRINT_STARTCODE & 0xff)) //判断起始码 { printf("start code error\n"); return -1; } if (recvBuf[4] != FINGERPRINT_ACKPACKET) //判断是否为应答包 { printf("not ack packet\n"); return -1; } if (recvBuf[5] != 0x01) //判断指令代码 { printf("verification failed\n"); return -1; } return 0; } int main() { ttlInit(); //初始化TTL if (fingerprintVerify() == 0) //指纹验证 { printf("verification succeed\n"); } else { printf("verification failed\n"); } return 0; }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值