2013-05-08 75 views
2

我在使用pyUSB庫從ELM327 OBDII向USB設備讀取數據時遇到問題。我知道我需要在寫入端點上向設備寫入命令,並在讀取端點上讀取接收到的數據。它似乎並不想爲我工作。使用pyUSB從ELM327 OBDII向USB設備讀取數據

我寫了這個我自己的類obdusb:

import usb.core 

class obdusb: 

     def __init__(self,_vend,_prod): 

    '''Handle to USB device''' 
    self.idVendor = _vend 
    self.idProduct = _prod 
    self._dev = usb.core.find(idVendor=_vend, idProduct=_prod) 

    return None 


def GetDevice(self): 
    '''Must be called after constructor''' 
    return self._dev 


def SetupEndpoint(self): 
    '''Must be called after constructor''' 
    try: 
     self._dev.set_configuration() 

    except usb.core.USBError as e: 
     sys.exit("Could not set configuration") 

    self._endpointWrite = self._dev[0][(0,0)][1] 
    self._endpointRead = self._dev[0][(0,0)][0] 

    #Resetting device and setting vehicle protocol (Auto) 
    #20ms is required as a delay between each written command 

    #ATZ resets device 
    self._dev.write(self._endpointWrite.bEndpointAddress,'ATZ',0) 
    sleep(0.002) 
    #ATSP 0 should set vehicle protocol automatically 
    self._dev.write(self._endpointWrite.bEndpointAddress,'ATSP 0',0) 
    sleep(0.02) 

    return self._endpointRead 


def GetData(self,strCommand): 

    data = [] 
    self._dev.write(self._endpintWrite.bEndpointAddress,strCommand,0) 
    sleep(0.002) 
    data = self._dev.read(self._endpointRead.bEndpointAddress, self._endpointRead.wMaxPacketSize) 

    return data 

所以我再使用這個類,並使用此代碼調用GetData方法:

import obdusb 

#Setting up library,device and endpoint 
lib = obdusb.obdusb(0x0403,0x6001) 
myDev = lib.GetDevice() 
endp = lib.SetupEndpoint() 

#Testing GetData function with random OBD command 
#0902 is VIN number of vehicle being requested 
dataArr = lib.GetData('0902') 
PrintResults(dataArr) 

raw_input("Press any key") 

def PrintResults(arr): 

    size = len(arr) 

    print "Data currently in buffer:" 

    for i in range(0,size): 
     print "[" + str(i) + "]: " + str(make[i]) 

這永遠只能輸出數字1和數組中的[0]和[1]元素爲60。沒有其他數據已從命令返回。無論設備是否連接到汽車,都是這種情況。我不知道這2條信息是什麼。我期待它返回一串十六進制數字。有人知道我在這裏做錯了嗎?

回答

2

如果您不使用ATST或ATAT,則必須在每個寫入/讀取組合之間的啓動時間超過200毫秒。

你是否在每條命令後發送'\ r'?它看起來像你沒有,所以它永遠在等待回車。

並提示:測試010D或010C或其他東西。 09xx可能很難預料。

更新: 你可以這樣做。只要你用回車「分開」每個命令。

http://elmelectronics.com/ELM327/AT_Commands.pdf http://elmelectronics.com/DSheets/ELM327DS.pdf(擴大清單)。

該命令列表對我來說非常有用。

ATAT可用於調整超時。 當您發送010D時,ELM芯片將通常等待200毫秒,以獲得所有可能的反應。有時你可以得到更多的回報,所以它等待200毫秒。

,你還可以做什麼,這是一個謎,因爲只有SCANTOOLS傾向於實現這一點:

「010D1/R」

的1命令後,指定ELM應該報到,當它有1個回覆。所以它能夠非常有效地減少延遲,但代價是無法從地址'010D'中獲得更多的值。 (這是速度!)

對不起,我希望寄給你正確的方向。

+1

感謝您的評論。我不知道它期待回車。由於沒有太多的信息,這些東西很難研究。我可以用命令發送回車還是必須單獨發送? ATAT命令實際上做了什麼?如果我使用它,我可以省略時間延遲?你能否向我指出一些與此相關的資源?這是很多問題:P再次感謝:) – Granttastic 2013-05-08 22:04:34

+0

@Granttastic,更新了我的答案! :) – 2013-05-09 18:35:33

+0

你能幫我關於獲取VIN號碼響應這個問題嗎? http://stackoverflow.com/questions/19158165/unable-to-get-vin-number-response-from-obd-2-device – iCoder 2013-10-05 06:47:35