Advertisement
Guest User

Untitled

a guest
Jun 28th, 2016
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.41 KB | None | 0 0
  1. addtestfreqdata.py
  2. from xbee import XBee,ZigBee
  3. import json
  4. from pprint import pprint
  5. import serial
  6. import time
  7. import thread
  8. import string
  9. import random
  10. import decimal
  11. import MySQLdb
  12. import sys
  13. from datetime import datetime as dt
  14. import urllib
  15. import urllib2
  16. import MySQLdb
  17.  
  18. PORT = '/dev/ttyUSB0'
  19. BAUD_RATE = 9600
  20.  
  21. # Open serial port
  22. ser = serial.Serial(PORT, BAUD_RATE)
  23.  
  24. # Create API object
  25. xbee = ZigBee(ser,escaped=True)
  26.  
  27. host = "http://192.168.1.163:12345"
  28. token = ""
  29. delay = 1000
  30.  
  31. # Connect to database
  32. try:
  33.     db = MySQLdb.connect("localhost","root","koelkast@123","db_csgrip")
  34.     cursor = db.cursor()
  35.     cursor.execute("SELECT VERSION()")
  36.     results = cursor.fetchone()
  37.     cursor.close()
  38.     # Check if anything at all is returned
  39.     if results:
  40.         print "Connected to db_csgrip"
  41.     else:
  42.         print "No connection to db_csgrip"
  43. except MySQLdb.Error:
  44.     print "ERROR IN CONNECTION"
  45.  
  46.  
  47. def addTestDataToDatabase(delay):
  48.     while True:
  49.         try:
  50.                 cursor = db.cursor()
  51.             cursor.execute("SELECT * FROM frequency ORDER BY ID desc LIMIT 1")
  52.             lastFreq = cursor.fetchall()[0][2]
  53.                 currentFreq = decimal.Decimal(random.randrange(4900,5100))/100
  54.             difference = float(currentFreq) - lastFreq
  55.             date = dt.now()
  56.             cursor.execute("INSERT INTO frequency(timestamp, current, last, difference) VALUES (%s,%s,%s,%s)", [date,currentFreq,lastFreq,difference])
  57.             db.commit()
  58.             cursor.close()
  59.             print "Added new Freq Row"
  60.         except Exception as e:
  61.              print "Error while adding test frequency data: " + str(e)
  62.         time.sleep(delay)
  63.                
  64.  
  65. #token = getToken()
  66. print token
  67.  
  68. print "Started threads"
  69. try:
  70.     thread.start_new_thread(addTestDataToDatabase, (5,))
  71. except:
  72.     print "Unable to start thread(s)"
  73.  
  74. while True:
  75.     pass
  76.  
  77. retrievefreqdata.py
  78. from xbee import XBee,ZigBee
  79. import json
  80. from pprint import pprint
  81. import serial
  82. import time
  83. import thread
  84. import string
  85. import random
  86. import decimal
  87. import MySQLdb
  88. import sys
  89. from datetime import datetime as dt
  90. import urllib
  91. import urllib2
  92. import MySQLdb
  93.  
  94. PORT = '/dev/ttyUSB0'
  95. BAUD_RATE = 9600
  96.  
  97. # Open serial port
  98. ser = serial.Serial(PORT, BAUD_RATE)
  99.  
  100. # Create API object
  101. xbee = ZigBee(ser,escaped=True)
  102.  
  103. host = "http://192.168.1.163:12345"
  104. token = ""
  105. delay = 1000
  106.  
  107. # Connect to database
  108. try:
  109.     db = MySQLdb.connect("localhost","root","koelkast@123","db_csgrip")
  110.     cursor = db.cursor()
  111.     cursor.execute("SELECT VERSION()")
  112.     results = cursor.fetchone()
  113.     cursor.close()
  114.     # Check if anything at all is returned
  115.     if results:
  116.         print "Connected to db_csgrip"
  117.     else:
  118.         print "No connection to db_csgrip"
  119. except MySQLdb.Error:
  120.     print "ERROR IN CONNECTION"
  121.  
  122. def getToken():
  123.     try:
  124.         username = 'testuser'
  125.         password = 'testpassword'
  126.         data = urllib.urlencode({
  127.         'username' : username,
  128.         'password' : password
  129.         })
  130.         req = urllib2.Request(host+"/apiv2/login",data)
  131.         resp = urllib2.urlopen(req,timeout = 5)
  132.         return resp
  133.     except Exception as e:
  134.         print "Error while fetching token: " + str(e)
  135.        
  136. def retrieveData(delay):
  137.     while True:
  138.         try:
  139.         req = urllib2.Request(host,"/apiv2/freq")
  140.         req.add_header('X-Access-Token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0ZXN0dXNlciIsImV4cCI6MTQ1NzcxMDEyOTc5NH0.8SD_J8C931qw4dkNU3h_dFunYVYmuEleSwTY3TqLOIo')
  141.         resp = urllib2.urlopen(req,timeout = 10)
  142.         content = resp.read()
  143.         print content
  144.             #cursor.execute("""INSERT INTO test(Naam) VALUES (%s)""",(ouih))
  145.         except Exception as e:
  146.             print "Error while fetching frequency data: " + str(e)
  147.             time.sleep(delay)
  148.  
  149. def send_data(delay):
  150.     while True:
  151.     try:
  152.             cursor = db.cursor()
  153.             cursor.execute("SELECT * FROM frequency ORDER BY timestamp desc limit 5")
  154.             frequencyData = cursor.fetchall()
  155.             cursor.close()
  156.             index = 0
  157.             totalFrequency = 0
  158.             for row in frequencyData:
  159.                index += 1
  160.                totalFrequency += row[2]
  161.             if index > 0:
  162.                averageFrequency = totalFrequency / index
  163.             else:
  164.                averageFrequency = 0
  165.             print "Sending frequency data..."
  166.             xbeeData = {}
  167.             xbeeData["frequency"] = averageFrequency #str(random.uniform(49,52))
  168.             json_data = json.dumps(xbeeData)
  169.         xbee.send("tx",dest_addr_long='\x00\x00\x00\x00\x00\x00\xFF\xFF',dest_addr='\xFF\xFF', data=json_data.replace('}','@'))
  170.         except Exception, e:
  171.         print "Error sending packet: " + str(e)
  172.     time.sleep(delay)
  173.  
  174. #token = getToken()
  175. print token
  176.  
  177. print "Started threads"
  178. try:
  179.     thread.start_new_thread(retrieveData, (1,))
  180.     thread.start_new_thread(send_data, (2,))
  181. except:
  182.     print "Unable to start thread(s)"
  183.  
  184. while True:
  185.     pass
  186.  
  187. retrievesensordata.py
  188. # Coordinator
  189. from xbee import XBee,ZigBee
  190. import json
  191. from pprint import pprint
  192. import serial
  193. import time
  194. import thread
  195. import string
  196. import random
  197. import MySQLdb
  198. import sys
  199. from datetime import datetime
  200.  
  201. PORT = '/dev/ttyUSB0'
  202. BAUD_RATE = 9600
  203.  
  204. # Open serial port
  205. ser = serial.Serial(PORT, BAUD_RATE)
  206.  
  207. # Connect to database
  208. try:
  209.     db = MySQLdb.connect("localhost","root","koelkast@123","db_csgrip")
  210.     cursor = db.cursor()                           
  211.     cursor.execute("SELECT VERSION()")
  212.     results = cursor.fetchone()
  213.     cursor.close()
  214.     # Check if anything at all is returned
  215.     if results:
  216.         print "Connected to db_csgrip"
  217.     else:
  218.         print "No connection to db_csgrip"      
  219. except MySQLdb.Error:
  220.     print "ERROR IN CONNECTION"
  221.  
  222. def decode_xbee_data(data):
  223.     data = data[:-1].replace('@','}')
  224.     jsonData = json.loads(data)
  225.     return jsonData
  226.  
  227. # Create API object
  228. xbee = ZigBee(ser,escaped=True)
  229. def read_data(threadName,delay):
  230.     while True:
  231.         try:
  232.             print "Waiting for incoming packet..."
  233.         response = xbee.wait_read_frame()['rf_data']
  234.             if '@' not in response:
  235.                 print 'No json code'
  236.                 continue
  237.             jsonObject = decode_xbee_data(response)
  238.             print jsonObject
  239.             temperatures = {}
  240.             humidities = {}
  241.            
  242.             totalTemp = 0
  243.             totalHum = 0
  244.             cursor = db.cursor()
  245.             for object in jsonObject:
  246.                 if object["id"] == "pressure":
  247.                    cursor.execute("INSERT INTO pressure(timestamp, value) VALUES (%s,%s)", [datetime.now(),object["pressure"]])
  248.                 else:
  249.                    temperatures[object["id"]] = object["temperature"]
  250.                    humidities[object["id"]] = object["humidity"]
  251.                    totalTemp += object["temperature"]
  252.                    totalHum += object["humidity"]
  253.  
  254.             avgTemp = (totalTemp - temperatures["freezer"]) / 2
  255.             avgHum = (totalHum - humidities["freezer"]) / 2            
  256.          
  257.             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])
  258.             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])
  259.                                
  260.             db.commit()
  261.             cursor.close()
  262.             print "Packet received: " + response
  263.         except Exception as e:
  264.         print "Unexpected error:" + str(e)
  265.             print "Error reading packet"
  266.  
  267. def async_task(threadName, delay):
  268.     while True:
  269.     print "Async task..."
  270.     time.sleep(delay)
  271.  
  272. def send_data(threadName, delay):
  273.     while True:
  274.     try:
  275.             print "Sending data..."
  276.            
  277.         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)))
  278.         except:
  279.         print "Error sending packet"
  280.     time.sleep(delay)
  281.  
  282. print "Started python.py"
  283. # Continuously read and print packets
  284. try:
  285.     thread.start_new_thread(read_data, ("read-thread", 0.5))
  286.   # thread.start_new_thread(send_data, ("write-thread", 5))
  287.   # thread.start_new_thread(async_task, ("print-thread", 2))
  288. except:
  289.     print "Unable to start thread(s)"
  290.  
  291. while True:
  292.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement