Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import socket
- import json
- from datetime import datetime
- from datetime import timedelta
- import time, sys, signal, atexit, pyupm_grove, mraa, array
- from math import sqrt
- import pyupm_mma7660 as upmMMA7660
- import pyupm_grove as grove
- import pyupm_mic as upmMicrophone
- import pyupm_ldt0028 as ldt0028
- import httplib
- ## Intel IoT Analytics parameters
- HOST = "127.0.0.1"
- PORT = 41234
- INTERVAL = 10
- ## Pin definitions
- # temperature pin
- tempPin = 0
- # microphone pin
- micPin = 2
- # piezo pin
- piezoPin = 1
- # light pin
- lightPin = 3
- ## Sensors definitions
- # Temp sensor
- temp = grove.GroveTemp(tempPin)
- # Create the LDT0-028 Piezo Vibration Sensor object using AIO pin <piezoPin>
- piezoSensor = ldt0028.LDT0028(piezoPin)
- # Sound Sensor
- myMic = upmMicrophone.Microphone(micPin)
- threshContext = upmMicrophone.thresholdContext()
- threshContext.averageReading = 0
- threshContext.runningAverage = 0
- threshContext.averagedOver = 2
- # Light Sensor
- lightSensor = grove.GroveLight(lightPin)
- # Accelerometer: Instantiate an MMA7660 on I2C bus 0
- myDigitalAccelerometer = upmMMA7660.MMA7660(
- upmMMA7660.MMA7660_I2C_BUS,
- upmMMA7660.MMA7660_DEFAULT_I2C_ADDR);
- ## Exit handlers ##
- # This function stops python from printing a stacktrace when you hit control-C
- def SIGINTHandler(signum, frame):
- raise SystemExit
- # This function lets you run code on exit, including functions from myDigitalAccelerometer
- def exitHandler():
- print "Exiting"
- sys.exit(0)
- # Register exit handlers
- atexit.register(exitHandler)
- signal.signal(signal.SIGINT, SIGINTHandler)
- ## Functions for internet connection checking
- #
- def have_internet():
- # conn = httplib.HTTPConnection("www.google.com")
- conn = httplib.HTTPConnection("dashboard.us.enableiot.com")
- try:
- conn.request("HEAD", "/")
- return True
- except:
- return False
- ## Functions for the Intel IoT Analytics
- # register_metric function opens the UDP socket to send the data types
- # reference: https://github.com/enableiot/iotkit-samples/blob/master/python/IoTkitSimpleExample.py
- def register_metric(metric_name, metric_type):
- msg = {
- "n": metric_name,
- "t": metric_type
- }
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.sendto(json.dumps(msg), (HOST, PORT))
- # send_data function opens the TCP socket to send the data values
- # reference: https://github.com/enableiot/iotkit-samples/blob/master/python/IoTkitSimpleExample.py
- def send_data(metric_name, value):
- msg = {
- "n": metric_name,
- "v": value
- }
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.sendto(json.dumps(msg), (HOST, PORT))
- # send_data function opens the TCP socket to send the data values
- # reference: https://github.com/enableiot/iotkit-samples/blob/master/python/IoTkitSimpleExample.py
- # more references: https://github.com/enableiot/iotkit-samples/blob/master/README.md
- def send_data_timestamp(metric_name, value, timestamp):
- msg = {
- "n": metric_name,
- "v": value,
- "on": timestamp
- }
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock.sendto(json.dumps(msg), (HOST, PORT))
- ## Functions to read sensors
- # This function reads value from temperature sensor
- def readTemperature():
- # Read temperature in Celsius degrees and write them on a csv file
- val = 0.1
- val = int(temp.value())
- return val
- # This function reads value from microphone sensor
- def readMic():
- # Read microphone signal value and write it on a csv file
- val = 0.1
- buffer = upmMicrophone.uint16Array(1)
- len = myMic.getSampledWindow(2, 1, buffer);
- val = int(buffer[0])
- return val
- # This function reads value from piezo sensor
- def readPiezo():
- # Read piezo signal value and write it on a csv file
- val = 0.1
- val = int(piezoSensor.getSample())
- return val
- # This function reads value from light sensor
- def readLight():
- # Read light sensor signal value and write it on a csv file
- #return int(lightSensor.raw_value())
- val = 0
- val = int(lightSensor.value())
- return val
- ## Accelerometer definitions
- # place device in standby mode so we can write registers
- myDigitalAccelerometer.setModeStandby()
- # enable 64 samples per second
- myDigitalAccelerometer.setSampleRate(upmMMA7660.MMA7660.AUTOSLEEP_64)
- # place device into active mode
- myDigitalAccelerometer.setModeActive()
- #
- x = upmMMA7660.new_intp()
- y = upmMMA7660.new_intp()
- z = upmMMA7660.new_intp()
- # about the csv output file
- fileName="data.csv"
- fn = open(fileName, "w")
- # other variables init
- num = 0
- accModOld = 0.1
- ## Options
- # Debug or not
- debugPrint = True
- # write headers in the csv file or not
- writeHeader = False
- # number of samples to be considered by the microphone sensor
- noSamples = 6
- # delay between two acquisitions from the sensor
- delayTime = 10
- ## Setup execution
- #
- print "beatBox v1.0\n"
- print "Starting\n"
- print HOST
- # Write headers (or not) in the .csv file
- if writeHeader == True:
- outputStr = ("T,S,P,L,x,y,z,A\n")
- if debugPrint:
- print "Headers ON\n"
- fn.write(outputStr)
- else:
- outputStr = ""
- if debugPrint:
- print "Headers OFF\n"
- prevInternet=have_internet()
- ## Intel IoT Analytics start
- # Install sensors
- register_metric("tempMax", "temperature.v1.0")
- register_metric("tempMin", "temperature.v1.0")
- register_metric("micMax", "micsensor.v1.0")
- register_metric("micMin", "micsensor.v1.0")
- register_metric("piezoMax", "piezosensor.v1.0")
- register_metric("piezoMin", "piezosensor.v1.0")
- register_metric("lightMax", "lightsensor.v1.0")
- register_metric("lightMin", "lightsensor.v1.0")
- register_metric("accMax", "accelerationmodulesensor.v1.0")
- register_metric("accMin", "accelerationmodulesensor.v1.0")
- next_send_time = 0
- ## Loop execution
- #
- print "Acquiring data\n"
- while True:
- while True:
- outputStr = ""
- val = 0.1
- tempMax = -100.1
- tempMin = 100.1
- micMax = 0.1
- micMin = 5000.1
- piezoMax = 0.1
- piezoMin = 5000.1
- lightMax = 0
- lightMin = 5000
- accMax = 0.1
- accMin = 5000.1
- xMax = 0.1
- yMax = 0.1
- zMax = 0.1
- accModNew = 0.1
- accMod = 0.1
- accModOld = 0.1
- start = datetime.now()
- while (datetime.now()-start) < timedelta(seconds=delayTime):
- # read temperature
- val = readTemperature()
- if tempMax < val:
- tempMax = val
- if tempMin > val:
- tempMin = val
- # read microphone
- val = readMic()
- if micMax < val:
- micMax = val
- if micMin > val:
- micMin = val
- # read piezo
- val = readPiezo()
- if piezoMin > val:
- piezoMin = val
- if piezoMax < val:
- piezoMax = val
- # read light
- val = readLight()
- if lightMax < val:
- lightMax = val
- if lightMin > val:
- lightMin = val
- # read Accelerometer modulo
- myDigitalAccelerometer.getRawValues(x, y, z)
- accModNew = sqrt( (upmMMA7660.intp_value(x) ** 2) + (upmMMA7660.intp_value(y) ** 2) + (upmMMA7660.intp_value(z) ** 2 ))
- accMod = abs(accModNew - accModOld)
- val = int(accMod)
- if accMax < val:
- accMax = val
- if accMin > val:
- accMin = val
- accModOld = accModNew
- if debugPrint:
- val=val
- # print "{} - {} - {} - {} - {} - {} - {} - {} - {} - {}".format(tempMax,tempMin,micMax,micMin,piezoMax,piezoMin,lightMax,lightMin,accMax,accMin)
- if debugPrint:
- print "{} useconds".format(datetime.now()-start)
- # Write time to a temporary variable int(time.time()) * 1000
- timestamp = int(time.time() * 1000)
- outputStr += ("{},").format(timestamp)
- # Write temperatures in Celsius degrees to a temporary variable
- outputStr += ("{},{},").format(tempMax,tempMin)
- # Write values from the sound sensor to a temporary variable
- outputStr += ("{},{},").format(micMax,micMin)
- # Write values from the piezo sensor to a temporary variable
- outputStr += ("{},{},").format(piezoMax,piezoMin)
- # Write values from the light sensor to a temporary variable
- outputStr += ("{},{},").format(lightMax,lightMin)
- # Write modulo values from the accelerometer to a temporary variable
- outputStr += ("{},{}").format(accMax,accMin)
- outputStr += "\n"
- num += 1
- if num > 0:
- internet=have_internet()
- if internet:
- if debugPrint:
- print "{} - {} - Sending data over the internet".format(num, timestamp)
- send_data("tempMax", tempMax)
- send_data("tempMin", tempMin)
- send_data("micMax", micMax)
- send_data("micMin", micMin)
- send_data("piezoMax", piezoMax)
- send_data("piezoMin", piezoMin)
- send_data("lightMax", lightMax)
- send_data("lightMin", lightMin)
- send_data("accMax", accMax)
- send_data("accMin", accMin)
- else:
- if debugPrint:
- print "{} - Writing data to local file".format(num)
- fn.write(outputStr)
- if internet and not prevInternet:
- # backup data from previous executions
- fn.close
- with open(fileName, "r") as fn:
- for line in fn:
- timestamp, tempMax, tempMin, micMax, micMin, piezoMax, piezoMin, lightMax, lightMin, accMax, accMin = line.split(",")
- if debugPrint:
- print "{} - Sending old data over the internet".format(timestamp)
- send_data_timestamp("tempMax", tempMax, timestamp)
- send_data_timestamp("tempMin", tempMin, timestamp)
- send_data_timestamp("micMax", micMax, timestamp)
- send_data_timestamp("micMin", micMin, timestamp)
- send_data_timestamp("piezoMax", piezoMax, timestamp)
- send_data_timestamp("piezoMin", piezoMin, timestamp)
- send_data_timestamp("lightMax", lightMax, timestamp)
- send_data_timestamp("lightMin", lightMin, timestamp)
- send_data_timestamp("accMax", accMax, timestamp)
- send_data_timestamp("accMin", accMin, timestamp)
- fn.close
- fn.truncate
- fn = open(fileName, "w")
- prevInternet=internet
- if debugPrint:
- # print "{} - {}".format(num, outputStr)
- prevInternet=internet
- prevInternet=internet
- if num >= noSamples:
- fn.close()
- sys.exit()
- #time.sleep(delayTime)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement