liquid = [l_press,l_dosage,l_bottle,l_position,l_clog,l_counter]
for j in range(len(liquid)):
data = liquid_filling(liquid[j])
publish.single(liquid[j],data,qos = 0, hostname = hostname,port=2259)
def liquid_filling(topic):
if topic == "Liquid_filling/pressure":
message = random.uniform(4.0,5.0)
elif topic == "Liquid_filling/dosage":
message = random.uniform(495.0,505.0)
elif topic == "Liquid_filling/bottle_presence" or topic== "Liquid_filling/position" or topic=="Caps/position":
if i % 2 == 0:
message = 'YES'
else:
message = 'NO'
elif topic == "Liquid_filling/counter":
message = i
return message
I receive the following error:
Error: local variable 'message' referenced before assignment
I think that it must be something related with the alignment of the code but I have double-check it and I can't find any problem. Also, the variable message is only used to return a value.
I have already checked other related questions in this forum and I still cannot find the answer.
I would appreciate your help.
CodePudding user response:
In your case this is happening because for some reason the topic
is not passing in your if
conditions.
As there is no else
, automatically when it does not pass the conditions you will not have message
defined, causing it to not find for the return.
Make a new check of the value sent for analysis of conditions or to test that it did not pass any of the conditions, add:
else:
message = 'not pass conditions'
And you will receive this (not pass conditions
) value as a return, proving that it did not pass the conditions.
In short: you are looking for the problem in the wrong place in your code.
CodePudding user response:
I solved it. It was that I had a topic named "Caps/position" and it should be named "Liquid_filling/position".
The code that works is as follows:
def liquid_filling(topic):
if topic == "Liquid_filling/pressure":
message = random.uniform(4.0,5.0)
elif topic == "Liquid_filling/dosage":
message = random.uniform(495.0,505.0)
elif topic == "Liquid_filling/bottle_presence" or topic== "Liquid_filling/position" or topic=="Liquid_filling/anti_clogging":
if i % 2 == 0:
message = 'YES'
else:
message = 'NO'
elif topic == "Liquid_filling/counter":
message = i
else:
message = 'There is an error'
return message
Thanks for your comments because I was able to realize the problem!