示例#1
0
def wait_for_change(pre_request_lux, direction="BOTH"):
    tolerance = lux_per_bright * TOLERANCE  # Sensitivity - How much the light should change to be considered different
    slept = 0  # Stores a counter to time out the check for a change in brightness in case the brightness is the same
    while True:  # Loops until the brightness changes or it times out
        current_lux = SensorsInterface.getAmbientLight(
        )  # Get the current light value to check against in a second
        time.sleep(
            1
        )  # Waits for a second before checking brightness again to see if there was a change
        post_request_lux = SensorsInterface.getAmbientLight(
        )  # Get the current light value to check for changes
        if (post_request_lux > pre_request_lux + tolerance or post_request_lux > current_lux + tolerance) \
                and (direction == "BOTH" or direction == "UP"):
            print("Brightness went up")
            time.sleep(
                2
            )  # Waits 2 seconds before breaking the loop in case the bulb is still changing brightness
            break  # Breaks the loop since a brightness change was detected
        elif (post_request_lux < pre_request_lux - tolerance or post_request_lux < current_lux - tolerance) \
                and (direction == "BOTH" or direction == "DOWN"):
            print("Brightness went down")
            time.sleep(
                2
            )  # Waits 2 seconds before breaking the loop in case the bulb is still changing brightness
            break  # Breaks the loop since a brightness change was detected
        if slept >= 20:  # Gives the check 20 seconds to catch rare edge cases where the IFTTT request takes a long time
            print("Timed out, brightness may be the same or similar")
            time.sleep(
                1
            )  # Waits a second before breaking the loop in case the bulb is still changing brightness
            break  # Breaks the loop since no brightness change was detected after 30 seconds
        slept += 1  # Increases the counter for how long the brightness has been checked
示例#2
0
def calibrate():
    print("Calibrating...")
    pre_request_lux = SensorsInterface.getAmbientLight(
    )  # Gets the current light level before the request
    CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT,
                             100)  # Sets the Philips Hue brightness to 100
    wait_for_change(
        pre_request_lux, "UP"
    )  # Waits until the brightness changes from the request or it times out
    global lux_at_max
    lux_at_max = SensorsInterface.getAmbientLight(
    )  # Stores the light value when the Philips Hue is set to max

    pre_request_lux = SensorsInterface.getAmbientLight(
    )  # Gets the current light level before the request
    CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT,
                             0)  # Sets the Philips Hue brightness to 0
    wait_for_change(
        pre_request_lux, "DOWN"
    )  # Waits until the brightness changes from the request or it times out
    global lux_at_min
    lux_at_min = SensorsInterface.getAmbientLight(
    )  # Stores the light value when the Philips Hue is set to min

    global lux_diff
    lux_diff = lux_at_max - lux_at_min  # Calculates the difference in light between the max and min setting

    global lux_per_bright
    lux_per_bright = lux_diff / 100.0  # Calculates how much the light level changes for each step of brightness

    print("Min: " + str(lux_at_min) + " Max: " + str(lux_at_max))
    print("Difference: " + str(lux_diff) + " LuxPerBright: " +
          str(lux_per_bright))
def setup():
    print("Setting up...")
    SensorsInterface.setupSensorian()  # Prepare the sensors on the Sensorian Shield
    time.sleep(2)  # Wait 2 seconds or some sensors won't be ready
    global desired_lux
    desired_lux = SensorsInterface.getAmbientLight()  # Sets the desired light level to that of when the program ran
    print("Desired Light: " + str(desired_lux))  # Print the desired light level
def setup():
    print("Setting up...")
    SensorsInterface.setupSensorian()  # Prepare the sensors on the Sensorian Shield
    time.sleep(2)  # Wait 2 seconds or some sensors won't be ready
    (x, y, z) = SensorsInterface.getMagnetometer()  # Get the current force values of the magnetometer
    sensor_string = "X: " + str(x) + " Y: " + str(y) + " Z: " + str(z)  # Add the magnet values to the string
    tft_printer.screen_print_rotated(sensor_string, 1)  # Print the completed string to the landscape display
示例#5
0
def setup():
    print("Setting up...")
    SensorsInterface.setupSensorian(
    )  # Prepare the sensors on the Sensorian Shield
    time.sleep(2)  # Wait 2 seconds or some sensors won't be ready
    global desired_lux
    desired_lux = SensorsInterface.getAmbientLight(
    )  # Sets the desired light level to that of when the program ran
    print("Desired Light: " +
          str(desired_lux))  # Print the desired light level
def main():
    print("Running...")
    global current_setting
    while True:
        current_lux = SensorsInterface.getAmbientLight()  # Get the current light level to see if it is in range
        sensor_string = "Light: " + str(current_lux)  # Add the light value to the string
        tft_printer.screen_print_rotated(sensor_string, 1)  # Print the completed string to the landscape display
        current_difference = current_lux - desired_lux  # Calculate how different the current and desired levels are
        if current_difference < 0 and abs(current_difference) > lux_per_bright:  # If negative difference, check low
            brightness_notches = math.floor(abs(current_difference) / lux_per_bright)  # Calculate how much to change
            current_setting += brightness_notches  # Increase the current brightness by the calculated amount
            print("Light too low, increasing brightness by " + str(brightness_notches) + " to " + str(current_setting))
            if current_setting > 100:  # If the setting attempts to cross the maximum of 100, set it to 100
                print("Can't go brighter than 100, capping it")
                current_setting = 100  # Cap the setting at the maximum of 100
            CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT, current_setting)
            wait_for_change(current_lux, "UP")  # Waits until the brightness changes/times out
        elif current_difference > 0 and current_difference > lux_per_bright:  # If positive difference, check high
            brightness_notches = math.floor(current_difference / lux_per_bright)  # Calculate how much to change
            current_setting -= brightness_notches  # Decrease the current brightness by the calculated amount
            print("Light too high, decreasing brightness by " + str(brightness_notches) + " to " + str(current_setting))
            if current_setting < 0:  # If the setting attempts to cross the minimum of 0, set it to 0
                print("Can't go darker than 0, capping it")
                current_setting = 0  # Cap the setting at the minimum of 0
            CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT, current_setting)  # Change the brightness
            wait_for_change(current_lux, "DOWN")  # Waits until the brightness changes/times out
        time.sleep(3)  # Wait for 3 seconds between each check for brightness
	def update(self):
		global VECT_X
		global VECT_Y
		global VECT_Z
		cube_orientation = list(SensorsInterface.getMagnetometer())
		#Low-pass when collecting data from the magnetometer
		VECT_X = 0.2*VECT_X + 0.8*cube_orientation[0]
		VECT_Y = 0.2*VECT_Y + 0.8*cube_orientation[1]
		VECT_Z = 0.2*VECT_Z + 0.8*cube_orientation[2]
		self.write_message(json.dumps((int(VECT_X/100),int(VECT_Y/100),int(VECT_Z/100))))
def calibrate():
    print("Calibrating...")
    pre_request_lux = SensorsInterface.getAmbientLight()  # Gets the current light level before the request
    CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT, 100)  # Sets the Philips Hue brightness to 100
    wait_for_change(pre_request_lux, "UP")  # Waits until the brightness changes from the request or it times out
    global lux_at_max
    lux_at_max = SensorsInterface.getAmbientLight()  # Stores the light value when the Philips Hue is set to max

    pre_request_lux = SensorsInterface.getAmbientLight()  # Gets the current light level before the request
    CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT, 0)  # Sets the Philips Hue brightness to 0
    wait_for_change(pre_request_lux, "DOWN")  # Waits until the brightness changes from the request or it times out
    global lux_at_min
    lux_at_min = SensorsInterface.getAmbientLight()  # Stores the light value when the Philips Hue is set to min

    global lux_diff
    lux_diff = lux_at_max - lux_at_min  # Calculates the difference in light between the max and min setting

    global lux_per_bright
    lux_per_bright = lux_diff/100.0  # Calculates how much the light level changes for each step of brightness

    print("Min: " + str(lux_at_min) + " Max: " + str(lux_at_max))
    print("Difference: " + str(lux_diff) + " LuxPerBright: " + str(lux_per_bright))
def wait_for_change(pre_request_lux, direction="BOTH"):
    tolerance = lux_per_bright * TOLERANCE  # Sensitivity - How much the light should change to be considered different
    slept = 0  # Stores a counter to time out the check for a change in brightness in case the brightness is the same
    while True:  # Loops until the brightness changes or it times out
        current_lux = SensorsInterface.getAmbientLight()  # Get the current light value to check against in a second
        time.sleep(1)  # Waits for a second before checking brightness again to see if there was a change
        post_request_lux = SensorsInterface.getAmbientLight()  # Get the current light value to check for changes
        if (post_request_lux > pre_request_lux + tolerance or post_request_lux > current_lux + tolerance) \
                and (direction == "BOTH" or direction == "UP"):
            print("Brightness went up")
            time.sleep(2)  # Waits 2 seconds before breaking the loop in case the bulb is still changing brightness
            break  # Breaks the loop since a brightness change was detected
        elif (post_request_lux < pre_request_lux - tolerance or post_request_lux < current_lux - tolerance) \
                and (direction == "BOTH" or direction == "DOWN"):
            print("Brightness went down")
            time.sleep(2)  # Waits 2 seconds before breaking the loop in case the bulb is still changing brightness
            break  # Breaks the loop since a brightness change was detected
        if slept >= 20:  # Gives the check 20 seconds to catch rare edge cases where the IFTTT request takes a long time
            print("Timed out, brightness may be the same or similar")
            time.sleep(1)  # Waits a second before breaking the loop in case the bulb is still changing brightness
            break  # Breaks the loop since no brightness change was detected after 30 seconds
        slept += 1  # Increases the counter for how long the brightness has been checked
def calibrate():
    global xClosed, yClosed, zClosed
    seconds = SECONDS  # The number of seconds to give the user to prepare the device in the door closed position
    while seconds > 0:  # While the user still has time to prepare
        # print("Calibrating door closed state in " + str(seconds))
        calibrating = "Calibrating door closed state in " + str(seconds)
        print(calibrating)
        tft_printer.screen_print_rotated(calibrating, 1)
        time.sleep(1)  # Wait for a second
        seconds -= 1  # Reduce the time remaining for preparation by 1 second
    (xClosed, yClosed, zClosed) = SensorsInterface.getMagnetometer()  # Get the current force values of the magnetometer
    calibrated = "Calibrated door closed state to " + str(TOLERANCE) + " within " + str((xClosed, yClosed, zClosed))
    print(calibrated)
    tft_printer.screen_print_rotated(calibrated, 1)
    time.sleep(3)  # Waits 3 seconds so the user can read the screen
示例#11
0
def main():
    print("Running...")
    global current_setting
    while True:
        current_lux = SensorsInterface.getAmbientLight(
        )  # Get the current light level to see if it is in range
        sensor_string = "Light: " + str(
            current_lux)  # Add the light value to the string
        tft_printer.screen_print_rotated(
            sensor_string,
            1)  # Print the completed string to the landscape display
        current_difference = current_lux - desired_lux  # Calculate how different the current and desired levels are
        if current_difference < 0 and abs(
                current_difference
        ) > lux_per_bright:  # If negative difference, check low
            brightness_notches = math.floor(
                abs(current_difference) /
                lux_per_bright)  # Calculate how much to change
            current_setting += brightness_notches  # Increase the current brightness by the calculated amount
            print("Light too low, increasing brightness by " +
                  str(brightness_notches) + " to " + str(current_setting))
            if current_setting > 100:  # If the setting attempts to cross the maximum of 100, set it to 100
                print("Can't go brighter than 100, capping it")
                current_setting = 100  # Cap the setting at the maximum of 100
            CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT,
                                     current_setting)
            wait_for_change(
                current_lux,
                "UP")  # Waits until the brightness changes/times out
        elif current_difference > 0 and current_difference > lux_per_bright:  # If positive difference, check high
            brightness_notches = math.floor(
                current_difference /
                lux_per_bright)  # Calculate how much to change
            current_setting -= brightness_notches  # Decrease the current brightness by the calculated amount
            print("Light too high, decreasing brightness by " +
                  str(brightness_notches) + " to " + str(current_setting))
            if current_setting < 0:  # If the setting attempts to cross the minimum of 0, set it to 0
                print("Can't go darker than 0, capping it")
                current_setting = 0  # Cap the setting at the minimum of 0
            CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT,
                                     current_setting)  # Change the brightness
            wait_for_change(
                current_lux,
                "DOWN")  # Waits until the brightness changes/times out
        time.sleep(3)  # Wait for 3 seconds between each check for brightness
def main():
    print("Running...")
    door_was_open = False  # A boolean to store whether or not the door was already open if it was detected open again
    while True:
        (x, y, z) = SensorsInterface.getMagnetometer()  # Get the current force values of the magnetometer
        sensor_string = "X: " + str(x) + " Y: " + str(y) + " Z: " + str(z)  # Add the magnet values to the string
        # If any of the sensor values differ from the calibrated closed amount by more than the tolerance, it is open
        if xClosed - TOLERANCE > x or x > xClosed + TOLERANCE or yClosed - TOLERANCE > y or y > yClosed + TOLERANCE or \
                zClosed - TOLERANCE > z or z > zClosed + TOLERANCE:
            if not door_was_open:
                sensor_string += " Door opened!"
                print(sensor_string)
                CloudTools.ifttt_trigger(IFTTT_KEY, IFTTT_EVENT, IFTTT_TIMEOUT)
                door_was_open = True
        else:
            door_was_open = False
        tft_printer.screen_print_rotated(sensor_string, 1)  # Print the completed string to the landscape display
        time.sleep(1)  # Wait for 1 seconds between each check for magnetic forces
示例#13
0
def output_handler(pin, value):
    #Sensorian-led
    if pin == 0:
        if value == "1":
            SensorsInterface.ledOn()
        else:
            SensorsInterface.ledOff()

    #Sensorian-tft
    elif pin == 1:
        print "update sensorian-tft was called"
        #Check TFT availablity
        print "waiting for TFT_available_lock"
        TFT_available_lock.acquire()
        print "acquired TFT_available_lock"
        availability = TFT_available
        TFT_available_lock.release()
        print "released TFT_available_lock"
        if availability == False:
            print "dropping TFT write."
            return
        print "waiting for TFT_orientation_lock"
        TFT_orientation_lock.acquire()
        print "acquired TFT_orientation_lock"
        orientation = TFT_orientation
        #orientation = 1
        TFT_orientation_lock.release()
        print "released TFT_orientation_lock"
        print "Writing to tft"
        #tft_printer.screen_print(str(value))
        print "Trying to acquire TFT_Lock"
        TFT_Lock.acquire()
        print "Acquired TFT_Lock"
        my_tft_writer = TFT_Thread(value, orientation)
        my_tft_writer.start()
        print "End of output handler"

    #Sensorian-rtcc.time
    elif pin == 2:
        try:
            #Extract the time
            time = str(value).split(",")
            year = int(time[0])
            month = int(time[1])
            date = int(time[2])
            hour = int(time[3])
            minute = int(time[4])
            second = int(time[5])
            #Set the time
            SensorsInterface.setRTCCtime(year, month, date, hour, minute,
                                         second)
            print "Time has been set"
        except:
            print "Error setting the time"

    #Sensorian-rtcc.alarmtime
    elif pin == 3:
        try:
            #Extract the time and alarm mode
            time = str(value).split(",")
            year = int(time[0])
            month = int(time[1])
            date = int(time[2])
            hour = int(time[3])
            minute = int(time[4])
            second = int(time[5])
            mode = int(time[6])
            #Set the alarm
            SensorsInterface.setRTCCalarm(year, month, date, hour, minute,
                                          second, mode)
            print "Alarm time has been set"
        except:
            print "Error setting the alarm"

    #Sensorian-rtcc.resetalarm
    elif pin == 4:
        SensorsInterface.resetRTCCalarm()
import json
import math
import time

import tornado.websocket
import tornado.web
import tornado.ioloop
import tornado.httpserver

import SensorsInterface

VECT_X = 0.00
VECT_Y = 0.00
VECT_Z = 0.00

SensorsInterface.setupSensorian() #Initialize Sensorian

clients = []

class RotationDataSocket(tornado.websocket.WebSocketHandler):
	def open(self):
		print "Websocket has been opened"
		clients.append(self)
	
	def on_message(self,message):
		print "I have received a message"
	
	def on_close(self):
		print "Websocket closed"
	
	def update(self):
示例#15
0
#!/usr/bin/env python
"""test.py: Tests the functionality of tft_printer, SensorsInterface and NetworkingTools"""

import time
import tft_printer
import SensorsInterface
import PiTools
import CloudTools

__author__ = "Dylan Kauling"
__maintainer__ = "Dylan Kauling"
__status__ = "Development"

SensorsInterface.setupSensorian(
)  # Prepare the sensors on the Sensorian Shield

SensorsInterface.ledOn()  # Turn on the Sensorian Orange LED

# Print White Hello World to the display in Portrait mode
tft_printer.screen_print_rotated("Hello world!", 0)

time.sleep(2)  # Wait for 2 seconds before continuing.

# Print a longer black string on a white background to the display in Landscape mode
tft_printer.screen_print_rotated(
    "This is a longer string to demonstrate the wrapping and text background",
    1,
    colour=(0, 0, 0, 0),
    background=(255, 255, 255))

time.sleep(2)  # Wait for 2 seconds before continuing.
示例#16
0
    def run(self):
        global sensors

        #self.flask_input = open('read_pipe','w')
        #self.flask_output = open('write_pipe','r')
        self.mmap_file = open('mmap_ipc', 'a+b')
        self.mmap_buf = mmap.mmap(self.mmap_file.fileno(),
                                  0,
                                  access=mmap.ACCESS_WRITE)

        self.mmap_altitude_file = open('/home/pi/.sensorian/mmap_altitude',
                                       'a+b')
        self.mmap_altitude = mmap.mmap(self.mmap_altitude_file.fileno(),
                                       0,
                                       access=mmap.ACCESS_WRITE)

        self.mmap_pressure_file = open('/home/pi/.sensorian/mmap_pressure',
                                       'a+b')
        self.mmap_pressure = mmap.mmap(self.mmap_pressure_file.fileno(),
                                       0,
                                       access=mmap.ACCESS_WRITE)

        self.mmap_temperature_file = open(
            '/home/pi/.sensorian/mmap_temperature', 'a+b')
        self.mmap_temperature = mmap.mmap(self.mmap_temperature_file.fileno(),
                                          0,
                                          access=mmap.ACCESS_WRITE)

        self.mmap_ambientlight_file = open(
            '/home/pi/.sensorian/mmap_ambientlight', 'a+b')
        self.mmap_ambientlight = mmap.mmap(
            self.mmap_ambientlight_file.fileno(), 0, access=mmap.ACCESS_WRITE)

        SensorsInterface.setupSensorian()

        #Setup a dummy alarm for now
        SensorsInterface.setRTCCtime(2016, 3, 4, 5, 33, 0)
        SensorsInterface.setRTCCalarm(2018, 1, 1, 1, 40, 20,
                                      1)  #MINUTES_MATCH mode

        prev_touchpad = SensorsInterface.getTouchpad()
        #prev_magnetometer = SensorsInterface.getMagnetometer()
        prev_magnetometer = mk_bin_tuple(SensorsInterface.getMagnetometer())
        prev_accelerometer = mk_bin_tuple(SensorsInterface.getAccelerometer())
        prev_alarmtrigger = SensorsInterface.pollRTCCalarm()
        while self.alive:
            sensors_lock.acquire()
            sensors = {}
            touchpad = SensorsInterface.getTouchpad()
            if touchpad != prev_touchpad:
                print "Touchpad: " + str(touchpad)
                #sensors_lock.acquire()
                sensors['touchpad'] = touchpad
                #sensors_lock.release()
            prev_touchpad = touchpad

            #magnetometer = SensorsInterface.getMagnetometer()
            magnetometer = mk_bin_tuple(SensorsInterface.getMagnetometer())
            if magnetometer != prev_magnetometer:
                print "Magnetometer: " + str(magnetometer)
                #sensors_lock.acquire()
                sensors['magnetometer'] = magnetometer
                #sensors_lock.release()
            prev_magnetometer = magnetometer

            accelerometer = mk_bin_tuple(SensorsInterface.getAccelerometer())
            if accelerometer != prev_accelerometer:
                print "Accelerometer: " + str(accelerometer)
                sensors['accelerometer'] = accelerometer
            prev_accelerometer = accelerometer

            alarmtrigger = SensorsInterface.pollRTCCalarm()
            if alarmtrigger != prev_alarmtrigger:
                print "Alarm Trigger: " + str(alarmtrigger)
                sensors['alarmtrigger'] = alarmtrigger
            prev_alarmtrigger = alarmtrigger

            #Poll flask_rtcc_interface.py for new updates to RTCC
            #print "polling flask_rtcc_interface.py"
            #self.flask_input.write("reqUpdate\n")
            #self.flask_input.flush()
            if self.mmap_buf[0] == '1':
                #Update the time
                new_time_tuple = get_time_from_mmap(self.mmap_buf, 2)
                SensorsInterface.setRTCCtime(
                    new_time_tuple[0], new_time_tuple[1], new_time_tuple[2],
                    new_time_tuple[3], new_time_tuple[4], new_time_tuple[5])
                print "done setting the time"
                self.mmap_buf[0] = '0'  #Clear NEW_TIME

            if self.mmap_buf[1] == '1':
                #Update the alarm
                new_alarm_tuple = get_alarm_from_mmap(self.mmap_buf, 16)
                SensorsInterface.setRTCCalarm(
                    new_alarm_tuple[0], new_alarm_tuple[1], new_alarm_tuple[2],
                    new_alarm_tuple[3], new_alarm_tuple[4], new_alarm_tuple[5],
                    new_alarm_tuple[6])
                print "done setting the alarm"
                self.mmap_buf[1] = '0'  #Clear NEW_ALARM

            #Altitude
            if self.mmap_altitude[0] == '1':
                #Send altitude data... but first set the BUSY byte
                self.mmap_altitude[1] = '1'
                #Get the Altitude data
                print "Getting altitude data"
                sensors['altitude'] = str(SensorsInterface.getAltitude())
                self.mmap_altitude[0] = '0'  #The request has been completed
                self.mmap_altitude[1] = '0'  #...and we are no longer busy

            #Pressure
            if self.mmap_pressure[0] == '1':
                #Send pressure data... but first set the BUSY byte
                self.mmap_pressure[1] = '1'
                #Get the Pressure data
                print "Getting pressure data"
                sensors['pressure'] = str(
                    SensorsInterface.getBarometricPressure())
                self.mmap_pressure[0] = '0'  #The request has been completed
                self.mmap_pressure[1] = '0'  #...and we are no longer busy

            #Temperature
            if self.mmap_temperature[0] == '1':
                #Send temperature data... but first set the BUSY byte
                self.mmap_temperature[1] = '1'
                #Get the Temperature data
                print "Getting temperature data"
                sensors['temperature'] = str(SensorsInterface.getTemperature())
                self.mmap_temperature[0] = '0'  #The request has been completed
                self.mmap_temperature[1] = '0'  #...and we are no longer busy

            #AmbientLight
            if self.mmap_ambientlight[0] == '1':
                #Send temperature data... but first set the BUSY byte
                self.mmap_ambientlight[1] = '1'
                #Get the Ambient Light data
                print "Getting ambient light data"
                sensors['ambientlight'] = str(
                    SensorsInterface.getAmbientLight())
                self.mmap_ambientlight[
                    0] = '0'  #The request has been completed
                self.mmap_ambientlight[1] = '0'  #...and we are no longer busy

            sensors_lock.release()
            """If there is new data stored in sensors --> sensors != {},
			then we should make this thread wait until it is sent to the
			socket. """
            if sensors != {}:
                data_ready_event.clear()
                data_ready_event.wait()
示例#17
0
    def run(self):
        self.alive = True
        while self.alive:
            self.sensors_lock.acquire()

            ######################### Touchpad ####################
            cap_button = SensorsInterface.getTouchpad()
            try:
                if cap_button != self.sensors[0]["da"]:
                    #self.sensors[0]["da"] = cap_button
                    #self.sensors[0]["dr"] = True
                    self.sensors[0] = {"da": cap_button, "dr": True}
                    print "Updating touchpad"
            except:
                #self.sensors[0]["da"] = cap_button
                #self.sensors[0]["dr"] = True
                self.sensors[0] = {"da": cap_button, "dr": True}
                print "Updating touchpad"

            #################### Ambient Light #####################
            ambient_light = SensorsInterface.getAmbientLight()
            try:
                if ambient_light != self.sensors[1]["da"]:
                    self.sensors[1] = {"da": ambient_light, "dr": True}
            except:
                self.sensors[1] = {"da": ambient_light, "dr": True}

            ##################### Barometric Pressure ################
            pressure = SensorsInterface.getBarometricPressure()
            try:
                if pressure != self.sensors[2]["da"]:
                    self.sensors[2] = {"da": pressure, "dr": True}
            except:
                self.sensors[2] = {"da": pressure, "dr": True}

            ##################### Altitude ############################
            altitude = SensorsInterface.getAltitude()
            try:
                if altitude != self.sensors[3]["da"]:
                    self.sensors[3] = {"da": altitude, "dr": True}
            except:
                self.sensors[3] = {"da": altitude, "dr": True}

            ##################### Temperature #########################
            temperature = SensorsInterface.getTemperature()
            try:
                if temperature != self.sensors[4]["da"]:
                    self.sensors[4] = {"da": temperature, "dr": True}
            except:
                self.sensors[4] = {"da": temperature, "dr": True}

            ##################### Accelerometer #######################
            accel = SensorsInterface.getAccelerometer()
            #-------- X component ---------
            accel_x = accel[0]
            try:
                if accel_x != self.sensors[5]["da"]:
                    self.sensors[5] = {"da": accel_x, "dr": True}
            except:
                self.sensors[5] = {"da": accel_x, "dr": True}

            #---------- Y component --------
            accel_y = accel[1]
            try:
                if accel_y != self.sensors[6]["da"]:
                    self.sensors[6] = {"da": accel_y, "dr": True}
            except:
                self.sensors[6] = {"da": accel_y, "dr": True}

            #---------- Z component ----------
            accel_z = accel[2]
            try:
                if accel_z != self.sensors[7]["da"]:
                    self.sensors[7] = {"da": accel_z, "dr": True}
            except:
                self.sensors[7] = {"da": accel_z, "dr": True}

            ##################### Magnetometer #######################
            magneto = SensorsInterface.getMagnetometer()
            #-------- X component ---------
            magneto_x = magneto[0]
            try:
                if magneto_x != self.sensors[8]["da"]:
                    self.sensors[8] = {"da": magneto_x, "dr": True}
            except:
                self.sensors[8] = {"da": magneto_x, "dr": True}

            #---------- Y component --------
            magneto_y = magneto[1]
            try:
                if magneto_y != self.sensors[9]["da"]:
                    self.sensors[9] = {"da": magneto_y, "dr": True}
            except:
                self.sensors[9] = {"da": magneto_y, "dr": True}

            #---------- Z component ----------
            magneto_z = magneto[2]
            try:
                if magneto_z != self.sensors[10]["da"]:
                    self.sensors[10] = {"da": magneto_z, "dr": True}
            except:
                self.sensors[10] = {"da": magneto_z, "dr": True}

            ###################### RTCC ##############################
            rtcc = SensorsInterface.getRTCCtime()

            #----------- year
            rtcc_year = rtcc[0]
            try:
                if rtcc_year != self.sensors[11]["da"]:
                    self.sensors[11] = {"da": rtcc_year, "dr": True}
            except:
                self.sensors[11] = {"da": rtcc_year, "dr": True}

            #---------- month
            rtcc_month = rtcc[1]
            try:
                if rtcc_month != self.sensors[12]["da"]:
                    self.sensors[12] = {"da": rtcc_month, "dr": True}
            except:
                self.sensors[12] = {"da": rtcc_month, "dr": True}

            #---------- date
            rtcc_date = rtcc[2]
            try:
                if rtcc_date != self.sensors[13]["da"]:
                    self.sensors[13] = {"da": rtcc_date, "dr": True}
            except:
                self.sensors[13] = {"da": rtcc_date, "dr": True}

            #---------- hour
            rtcc_hour = rtcc[3]
            try:
                if rtcc_hour != self.sensors[14]["da"]:
                    self.sensors[14] = {"da": rtcc_hour, "dr": True}
            except:
                self.sensors[14] = {"da": rtcc_hour, "dr": True}

            #---------- minute
            rtcc_minute = rtcc[4]
            try:
                if rtcc_minute != self.sensors[15]["da"]:
                    self.sensors[15] = {"da": rtcc_minute, "dr": True}
            except:
                self.sensors[15] = {"da": rtcc_minute, "dr": True}

            #---------- second
            rtcc_second = rtcc[5]
            try:
                if rtcc_second != self.sensors[16]["da"]:
                    self.sensors[16] = {"da": rtcc_second, "dr": True}
            except:
                self.sensors[16] = {"da": rtcc_second, "dr": True}

            #------------- alarm trigger
            alarm_trigger = SensorsInterface.pollRTCCalarm()
            try:
                if alarm_trigger != self.sensors[17]["da"]:
                    self.sensors[17] = {"da": alarm_trigger, "dr": True}
            except:
                self.sensors[17] = {"da": alarm_trigger, "dr": True}

            self.sensors_lock.release()

            for s in self.exported_sensors:
                if self.sensors[s]["dr"] == True:
                    #Wait here until data has been sent to socket
                    self.has_data_event.clear()
                    self.has_data_event.wait()
                    break
示例#18
0
                print "Connected with MQTT Broker: " + str(MQTT_Broker)

def on_publish(client, userdata, mid):
        pass

