Python Forum
Python code with serial port and global undefined
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python code with serial port and global undefined
#1
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:]
Reply
#2
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?
Reply
#3
No, I didn't post the whole code, just the relevant methods
Reply
#4
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.
Reply
#5
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?
Reply
#6
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.
Reply
#7
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)
Reply
#8
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.)
Reply
#9
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.
Reply
#10
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Waiting for input from serial port, then move on KenHorse 3 999 Apr-17-2024, 07:21 AM
Last Post: DeaD_EyE
  MCU reboots after opening Serial port when ran from Raspberry PI zazas321 3 428 Mar-19-2024, 09:02 AM
Last Post: zazas321
  pyserial/serial "has no attribute 'Serial' " gowb0w 9 3,884 Aug-24-2023, 07:56 AM
Last Post: gowb0w
  Python error on mentioned Arduino port name dghosal 5 847 Aug-22-2023, 04:54 PM
Last Post: deanhystad
  Why Pip is not listed in the official Global Python Module index? quazirfan 2 755 Apr-21-2023, 10:55 AM
Last Post: snippsat
  Serial Port As Global Prasanjith 2 1,486 Mar-23-2023, 08:54 PM
Last Post: deanhystad
  Python Serial: How to read the complete line to insert to MySQL? sylar 1 817 Mar-21-2023, 10:06 PM
Last Post: deanhystad
  undefined function error JonWayn 5 1,440 Sep-11-2022, 03:38 AM
Last Post: JonWayn
  Undefined Led_Zeppelin 4 1,410 Aug-02-2022, 11:57 AM
Last Post: buran
  python serial port barryjo 2 1,653 Dec-27-2021, 11:09 PM
Last Post: barryjo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020