Python Forum
Python code with serial port and global undefined - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python code with serial port and global undefined (/thread-1605.html)

Pages: 1 2


Python code with serial port and global undefined - marciokoko - Jan-16-2017

I have the following code and I got this error after adding a few ser.close() lines (identified with *** down below):

Quote:File "tsrb430.py", line 162, in read
    responseBits = convert_hex_to_bin_str (x)
NameError: global name 'convert_hex_to_bin_str' is not defined

Could it be because after the serial is opened in the self.write() method, execution is sent to the self.read() method which at its end closes the serial with a ser.close() which I just added, and returns execution to the two self.read() calls in self.write()?  Because I didnt get this error before.  But then again I wasnt really calling self.read() either.

def relayToggle(self):
timestring = AIHome.results['Relay1ON']
print timestring
hours,minutes = timestring.split(":")
print hours
print minutes
print(datetime.datetime.now())
ref_time = datetime.datetime.combine(datetime.datetime.now(), datetime.time(int(hours), int(minutes)))
if ref_time > datetime.datetime.now():
print("ref_time>relay should be OFF")
self.write(1,0)
else:
print("now>relay should be ON")
self.write(1,1)

def write(self, relay, state):
ser = serial.Serial(
port='/dev/serial0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print "Serial is open: " + str(ser.isOpen())
print "Now Writing"
print relay
print state
self.read()***

while True:
# Relay1ON 1
if relay == 1 & state == 0:
ser.write("o")
print ('Relay toggled off')
break

# case 2
if relay == 1 & state == 1:
ser.write("e")
print ('Relay toggled on')
break

# else case 3
print ('something else')
ser.write("o")
x = ser.readline()
print "Something else '" + x + "'"
break

print "Did write, now read"
x = ser.readline()
print "Writing & Reading got '" + x + "'"
self.read()***
ser.close()


def read(self):
ser = serial.Serial(
port='/dev/serial0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)

print "Read:Serial is open: " + str(ser.isOpen())
print "Read:Now Reading"
ser.write("[")
print "Did read"
x = ser.readline()
print "Read:Reading got '" + x + "'"
responseBits = convert_hex_to_bin_str (x)
responseBits = responseBits.zfill(4)
responseBits = list(responseBits)
responseBits.reverse()
relayStates = {}
relay = 1
for bit in responseBits:
relayStates[relay] = int(bit)
relay += 1
self.relayStatesD = relayStates
#report states to someone?
print relayStatesD
ser.close()***

def convert_hex_to_int(hexChars):
try:
ints = [ord(char) for char in hexChars]
return ints
except TypeError:
pass
return []

def convert_hex_to_bin_str(hexChars):
response = convert_hex_to_int(hexChars)[0]
responseBinary = bin(response)
return responseBinary[2:]



RE: Python code with serial port and global undefined - Larz60+ - Jan-16-2017

The error your getting is for line #162
Your script ends at line 99

See something wrong here?

Your code listing is totally messed up, indentation in wrong places,
Also the script is convert_hex_to_bin_str is not defined.

Is line 162 in another function?


RE: Python code with serial port and global undefined - marciokoko - Jan-16-2017

No, I didn't post the whole code, just the relevant methods


RE: Python code with serial port and global undefined - micseydel - Jan-16-2017

You should post enough code to reproduce the problem. If that's too much code, then hard-code around the problem until you have a small representative snippet.


RE: Python code with serial port and global undefined - Larz60+ - Jan-16-2017

Quote:No, I didn't post the whole code, just the relevant methods

But, if the error is in code that's not posted, don't you think that code is relevant?


RE: Python code with serial port and global undefined - marciokoko - Jan-16-2017

Yes, you are right, I understand. I guess I should have mentioned that line 162 corresponds to line 97 in the posted code. But sure, Ill post the code when I get home as I am away from that computer at the moment.


RE: Python code with serial port and global undefined - marciokoko - Jan-16-2017

Ok here it is:

# class to hold read and write
#!/usr/bin/env python

import serial
import logging
import time, datetime
from firebase import firebase
from firebase_token_generator import create_token
from apscheduler.schedulers.blocking import BlockingScheduler

class AIHome:

def __init__(self, onTime, offTime):

self.onTime=onTime
self.offTime=offTime
self.updateInterval = 6
self.webPush = False
self.relayStatesA = []
self.relayStatesD = {}
logging.basicConfig()
#Call fetchUpdate every 6 hours

print('initting AIHome...scheduling job')
sched = BlockingScheduler()
@sched.scheduled_job('interval', hours=1)
def timed_job():
print('This job runs every 6 hrs. timed_job gets called or something else')
#call fetchUpdate()
self.fetchUpdate();

sched.configure()
#options_from_ini_file
sched.start()
 
def fetchUpdate(self):
   #Must separate credentials
AIHome.authentication = firebase.FirebaseAuthentication('key', 'iemail', extra={'id': 123})
AIHome.firebase = firebase.FirebaseApplication('https://myapp.firebaseio.com/', AIHome.authentication)
print AIHome.authentication.extra

AIHome.user = AIHome.authentication.get_user()
print AIHome.user.firebase_auth_token

#Data format returned = {u'Relay1ON': 1800, u'Relay1OFF': u'0600'} 
AIHome.results = AIHome.firebase.get('/Relays', None)#, {'print': 'pretty'})
print AIHome.results

#Commented out for debugging purposes
print AIHome.results['Relay1ON']
print AIHome.results['Relay1OFF']

#Call time comparator method
self.relayToggle()



def relayToggle(self):

timestring = AIHome.results['Relay1ON']
print timestring
hours,minutes = timestring.split(":")
print hours
print minutes
print(datetime.datetime.now())
ref_time = datetime.datetime.combine(datetime.datetime.now(), datetime.time(int(hours), int(minutes)))
if ref_time > datetime.datetime.now():
print("ref_time>relay should be OFF")
self.write(1,0)
else:
print("now>relay should be ON")
self.write(1,1)

def write(self, relay, state):
   #MUST contain code to reconnect or connect to MAC
   #IF BT NOT CONNECTED THEN AT+CONNL or SEARHCH FOR THIS MAC & CONNECT:___________ 
ser = serial.Serial(
port='/dev/serial0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print "Serial is open: " + str(ser.isOpen())
print "Now Writing"
#ser.write("AT+CONNL")
print relay
print state
self.read()

#switch case
while True:
# Relay1ON 1
if relay == 1 & state == 0:
ser.write("o")
print ('Relay toggled off')
break

# case 2
if relay == 1 & state == 1:
ser.write("e")
print ('Relay toggled on')
break

# else case 3
print ('something else')
ser.write("o")
x = ser.readline()
print "Something else '" + x + "'"
break


print "Did write, now read"
x = ser.readline()
print "Writing & Reading got '" + x + "'"
self.read()
ser.close()

# To be used later when fetching relay states from app or web
def read(self):
ser = serial.Serial(
port='/dev/serial0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)

print "Read:Serial is open: " + str(ser.isOpen())
print "Read:Now Reading"
ser.write("[")
print "Did read"
x = ser.readline()
print "Read:Reading got '" + x + "'"
#***if ser.close() at self.read then response will be null/false, so code around it or dont close***
responseBits = convert_hex_to_bin_str (x)
responseBits = responseBits.zfill(4)
responseBits = list(responseBits)
responseBits.reverse()
relayStates = {}
relay = 1
for bit in responseBits:
relayStates[relay] = int(bit)
relay += 1
self.relayStatesD = relayStates
#report states to someone?
print relayStatesD
#***ser.close()

def convert_hex_to_int(hexChars):
#convert string of hex chars to a list of ints
try:
ints = [ord(char) for char in hexChars]
return ints
except TypeError:
pass
return []

def convert_hex_to_bin_str(hexChars):
#convert hex char into byte string
response = convert_hex_to_int(hexChars)[0]
# convert int to binary string
responseBinary = bin(response)
# first 2 chars of binary string are '0b' so ignore these
return responseBinary[2:]

x = AIHome(1,2)



RE: Python code with serial port and global undefined - micseydel - Jan-16-2017

The code snippet should be runnable; the indentation is essential.

I think we have a bug on the site right now where tabs are ignored. If that's what's happening to you, please convert to spaces for the sake of the post (any modern editor should be able to do this automatically, it should not be a burden.)


RE: Python code with serial port and global undefined - marciokoko - Jan-17-2017

Ok but I actually took the text from TextWrangler, selected and copied and pasted. In TW the text is indented but the problem is that it loses that indentation when I paste it here. What am I doing wrong?

BTW, I moved the hex>bin>hex helper methods before the read method and it works.


RE: Python code with serial port and global undefined - micseydel - Jan-17-2017

Apologies, the forum is having technical difficulties...

The current workaround is to use the Quick Reply at the bottom of the page. Type out the [[python]] tags yourself, put your code between them, and post the reply without previewing and that should really help us to see your code the way it is supposed to be.