Search code examples
pythonreal-timeobd-iireal-time-updates

Python constantly refresh variable


I don't know if it's a dumb question, but I'm really struggling with solving this problem.

I'm coding with the obd library. Now my problem with that is the continuous actualization of my variables. For instance, one variable outputs the actual speed of the car. This variable has to be updated every second or 2 seconds. To do this update I have to run 2 lines of code

cmd = obd.commands.RPM
rpm = connection.query(cmd)

but I have to check the rpm variable in some while loops and if statements. (in realtime)

Is there any opportunity to get this thing done ? (another class or thread or something) It would really help me take a leap forward in my programming project.

Thanks :)


Solution

  • use the Async interface instead of the OBD:

    Since the standard query() function is blocking, it can be a hazard for UI event loops. To deal with this, python-OBD has an Async connection object that can be used in place of the standard OBD object. Async is a subclass of OBD, and therefore inherits all of the standard methods. However, Async adds a few in order to control a threaded update loop. This loop will keep the values of your commands up to date with the vehicle. This way, when the user querys the car, the latest response is returned immediately.

    The update loop is controlled by calling start() and stop(). To subscribe a command for updating, call watch() with your requested OBDCommand. Because the update loop is threaded, commands can only be watched while the loop is stoped.

    import obd
    
    connection = obd.Async() # same constructor as 'obd.OBD()'
    
    connection.watch(obd.commands.RPM) # keep track of the RPM
    
    connection.start() # start the async update loop
    
    print connection.query(obd.commands.RPM) # non-blocking, returns immediately
    

    http://python-obd.readthedocs.io/en/latest/Async%20Connections/