19#include <radio_tool/device/ymodem_device.hpp>
36YModemDevice::YModemDevice(
const std::string& port,
const std::string& filename) : port(port), filename(filename), fd(-1)
40 std::stringstream portPath;
41 portPath <<
"\\\\.\\" << port;
43 fdOpen = (int)CreateFileA(portPath.str().c_str(), GENERIC_READ | GENERIC_WRITE, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
45 fdOpen = open(port.c_str(), O_RDWR | O_NOCTTY | O_SYNC);
50 throw std::runtime_error(
"Failed to open port: " + port);
55auto YModemDevice::SetAddress(
const uint32_t&)
const ->
void
57 throw std::runtime_error(
"SetAddress not supported for YModem device");
60auto YModemDevice::Erase(
const uint32_t&)
const ->
void
62 throw std::runtime_error(
"Erase not supported for YModem device");
65auto YModemDevice::Write(
const std::vector<uint8_t>& data)
const ->
void
67 auto fn = std::string(filename);
68 size_t wlen = fymodem_send(fd, (uint8_t*)data.data(), data.size(), fn.data());
69 if (wlen != data.size())
71 throw std::runtime_error(
"Write error");
75auto YModemDevice::Read(
const uint16_t& size)
const -> std::vector<uint8_t>
77 auto ret = std::vector<uint8_t>();
80 auto fn = std::string(filename);
81 auto rsize = fymodem_receive(ret.data(), size, fn.data());
84 throw std::runtime_error(
"Read error");
89auto YModemDevice::Status() const -> const std::
string
94auto YModemDevice::SetInterfaceAttribs(
const uint32_t& speed,
const int& parity)
const ->
int
98 DCB serialParams = { 0 };
99 serialParams.DCBlength =
sizeof(serialParams);
101 auto handle = (HANDLE)fd;
102 GetCommState(handle, &serialParams);
103 serialParams.BaudRate = speed;
104 serialParams.ByteSize = 8;
105 serialParams.StopBits = TWOSTOPBITS;
106 serialParams.Parity = parity;
107 SetCommState(handle, &serialParams);
110 COMMTIMEOUTS timeout = { 0 };
111 timeout.ReadIntervalTimeout = 50;
112 timeout.ReadTotalTimeoutConstant = 50;
113 timeout.ReadTotalTimeoutMultiplier = 50;
114 timeout.WriteTotalTimeoutConstant = 50;
115 timeout.WriteTotalTimeoutMultiplier = 10;
117 SetCommTimeouts(handle, &timeout);
121 if (tcgetattr(fd, &tty) != 0)
123 throw std::runtime_error(
"Error accessing TTY attributes");
127 cfsetospeed(&tty, speed);
128 cfsetispeed(&tty, speed);
130 tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;
133 tty.c_iflag &= ~IGNBRK;
138 tty.c_cc[VTIME] = 20;
140 tty.c_iflag &= ~(IXON | IXOFF | IXANY);
142 tty.c_cflag |= (CLOCAL | CREAD);
144 tty.c_cflag &= ~(PARENB | PARODD);
145 tty.c_cflag |= parity;
146 tty.c_cflag &= ~CSTOPB;
147 tty.c_cflag &= ~CRTSCTS;
149 if (tcsetattr(fd, TCSANOW, &tty) != 0)
151 throw std::runtime_error(
"Error setting TTY attributes");