def on_disconnect(client, userdata, rc):
        if rc !=0:
                pass

mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_publish = on_publish
mqttc.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval))

sensor.setupSensorian()

time.sleep(2)

while True:
        temp = str(sensor.getTemperature())
        light = str(sensor.getAmbientLight())
        press = str(sensor.getBarometricPressure())
        alt = str(sensor.getAltitude())

        mqttc.publish(topic_temp, temp)
        time.sleep(2)
        print temp
        mqttc.publish(topic_light, light)
        time.sleep(2)
        print light
示例#19
0
#!/usr/bin/env python

"""test.py: Tests the functionality of tft_printer, SensorsInterface and NetworkingTools"""

import time
import tft_printer
import SensorsInterface
import PiTools
import CloudTools

__author__ = "Dylan Kauling"
__maintainer__ = "Dylan Kauling"
__status__ = "Development"

SensorsInterface.setupSensorian()  # Prepare the sensors on the Sensorian Shield

SensorsInterface.ledOn()  # Turn on the Sensorian Orange LED

# Print White Hello World to the display in Portrait mode
tft_printer.screen_print_rotated("Hello world!", 0)

time.sleep(2)  # Wait for 2 seconds before continuing.

# Print a longer black string on a white background to the display in Landscape mode
tft_printer.screen_print_rotated("This is a longer string to demonstrate the wrapping and text background", 1,
                                 colour=(0, 0, 0, 0), background=(255, 255, 255))

time.sleep(2)  # Wait for 2 seconds before continuing.

sensor_string = ""  # Prepare an empty string to be printed to the screen 
示例#20
0
    def run(self):
        self.alive = True
        while self.alive:
            self.sensors_lock.acquire()

            ######################### Touchpad ####################
            cap_button = SensorsInterface.getTouchpad()
            try:
                if cap_button != self.sensors[0]["da"]:
                    # self.sensors[0]["da"] = cap_button
                    # self.sensors[0]["dr"] = True
                    self.sensors[0] = {"da": cap_button, "dr": True}
                    print "Updating touchpad"
            except:
                # self.sensors[0]["da"] = cap_button
                # self.sensors[0]["dr"] = True
                self.sensors[0] = {"da": cap_button, "dr": True}
                print "Updating touchpad"

                #################### Ambient Light #####################
            ambient_light = SensorsInterface.getAmbientLight()
            try:
                if ambient_light != self.sensors[1]["da"]:
                    self.sensors[1] = {"da": ambient_light, "dr": True}
            except:
                self.sensors[1] = {"da": ambient_light, "dr": True}

                ##################### Barometric Pressure ################
            pressure = SensorsInterface.getBarometricPressure()
            try:
                if pressure != self.sensors[2]["da"]:
                    self.sensors[2] = {"da": pressure, "dr": True}
            except:
                self.sensors[2] = {"da": pressure, "dr": True}

                ##################### Altitude ############################
            altitude = SensorsInterface.getAltitude()
            try:
                if altitude != self.sensors[3]["da"]:
                    self.sensors[3] = {"da": altitude, "dr": True}
            except:
                self.sensors[3] = {"da": altitude, "dr": True}

                ##################### Temperature #########################
            temperature = SensorsInterface.getTemperature()
            try:
                if temperature != self.sensors[4]["da"]:
                    self.sensors[4] = {"da": temperature, "dr": True}
            except:
                self.sensors[4] = {"da": temperature, "dr": True}

                ##################### Accelerometer #######################
            accel = SensorsInterface.getAccelerometer()
            # -------- X component ---------
            accel_x = accel[0]
            try:
                if accel_x != self.sensors[5]["da"]:
                    self.sensors[5] = {"da": accel_x, "dr": True}
            except:
                self.sensors[5] = {"da": accel_x, "dr": True}

                # ---------- Y component --------
            accel_y = accel[1]
            try:
                if accel_y != self.sensors[6]["da"]:
                    self.sensors[6] = {"da": accel_y, "dr": True}
            except:
                self.sensors[6] = {"da": accel_y, "dr": True}

                # ---------- Z component ----------
            accel_z = accel[2]
            try:
                if accel_z != self.sensors[7]["da"]:
                    self.sensors[7] = {"da": accel_z, "dr": True}
            except:
                self.sensors[7] = {"da": accel_z, "dr": True}

                ##################### Magnetometer #######################
            magneto = SensorsInterface.getMagnetometer()
            # -------- X component ---------
            magneto_x = magneto[0]
            try:
                if magneto_x != self.sensors[8]["da"]:
                    self.sensors[8] = {"da": magneto_x, "dr": True}
            except:
                self.sensors[8] = {"da": magneto_x, "dr": True}

                # ---------- Y component --------
            magneto_y = magneto[1]
            try:
                if magneto_y != self.sensors[9]["da"]:
                    self.sensors[9] = {"da": magneto_y, "dr": True}
            except:
                self.sensors[9] = {"da": magneto_y, "dr": True}

                # ---------- Z component ----------
            magneto_z = magneto[2]
            try:
                if magneto_z != self.sensors[10]["da"]:
                    self.sensors[10] = {"da": magneto_z, "dr": True}
            except:
                self.sensors[10] = {"da": magneto_z, "dr": True}

                ###################### RTCC ##############################
            rtcc = SensorsInterface.getRTCCtime()

            # ----------- year
            rtcc_year = rtcc[0]
            try:
                if rtcc_year != self.sensors[11]["da"]:
                    self.sensors[11] = {"da": rtcc_year, "dr": True}
            except:
                self.sensors[11] = {"da": rtcc_year, "dr": True}

                # ---------- month
            rtcc_month = rtcc[1]
            try:
                if rtcc_month != self.sensors[12]["da"]:
                    self.sensors[12] = {"da": rtcc_month, "dr": True}
            except:
                self.sensors[12] = {"da": rtcc_month, "dr": True}

                # ---------- date
            rtcc_date = rtcc[2]
            try:
                if rtcc_date != self.sensors[13]["da"]:
                    self.sensors[13] = {"da": rtcc_date, "dr": True}
            except:
                self.sensors[13] = {"da": rtcc_date, "dr": True}

                # ---------- hour
            rtcc_hour = rtcc[3]
            try:
                if rtcc_hour != self.sensors[14]["da"]:
                    self.sensors[14] = {"da": rtcc_hour, "dr": True}
            except:
                self.sensors[14] = {"da": rtcc_hour, "dr": True}

                # ---------- minute
            rtcc_minute = rtcc[4]
            try:
                if rtcc_minute != self.sensors[15]["da"]:
                    self.sensors[15] = {"da": rtcc_minute, "dr": True}
            except:
                self.sensors[15] = {"da": rtcc_minute, "dr": True}

                # ---------- second
            rtcc_second = rtcc[5]
            try:
                if rtcc_second != self.sensors[16]["da"]:
                    self.sensors[16] = {"da": rtcc_second, "dr": True}
            except:
                self.sensors[16] = {"da": rtcc_second, "dr": True}

                # ------------- alarm trigger
            alarm_trigger = SensorsInterface.pollRTCCalarm()
            try:
                if alarm_trigger != self.sensors[17]["da"]:
                    self.sensors[17] = {"da": alarm_trigger, "dr": True}
            except:
                self.sensors[17] = {"da": alarm_trigger, "dr": True}

            self.sensors_lock.release()

            for s in self.exported_sensors:
                if self.sensors[s]["dr"] == True:
                    # Wait here until data has been sent to socket
                    self.has_data_event.clear()
                    self.has_data_event.wait()
                    break
