Pārlūkot izejas kodu

出差中修改了部分代码,现在属于一个较为稳定版本:1.增加了通过配置文件进行修改的信号延迟选项;2.增加了usb设备的序号配置文件选项;3.修改了信号延迟方式;4.目前通过usb设备的总线跟地址从小到大进行排序来对设备进行排序,确定了每个设备的顺序

kappo96 1 mēnesi atpakaļ
vecāks
revīzija
67d75db82c

+ 5 - 0
.gitignore

@@ -4150,3 +4150,8 @@ build/CMakeFiles/UVC_Demo.dir/LogRecorder/LogOutput.cpp.o
 build/configure/config.json
 build/configure/log.json
 build/log/UsbDevice.log
+
+# under build directory all ignored files
+build/*
+
+

BIN
16ddc9f52cb0ac4409f650e606782d28.png


+ 2 - 3
AIManager/PPYOLOE.cpp

@@ -8,7 +8,6 @@
 #include <exception>
 #include <iostream>
 
-
 PPYOLOE::PPYOLOE() : ctx(0), model_data(nullptr), model_data_size(0), resize_buf(nullptr) {}
 
 PPYOLOE::~PPYOLOE()
@@ -95,7 +94,7 @@ bool PPYOLOE::initialize(const std::string &model_path)
 /// @param input_image 输入图像的格式为BGR
 /// @param output_image 直接将结果绘制到输出图像
 /// @return
-bool PPYOLOE::infer(int index, unsigned char *input_data, int input_width, int intput_height,DataPackage* result)
+bool PPYOLOE::infer(int index, unsigned char *input_data, int input_width, int intput_height, DataPackage *result)
 {
     rknn_input inputs[io_num.n_input];
     rknn_output outputs[io_num.n_output];
@@ -103,7 +102,7 @@ bool PPYOLOE::infer(int index, unsigned char *input_data, int input_width, int i
     memset(outputs, 0, sizeof(outputs));
 
     const float nms_threshold = 0.45;     // 默认的NMS阈值
-    const float box_conf_threshold = 0.5; // 默认的置信度阈值
+    const float box_conf_threshold = 0.3; // 默认的置信度阈值
 
     inputs[0].index = 0;
     inputs[0].type = RKNN_TENSOR_UINT8;

+ 3 - 7
AIManager/RKNNManager.cpp

@@ -82,6 +82,8 @@ void RKNNManager::taskThread(std::string modelpath)
                         LOG_ERROR("Inference failed for index {}", index);
                     }
 
+                    std::cout << "Inference result count " << dataPackage->Result.count << std::endl;
+
                     DataList *pDatalist = client.R360SendMessage(dataPackage);
 
                     if (!writer->Write(*pDatalist))
@@ -104,13 +106,7 @@ void RKNNManager::taskThread(std::string modelpath)
                     LOG_ERROR("Exception in data processing loop: {}", e.what());
                     if (dataPackage)
                     {
-                        try
-                        {
-                            DataManager::getInstance().releaseDataBuffer<DataPackage>(dataPackage);
-                        }
-                        catch (...)
-                        { /* 忽略释放时的异常 */
-                        }
+                        DataManager::getInstance().releaseDataBuffer<DataPackage>(dataPackage);
                     }
                 }
                 catch (...)

+ 96 - 96
ImageTest/ImageTest.h

@@ -74,101 +74,101 @@ namespace UsbTest
         }
     };
 
