实现串口监控功能,重构 ComKit::Work 方法以支持指定端口

This commit is contained in:
JIe 2024-11-07 17:35:02 +08:00
parent cea5209222
commit 7316c326d0
7 changed files with 365 additions and 312 deletions

View File

@ -38,7 +38,7 @@ class ComKit {
static std::vector<ComStruct> *GetAllComPortNames();
static void Start(std::string, std::string);
static void End();
static void Work();
static void Work(const std::string& port_name);
static bool ChangeComPortNumber(const std::string &oldPortName,
const std::string &newPortName);
static std::vector<std::string> watchingComPort;

28
include/ComWatch.h Normal file
View File

@ -0,0 +1,28 @@
#ifndef COMWATCH_H
#include "serial.h"
#include "spdlog/spdlog.h"
#include <functional>
#include <string>
#include <mutex>
#include <thread>
enum class SIGNAL_TYPE{
REMOVE_,
ADD_,
};
class SerialWatch {
private:
std::function<void(const std::string&, SIGNAL_TYPE type)> callback;
std::jthread work_thread;
std::stop_source s;
std::mutex m;
public:
SerialWatch() = default;
~SerialWatch();
void set_callback(std::function<void(const std::string&, SIGNAL_TYPE type)> func);
void work();
};
#endif // !COMWATCH_H

View File

@ -73,11 +73,9 @@ namespace serial {
template <_SupportString T> [[maybe_unused]] std::string _to_string(T &&str) {
if constexpr (std::is_same_v<std::decay_t<T>, std::string>) {
return str;
}
else if constexpr (std::is_same_v<std::decay_t<T>, std::string_view>) {
} else if constexpr (std::is_same_v<std::decay_t<T>, std::string_view>) {
return std::move(std::string(str.data()));
}
else if constexpr (std::is_same_v<std::decay_t<T>, const char*>) {
} else if constexpr (std::is_same_v<std::decay_t<T>, const char *>) {
return std::string(str);
}
}
@ -94,8 +92,10 @@ namespace serial {
comname.c_str(), static_cast<DWORD>(GENERIC_WRITE) | GENERIC_READ,
0U, nullptr, OPEN_EXISTING, 0U, nullptr);
if (m_handle != INVALID_HANDLE_VALUE) {
portArray.push_back(showname);
portArray.emplace_back(showname);
CloseHandle(m_handle);
} else if(GetLastError() == ERROR_ACCESS_DENIED){
portArray.emplace_back(showname);
}
comname.clear();
showname.clear();
@ -185,8 +185,7 @@ namespace serial {
static_cast<::SerialStopBits>(stopBits));
if (code == 1) {
return true;
}
else {
} else {
return false;
}
}
@ -291,8 +290,7 @@ namespace serial {
}
template <int timeout = 200, _SupportString T, _SupportString... Args>
std::string GetAtUntilAndReturn(T command, Args... expect)
{
std::string GetAtUntilAndReturn(T command, Args... expect) {
auto endTime = std::chrono::system_clock::now() +
std::chrono::milliseconds(timeout);
ser.flushReceiver();

View File

@ -136,21 +136,12 @@ void ComKit::Start(std::string watchingPort, std::string input_commands) {
commands = std::move(Split(input_commands));
isWorking = true;
}
void ComKit::Work() {
void ComKit::Work(const std::string &port_name) {
if (isWorking) {
std::thread([]() {
std::lock_guard<std::mutex> lock(m);
auto currentPortStructures = GetAllComPortNames();
std::vector<std::string> currentPorts;
for (auto s : *currentPortStructures) {
currentPorts.emplace_back(s.comPortName);
}
for (auto &port : watchingComPort) {
if (std::find(currentPorts.begin(), currentPorts.end(), port) !=
currentPorts.end()) {
spdlog::info(
std::format("Start Work With Port [{}]", port));
device.OpenDevice(port);
if (ranges::find(watchingComPort, port_name) != watchingComPort.end())
std::thread([&port_name]() {
spdlog::info(std::format("start working with [{}]", port_name));
device.OpenDevice(port_name);
for (auto &command : commands) {
spdlog::info(std::format("Send Command: {}", command));
std::this_thread::sleep_for(50ms);
@ -159,8 +150,6 @@ void ComKit::Work() {
FlushLog();
}
device.CloseDevice();
}
}
}).detach();
}
}

45
src/ComWatch.cc Normal file
View File

@ -0,0 +1,45 @@
#include "ComWatch.h"
#include <algorithm>
#include <chrono>
#include <ranges>
namespace ranges = std::ranges;
namespace views = std::ranges::views;
using namespace std::literals::chrono_literals;
SerialWatch::~SerialWatch() {
s.request_stop();
if (work_thread.joinable()) {
work_thread.join();
}
}
void SerialWatch::set_callback(
std::function<void(const std::string&, SIGNAL_TYPE type)> func) {
this->callback = func;
}
void SerialWatch::work() {
this->work_thread = std::jthread(
[this](std::stop_token token) {
std::vector<std::string> pre_ports;
while (!token.stop_requested()) {
auto curr_ports = serial::GetUsbPorts();
for (auto &&port : pre_ports) {
if (ranges::find(curr_ports, port) == curr_ports.end()) {
std::lock_guard<std::mutex> lock(m);
if (callback)
callback(port, SIGNAL_TYPE::REMOVE_);
}
}
for (auto &&port : curr_ports) {
if (ranges::find(pre_ports, port) == pre_ports.end()) {
std::lock_guard<std::mutex> lock(m);
if (callback)
callback(port, SIGNAL_TYPE::ADD_);
}
}
pre_ports = std::move(curr_ports);
std::this_thread::sleep_for(500ms);
}
},
s.get_token());
}

View File

@ -1,4 +1,5 @@
#include "ComKit.h"
#include "ComWatch.h"
#include "imgui_helper.h"
#include "imgui_stdlib.h"
#include "spdlog/sinks/basic_file_sink.h"
@ -67,6 +68,25 @@ int main(int argc, char **) {
filterComName = config.at("ComPorts").as_string();
inputCommands = config.at("Commands").as_string();
}
SerialWatch watcher;
watcher.set_callback([](const std::string &port_name, SIGNAL_TYPE type) {
switch (type) {
case SIGNAL_TYPE::REMOVE_:
spdlog::log(spdlog::level::debug,
std::format("port: [{}] removed", port_name));
ComKit::FlushLog();
ComKit::GetAllComPortNames();
break;
case SIGNAL_TYPE::ADD_:
spdlog::log(spdlog::level::debug,
std::format("port: [{}] add", port_name));
ComKit::FlushLog();
ComKit::GetAllComPortNames();
ComKit::Work(port_name);
break;
}
});
watcher.work();
while (isRunning)
helper.Render(
[&]() {

View File

@ -90,34 +90,7 @@ LRESULT ImGuiHelper::WndProc(HWND hWnd, UINT msg, WPARAM wParam,
PDEV_BROADCAST_HDR pHdr = reinterpret_cast<PDEV_BROADCAST_HDR>(lParam);
switch (wParam) {
case DBT_DEVICEARRIVAL:
if (pHdr->dbch_devicetype == DBT_DEVTYP_PORT) {
PDEV_BROADCAST_PORT pPort =
reinterpret_cast<PDEV_BROADCAST_PORT>(pHdr);
spdlog::log(spdlog::level::debug,
std::format("port: [{}] add", pPort->dbcp_name));
ComKit::FlushLog();
ComKit::GetAllComPortNames();
ComKit::Work();
} else {
spdlog::log(spdlog::level::debug,
std::format("port: other device [{}] add",
pHdr->dbch_devicetype));
}
break;
case DBT_DEVICEREMOVECOMPLETE:
if (pHdr->dbch_devicetype == DBT_DEVTYP_PORT) {
PDEV_BROADCAST_PORT pPort =
reinterpret_cast<PDEV_BROADCAST_PORT>(pHdr);
spdlog::log(
spdlog::level::debug,
std::format("port: [{}] removed", pPort->dbcp_name));
ComKit::FlushLog();
ComKit::GetAllComPortNames();
} else {
spdlog::log(spdlog::level::debug,
std::format("port: other device [{}] add",
pHdr->dbch_devicetype));
}
break;
}
}