示例#21
0
def output_handler(pin, value):
    # Sensorian-led
    if pin == 0:
        if value == "1":
            SensorsInterface.ledOn()
        else:
            SensorsInterface.ledOff()

            # Sensorian-tft
    elif pin == 1:
        print "update sensorian-tft was called"
        # Check TFT availablity
        print "waiting for TFT_available_lock"
        TFT_available_lock.acquire()
        print "acquired TFT_available_lock"
        availability = TFT_available
        TFT_available_lock.release()
        print "released TFT_available_lock"
        if availability == False:
            print "dropping TFT write."
            return
        print "waiting for TFT_orientation_lock"
        TFT_orientation_lock.acquire()
        print "acquired TFT_orientation_lock"
        orientation = TFT_orientation
        # orientation = 1
        TFT_orientation_lock.release()
        print "released TFT_orientation_lock"
        print "Writing to tft"
        # tft_printer.screen_print(str(value))
        print "Trying to acquire TFT_Lock"
        TFT_Lock.acquire()
        print "Acquired TFT_Lock"
        my_tft_writer = TFT_Thread(value, orientation)
        my_tft_writer.start()
        print "End of output handler"

        # Sensorian-rtcc.time
    elif pin == 2:
        try:
            # Extract the time
            time = str(value).split(",")
            year = int(time[0])
            month = int(time[1])
            date = int(time[2])
            hour = int(time[3])
            minute = int(time[4])
            second = int(time[5])
            # Set the time
            SensorsInterface.setRTCCtime(year, month, date, hour, minute, second)
            print "Time has been set"
        except:
            print "Error setting the time"

            # Sensorian-rtcc.alarmtime
    elif pin == 3:
        try:
            # Extract the time and alarm mode
            time = str(value).split(",")
            year = int(time[0])
            month = int(time[1])
            date = int(time[2])
            hour = int(time[3])
            minute = int(time[4])
            second = int(time[5])
            mode = int(time[6])
            # Set the alarm
            SensorsInterface.setRTCCalarm(year, month, date, hour, minute, second, mode)
            print "Alarm time has been set"
        except:
            print "Error setting the alarm"

            # Sensorian-rtcc.resetalarm
    elif pin == 4:
        SensorsInterface.resetRTCCalarm()
示例#22
0
        selected_sensor_numbers.append(6)
        selected_sensor_numbers.append(7)
    if var_args["magnetometer"]:
        selected_sensor_numbers.append(8)
        selected_sensor_numbers.append(9)
        selected_sensor_numbers.append(10)
    if var_args["rtcc"]:
        selected_sensor_numbers.append(11)
        selected_sensor_numbers.append(12)
        selected_sensor_numbers.append(13)
        selected_sensor_numbers.append(14)
        selected_sensor_numbers.append(15)
        selected_sensor_numbers.append(16)
        selected_sensor_numbers.append(17)

SensorsInterface.setupSensorian()

# Ensure all alarms are off
SensorsInterface.resetRTCCalarm()

sensormonitor = SensorMonitor(selected_sensor_numbers)
sensormonitor.start()

if var_args["connect"]:
    remote_host = var_args["connect"][0]
    client = ScratchHandler(selected_sensor_numbers, host=remote_host)
else:
    client = ScratchHandler(selected_sensor_numbers)

