2

I'm developing a python program the reads information from a *.dbc file

dbc_path_in = Path(path, dbc_directory)
dbc_files = {"CAN": [(dbc, 0) for dbc in list(dbc_path_in.glob("*" + ".dbc"))]}
print("dbc_files = " + str(dbc_files))

The dbc file I want to read from has the following format:

BO_ 2024 OBD2: 8 Vector__XXX
 SG_ S1_PID_00_PIDsSupported_01_20 m0 : 31|32@0+ (1,0) [0|4294967295] "" Vector__XXX
 SG_ S1_PID_01_MonitorStatus m1 : 31|32@0+ (1,0) [0|4294967295] "" Vector__XXX
 SG_ S1_PID_02_FreezeDTC m2 : 31|16@0+ (1,0) [0|65535] "" Vector__XXX
 SG_ S1_PID_03_FuelSystemStatus m3 : 31|16@0+ (1,0) [0|65535] "" Vector__XXX
 SG_ S1_PID_04_CalcEngineLoad m4 : 31|8@0+ (0.39216,0) [0|100] "%" Vector__XXX
 SG_ S1_PID_05_EngineCoolantTemp m5 : 31|8@0+ (1,-40) [-40|215] "degC" Vector__XXX
 SG_ S1_PID_06_ShortFuelTrimBank1 m6 : 31|8@0+ (0.78125,-100) [-100|99.21875] "%" Vector__XXX
 SG_ S1_PID_07_LongFuelTrimBank1 m7 : 31|8@0+ (0.78125,-100) [-100|99.21875] "%" Vector__XXX
 SG_ S1_PID_08_ShortFuelTrimBank2 m8 : 31|8@0+ (0.78125,-100) [-100|99.21875] "%" Vector__XXX
 SG_ S1_PID_09_LongFuelTrimBank2 m9 : 31|8@0+ (0.78125,-100) [-100|99.21875] "%" Vector__XXX
 SG_ S1_PID_0A_FuelPressure m10 : 31|8@0+ (3,0) [0|765] "kPa" Vector__XXX
 SG_ S1_PID_0B_IntakeManiAbsPress m11 : 31|8@0+ (1,0) [0|255] "kPa" Vector__XXX
 SG_ S1_PID_0C_EngineRPM m12 : 31|16@0+ (0.25,0) [0|16383.75] "rpm" Vector__XXX
 SG_ S1_PID_0D_VehicleSpeed m13 : 31|8@0+ (1,0) [0|255] "km/h" Vector__XXX

How can I search the dbc_files for the following string CM_ SG_ and store the name that comes after in an array for example

array = {"PIDsSupported", "MonitorStatus", "FreezeDTC",  ... etc} 

2 Answers2

1

This should do it

matched_strings = []
for i in dbc_files["CAN"]:
    with open(i[0], "r") as f:
        for line in f.readlines():
            if ("CM_" in line):
                matched_strings.append(line.split("CM_",1)[1])
            elif ("SG_" in line):
                matched_strings.append(line.split("SG_",1)[1])

I'm assuming by the file provided that you want to match either "CM_" or "SG_", not "CM_ SG_" as stated in the question. If you want to match "CM_ SG_" specifically:

matched_strings = []
for i in dbc_files["CAN"]:
    with open(i[0], "r") as f:
        for line in f.readlines():
            if ("CM_ SG_" in line):
                matched_strings.append(line.split("CM_",1)[1])

0
new_string = str(dbc_files).split(' ')

matched  = []

for i ,string_ in enumerate(new_string):
    if string_ in ["CM_","SG_"]:
        matched.append(new_string[i+1].split('_')[3])

print(matched)

will return:

['PIDsSupported', 'MonitorStatus', 'FreezeDTC', 'FuelSystemStatus', 'CalcEngineLoad', 'EngineCoolantTemp', 'ShortFuelTrimBank1', 'LongFuelTrimBank1', 'ShortFuelTrimBank2', 'LongFuelTrimBank2', 'FuelPressure', 'IntakeManiAbsPress', 'EngineRPM', 'VehicleSpeed']
Guinther Kovalski
  • 1,629
  • 1
  • 7
  • 15