-    class SimulateTrigger
-    {
-    public:
-        static SimulateTrigger &getInstance()
-        {
-            static SimulateTrigger instance;
-            return instance;
-        }
-
-        void startTrigger()
-        {
-            if (!triggering)
-            {
-                triggering = true;
-                triggerStatus.resize(3);
-                triggerStatus[0] = false;
-                triggerStatus[1] = false;
-                triggerStatus[2] = false;
-                triggerThread = std::thread(&SimulateTrigger::triggerLoop, this);
-            }
-        }
-
-        void stopTrigger()
-        {
-            if (triggering)
-            {
-                triggering = false;
-                if (triggerThread.joinable())
-                {
-                    triggerThread.join();
-                }
-            }
-        }
-
-        bool isTriggering(int index)
-        {
-            bool status = triggerStatus[index];
-            std::lock_guard<std::mutex> lock(triggerMutex);
-            triggerStatus[index] = false;
-            return status;
-        }
-
-    private:
-        SimulateTrigger() : triggering(false) {}
-        ~SimulateTrigger()
-        {
-            stopTrigger();
-        }
-
-        // Delete copy constructor and assignment operator to prevent copying
-        SimulateTrigger(const SimulateTrigger &) = delete;
-        SimulateTrigger &operator=(const SimulateTrigger &) = delete;
-
-        void triggerLoop()
-        {
-            while (triggering)
-            {
-                std::this_thread::sleep_for(std::chrono::milliseconds(188));
-                if (triggering)
-                {
-                    // Simulate the trigger signal
-                    std::lock_guard<std::mutex> lock(triggerMutex);
-                    triggerStatus[0] = true;
-                    triggerStatus[1] = true;
-                    triggerStatus[2] = true;
-                }
-            }
-        }
-
-        std::atomic<bool> triggering;
-        std::thread triggerThread;
-        std::mutex triggerMutex;
-        std::vector<bool> triggerStatus;
-    };
-
-    class GlobalResolutionTimer : public HighResolutionTimer
-    {
-    public:
-        static GlobalResolutionTimer &getInstance()
-        {
-            static GlobalResolutionTimer instance;
-            return instance;
-        }
-
-        void start()
-        {
-            start_time = std::chrono::high_resolution_clock::now();
-        }
-
-        std::string pressStopWatchString()
-        {
-            end_time = std::chrono::high_resolution_clock::now();
-            return "Elapsed Time: " + std::to_string(elapsed_milliseconds()) + " ms";
-        }
-    };
+    // class SimulateTrigger
+    // {
+    // public:
+    //     static SimulateTrigger &getInstance()
+    //     {
+    //         static SimulateTrigger instance;
+    //         return instance;
+    //     }
+
+    //     void startTrigger()
+    //     {
+    //         if (!triggering)
+    //         {
+    //             triggering = true;
+    //             triggerStatus.resize(3);
+    //             triggerStatus[0] = false;
+    //             triggerStatus[1] = false;
+    //             triggerStatus[2] = false;
+    //             triggerThread = std::thread(&SimulateTrigger::triggerLoop, this);
+    //         }
+    //     }
+
+    //     void stopTrigger()
+    //     {
+    //         if (triggering)
+    //         {
+    //             triggering = false;
+    //             if (triggerThread.joinable())
+    //             {
+    //                 triggerThread.join();
+    //             }
+    //         }
+    //     }
+
+    //     bool isTriggering(int index)
+    //     {
+    //         bool status = triggerStatus[index];
+    //         std::lock_guard<std::mutex> lock(triggerMutex);
+    //         triggerStatus[index] = false;
+    //         return status;
+    //     }
+
+    // private:
+    //     SimulateTrigger() : triggering(false) {}
+    //     ~SimulateTrigger()
+    //     {
+    //         stopTrigger();
+    //     }
+
+    //     // Delete copy constructor and assignment operator to prevent copying
+    //     SimulateTrigger(const SimulateTrigger &) = delete;
+    //     SimulateTrigger &operator=(const SimulateTrigger &) = delete;
+
+    //     void triggerLoop()
+    //     {
+    //         while (triggering)
+    //         {
+    //             std::this_thread::sleep_for(std::chrono::milliseconds(188));
+    //             if (triggering)
+    //             {
+    //                 // Simulate the trigger signal
+    //                 std::lock_guard<std::mutex> lock(triggerMutex);
+    //                 triggerStatus[0] = true;
+    //                 triggerStatus[1] = true;
+    //                 triggerStatus[2] = true;
+    //             }
+    //         }
+    //     }
+
+    //     std::atomic<bool> triggering;
+    //     std::thread triggerThread;
+    //     std::mutex triggerMutex;
+    //     std::vector<bool> triggerStatus;
+    // };
+
+    // class GlobalResolutionTimer : public HighResolutionTimer
+    // {
+    // public:
+    //     static GlobalResolutionTimer &getInstance()
+    //     {
+    //         static GlobalResolutionTimer instance;
+    //         return instance;
+    //     }
+
+    //     void start()
+    //     {
+    //         start_time = std::chrono::high_resolution_clock::now();
+    //     }
+
+    //     std::string pressStopWatchString()
+    //     {
+    //         end_time = std::chrono::high_resolution_clock::now();
+    //         return "Elapsed Time: " + std::to_string(elapsed_milliseconds()) + " ms";
+    //     }
+    // };
 
     class SimulateTrigger
     {
@@ -227,7 +227,7 @@ namespace UsbTest
         {
             while (triggering)
             {
-                std::this_thread::sleep_for(std::chrono::milliseconds(188));
+                std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                 if (triggering)
                 {
                     // Simulate the trigger signal

+ 29 - 27
UVCGrabber/UVCCallBack.cpp

@@ -5,6 +5,7 @@
 #include <fstream>
 #include <vector>
 #include <memory>
+#include <filesystem>
 #include "../libuvc/libuvc.h"
 #include "UVCDeviceManager.h"
 #include "../DataManager/DataManager.h"
@@ -29,23 +30,12 @@ void cbSaveToLocal(uvc_frame_t *frame, void *ptr)
   static const char *H264_FILE = "iOSDevLog.h264";
   static const char *MJPEG_FILE = ".jpeg";
   char filename[264];
+  std::string FileSavePath = "";
   std::fstream log_file("CallBackLog.txt", std::ios::app);
   DataPackagePtr dataPackage = nullptr;
   // static MemoryPool<DataPackage> dataPool(BUFFER_SIZE, 3840, 2160);
   std::shared_ptr<DataPipe<DataPackage>> pipe;
 
-  // std::fstream readImage("./auv.jpg", std::ios::binary | std::ios::in);
-  // if (!readImage)
-  // {
-  //   std::cerr << "不能打开文件 example.bin" << std::endl;
-  // }
-  // readImage.seekg(0, std::ios::end);
-  // std::streamsize fileSize = readImage.tellg();
-  // readImage.seekg(0, std::ios::beg);
-  // unsigned char *buffer = new unsigned char[fileSize];
-  // readImage.read((char *)buffer, fileSize);
-  // readImage.close();
-
   switch (frame->frame_format)
   {
   case UVC_FRAME_FORMAT_H264:
@@ -56,22 +46,41 @@ void cbSaveToLocal(uvc_frame_t *frame, void *ptr)
     break;
   case UVC_COLOR_FORMAT_MJPEG:
 
-    // if (!g_gpioExplorer->getFailingStatus(index))
+    if (!g_gpioExplorer->getFailingStatus(index))
+    {
+      // std::cout << "Pass this wave" << std::endl;
+      break;
+    }
+    g_gpioExplorer->resetFailingStatus(index);
+
+    // if(!UsbTest::SimulateTrigger::getInstance().isTriggering(index))
     // {
-    //   // std::cout << "Pass this wave" << std::endl;
     //   break;
     // }
-    // g_gpioExplorer->resetFailingStatus(index);
 
-    if(!UsbTest::SimulateTrigger::getInstance().isTriggering(index))
-    {
-      break;
-    }
 
     if (jpeg_count[index] / 23 >= 1)
       jpeg_group[index]++;
     jpeg_count[index] = jpeg_count[index] % 23;
     std::cout << "Current File Device " << index << " UVC Index : " << jpeg_count[index] << std::endl;
+
+    // 在 data/ 文件夹下创建文件夹,文件夹名称为设备索引
+    // if (!std::filesystem::exists("./data/" + std::to_string(index)))
+    // {
+    //   std::filesystem::create_directory("./data/" + std::to_string(index));
+    // }
+
+    // FileSavePath = "./data/" + std::to_string(index) + "/" + std::to_string(jpeg_group[index]) + "-" + std::to_string(jpeg_count[index]++) + MJPEG_FILE;
+
+    // fp = fopen(FileSavePath.c_str(), "wb");
+    // if (fp == NULL)
+    // {
+    //   std::cerr << "Failed to open file: " << FileSavePath << std::endl;
+    //   return;
+    // }
+    // fwrite(frame->data, 1, frame->data_bytes, fp);
+    // fclose(fp);
+
     // sprintf(filename, "./data/%d/%d-%d%s", index, jpeg_group[index], jpeg_count[index]++, MJPEG_FILE);
 
     dataPackage = DataManager::getInstance().acquireDataBuffer<DataPackage>();
@@ -82,18 +91,11 @@ void cbSaveToLocal(uvc_frame_t *frame, void *ptr)
     dataPackage->nWidth = frame->width;
     dataPackage->nHeight = frame->height;
     dataPackage->nTimeStamp = frame->capture_time_finished.tv_sec * 1000 + frame->capture_time_finished.tv_nsec / 1000000;
-    dataPackage->nCameraID = index;
+    dataPackage->nCameraID = UVCManager::getInstance().getDeviceNumber(index);
     dataPackage->dDegree = jpeg_count[index]++;
 
-    //std::string logMessage = "UVC Frame Received: Device " + std::to_string(index) + " UVC Received: Degree: " + std::to_string(jpeg_count[index] - 1) + UsbTest::GlobalResolutionTimer::getInstance().pressStopWatchString();
-    //UsbTest::TimeRecorder::getInstance().recordTime(logMessage);
-
     DataManager::getInstance().pushData<DataPackage>("uvc" + std::to_string(index), dataPackage);
 
-    // fp = fopen("./Ouput4k.jpg", "w");
-    // fwrite(frame->data, 1, frame->data_bytes, fp);
-    // fclose(fp);
-
     break;
   case UVC_COLOR_FORMAT_YUYV:
     break;

+ 18 - 3
UVCGrabber/UVCDevice.cpp

@@ -1,7 +1,7 @@
 #include "UVCDevice.h"
 #include <iostream>
 
-void UVCDevice::init(int index,uvc_context_t *ctx, uvc_device_t *dev)
+void UVCDevice::init(int index, uvc_context_t *ctx, uvc_device_t *dev)
 {
     uvc_error_t ret;
     uvc_device_descriptor_t *des;
@@ -63,6 +63,8 @@ void UVCDevice::startStreaming()
 {
     uvc_error_t res;
 
+    uvc_device_t *dev_device = uvc_get_device(devh);
+
     res = uvc_get_stream_ctrl_format_size(devh, &ctrl, frame_format, width, height, fps);
     if (res < 0)
     {
@@ -81,11 +83,24 @@ void UVCDevice::startStreaming()
     puts("Streaming...");
     /* enable auto exposure - see uvc_set_ae_mode documentation */
     puts("Enabling auto exposure ...");
-    const uint8_t UVC_AUTO_EXPOSURE_MODE_AUTO = 2;
+    const uint8_t UVC_AUTO_EXPOSURE_MODE_AUTO = 4;
     res = uvc_set_ae_mode(devh, UVC_AUTO_EXPOSURE_MODE_AUTO);
     if (res == UVC_SUCCESS)
     {
-        puts(" ... enabled auto exposure");
+        // puts(" ... enabled auto exposure");
+        //set exposure time
+        uint32_t exposure_time = 250; // 1 second in microseconds
+        res = uvc_set_exposure_abs(devh, exposure_time);
+        // res = uvc_set_white_balance_component_auto(devh,0);
+        if (res < 0)
+        {
+            uvc_perror(res, " ... uvc_set_exposure_abs failed");
+        }
+        else
+        {
+            puts(" ... exposure time set to 1 second");
+        }
+
     }
     else if (res == UVC_ERROR_PIPE)
     {

+ 5 - 0
UVCGrabber/UVCDevice.h

@@ -21,6 +21,9 @@ public:
 
   uvc_device_handle_t *getDevh() { return devh; }
 
+  void setTotalIndex(int total_index) { this->total_index = total_index; }
+  int getTotalIndex() { return total_index; }
+
   // start streaming
   void startStreaming();
   // stop streaming
@@ -44,5 +47,7 @@ private:
 
   uvc_frame_callback_t *cb;
 
+  int total_index{0};
+
   // store the frame data
 };

+ 40 - 3
UVCGrabber/UVCDeviceManager.cpp

@@ -2,7 +2,7 @@
 #include "../DataManager/DataManager.h"
 #include "../DataManager/DataPackage.h"
 
-void UVCManager::init()
+void UVCManager::init(int nWaitingTime)
 {
     // get device list
     uvc_device_t **deviceList;
@@ -16,19 +16,56 @@ void UVCManager::init()
     }
     std::cout << "Device Number: " << deviceNum << std::endl;
 
+    uvc_device_t **OrderedDeviceList = new uvc_device_t *[deviceNum];
+    for (int i = 0; i < deviceNum; i++)
+    {
+        int minBus = 255;
+        int minAddress = 255;
+        int minBusIndex = -1;
+        int minAddressIndex = -1;
+        for (int j = 0; j < deviceNum; j++)
+        {
+            if (deviceList[j] == nullptr)
+            {
+                continue;
+            }
+            int bus = uvc_get_bus_number(deviceList[j]);
+            if (bus < minBus)
+            {
+                minBus = bus;
+                minBusIndex = j;
+                minAddress = uvc_get_device_address(deviceList[j]);
+                minAddressIndex = j;
+            }
+            else if (bus == minBus && uvc_get_device_address(deviceList[j]) < minAddress)
+            {
+                minAddress = uvc_get_device_address(deviceList[j]);
+                minAddressIndex = j;
+            }
+        }
+        OrderedDeviceList[i] = deviceList[minBusIndex];
+        deviceList[minBusIndex] = nullptr;
+    }
+
     // init the Uvc device by deviceNum
     for (int i = 0; i < deviceNum; i++)
     {
         UVCDevice *uvcDevice = new UVCDevice();
-        uvcDevice->init(i, ctx, deviceList[i]);
+        uvcDevice->init(i, ctx, OrderedDeviceList[i]);
         uvcDevice->setCallBack(cbSaveToLocal);
         uvcDeviceList.push_back(uvcDevice);
 
+        int bus = uvc_get_bus_number(OrderedDeviceList[i]);
+        int address = uvc_get_device_address(OrderedDeviceList[i]);
+        std::cout << "Device " << i << " Bus: " << bus << " Address: " << address << std::endl;
+
         // init the data manager
-        DataManager::getInstance().addDataPipe<DataPackage>("uvc" + std::to_string(i));
+        DataManager::getInstance()
+            .addDataPipe<DataPackage>("uvc" + std::to_string(i));
     }
 
     m_GpioExplorer = std::make_shared<GPIOExplorer>("gpiochip0", 16);
+    m_GpioExplorer->setWaitingTime(nWaitingTime);
 }
 
 int UVCManager::deliverFrameInCallBack(uvc_device_handle_t *devh)

+ 28 - 5
UVCGrabber/UVCDeviceManager.h

@@ -1,7 +1,6 @@
 #ifndef UVCDEVICE_MANAGER_H
 #define UVCDEVICE_MANAGER_H
 
-
 #include "../libuvc/libuvc.h"
 #include "../MppDecoder/MppDecoder.h"
 #include <stdio.h>
@@ -24,7 +23,34 @@ public:
         return instance;
     }
 
-    void init();
+    void init(int nWaitingTime);
+
+    void setDeviceNumber(int deviceNumber, int TotoalDeviceNumber)
+    {
+        int nNumber = int(uvcDeviceList.size());
+        if (deviceNumber >= nNumber)
+        {
+            std::cerr << "Device number out of range" << std::endl;
+            return;
+        }
+        std::list<UVCDevice *>::iterator it = uvcDeviceList.begin();
+        std::advance(it, deviceNumber);
+        std::cout << "Setting device number: " << TotoalDeviceNumber << std::endl;
+        (*it)->setTotalIndex(TotoalDeviceNumber);
+    }
+
+    int getDeviceNumber(int deviceNumber)
+    {
+        int nNumber = int(uvcDeviceList.size());
+        if (deviceNumber >= nNumber)
+        {
+            std::cerr << "Device number out of range" << std::endl;
+            return -1;
+        }
+        std::list<UVCDevice *>::iterator it = uvcDeviceList.begin();
+        std::advance(it, deviceNumber);
+        return (*it)->getTotalIndex();
+    }
 
     int deliverFrameInCallBack(uvc_device_handle_t *devh);
 
@@ -62,9 +88,6 @@ private:
 
     //
     std::shared_ptr<GPIOExplorer> m_GpioExplorer;
-
-    
-
 };
 
 #endif // UVCDEVICE_MANAGER_H

+ 6 - 0
config.json

@@ -2,4 +2,10 @@
     "grpc_server_address": "192.168.210.37:50051",
     "rknn_model_path": "../ppyoloe.rknn",
     "log_path": "./log.txt"
+    ,"usb_device_number":[
+        17,
+        7,
+        13
+    ]
+    ,"usb_grab_waiting_time":100
 }

+ 2 - 1
gpio_explorer.cpp

@@ -48,9 +48,10 @@ GPIOExplorer::GPIOExplorer(const char *chipname, int line_offset)
                     if(detectZWave())
                     {
                         std::lock_guard<std::mutex> lock(m_mutex);
+                        std::this_thread::sleep_for(std::chrono::milliseconds(m_nWaitingTime));
                         FailingStatus = 0x07;
                         //std::cout << "Status changed!!" << std::endl;
-                        std::this_thread::sleep_for(std::chrono::milliseconds(50));
+                        //std::cout << "Waiting time is " << m_nWaitingTime <<std::endl;
                     }
                     StatusKeep = ret;
                 }

+ 6 - 0
gpio_explorer.hpp

@@ -8,6 +8,10 @@ class GPIOExplorer
 public:
     GPIOExplorer(const char *chipname, int line_offset);
     ~GPIOExplorer();
+    int setWaitingTime(int nTime){
+        std::lock_guard<std::mutex> lock(m_mutex);
+        m_nWaitingTime = nTime;
+    }
     int read();
     int monitorRisingEdge();
     bool getFailingStatus(int index) { 
@@ -32,6 +36,8 @@ private:
     unsigned char FailingStatus{0x00};
 
     std::mutex m_mutex;
+
+    int m_nWaitingTime = 50;
 };
 
 extern GPIOExplorer* g_gpioExplorer;

+ 17 - 3
main.cpp

@@ -8,6 +8,7 @@
 #include "ImageTest/ImageTest.h"
 #include <stdexcept>
 #include <iostream>
+#include <thread>
 #include <json.hpp>
 
 #define DEVICE_NUM 3
@@ -42,11 +43,17 @@ int main(int argc, char **argv)
     if (OmniLoger::CLoger::get_instance().log_sink != nullptr)
     {
         std::cout << "Log initialized successfully" << std::endl;
-        OmniLoger::CLoger::get_instance().log_sink->error("Error occurred during initialization");
+        //OmniLoger::CLoger::get_instance().log_sink->error("Error occurred during initialization");
     }
 
     // Initialize the UVC manager
-    UVCManager::getInstance().init();
+    UVCManager::getInstance().init(int(config["usb_grab_waiting_time"]));
+
+
+
+    UVCManager::getInstance().setDeviceNumber(0, config["usb_device_number"][0]);
+    UVCManager::getInstance().setDeviceNumber(1, config["usb_device_number"][1]);
+    UVCManager::getInstance().setDeviceNumber(2, config["usb_device_number"][2]);
 
     MppManager::getInstance().addMppDecode();
 
@@ -57,8 +64,15 @@ int main(int argc, char **argv)
     // Start all streaming
     UVCManager::getInstance().startAllStreaming();
 
+    OmniLoger::CLoger::get_instance().log_sink->info("All streaming started successfully");
+
     // Wait for the user to press a key
-    std::cin.get();
+    while(true){
+     std::this_thread::sleep_for(std::chrono::seconds(1));
+    }
+    // std::cin.get();
+
+    std::cout << "Stopping all streaming..." << std::endl;
 
     RKNNManager::getInstance().StopProcessData();