asyncore.loop()
	def run(self):
		global sensors
		
		#self.flask_input = open('read_pipe','w')
		#self.flask_output = open('write_pipe','r')
		self.mmap_file = open('mmap_ipc','a+b')
		self.mmap_buf = mmap.mmap(self.mmap_file.fileno(),0,access=mmap.ACCESS_WRITE)
		
		self.mmap_altitude_file = open('/home/pi/.sensorian/mmap_altitude','a+b')
		self.mmap_altitude = mmap.mmap(self.mmap_altitude_file.fileno(),0,access=mmap.ACCESS_WRITE)
		
		self.mmap_pressure_file = open('/home/pi/.sensorian/mmap_pressure','a+b')
		self.mmap_pressure = mmap.mmap(self.mmap_pressure_file.fileno(),0,access=mmap.ACCESS_WRITE)
		
		self.mmap_temperature_file = open('/home/pi/.sensorian/mmap_temperature','a+b')
		self.mmap_temperature = mmap.mmap(self.mmap_temperature_file.fileno(),0,access=mmap.ACCESS_WRITE)
		
		self.mmap_ambientlight_file = open('/home/pi/.sensorian/mmap_ambientlight','a+b')
		self.mmap_ambientlight = mmap.mmap(self.mmap_ambientlight_file.fileno(),0,access=mmap.ACCESS_WRITE)
		
		SensorsInterface.setupSensorian()
		
		#Setup a dummy alarm for now
		SensorsInterface.setRTCCtime(2016,3,4,5,33,0)
		SensorsInterface.setRTCCalarm(2018,1,1,1,40,20,1) #MINUTES_MATCH mode
		
		prev_touchpad = SensorsInterface.getTouchpad()
		#prev_magnetometer = SensorsInterface.getMagnetometer()
		prev_magnetometer = mk_bin_tuple(SensorsInterface.getMagnetometer())
		prev_accelerometer = mk_bin_tuple(SensorsInterface.getAccelerometer())
		prev_alarmtrigger = SensorsInterface.pollRTCCalarm()
		while self.alive:
			sensors_lock.acquire()
			sensors = {}
			touchpad = SensorsInterface.getTouchpad()
			if touchpad != prev_touchpad:
				print "Touchpad: " + str(touchpad)
				#sensors_lock.acquire()
				sensors['touchpad'] = touchpad
				#sensors_lock.release()
			prev_touchpad = touchpad
			
			#magnetometer = SensorsInterface.getMagnetometer()
			magnetometer = mk_bin_tuple(SensorsInterface.getMagnetometer())
			if magnetometer != prev_magnetometer:
				print "Magnetometer: " + str(magnetometer)
				#sensors_lock.acquire()
				sensors['magnetometer'] = magnetometer
				#sensors_lock.release()
			prev_magnetometer = magnetometer
			
			accelerometer = mk_bin_tuple(SensorsInterface.getAccelerometer())
			if accelerometer != prev_accelerometer:
				print "Accelerometer: " + str(accelerometer)
				sensors['accelerometer'] = accelerometer
			prev_accelerometer = accelerometer
			
			alarmtrigger = SensorsInterface.pollRTCCalarm()
			if alarmtrigger != prev_alarmtrigger:
				print "Alarm Trigger: " + str(alarmtrigger)
				sensors['alarmtrigger'] = alarmtrigger
			prev_alarmtrigger = alarmtrigger
			
			#Poll flask_rtcc_interface.py for new updates to RTCC
			#print "polling flask_rtcc_interface.py"
			#self.flask_input.write("reqUpdate\n")
			#self.flask_input.flush()
			if self.mmap_buf[0] == '1':
				#Update the time
				new_time_tuple = get_time_from_mmap(self.mmap_buf,2)
				SensorsInterface.setRTCCtime(new_time_tuple[0],new_time_tuple[1],new_time_tuple[2],new_time_tuple[3],new_time_tuple[4],new_time_tuple[5])
				print "done setting the time"
				self.mmap_buf[0] = '0' #Clear NEW_TIME
			
			if self.mmap_buf[1] == '1':
				#Update the alarm
				new_alarm_tuple = get_alarm_from_mmap(self.mmap_buf,16)
				SensorsInterface.setRTCCalarm(new_alarm_tuple[0],new_alarm_tuple[1],new_alarm_tuple[2],new_alarm_tuple[3],new_alarm_tuple[4],new_alarm_tuple[5],new_alarm_tuple[6])
				print "done setting the alarm"
				self.mmap_buf[1] = '0' #Clear NEW_ALARM
			
			#Altitude
			if self.mmap_altitude[0] == '1':
				#Send altitude data... but first set the BUSY byte
				self.mmap_altitude[1] = '1'
				#Get the Altitude data
				print "Getting altitude data"
				sensors['altitude'] = str(SensorsInterface.getAltitude())
				self.mmap_altitude[0] = '0' #The request has been completed
				self.mmap_altitude[1] = '0' #...and we are no longer busy
			
			#Pressure
			if self.mmap_pressure[0] == '1':
				#Send pressure data... but first set the BUSY byte
				self.mmap_pressure[1] = '1'
				#Get the Pressure data
				print "Getting pressure data"
				sensors['pressure'] = str(SensorsInterface.getBarometricPressure())
				self.mmap_pressure[0] = '0' #The request has been completed
				self.mmap_pressure[1] = '0' #...and we are no longer busy
			
			#Temperature
			if self.mmap_temperature[0] == '1':
				#Send temperature data... but first set the BUSY byte
				self.mmap_temperature[1] = '1'
				#Get the Temperature data
				print "Getting temperature data"
				sensors['temperature'] = str(SensorsInterface.getTemperature())
				self.mmap_temperature[0] = '0' #The request has been completed
				self.mmap_temperature[1] = '0' #...and we are no longer busy
			
			#AmbientLight
			if self.mmap_ambientlight[0] == '1':
				#Send temperature data... but first set the BUSY byte
				self.mmap_ambientlight[1] = '1'
				#Get the Ambient Light data
				print "Getting ambient light data"
				sensors['ambientlight'] = str(SensorsInterface.getAmbientLight())
				self.mmap_ambientlight[0] = '0' #The request has been completed
				self.mmap_ambientlight[1] = '0' #...and we are no longer busy
			
			sensors_lock.release()
			
			"""If there is new data stored in sensors --> sensors != {},
			then we should make this thread wait until it is sent to the
			socket. """
			if sensors != {}:
				data_ready_event.clear()
				data_ready_event.wait()
示例#24
0
        selected_sensor_numbers.append(6)
        selected_sensor_numbers.append(7)
    if var_args['magnetometer']:
        selected_sensor_numbers.append(8)
        selected_sensor_numbers.append(9)
        selected_sensor_numbers.append(10)
    if var_args['rtcc']:
        selected_sensor_numbers.append(11)
        selected_sensor_numbers.append(12)
        selected_sensor_numbers.append(13)
        selected_sensor_numbers.append(14)
        selected_sensor_numbers.append(15)
        selected_sensor_numbers.append(16)
        selected_sensor_numbers.append(17)

SensorsInterface.setupSensorian()

#Ensure all alarms are off
SensorsInterface.resetRTCCalarm()

sensormonitor = SensorMonitor(selected_sensor_numbers)
sensormonitor.start()

if var_args['connect']:
    remote_host = var_args['connect'][0]
    client = ScratchHandler(selected_sensor_numbers, host=remote_host)
else:
    client = ScratchHandler(selected_sensor_numbers)

asyncore.loop()