Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- addtestfreqdata.py
- from xbee import XBee,ZigBee
- import json
- from pprint import pprint
- import serial
- import time
- import thread
- import string
- import random
- import decimal
- import MySQLdb
- import sys
- from datetime import datetime as dt
- import urllib
- import urllib2
- import MySQLdb
- PORT = '/dev/ttyUSB0'
- BAUD_RATE = 9600
- # Open serial port
- ser = serial.Serial(PORT, BAUD_RATE)
- # Create API object
- xbee = ZigBee(ser,escaped=True)
- host = "http://192.168.1.163:12345"
- token = ""
- delay = 1000
- # Connect to database
- try:
- db = MySQLdb.connect("localhost","root","koelkast@123","db_csgrip")
- cursor = db.cursor()
- cursor.execute("SELECT VERSION()")
- results = cursor.fetchone()
- cursor.close()
- # Check if anything at all is returned
- if results:
- print "Connected to db_csgrip"
- else:
- print "No connection to db_csgrip"
- except MySQLdb.Error:
- print "ERROR IN CONNECTION"
- def addTestDataToDatabase(delay):
- while True:
- try:
- cursor = db.cursor()
- cursor.execute("SELECT * FROM frequency ORDER BY ID desc LIMIT 1")
- lastFreq = cursor.fetchall()[0][2]
- currentFreq = decimal.Decimal(random.randrange(4900,5100))/100
- difference = float(currentFreq) - lastFreq
- date = dt.now()
- cursor.execute("INSERT INTO frequency(timestamp, current, last, difference) VALUES (%s,%s,%s,%s)", [date,currentFreq,lastFreq,difference])
- db.commit()
- cursor.close()
- print "Added new Freq Row"
- except Exception as e:
- print "Error while adding test frequency data: " + str(e)
- time.sleep(delay)
- #token = getToken()
- print token
- print "Started threads"
- try:
- thread.start_new_thread(addTestDataToDatabase, (5,))
- except:
- print "Unable to start thread(s)"
- while True:
- pass
- retrievefreqdata.py
- from xbee import XBee,ZigBee
- import json
- from pprint import pprint
- import serial
- import time
- import thread
- import string
- import random
- import decimal
- import MySQLdb
- import sys
- from datetime import datetime as dt
- import urllib
- import urllib2
- import MySQLdb
- PORT = '/dev/ttyUSB0'
- BAUD_RATE = 9600
- # Open serial port
- ser = serial.Serial(PORT, BAUD_RATE)
- # Create API object
- xbee = ZigBee(ser,escaped=True)
- host = "http://192.168.1.163:12345"
- token = ""
- delay = 1000
- # Connect to database
- try:
- db = MySQLdb.connect("localhost","root","koelkast@123","db_csgrip")
- cursor = db.cursor()
- cursor.execute("SELECT VERSION()")
- results = cursor.fetchone()
- cursor.close()
- # Check if anything at all is returned
- if results:
- print "Connected to db_csgrip"
- else:
- print "No connection to db_csgrip"
- except MySQLdb.Error:
- print "ERROR IN CONNECTION"
- def getToken():
- try:
- username = 'testuser'
- password = 'testpassword'
- data = urllib.urlencode({
- 'username' : username,
- 'password' : password
- })
- req = urllib2.Request(host+"/apiv2/login",data)
- resp = urllib2.urlopen(req,timeout = 5)
- return resp
- except Exception as e:
- print "Error while fetching token: " + str(e)
- def retrieveData(delay):
- while True:
- try:
- req = urllib2.Request(host,"/apiv2/freq")
- req.add_header('X-Access-Token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0ZXN0dXNlciIsImV4cCI6MTQ1NzcxMDEyOTc5NH0.8SD_J8C931qw4dkNU3h_dFunYVYmuEleSwTY3TqLOIo')
- resp = urllib2.urlopen(req,timeout = 10)
- content = resp.read()
- print content
- #cursor.execute("""INSERT INTO test(Naam) VALUES (%s)""",(ouih))
- except Exception as e:
- print "Error while fetching frequency data: " + str(e)
- time.sleep(delay)
- def send_data(delay):
- while True:
- try:
- cursor = db.cursor()
- cursor.execute("SELECT * FROM frequency ORDER BY timestamp desc limit 5")
- frequencyData = cursor.fetchall()
- cursor.close()
- index = 0
- totalFrequency = 0
- for row in frequencyData:
- index += 1
- totalFrequency += row[2]
- if index > 0:
- averageFrequency = totalFrequency / index
- else:
- averageFrequency = 0
- print "Sending frequency data..."
- xbeeData = {}
- xbeeData["frequency"] = averageFrequency #str(random.uniform(49,52))
- json_data = json.dumps(xbeeData)
- xbee.send("tx",dest_addr_long='\x00\x00\x00\x00\x00\x00\xFF\xFF',dest_addr='\xFF\xFF', data=json_data.replace('}','@'))
- except Exception, e:
- print "Error sending packet: " + str(e)
- time.sleep(delay)
- #token = getToken()
- print token
- print "Started threads"
- try:
- thread.start_new_thread(retrieveData, (1,))
- thread.start_new_thread(send_data, (2,))
- except:
- print "Unable to start thread(s)"
- while True:
- pass
- retrievesensordata.py
- # Coordinator
- from xbee import XBee,ZigBee
- import json
- from pprint import pprint
- import serial
- import time
- import thread
- import string
- import random
- import MySQLdb
- import sys
- from datetime import datetime
- PORT = '/dev/ttyUSB0'
- BAUD_RATE = 9600
- # Open serial port
- ser = serial.Serial(PORT, BAUD_RATE)
- # Connect to database
- try:
- db = MySQLdb.connect("localhost","root","koelkast@123","db_csgrip")
- cursor = db.cursor()
- cursor.execute("SELECT VERSION()")
- results = cursor.fetchone()
- cursor.close()
- # Check if anything at all is returned
- if results:
- print "Connected to db_csgrip"
- else:
- print "No connection to db_csgrip"
- except MySQLdb.Error:
- print "ERROR IN CONNECTION"
- def decode_xbee_data(data):
- data = data[:-1].replace('@','}')
- jsonData = json.loads(data)
- return jsonData
- # Create API object
- xbee = ZigBee(ser,escaped=True)
- def read_data(threadName,delay):
- while True:
- try:
- print "Waiting for incoming packet..."
- response = xbee.wait_read_frame()['rf_data']
- if '@' not in response:
- print 'No json code'
- continue
- jsonObject = decode_xbee_data(response)
- print jsonObject
- temperatures = {}
- humidities = {}
- totalTemp = 0
- totalHum = 0
- cursor = db.cursor()
- for object in jsonObject:
- if object["id"] == "pressure":
- cursor.execute("INSERT INTO pressure(timestamp, value) VALUES (%s,%s)", [datetime.now(),object["pressure"]])
- else:
- temperatures[object["id"]] = object["temperature"]
- humidities[object["id"]] = object["humidity"]
- totalTemp += object["temperature"]
- totalHum += object["humidity"]
- avgTemp = (totalTemp - temperatures["freezer"]) / 2
- avgHum = (totalHum - humidities["freezer"]) / 2
- cursor.execute("INSERT INTO humidity(timestamp, fridgeTop, fridgeBottom, fridgeBack, freezer, average) VALUES (%s,%s,%s,%s,%s,%s)" ,[datetime.now(),humidities["top"],humidities["bottom"],humidities["top"],humidities["freezer"], avgHum])
- cursor.execute("INSERT INTO temperature(timestamp, fridgeTop, fridgeBottom, fridgeBack, freezer, average) VALUES (%s,%s,%s,%s,%s,%s)" ,[datetime.now(),temperatures["top"],temperatures["bottom"],temperatures["top"],temperatures["freezer"],avgTemp])
- db.commit()
- cursor.close()
- print "Packet received: " + response
- except Exception as e:
- print "Unexpected error:" + str(e)
- print "Error reading packet"
- def async_task(threadName, delay):
- while True:
- print "Async task..."
- time.sleep(delay)
- def send_data(threadName, delay):
- while True:
- try:
- print "Sending data..."
- xbee.send("tx",dest_addr_long='\x00\x00\x00\x00\x00\x00\xFF\xFF',dest_addr='\xFF\xFF', data=''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10)))
- except:
- print "Error sending packet"
- time.sleep(delay)
- print "Started python.py"
- # Continuously read and print packets
- try:
- thread.start_new_thread(read_data, ("read-thread", 0.5))
- # thread.start_new_thread(send_data, ("write-thread", 5))
- # thread.start_new_thread(async_task, ("print-thread", 2))
- except:
- print "Unable to start thread(s)"
- while True:
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement