У меня есть некоторые проблемы с интерфейсом COM. Я хочу получить необработанные данные (моя последняя цель — заставить их работать на низком уровне) от датчиков, но приведенные примеры кодов приведены только для MATLAB и C ++. Итак, я просто следую коду MATLAB и преобразовываю их в python.
Проблема здесь. Каждая команда инициализации и настройки выполнена. И сенсор работает нормально (точно работает). Но я понятия не имею с чтением данных из буфера, который, вероятно, уже прибыл.
Итак, я был бы очень рад услышать ваш совет ……..
Благодарю.
import win32com.client
import win32api
import win32event
import pythoncom
from win32com.client import gencache
import numpy as npclass XdaCallbacks:
def OnLiveDataAvailable(self, p_data):
dev = p_data[0] # did = g_xda.XsDevice_deviceId(dev) #print ("Data received for ", g_xda.XsDeviceId_toString(did))
pack = p_data[1]
if (g_xda.XsDataPacket_containsOrientation(pack)):
print(g_xda.XsDataPacket_orientationEuler(pack, g_xda.XsOutputSettings_XOS_Coordinates_Ned()))
g_xda.dataPacketHandled(dev, pack)pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
xda = win32com.client.Dispatch("xsensdeviceapi_com64.IXsensDeviceApi")
xda2=win32com.client.DispatchWithEvents("xsensdeviceapi_com64.IXsensDeviceApi.OnLiveDataAvailable", XdaCallbacks)
g_xda = xda
version = xda.XsControl_version
print(version)
xda.XsControl_flushInputBuffers()def stopAll() :
if(np.all(xda.eventlistners)!=0) :
xda.unregisterevent(['onLiveDataAvailable',id(handleData)])
xda.setCallbackOption(xda.XsComCallbackOptions_XSC_None, xda.XsComCallbackOptions_XSC_LivePacket)
else : print('Endup all')
xda.XsDevice_stopRecording(device)
xda.XsDevice_gotoConfig(device)
xda.XsDevice_disableRadio(device)
xda.XsDevice_closeLogFile(device)
xda.XsControl_closePort(portS)
xda.XsControl_close()
del (xda, g_xda)######################################################################################################
# Scanning connection ports
# if errors occured 'isMtw' are not in tuple or something > you should double check that Dongle is in sleepmode or notp_br = xda.XsScanner_scanPorts(0, 100, 1, 0)
print('p_br=', p_br)
lengpbr = len(p_br)
print('Array Length of p_br is', lengpbr)
print(type(p_br))
isMtw = xda.XsDeviceId_isMtw(p_br[0][0])
isDongle = xda.XsDeviceId_isAwindaDongle(p_br[0][0])
isAwindaStation = xda.XsDeviceId_isAwindaStation(p_br[0][0])
message = 'What device is connected at COM[MTw=%s , Dongle=%s, AwindaStation=%s]' % (isMtw, isDongle, isAwindaStation)
print(message)# port scan gives back information about the device, use first device found.
deviceID = p_br[0][0]
portS = p_br[0][2]
baudRate = p_br[0][3]
print(deviceID)
print(portS)
print(baudRate)
message = "\nFound %s on port %s, with ID: %s and baudRate: %d \n" % (devTypeStr, portS, str(deviceID), baudRate)
print(message)
if not (xda.XsControl_openPort(portS, baudRate, 0, 1)):
print('\nUnable to open port %s. \n' % portS)
xda.XsControl_close()
del xda
##################################################################################################
##Initialize Master Device
device = xda.XsControl_device(deviceID) # To get device handle.
## To be able to get orientation data from a MTw, the filter in the software needs to be turned on:
xda.XsDevice_gotoConfig(device)
xda.XsDevice_setOptions(device, 0, 0) # The second input parameter data type is an integer
# print(xda.XsDevice_areOptionsEnabled) #XsOptions are true if it's enabled, if not false##Setup update rate>>Supported update rate in MTw User manual p.34
supportUpdateRates = xda.XsDevice_supportedUpdateRates(device, 0)
upRateIndex = 0.1
while (np.all(upRateIndex == 0.1)):
print('\n The supported update rates are: ')
print(supportUpdateRates)
print('\n')
selectedUpdateRate = int(input(' Which update rate do you want to use ? '))
if (np.all(selectedUpdateRate == 0)):
continue
upRateIndex = supportUpdateRates.index(selectedUpdateRate)
print('Selected Update Rate = ', supportUpdateRates[upRateIndex])xda.XsDevice_setUpdateRate(device, supportUpdateRates[upRateIndex]) # Selected upRateIndex 설정##Setting Radio channel
AvailableRadioChannels = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
upRadioChIndex = 0.1
while (np.all(upRadioChIndex == 0.1)):
print('\n The Available radio channels are : ')
print(AvailableRadioChannels)
selectedRadioCh = int(input('Which radio channel do you want to use ?'))
if (np.all(selectedRadioCh == 0)):
continue
upRadioChIndex = AvailableRadioChannels.index(selectedRadioCh)
print('Selected Radio Channel =', AvailableRadioChannels[upRadioChIndex])
try:
xda.XsDevice_enableRadio(device, AvailableRadioChannels[upRadioChIndex]) # select radio channel
except:
print("Radio is still turned on, remove device from pc and try again")
input('\n Undock the MTw devices from the Awinda station and wait until the devices are connected(synced leds), then press enter...\n')
# If all the sequences are done within this step, Every MTws have to be synchronized together.##Check which devices are found
children = xda.XsDevice_children(device)
print(children)
devIdAll = [None] * len(children)
devIdAllarraylength = len(devIdAll)
for i in range(0, (devIdAllarraylength)):
devIdAll[i] = hex(xda.XsDevice_deviceId(children[i]))
print(devIdAll)
isMtw = xda.XsDeviceId_isMtw(xda.XsDevice_deviceId(children[0]))################################################################################################
##Entering measurement modeoutput = xda.XsDevice_gotoMeasurement(device) ##goto measurement
print('\n Activate measurement mode =', output)if (isDongle & isMtw): ## display radio connection information
print('\n Connection has been established on channel ', xda.XsDevice_radioChannel(device),
'with an update rate of ', xda.XsDevice_updateRate(device), 'Hz\n')
else:
assert (np.all(isMtw == 0))
print('\n Connection has been established with an update rate of', xda.XsDevice_updateRate(device), 'Hz\n')xda.XsDevice_createLogFile(device, 'exampleLogfile.txt')
xda.XsDevice_startRecording(device)
xda.setCallbackOption(xda.XsComCallbackOptions_XSC_Packets(), xda.XsComCallbackOptions_XSC_None())
#win32com.client.DispatchWithEvents("OnLiveDataAvailable", XdaCallbacks)
input("Press any key to finish")stopAll()
Задача ещё не решена.
Других решений пока нет …