Can someone help with this code please

Hello, I have a current cost cc128 unit clamp on power monitor which I have successfully conected to a raspberry pi’s serial port. I’m a beginner and most of this code is cut/paste/learn process.

I have commented out the posting to my emoncms because it didnt work, so I added “print watts” too see what was going on, and I am getting the error “NameError: name ‘watts’ is not defined”

Can anyone help, my code is…


import os                                                  
import glob                                                
import time
import urllib
import urllib2
import httplib
import json
import time
import serial

# Read serial port data
# See http://www.currentcost.com/cc128/xml.htm
# My cc128xml variable shows as....
# ['<msg><src>CC128-v0.11</src><dsb>00009</dsb><time>08:07:14</time><tmpr>21.6</tmpr><sensor>0</sensor><id>03830</id><type>1</type><ch1><watts>00335</watts></ch1></msg>\r\n']

cc128 = serial.Serial("/dev/ttyAMA0", 57600, timeout=6)
cc128xml = cc128.readlines(6)

try:
        # Find ch1
        ch1start=cc128xml[0].find("")+len("")
        ch1end=cc128xml[0].find("",ch1start)
        ch1=cc128xml[0][ch1start:ch1end]
        # Find the power in watts
        wattsstart=ch1.find("")+len("")
        wattsend=ch1.find("",wattsstart)
        watts=int(ch1[wattsstart:wattsend])
        print "C, Power " + str(watts) + "watts"
except:
        print cc128xml

print watts

#Post to emoncms
#     url = "http://192.168.1.14/emoncms/input/post?node=1&apikey=xxxxxxxxxxxxxxxxxxxxxxxxxx&json={'PowerUsage':"
#     url = url + watts + "}"
#     urllib2.urlopen(url)

Disclaimer: I am by no measure a Python expert.

It looks to me as if watts is only known inside the try ... except block, so the rest of the program has no knowledge of it. This is called the scope of the variable.

This isn’t meant as a criticism of what you’re doing, but I’d suggest you get hold of a Python tutorial and work your way through, so that you understand just how the language works.

Depending on what you really want to do, one quick solution to get you over this immediate problem would be to send to emoncms inside the try: block - where watts is known.

If you really want it outside that block - meaning that it will be sent whether or not it reads the value from the CurrentCost device, therefore it might send a good value, an old value or plain rubbish, you’ll never know which - look up the ‘scope of variables’ in a tutorial and see what it says about “local” and “global” variables. But I still suggest you try to follow a more structured approach, because it will be a lot easier, probably quicker and less frustrating in the long run.

I’m not a Python expert either. I’ll leave that to PB. :wink:

Not being certain if “scope” is applicable to the try/except construct, (the Python error handler),
I added #!/usr/bin/python to the script, assigned a value of 5 to the “watts” variable
and reduced his code snippet to:

#!/usr/bin/python

try:
        watts=5
        print "C, Power " + str(watts) + "watts"
except:
        printcc128xml
print watts

running it yielded:

bt@61:~$ ./test.py
C, Power 5watts
5
bt@61:~$

which suggests “scope” isn’t the problem.

One thing I noticed was a lack of #!/usr/bin/python at the top of the code.
If that line is indeed missing, it means the script has to be run in this manner: python scriptname.py
(assuming python is in the search path, and “scriptname” ends with .py)

If the first line of the script is #!/usr/bin/python and the script permissions have been set correctly,
the the script may be run by calling it directly. e.g. from the current directory, ./scriptname.py
Otherwise it can be called via a fully qualified pathname if the current directory is not the one the script
is located in. e.g. /home/bill/scriptname.py

Hi

thanks for replies, unfortunantly my goal was to just do this as quick as possible, as I wont be touching python again much after :slight_smile:
Any ways I managed to google “python truncated” and came up with a quick and dirty fix below, so happily logging now to my local emoncms !!

 #!/usr/bin/python

import os                                                  
import re
import glob                                                
import time
import urllib
import urllib2
import httplib
import json
import time
import serial
import xml.etree.ElementTree as ET
from xml.etree import ElementTree

# Read serial port data
# XML output is formatted as in following example....
# <msg><src>CC128-v0.11</src><dsb>00009</dsb><time>08:07:14</time><tmpr>21.6</tmpr><sensor>0</sensor><id>03830</id><type>1</type><ch1><watts>00335</watts></ch1></msg>

while True:

	cc128 = serial.Serial("/dev/ttyAMA0", 57600, timeout=10)
	cc128xml = cc128.readline()

	watts = cc128xml[139:-22]

	url = "http://192.168.1.14/emoncms/input/post?node=6&apikey=XXXXXXXXXXXXXXXXXXXX&json={'PowerUsage':"

	url = url + watts + "}"

	urllib2.urlopen(url)

	time.sleep(1)