Skip to content

Instantly share code, notes, and snippets.

@niektemme
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niektemme/e153fbd6d89b8578d494 to your computer and use it in GitHub Desktop.
Save niektemme/e153fbd6d89b8578d494 to your computer and use it in GitHub Desktop.
Smart Thermostat Raspberry PI - Part XBee Receive
import threading
from xbee import ZigBee #xbee 2
import apsw #alternative python sqlite wrapper
import serial
import struct
import codecs
import sys
import time
import datetime
import logging
...
#basic logging information change to log file
logging.basicConfig(filename='/usr/local/tempniek/18log.log',level=logging.INFO)
logging.info('I told you so')
try:
#xbee connection
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=5)
xbee = ZigBee(ser,escaped=True)
#classes used for multithreading
#(one class for every function that runs as a separate thread)
class myThreadInsert (threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
try:
xinsert()
except Exception:
logging.exception("xinsert")
...
def fins(fvcurtime,fvsource,fvid,fvdata):
"""
This function inserts data into the sensvals table.
Sets rowkey used by HBASE and seperate key parts for indexing.
Key format: <device id>_<port id>_<reverse epoch>_<reverse milliseconds>.
For example: 40b5af01_rx000A01_8571346790_9184822.
Used by xinsert() function.
"""
bvepoch = 9999999999
bvsub = 9999999
fvepoch = int(fvcurtime) #remove sub seconds from epoch
fkepoch = bvepoch - fvepoch
fvsub = bvsub - int(datetime.datetime.fromtimestamp(fvcurtime).strftime('%f')) #only milisecond part from epoch
fvprekey = fvsource + '_' + fvid + '_'
fvkey = fvprekey + str(fkepoch) + '_' + str(fvsub)
dbi = dbc.cursor()
dbi.execute("INSERT INTO sensvals (vkey,vepoch,vsub,vsource,vport,vprekey,vvalue) VALUES(?,?,?,?,?,?,?)",(fvkey,fvepoch,fvsub,fvsource,fvid,fvprekey,fvdata))
dbi.close()
def xinsert():
"""
Receives and sends data from and to the XBee.
Sending and receiving combined in one thread because only one tread can use GPIO port.
Recieving is done as fast as possible.
Sinding only at 1 second interval.
Runs as a sperate thread.
"""
ficurtime = 0
fivepoch = 0
while True:
logging.debug("insert started")
logging.debug(datetime.datetime.utcnow())
try:
#start with receive part
ficurtime = time.time()
fivepoch = int(ficurtime)
fimintime = fivepoch - 5
response = xbee.wait_read_frame()
logging.debug(response)
vid = (response['id'])
if vid != 'tx_status':
vsource = (codecs.decode(codecs.encode(response['source_addr_long'],'hex'),'utf-8')[8:])
logging.debug(vsource)
logging.debug(vid)
vdata = codecs.decode(response['rf_data'],'utf-8')
logging.debug(vdata)
if vid == 'rx': #special case if port is rx. Assumes arduino is sending data.
vid = 'rx'+(vdata[0:3].zfill(6)) #first part of payload is sendor ID
vdata = vdata[4:]
vdatas = vdata.split(',') #assumes array of values
for vdatasv in vdatas:
vdatasv = int(vdatasv)
fins(time.time(),vsource,vid,vdatasv) #use fins() function to actuall insert data in database
else: #case of normal xbee payload
vid = vid.zfill(8)
vdata = int(vdata)
fins(time.time(),vsource,vid,vdata) #use fins() function to actuall insert data in database
except Exception:
logging.exception("fxinsert")
time.sleep(0.001)
def fmain():
"""
Main thread function.
"""
try:
time.sleep(1)
logging.info("hallostart")
dbstart() #start initial SQLite
hbasestart() #start initial HBase
time.sleep(3)
#start the functions that run as seperate threads
threadInsert = myThreadInsert()
threadInsert.start()
...
except Exception:
logging.exception("fmain")
if __name__=="__main__":
fmain()
except Exception:
logging.exception("main")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment