agrobot_base/Python/waveshare_usb_can_fd/test4.py

88 lines
2.6 KiB
Python

import ctypes
import time
import os
# Carrega a DLL
dll = ctypes.cdll.LoadLibrary(os.path.abspath("ControlCANFD.dll"))
DEVICE_TYPE = 41 # Confirmado: Waveshare USB-CAN-FD
DEVICE_INDEX = 0
CHANNEL_INDEX = 0
# === Estruturas ===
class VCI_INIT_CONFIG(ctypes.Structure):
_fields_ = [
("AccCode", ctypes.c_uint),
("AccMask", ctypes.c_uint),
("Reserved", ctypes.c_uint),
("Filter", ctypes.c_ubyte),
("Timing0", ctypes.c_ubyte),
("Timing1", ctypes.c_ubyte),
("Mode", ctypes.c_ubyte)
]
class VCI_CAN_OBJ(ctypes.Structure):
_fields_ = [
("ID", ctypes.c_uint),
("TimeStamp", ctypes.c_uint),
("TimeFlag", ctypes.c_ubyte),
("SendType", ctypes.c_ubyte),
("RemoteFlag", ctypes.c_ubyte),
("ExternFlag", ctypes.c_ubyte),
("DataLen", ctypes.c_ubyte),
("Data", ctypes.c_ubyte * 8),
("Reserved", ctypes.c_ubyte * 3)
]
# === Abrir dispositivo ===
ret = dll.VCI_OpenDevice(DEVICE_TYPE, DEVICE_INDEX, 0)
if ret != 1:
print("❌ Falha ao abrir dispositivo.")
exit()
print("✅ Dispositivo aberto.")
# === Configurar canal ===
config = VCI_INIT_CONFIG()
config.AccCode = 0x00000000
config.AccMask = 0xFFFFFFFF
config.Reserved = 0
config.Filter = 0
config.Timing0 = 0x00 # para 500 kbps
config.Timing1 = 0x1C
config.Mode = 0 # normal
ret = dll.VCI_InitCAN(DEVICE_TYPE, DEVICE_INDEX, CHANNEL_INDEX, ctypes.byref(config))
if ret != 1:
print("❌ Falha ao inicializar CAN.")
exit()
dll.VCI_StartCAN(DEVICE_TYPE, DEVICE_INDEX, CHANNEL_INDEX)
print("🚀 Canal iniciado.")
# === Montar frame ===
send_data = VCI_CAN_OBJ()
send_data.ID = 0x011
send_data.SendType = 0 # Normal send
send_data.RemoteFlag = 0
send_data.ExternFlag = 0
send_data.DataLen = 2
send_data.Data[0] = 0x00
send_data.Data[1] = 0x00
ret = dll.VCI_Transmit(DEVICE_TYPE, DEVICE_INDEX, CHANNEL_INDEX, ctypes.byref(send_data), 1)
print(f"📤 Enviado para ID 0x011: 00 00 - Resultado: {ret}")
# === Escutar resposta ===
recv_buffer = (VCI_CAN_OBJ * 100)()
print("🔎 Aguardando resposta por até 3 segundos...")
start = time.time()
while time.time() - start < 3:
recv_count = dll.VCI_Receive(DEVICE_TYPE, DEVICE_INDEX, CHANNEL_INDEX, ctypes.byref(recv_buffer), 100, 100)
if recv_count > 0:
for i in range(recv_count):
can_obj = recv_buffer[i]
data = " ".join(f"{can_obj.Data[j]:02X}" for j in range(can_obj.DataLen))
print(f"🔁 ID: {can_obj.ID:03X}, DLC: {can_obj.DataLen}, Data: {data}")
break
time.sleep(0.1)
else:
print("⌛ Nenhuma resposta recebida.")