Advertisement
pluisi

BeatBox v0.2

Jun 20th, 2015
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.95 KB | None | 0 0
  1. import os
  2. import socket
  3. import json
  4. from datetime import datetime
  5. from datetime import timedelta
  6.  
  7. import time, sys, signal, atexit, pyupm_grove, mraa, array
  8. from math import sqrt
  9. import pyupm_mma7660 as upmMMA7660
  10. import pyupm_grove as grove
  11. import pyupm_mic as upmMicrophone
  12. import pyupm_ldt0028 as ldt0028
  13. import httplib
  14. ## Intel IoT Analytics parameters
  15. HOST = "127.0.0.1"
  16. PORT = 41234
  17. INTERVAL = 10
  18.  
  19. ## Pin definitions
  20. #  temperature pin
  21. tempPin = 0
  22. #  microphone pin
  23. micPin = 2
  24. #  piezo pin  
  25. piezoPin = 1
  26. #  light pin  
  27. lightPin = 3
  28.  
  29. ## Sensors definitions
  30. # Temp sensor
  31. temp = grove.GroveTemp(tempPin)
  32.  
  33. # Create the LDT0-028 Piezo Vibration Sensor object using AIO pin <piezoPin>
  34. piezoSensor = ldt0028.LDT0028(piezoPin)
  35.  
  36. # Sound Sensor
  37. myMic = upmMicrophone.Microphone(micPin)
  38. threshContext = upmMicrophone.thresholdContext()
  39. threshContext.averageReading = 0
  40. threshContext.runningAverage = 0
  41. threshContext.averagedOver = 2
  42.  
  43. # Light Sensor
  44. lightSensor = grove.GroveLight(lightPin)
  45.  
  46. # Accelerometer: Instantiate an MMA7660 on I2C bus 0
  47. myDigitalAccelerometer = upmMMA7660.MMA7660(
  48.                     upmMMA7660.MMA7660_I2C_BUS,
  49.                     upmMMA7660.MMA7660_DEFAULT_I2C_ADDR);
  50.  
  51. ## Exit handlers ##
  52. # This function stops python from printing a stacktrace when you hit control-C
  53. def SIGINTHandler(signum, frame):
  54.     raise SystemExit
  55.  
  56. # This function lets you run code on exit, including functions from myDigitalAccelerometer
  57. def exitHandler():
  58.     print "Exiting"
  59.     sys.exit(0)
  60.  
  61. # Register exit handlers
  62. atexit.register(exitHandler)
  63. signal.signal(signal.SIGINT, SIGINTHandler)
  64.  
  65. ## Functions for internet connection checking
  66. #  
  67. def have_internet():
  68.     # conn = httplib.HTTPConnection("www.google.com")
  69.     conn = httplib.HTTPConnection("dashboard.us.enableiot.com")
  70.     try:
  71.         conn.request("HEAD", "/")
  72.         return True
  73.     except:
  74.         return False
  75.  
  76. ## Functions for the Intel IoT Analytics
  77. #  register_metric function opens the UDP socket to send the data types
  78. #  reference: https://github.com/enableiot/iotkit-samples/blob/master/python/IoTkitSimpleExample.py
  79. def register_metric(metric_name, metric_type):
  80.     msg = {
  81.         "n": metric_name,
  82.         "t": metric_type
  83.     }
  84.  
  85.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  86.     sock.sendto(json.dumps(msg), (HOST, PORT))
  87.  
  88. #  send_data function opens the TCP socket to send the data values
  89. #  reference: https://github.com/enableiot/iotkit-samples/blob/master/python/IoTkitSimpleExample.py
  90. def send_data(metric_name, value):
  91.     msg = {
  92.         "n": metric_name,
  93.         "v": value
  94.     }
  95.  
  96.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  97.     sock.sendto(json.dumps(msg), (HOST, PORT))
  98.  
  99. #  send_data function opens the TCP socket to send the data values
  100. #  reference: https://github.com/enableiot/iotkit-samples/blob/master/python/IoTkitSimpleExample.py
  101. #  more references: https://github.com/enableiot/iotkit-samples/blob/master/README.md
  102. def send_data_timestamp(metric_name, value, timestamp):
  103.     msg = {
  104.         "n": metric_name,
  105.         "v": value,
  106.         "on": timestamp
  107.     }
  108.  
  109.     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  110.     sock.sendto(json.dumps(msg), (HOST, PORT))
  111.  
  112. ## Functions to read sensors
  113. #  This function reads value from temperature sensor
  114. def readTemperature():
  115.     # Read temperature in Celsius degrees and write them on a csv file
  116.     val = 0.1
  117.     val = int(temp.value())
  118.     return val
  119.  
  120. #  This function reads value from microphone sensor
  121. def readMic():
  122.     # Read microphone signal value and write it on a csv file
  123.     val = 0.1
  124.     buffer = upmMicrophone.uint16Array(1)
  125.     len = myMic.getSampledWindow(2, 1, buffer);
  126.     val = int(buffer[0])
  127.     return val
  128.  
  129. #  This function reads value from piezo sensor
  130. def readPiezo():
  131.     # Read piezo signal value and write it on a csv file
  132.     val = 0.1
  133.     val = int(piezoSensor.getSample())
  134.     return val
  135.  
  136. #  This function reads value from light sensor
  137. def readLight():
  138.     # Read light sensor signal value and write it on a csv file
  139.     #return int(lightSensor.raw_value())
  140.     val = 0
  141.     val = int(lightSensor.value())
  142.     return val
  143.  
  144. ## Accelerometer definitions
  145. # place device in standby mode so we can write registers
  146. myDigitalAccelerometer.setModeStandby()
  147. # enable 64 samples per second
  148. myDigitalAccelerometer.setSampleRate(upmMMA7660.MMA7660.AUTOSLEEP_64)
  149. # place device into active mode
  150. myDigitalAccelerometer.setModeActive()
  151.  
  152. #
  153. x = upmMMA7660.new_intp()
  154. y = upmMMA7660.new_intp()
  155. z = upmMMA7660.new_intp()
  156.  
  157. # about the csv output file
  158. fileName="data.csv"
  159. fn = open(fileName, "w")
  160.  
  161. # other variables init
  162. num = 0
  163. accModOld = 0.1
  164.  
  165. ## Options
  166. #  Debug or not
  167. debugPrint = True
  168. #  write headers in the csv file or not
  169. writeHeader = False
  170. #  number of samples to be considered by the microphone sensor
  171. noSamples = 6
  172. #  delay between two acquisitions from the sensor
  173. delayTime = 10
  174.  
  175. ## Setup execution
  176. #  
  177. print "beatBox v1.0\n"
  178. print "Starting\n"
  179. print HOST
  180. #  Write headers (or not) in the .csv file
  181. if writeHeader == True:
  182.     outputStr = ("T,S,P,L,x,y,z,A\n")
  183.     if debugPrint:
  184.         print "Headers ON\n"
  185.     fn.write(outputStr)
  186. else:
  187.     outputStr = ""
  188.     if debugPrint:
  189.         print "Headers OFF\n"
  190.  
  191. prevInternet=have_internet()
  192.  
  193. ## Intel IoT Analytics start
  194. #  Install sensors
  195. register_metric("tempMax", "temperature.v1.0")
  196. register_metric("tempMin", "temperature.v1.0")
  197. register_metric("micMax", "micsensor.v1.0")
  198. register_metric("micMin", "micsensor.v1.0")
  199. register_metric("piezoMax", "piezosensor.v1.0")
  200. register_metric("piezoMin", "piezosensor.v1.0")
  201. register_metric("lightMax", "lightsensor.v1.0")
  202. register_metric("lightMin", "lightsensor.v1.0")
  203. register_metric("accMax", "accelerationmodulesensor.v1.0")
  204. register_metric("accMin", "accelerationmodulesensor.v1.0")
  205. next_send_time = 0
  206.  
  207. ## Loop execution
  208. #  
  209. print "Acquiring data\n"
  210. while True:
  211.  
  212.     while True:
  213.         outputStr = ""
  214.         val = 0.1
  215.         tempMax = -100.1
  216.         tempMin = 100.1
  217.         micMax = 0.1
  218.         micMin = 5000.1
  219.         piezoMax = 0.1
  220.         piezoMin = 5000.1
  221.         lightMax = 0
  222.         lightMin = 5000
  223.         accMax = 0.1
  224.         accMin = 5000.1
  225.         xMax = 0.1
  226.         yMax = 0.1
  227.         zMax = 0.1
  228.         accModNew = 0.1
  229.         accMod = 0.1
  230.         accModOld = 0.1
  231.         start = datetime.now()
  232.        
  233.         while (datetime.now()-start) < timedelta(seconds=delayTime):
  234.             # read temperature
  235.             val = readTemperature()
  236.             if tempMax < val:
  237.                 tempMax = val
  238.             if tempMin > val:
  239.                 tempMin = val
  240.             # read microphone
  241.             val = readMic()
  242.             if micMax < val:
  243.                 micMax = val
  244.             if micMin > val:
  245.                 micMin = val
  246.             # read piezo
  247.             val = readPiezo()
  248.             if piezoMin > val:
  249.                 piezoMin = val
  250.             if piezoMax < val:
  251.                 piezoMax = val
  252.             # read light
  253.             val = readLight()
  254.             if lightMax < val:
  255.                 lightMax = val
  256.             if lightMin > val:
  257.                 lightMin = val
  258.             # read Accelerometer modulo
  259.             myDigitalAccelerometer.getRawValues(x, y, z)
  260.             accModNew = sqrt( (upmMMA7660.intp_value(x) ** 2) + (upmMMA7660.intp_value(y) ** 2) + (upmMMA7660.intp_value(z) ** 2 ))
  261.             accMod = abs(accModNew - accModOld)
  262.             val = int(accMod)
  263.             if accMax < val:
  264.                 accMax = val
  265.             if accMin > val:
  266.                 accMin = val
  267.             accModOld = accModNew
  268.             if debugPrint:
  269.                 val=val
  270.                 # print "{} - {} - {} - {} - {} - {} - {} - {} - {} - {}".format(tempMax,tempMin,micMax,micMin,piezoMax,piezoMin,lightMax,lightMin,accMax,accMin)
  271.        
  272.         if debugPrint:
  273.             print "{} useconds".format(datetime.now()-start)
  274.  
  275.         # Write time to a temporary variable int(time.time()) * 1000
  276.         timestamp = int(time.time() * 1000)
  277.         outputStr += ("{},").format(timestamp)
  278.  
  279.         # Write temperatures in Celsius degrees to a temporary variable
  280.         outputStr += ("{},{},").format(tempMax,tempMin)
  281.        
  282.         # Write values from the sound sensor to a temporary variable
  283.         outputStr += ("{},{},").format(micMax,micMin)
  284.        
  285.         # Write values from the piezo sensor to a temporary variable
  286.         outputStr += ("{},{},").format(piezoMax,piezoMin)
  287.        
  288.         # Write values from the light sensor to a temporary variable
  289.         outputStr += ("{},{},").format(lightMax,lightMin)
  290.        
  291.         # Write modulo values from the accelerometer to a temporary variable
  292.         outputStr += ("{},{}").format(accMax,accMin)
  293.        
  294.         outputStr += "\n"
  295.        
  296.         num += 1
  297.        
  298.         if num > 0:
  299.             internet=have_internet()
  300.             if internet:
  301.                 if debugPrint:
  302.                     print "{} - {} - Sending data over the internet".format(num, timestamp)
  303.                 send_data("tempMax", tempMax)
  304.                 send_data("tempMin", tempMin)
  305.                 send_data("micMax", micMax)
  306.                 send_data("micMin", micMin)
  307.                 send_data("piezoMax", piezoMax)
  308.                 send_data("piezoMin", piezoMin)
  309.                 send_data("lightMax", lightMax)
  310.                 send_data("lightMin", lightMin)
  311.                 send_data("accMax", accMax)
  312.                 send_data("accMin", accMin)
  313.             else:
  314.                 if debugPrint:
  315.                     print "{} - Writing data to local file".format(num)
  316.                 fn.write(outputStr)
  317.             if internet and not prevInternet:
  318.                 # backup data from previous executions
  319.                 fn.close
  320.                 with open(fileName, "r") as fn:
  321.                     for line in fn:
  322.                         timestamp, tempMax, tempMin, micMax, micMin, piezoMax, piezoMin, lightMax, lightMin, accMax, accMin = line.split(",")
  323.                         if debugPrint:
  324.                             print "{} - Sending old data over the internet".format(timestamp)
  325.                         send_data_timestamp("tempMax", tempMax, timestamp)
  326.                         send_data_timestamp("tempMin", tempMin, timestamp)
  327.                         send_data_timestamp("micMax", micMax, timestamp)
  328.                         send_data_timestamp("micMin", micMin, timestamp)
  329.                         send_data_timestamp("piezoMax", piezoMax, timestamp)
  330.                         send_data_timestamp("piezoMin", piezoMin, timestamp)
  331.                         send_data_timestamp("lightMax", lightMax, timestamp)
  332.                         send_data_timestamp("lightMin", lightMin, timestamp)
  333.                         send_data_timestamp("accMax", accMax, timestamp)
  334.                         send_data_timestamp("accMin", accMin, timestamp)
  335.                        
  336.                 fn.close
  337.                 fn.truncate
  338.                
  339.                 fn = open(fileName, "w")
  340.                
  341.                 prevInternet=internet
  342.             if debugPrint:
  343.                 # print "{} - {}".format(num, outputStr)
  344.                 prevInternet=internet
  345.             prevInternet=internet
  346.  
  347.         if num >= noSamples:
  348.             fn.close()
  349.             sys.exit()
  350.  
  351.        
  352.         #time.sleep(delayTime)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement