У меня есть сценарий Python, который отправляет поток данных, а затем у меня есть встроенный компьютер Linux, принимающий данные (код написан на C ++).В большинстве случаев это работает, однако я замечаю, что данные искажаются при отправке определенных шаблонов байтов .Некоторое время я боролся с этим и не знаю, как его решить.
Скрипт Python (отправитель):
serial = serial.Serial("COM2", 115200, timeout=5)
all_bytes = [0x63,0x20,0x72,0x69,0x67,0x68,0x74,0x73,0x20,0x61,0x6e,0x64,0x20,0x72,0x65,0x73,0x74,0x72,0x69,0x63,0x74,0x69,0x6f,0x6e,0x73,0x20,0x69,0x6e,0x0a,0x68,0x6f,0x77,0xff,0x20,0xf0,0x8b]
fmt = "B"*len(all_bytes)
byte_array = struct.pack(fmt,*all_bytes)
serial.write(byte_array)
Код C ++ (получатель)
typedef std::vector<uint8_t> ustring; // ustring = vector containing a bunch of uint8_t elements
// configure the port
int UART::configure_port()
{
struct termios port_settings; // structure to store the port settings in
cfsetispeed(&port_settings, B115200); // set baud rates
cfsetospeed(&port_settings, B115200);
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
port_settings.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
port_settings.c_cc[VTIME] = 10; // n seconds read timeout
//port_settings.c_cc[VMIN] = 0; // blocking read until 1 character arrives
port_settings.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
port_settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
port_settings.c_oflag &= ~OPOST; // make raw
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
return(fd);
}
int UART::uart_read(ustring *data,int buffer_size)
{
// Buffer
uint8_t * buf = new uint8_t[buffer_size];
// Flush contents of the serial port
//tcflush(fd, TCIOFLUSH);
//usleep(1000);
ustring data_received;
// Read
int n_bytes = 0;
while (n_bytes < buffer_size)
{
int n = read( fd, buf , buffer_size );
// Some bytes were read!
if (n > 0)
{
n_bytes+=n;
// Add to buffer new data!
for( int i=0; i<n; i++ )
{
data_received.push_back(buf[i]);
}
}
}
// String received
*data = data_received;
cout << "Data received..." << endl;
print_ustring(data_received);
delete[] buf;
return read_valid;
}
int main()
{
UART uart_connection;
vector<uint8_t> data;
vector<uint8_t> *data_ptr = &data;
int status = uart_connection.uart_read(data_ptr,36);
return 0;
}
Вот что происходит:
Если я отправляю следующие байты (из python):
0x632072696768747320616e64207265737472696374696f6e7320696e0a686f77ff20f08b
Это то, что я получаю (в программе C ++):
0x632072696768747320616e64207265737472696374696f6e7320696e0a686f77ffff20f0
Как видите, в конце есть несколько байтов (CRC), которые изменились, остальные, кажется, в порядке.Но это не всегда происходит, это происходит только при отправке определенного шаблона байтов.
Допустим, я отправляю, например, следующее (какой-то другой шаблон):
0x6868686868686868686868686868686868686868686868686868686868686868b18cf5b2
Я получаю именно то, что отправляю в вышеуказанном шаблоне!
Как вы думаете,это может быть Pyserial, меняющий мои неподписанные байты на ASCII?Я понятия не имею, что происходит.Я боролся с этим в течение нескольких дней!
РЕДАКТИРОВАТЬ
Для всех, кто заинтересован, очевидно, проблема заключалась в том, что struct termios должна быть инициализирована сразу после ее объявления.
Вот код, который решил это:
// configure the port
int UART::configure_port()
{
struct termios port_settings; // structure to store the port settings in
tcgetattr(fd, &port_settings);
// Open ttys4
fd = open("/dev/ttyS4", O_RDWR | O_NOCTTY );
if(fd == -1) // if open is unsucessful
{
//perror("open_port: Unable to open /dev/ttyS0 - ");
printf("open_port: Unable to open /dev/ttyS4. \n");
}
else
{
fcntl(fd, F_SETFL, 0);
/* get the current options */
printf("port is open.\n");
cfsetispeed(&port_settings, B9600); // set baud rates
cfsetospeed(&port_settings, B9600);
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB; //Stop bits = 1
port_settings.c_cflag &= ~CSIZE; // clear mask
port_settings.c_cflag |= CS8; // data bits = 8
port_settings.c_cflag &= ~CRTSCTS; // Turn off hardware flow control
port_settings.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
port_settings.c_cc[VMIN] = 0; // blocking read until 1 character arrives
// port_settings.c_cc[VTIME] = 10; // n seconds read timeout
port_settings.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
port_settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw -- NON Cannonical mode
// port_settings.c_iflag |= IGNPAR; // Input parity options
// port_settings.c_oflag &= ~OPOST; // make raw
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
}
return(fd);
}