如何从 pyserialtransfer 的数字列表中重建 python 中的结构

How to reconstruct the structure in python from pyserialtransfer's list of numbers

我正在尝试通过来回传递通用结构在我的笔记本电脑和我的 arduino 之间进行双向通信,但是我无法解压缩从 Arduino 返回的字节。使用 pySerialTransfer,rxBuff returns 似乎是一个数字列表,我无法弄清楚如何将其转换为字节字符串以供 struct.unpack 呈现回我开始使用的数字。

目前,Arduino 代码只是接收数据并将其吐回,没有在 Arduino 端进行任何转换或操作。这是我的 Arduino 代码:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

struct POSITION {
  long id;
  float azimuth;
  float altitude;
} position;


void setup()
{
  Serial.begin(9600);
  myTransfer.begin(Serial);
}

void loop()
{
  if(myTransfer.available())
  {

    myTransfer.rxObj(position, sizeof(position));

    myTransfer.txObj(position, sizeof(position));
    myTransfer.sendData(sizeof(position));

  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}

还有我的 python 代码:

import time
import struct
from pySerialTransfer import pySerialTransfer


def StuffObject(txfer_obj, val, format_string, object_byte_size, start_pos=0):
  """Insert an object into pySerialtxfer TX buffer starting at the specified index.

  Args:
    txfer_obj: txfer - Transfer class instance to communicate over serial
    val: value to be inserted into TX buffer
    format_string: string used with struct.pack to pack the val
    object_byte_size: integer number of bytes of the object to pack
    start_pos: index of the last byte of the float in the TX buffer + 1

  Returns:
    start_pos for next object
  """
  val_bytes = struct.pack(format_string, *val)
  for index in range(object_byte_size):
    txfer_obj.txBuff[index + start_pos] = val_bytes[index]
  return object_byte_size + start_pos


if __name__ == '__main__':
  try:
    link = pySerialTransfer.SerialTransfer('/dev/cu.usbmodem14201', baud=9600)

    link.open()
    time.sleep(2) # allow some time for the Arduino to completely reset
    base = time.time()

    while True:
      time.sleep(0.2)

      sent = (4, 1.2, 2.5)
      format_string = 'iff'
      format_size = 4+4+4
      StuffObject(link, sent, format_string, format_size, start_pos=0)
      link.send(format_size)

      start_time = time.time()
      elapsed_time = 0
      while not link.available() and elapsed_time < 2:
        if link.status < 0:
          print('ERROR: {}'.format(link.status))
        else:
          print('.', end='')
        elapsed_time = time.time()-start_time
      print()

      response =  link.rxBuff[:link.bytesRead]
      print(response)
      response = struct.unpack(format_string, response)

      print('SENT: %s' % str(sent))
      print('RCVD: %s' % str(response))
      print(' ')

  except KeyboardInterrupt:
    link.close()

当我 运行 python 代码时,出现以下错误:

Traceback (most recent call last):
  File "double_float.py", line 54, in <module>
    response = struct.unpack(format_string, response)
TypeError: a bytes-like object is required, not 'list'

但就在错误之前,我打印了响应:[4, 0, 0, 0, 154, 153, 153, 63, 0, 0, 32, 64]

如何将该列表转换成 struct.unpack 可以使用的内容?或者我如何直接解压该数字列表?非常感谢!

这是您要找的吗:

import struct
data = [4, 0, 0, 0, 154, 153, 153, 63, 0, 0, 32, 64]
binary_str = bytearray(data)
result = struct.unpack("<lff", binary_str)
print(result)

输出

(4, 1.2000000476837158, 2.5)