Files
CpCtrl/Main/Send.cpp

93 lines
2.9 KiB
C++
Raw Normal View History

2025-06-12 15:28:37 +08:00
#include <cstring>
#include "Send.h"
#include "GlobalDefs.h"
using namespace std;
Send::Send() {
try {
running_ = true;
std::unordered_map<std::string, std::string> config;
configFromIni("./CPCtrlConfig.ini", config);
if (config["mode"] == "udp") {
isUdp = true;
UdpReceiver.reset(new UDPReceiver(stoi(config["recvPort"])));
UdpReceiver->start_receiving(([](const std::vector<uint8_t> &data, sockaddr_in addr,
socklen_t len) {
myDateTime tmp;
string log = tmp.toDateTime() + " Recv: " + string(data.begin(), data.end());
cout << log;
historyList.push_back(log);
}));
UdpSender.reset(new UDPSender(UdpReceiver->sockfd_));
UdpSender->set_destination(config["ip"], stoi(config["sendPort"]));
cout << "udp link [" + config["recvPort"] + "] sendto \"" + config["ip"] + ":" + config["sendPort"]+"\"" << endl;
}
else {
isUdp = false;
if (config["hh"] == "true") {
isHH = true;
}
else {
isHH = false;
}
Serial.reset(new SerialPort(config["device"], stoi(config["baudRate"])));
Serial->start_receiving(([](const std::vector<uint8_t> &data) {
myDateTime tmp;
string log = tmp.toDateTime() + " Recv: " + string(data.begin(), data.end());
cout << log;
historyList.push_back(log);
}));
cout << "serial link [" + config["device"] + "] baudRate:" + config["baudRate"] + " HH:" + config["hh"]<<endl;
}
}
catch (std::exception &e) {
cerr << e.what() << endl;
running_ = false;
}
}
size_t Send::sendto(const string &data) {
if (isUdp) {
return UdpSender->send((uint8_t *) data.data(), data.size());
}
else {
if (isHH) {
char tmp[6] = "\xeb\x90\x07\x00";
uint16_t len = htons(data.size());
memcpy(tmp + 4, &len, 2);
string str = string(tmp,tmp+6) + data;
return Serial->write(str);
}
else {
return Serial->write(data);
}
}
}
size_t Send::sendto(const vector<uint8_t> &data) {
if (isUdp) {
return UdpSender->send((uint8_t *) data.data(), data.size());
}
else {
if (isHH) {
vector<uint8_t> tmpStr(data);
char tmp[6] = "\xeb\x90\x07\x00";
uint16_t len = htons(data.size());
memcpy(tmp + 4, &len, 2);
vector<uint8_t> str = vector<uint8_t>(tmp,tmp+6);
for (auto i: data) {
str.push_back(i);
}
return Serial->write(str);
}
else {
return Serial->write(data);
}
}
}
bool Send::isRunning() const {
return running_;
}