Python Forum

Full Version: best way to use switch case?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello.
I'm reading data that could have ~ 20 differents options (PID from canbus)
what would be the best way to analayze it?
using switcher case?
using if,elif?
other option ?

Thanks,
what do you want to do based on different PID values?
today I know what data goes on which pid
for example :
pid 789 data spped
pid f14 data is total distance
.
.
.

I know how to read and analyze them (this is no the problem)

I want to know waht will be the best way to get and work with them
(Aug-11-2021, 01:16 PM)korenron Wrote: [ -> ]I want to know waht will be the best way to get and work with them
That's exactly what I ask - what "work" you want to do, e.g. "based on PID value execute different function"
Or do you mean how to store each message (e.g. in some data structure)

There is not enough information on what you want to achieve
OK
I didn't thought it metter

this is what I want to do:
read canbus data (I have this working now)
read the PID ( I have this working now)
according to the PID analyze and print what can I know from it( so if I get 7F7 - it will print "this is Speed")
after I will know on with data I'm , I will analyze the data according to the DB ( Byte 1-2 its current speed, byte 3-4 it's avarage speed, 5-7 max speed)
****the speed is only example****
Quote:OBD-II PIDs (On-board diagnostics Parameter IDs) are codes used to request data from a vehicle, used as a diagnostic tool.

But programmers think of Process ID, if they read PID.

Each parameter has it's own PID.
You can define function for each PID, then put all functions in a dict with PID as key and function as value, then read PID from msg, and call the function accordingly, e.g. very simplified example


def speed(message):
    print('This is speed')
    # here you process message

def total_distance(message):
    print('This is total distance')
    # here you process message

pids = {'pid1':speed, 'pid2':total_distance} # preplace pid1, pid2 with actual values
message = read_message() # here is you reading the message
pids[message.id](message)
A step further may be to organize these functions as methods of class that process messages.
OK,
love the idea :-)
but as I said I ahve around 20 PID to analyze ,
so I guess the best and clean way will be methods ?
but I never done it before , can you show example \ link for exaplin ?

Thanks ,
u can try:
class Switch:
    case = {
        1: 'print("banana")',
        2: 'x = 13',
        3: 'x, y = 5, 7',
        4: 'a = [i for i in range(10)]',
        5: 'print("apple")'
        }

myCase = Switch()

exec(myCase.case[3])
print(x, y)
Output:
5 7