Your not just in a separate thread, but a separate process. (Look up thread vs process if your unaware of the difference)  You must do all actions on the USB in that separate process and use queues or other ipc get the data to and from the USB process.





On Feb 26, 2014, at 10:41 AM, Dean Chester <dean.g.chester@gmail.com> wrote:

Hi Wander,

Have you got a suggestion on how to refactor this to get around this issue my current design looks something like this: 
TracerAccess.py: 
import usb
from types import *
import sys
from multiprocessing import Process, Queue
import time


__idVendor__ = 0xFFFF
__idProduct__ = 0xFFFF

END_POINT = 0x82

def __printHEXList__(list):
    print ' '.join('%02x' % b for b in list)

def checkDeviceConnected():
    dev = usb.core.find(idVendor=__idVendor__, idProduct=__idProduct__)
    if dev is None:
        return False
    else:
        return True

class LowLevelAccess():
    def __init__(self):
        self.rawIn = []
        self.tracer = usb.core.find(idVendor=__idVendor__, idProduct=__idProduct__)
        if self.tracer is None:
            raise ValueError("Device not connected")
        self.tracer.set_configuration()

    def readUSB(self):
        """
        This method reads the USB data from the simtracer.
        """
        try:
            tmp = self.tracer.read(END_POINT, 10000,None, 100000).tolist()
            while(self.checkForEmptyData(tmp)):
                tmp = self.tracer.read(END_POINT, 10000,None, 100000).tolist()
            self.rawIn = tmp
        except:
            time.sleep(1)
            self.readUSB()

    def checkForEmptyData(self, raw):
        if(len(raw) == 10 or raw[10] is 0x60 or len(raw) == 11):
            return True
        else:
            return False

class DataAbstraction:
    def __init__(self, queue):
        self.queue = queue
        self.lowLevel = LowLevelAccess()
    def readInput(self):
        while True:
            self.lowLevel.readUSB()
            raw = self.lowLevel.rawIn
            self.queue.put(raw)
ui.py: 
from Tkinter import *
import time
import TracerAccess as io
from multiprocessing import Process, Queue
from Queue import Empty
from math import ceil

def findNumberOfLines(message):
    lines = message.split("\n")
    return len(lines)


class Application(Frame):
    def addTextToRaw(self, text, changeColour=False, numberOfLines=0):
        self.rawText.config(state=NORMAL)
        if changeColour is True:
            self.rawText.insert(END,text, 'oddLine')
        else:
            self.rawText.insert(END,text)
        self.rawText.config(state=DISABLED)

    def updateRaw(self, text):
        if(self.numberOfData() % 2 is not 0):
            self.addTextToRaw(text, True)
        else:
            self.addTextToRaw(text)
    def startTrace(self):
        self.dataAbstraction = io.DataAbstraction(self.queue)
        self.splitProc = Process(target=self.dataAbstraction.readInput)
        self.stopButton.config(state="normal")
        self.startButton.config(state="disabled")
        self.splitProc.start()

    def pollQueue(self):
        try:
            data = self.queue.get(0)
            self.dataReturned.append(data)
            self.updateRaw(str(data).upper())
            self.rawText.tag_config("oddLine", background="#F3F6FA")
        except Empty:
            pass
        finally:
            try:
                if(self.splitProc.is_alive() is False):
                    self.stopButton.config(state="disabled")
                    self.startButton.config(state="normal")
            except AttributeError:
                pass
            self.master.after(10, self.pollQueue)

    def stopTrace(self):
        self.splitProc.join()
        self.stopButton.config(state="disabled")
        self.startButton.config(state="normal")

    def createWidgets(self):
        self.startButton = Button(self)
        self.startButton["text"] = "Start"
        self.startButton["command"] = self.startTrace
        self.startButton.grid(row = 0, column=0)

        self.stopButton = Button(self)
        self.stopButton["text"] = "Stop"
        self.stopButton["command"] = self.stopTrace
        self.stopButton.config(state="disabled")
        self.stopButton.grid(row = 0, column=1)

        self.rawText = Text(self, state=DISABLED, width=82)
        self.rawText.grid(row=1, columnspan=4)


    def __init__(self, master):
        Frame.__init__(self, master)
        self.queue = Queue()
        self.master.after(10, self.pollQueue)
        self.pack()
        self.dataReturned = []
        self.createWidgets()

    def numberOfData(self):
        return len(self.dataReturned)

Main.py:
import ui as ui

if __name__ == "__main__":
    root = Tk()
    root.columnconfigure(0,weight=1)
    app = ui.Application(root)
    app.mainloop()


Kind Regards, 

Dean Chester

On 26 February 2014 16:37, Wander Lairson Costa <wander.lairson@gmail.com> wrote:
2014-02-21 10:19 GMT-03:00 Dean Chester <dean.g.chester@gmail.com>:
> Hi,
>
> I'm running my read call in a separate thread, is this likely to cause
> problems doing this? As currently it keeps failing to read the USB despite
> there being data for it to read. The code works when I run it in the same
> thread as the main application on its own, however now using Process from
> the multiprocessing module it fails to read.
>
> Attached is some of the output with libusb at DEBUG for the log level.
>
> It was working before I put the whole thing in a background process.
>
> What could be going wrong?
>

Hi,

First of all, sorry for the delay, I was in a trip and couldn't check
my email for a few days.

You cannot access the device from different process due to interface
claiming. PyUSB 1.0.0 will be thread safe, but it is not for now (this
is one of pending things that prevents the stable release).


--
Best Regards,
Wander Lairson Costa

------------------------------------------------------------------------------
Flow-based real-time traffic analytics software. Cisco certified tool.
Monitor traffic, SLAs, QoS, Medianet, WAAS etc. with NetFlow Analyzer
Customize your own dashboards, set traffic alerts and generate reports.
Network behavioral analysis & security monitoring. All-in-one tool.
http://pubads.g.doubleclick.net/gampad/clk?id=126839071&iu=/4140/ostg.clktrk
_______________________________________________
pyusb-users mailing list
pyusb-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/pyusb-users

------------------------------------------------------------------------------
Flow-based real-time traffic analytics software. Cisco certified tool.
Monitor traffic, SLAs, QoS, Medianet, WAAS etc. with NetFlow Analyzer
Customize your own dashboards, set traffic alerts and generate reports.
Network behavioral analysis & security monitoring. All-in-one tool.
http://pubads.g.doubleclick.net/gampad/clk?id=126839071&iu=/4140/ostg.clktrk
_______________________________________________
pyusb-users mailing list
pyusb-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/pyusb-users