def test_events_publish_file_text(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] dir_path = os.path.dirname(os.path.realpath(__file__)) result = wia.Event.publish(name='test_event_other_file', file=(dir_path + '/test-file.txt')) wia.access_token = None
def test_events_publish_file_text(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] dir_path = os.path.dirname(os.path.realpath(__file__)) event = wia.Event.publish(name='test_event_other_file', file=(dir_path+'/test-file.txt')) self.assertTrue(event.id is not None) wia.access_token = None
def test_location_publish_wrong_params(self): logging.info("Started test_location_publish_wrong_params") wia = Wia() wia.access_token = os.environ['WIA_TEST_DEVICE_SECRET_KEY'] location = wia.Location.publish(name='fail') self.assertIsInstance(location, WiaError) wia.access_token = None logging.info("Finished test_location_publish_wrong_params")
def test_locations_publish_rest(self): logging.info("Started test_locations_publish_rest") wia = Wia() wia.access_token = os.environ['WIA_TEST_DEVICE_SECRET_KEY'] location = wia.Location.publish(latitude=50, longitude=60) self.assertTrue(location.id is not None) wia.access_token = None logging.info("Finished test_locations_publish_rest")
def test_events_publish_file(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] dir_path = os.path.dirname(os.path.realpath(__file__)) event = Wia().Event.publish(name='test_event_other_filesud', data=1300, file=open(dir_path + '/test-file.txt', 'rb')) self.assertTrue(event.id is not None) wia.access_token = None
def test_command_create_retrieve_update_run_delete(self): app_key = os.environ['WIA_TEST_APP_KEY'] wia = Wia() wia.app_key = app_key access_token = wia.access_token_create( username=os.environ['WIA_TEST_USERNAME'], password=os.environ['WIA_TEST_PASSWORD']) command = wia.Command.create(**{ "name": "runTest", "device.id": os.environ['device_id'] }) self.assertEqual(command.name, 'runTest') command = wia.Command.retrieve(command.id) self.assertEqual(command.name, 'runTest') commandUpdated = wia.Command.update( **{ "id": command.id, "name": "runTestUpdated", "device.id": os.environ['device_id'], "slug": command.slug }) self.assertEqual(commandUpdated.name, 'runTestUpdated') commandRun = wia.Command.run( **{ "id": command.id, "name": "runTestUpdated", "device.id": os.environ['device_id'], "slug": command.slug }) self.assertTrue(wia.Command.delete(commandUpdated.id)) wia.access_token = None
def verifyUser(): camera = PiCamera() camera.resolution = (1000, 800) camera.start_preview() time.sleep(2) fileName = str(uuid.uuid4()) + ".jpeg" camera.capture('/home/pi/Desktop/scrot/' + fileName) camera.stop_preview() camera.close() wia = Wia() wia.access_token = "d_sk_Dku9mWR5BvmqGBu4DlVbleEZ" try: wia.Event.publish(name="image", file='/home/pi/Desktop/scrot/' + fileName) print("") print("Image uploading...") time.sleep(1) print("") print("Image uploaded!") print("") except Exception as error: print(error) eucDst(retrieveUser(), retrieveImage())
def start(): #Starting new Wia class and setting decivce's secret access token wia = Wia() wia.access_token = "" #Infinte Loop taking images and uploading them to WIA flow count = 0 while (count < 1): #Calling image image = capture() #Check is the image is null if image is not None: #If Image is not null try to upload it to WIA flow by #publishing it to event named image #If the publish fails print the error try: wia.Event.publish(name="image", file=image) except Exception as e: print(e) else: #If Image is null print error mesage print("Error Capturing Image") #Sleep 10 seconds before taking another image ##time.sleep(10) count += 1
def test_init_access_token(self): logging.info("Starting test_init_access_token") access_token = os.environ['WIA_TEST_DEVICE_SECRET_KEY'] wia = Wia() wia.access_token = access_token whoami = wia.WhoAmI.retrieve() self.assertIsInstance(whoami, type(wia.WhoAmI)) access_token = None logging.info("Finished test_init_access_token")
def test_command_list(self): app_key = os.environ['WIA_TEST_APP_KEY'] wia = Wia() wia.app_key = app_key access_token = wia.access_token_create(username=os.environ['WIA_TEST_USERNAME'], password=os.environ['WIA_TEST_PASSWORD']) commands = wia.Command.list(**{"device.id": os.environ['device_id']}) self.assertTrue(type(commands['commands']) == list) wia.access_token = None
def test_command_list(self): app_key = os.environ['WIA_TEST_APP_KEY'] wia = Wia() wia.app_key = app_key access_token = wia.access_token_create( username=os.environ['WIA_TEST_USERNAME'], password=os.environ['WIA_TEST_PASSWORD']) commands = wia.Command.list(**{"device.id": os.environ['device_id']}) self.assertTrue(type(commands['commands']) == list) wia.access_token = None
def publish_presence(name, result): buffer = StringIO.StringIO() fileName = name + '.png' if result[-8:] == 'not home': fileName = 'x.png' print(fileName) buffer.write(open(fileName, 'rb').read()) buffer.seek(0) wia = Wia() wia.access_token = config.get('wia.io', 'access_token') wia.Event.publish(name="temperature", data=21.5) wia.Event.publish(name=name, file=buffer) buffer.close()
def test_command_create_retrieve_update_run_delete(self): app_key = os.environ['WIA_TEST_APP_KEY'] wia = Wia() wia.app_key = app_key access_token = wia.access_token_create(username=os.environ['WIA_TEST_USERNAME'], password=os.environ['WIA_TEST_PASSWORD']) command = wia.Command.create(**{"name": "runTest", "device.id": os.environ['device_id']}) self.assertEqual(command.name, 'runTest') command = wia.Command.retrieve(command.id) self.assertEqual(command.name, 'runTest') commandUpdated = wia.Command.update(**{"id": command.id, "name": "runTestUpdated", "device.id": os.environ['device_id'], "slug": command.slug}) self.assertEqual(commandUpdated.name, 'runTestUpdated') commandRun = wia.Command.run(**{"id": command.id, "name": "runTestUpdated", "device.id": os.environ['device_id'], "slug": command.slug}) self.assertTrue(wia.Command.delete(commandUpdated.id)) wia.access_token = None
def test_events_publish_rest_error(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] result = wia.Event.publish(abc='def') self.assertIsInstance(result, WiaError) wia.access_token = None
def test_events_publish_rest(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] event = wia.Event.publish(name='test_event_other_rest', data=130) self.assertTrue(event.id is not None) wia.access_token = None
import datetime from twilio.rest import Client import json from wia import Wia import bluetooth import mysql.connector from sense_hat import SenseHat sense = SenseHat() account_sid = 'AC36ac6c1777bf527f2968c401d1118457' auth_token = 'f4d63d14fa37afbc3fa1c908cc55398f' client = Client(account_sid, auth_token) wia = Wia() wia.access_token = "d_sk_3HzhRkBfOYVoxjp7Yo8myN14" while True: for event in sense.stick.get_events(): if event.action == "pressed" and event.direction == "middle": wia.Event.publish(name="button", data="Hi there") ################################################################################################ def Authenticate(addr): #Return the user of the device from the database mydb = mysql.connector.connect(host="127.0.0.1", user="******", passwd="Liverpool2020!", database="whoisathome")
return acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0) y = round(y, 0) z = round(z, 0) init_val = [x, y, z] wia = Wia() wia.access_token = 'Wia_key' #here I intended to work on a piece of code which activates sound via bluetooth... but due to lack of time related to my newborn I ended up suspending this id$ timestamp = [0, 0, 0, 0] i = 0 while True: acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0) y = round(y, 0) z = round(z, 0) sens_val = [x, y, z] if (init_val[0] != sens_val[0] or init_val[1] != sens_val[1]
def test_create_device_invalid_params(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] device = wia.Device.create(name='fail', public='Oops') self.assertIsInstance(device, WiaError) wia.access_token = None
def test_create_device_wrong_params(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] device = wia.Device.create(name='fail', data=100) self.assertIsInstance(device, WiaError) wia.access_token = None
import pygame from pygame import mixer from wia import Wia from picamera import PiCamera pygame.init() pygame.mixer.init() mysound = mixer.Sound("SonnetteHaute.wav") GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP) wia = Wia() wia.access_token = 'd_sk_wi9s8K9wVwuO812oUc9QecOk' camera = PiCamera() while True: input_state = GPIO.input(25) if input_state == False: print('Button Pressed') mysound.play() ## Start up PiCam camera.start_preview() ## sleep for a few seconds to let camera focus/adjust to light time.sleep(5) ## Capture photo camera.capture('/home/pi/image.jpg') ## Stop the PiCam camera.stop_preview()
def test_create_device_not_authorized(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] device = wia.Device.create(name='fail', public=True) self.assertIsInstance(device, WiaError) wia.access_token = None
#!/usr/bin/python import bme680 import bluetooth import time #Wia Setup from wia import Wia wia = Wia() wia.access_token = "" # Change to whatever secret key for your wia # Temperature Sensor try: sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY) except IOError: sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY) sensor.set_temperature_oversample(bme680.OS_8X) print ("================================================") print (" Vehicle Interior Safety System Check ") print ("================================================") # Loop to continuously check variable status values while True: #Bluetooth Proximity nearby_devices = bluetooth.discover_devices() result = bluetooth.lookup_name("AA:BB:CC:DD:EE:FF", timeout=30) # Enter MAC address of the BT device to lookout for #Temperature Sensor check_sensors = sensor.get_sensor_data() temp = sensor.data.temperature
from wia import Wia import serial import string import time import simplejson as json import os # Messaging Service configuration with secret token file wia = Wia() __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) token_file = open(os.path.join(__location__, 'token_file.json')) d = json.loads(token_file.read()) wia.access_token = d["token"] # Configuration of serial connexion to Arduino ser = serial.Serial(port='/dev/ttyUSB0', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1) ser.flushInput() # The actual serial work retreiveing data only once for both temperature and humidity data while True: # Previous Method to read and decode serial line, to be deleted when saved #ser_bytes = ser.readline() #decoded_bytes = str(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
import RPi.GPIO as GPIO import time from wia import Wia wia = Wia() wia.access_token = "d_sk_fm6TFc3vluFMTpA21MzJncs9" GPIO.setmode(GPIO.BOARD) # Variable to hold the input pin value pin_to_circuit = 7 def rc_time(pin_to_circuit): count = 0 # Output on the pin for GPIO.setup(pin_to_circuit, GPIO.OUT) GPIO.output(pin_to_circuit, GPIO.LOW) time.sleep(50.0) # Change the pin back to input GPIO.setup(pin_to_circuit, GPIO.IN) # while loop to count until the pin goes high while (GPIO.input(pin_to_circuit) == GPIO.LOW): count += 1 return count
from wia import Wia from subprocess import call import os import time ##While loop to continuously run program While(1): ##Take image using USB Camera call(["fswebcam", "--no-banner", "image.jpg"]) ##Wia Device information wia = Wia() wia.access_token = "" ##Publish Image to WIA wia.Event.publish(name = "image",file = open('/home/pi/image.jpg')) print("Image published") ##Deletes previous picture from RPI memory to conserve space path = '/home/pi' img_name = 'image.jpg' os.remove(path + '/' + img_name) ##Add delay between iterations of program taking and broadcasting pictures. time.sleep(2.5)
from sense_hat import SenseHat from wia import Wia import time import config import json import urllib2 WRITE_API_KEY = config.api_key baseURL = 'https://api.thingspeak.com/update?api_key=%s' % WRITE_API_KEY wia = Wia() wia.access_token = config.wia_token sense = SenseHat() sense.clear() #Define below colours to display on sensehat green = (0, 255, 0) orange = (255, 165, 0) red = (255, 0, 0) #writeData defined to send temp data to Thingspeak def writeData(temp): #Send data to Thingspeak in the query string conn = urllib2.urlopen(baseURL + '&field1=%s' % (temp)) print(conn.read()) #Connection closed conn.close()
#!/usr/bin/python ''' Setup: - sudo apt-get install bluez - sudo apt-get install python-bluez ''' from wia import Wia import bluetooth import time wia = Wia() wia.access_token = "" # Wia secret key. print ("Proximity Check") while True: print ("Checking " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())) nearby_devices = bluetooth.discover_devices() result = bluetooth.lookup_name("AA:BB:CC:DD:EE:FF", timeout=3) # Enter your device MAC address found in mobile settings. [Settings -> about (if on iphone)]. if (result != None): print ("Parent: Present") presence = 'Present' else: print ("Parent: Absent") presence = 'Absent'
def test_device_retrieve_unknown(self): wia = Wia() wia.access_token = os.environ['device_secret_key'] device = wia.Device.retrieve('dev_nonexisting') self.assertIsInstance(device, WiaError) wia.access_token = None
import time import datetime import os import sys from multiprocessing import Process from contextlib import contextmanager import urllib2 from wia import Wia from sense_hat import SenseHat # set up Wia wia = Wia() wia.access_token = "d_sk_yxhosMPKxwC9HIg2pZLxi4w3" # set up Thingspeak WRITE_API_KEY='ON0J9PUVWMEQZ9RH' baseURL='https://api.thingspeak.com/update?api_key=%s' % WRITE_API_KEY # instnsiate SenseHat object and apply settings sense = SenseHat() sense.set_rotation(270) sense.clear() red = (255,0,0) green = (0,255,0) # create database on DB server (Macbook Pro), if it does not already exist os.system("mysql -uroot -h192.168.0.45 --password='******' -e \"CREATE DATABASE IF NOT EXISTS doorOpenDB\"") os.system("mysql -uroot -h192.168.0.45 --password='******' -e \"CREATE TABLE IF NOT EXISTS doorOpenDB.OpenEvents (doorOpen TIMESTAMP)\"") # count arguments args = len(sys.argv)-1
#!/usr/bin/python from wia import Wia wia = Wia() wia.access_token ='d_sk_rRAIym38IJ1KiYJplo9AfueQ' wia.Event.publish(name='motion', data=1)
sensor.select_gas_heater_profile(0) # start_time and curr_time ensure that the # burn_in_time (in seconds) is kept track of. start_time = time.time() curr_time = time.time() burn_in_time = 60 burn_in_data = [] buzzer = Buzzer(13) wia = Wia() wia.access_token = "" #Access token GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # to use Raspberry Pi board pin numbers GPIO.setup(29, GPIO.OUT) # set up GPIO output channel GPIO.setup(31, GPIO.OUT) # set up GPIO output channel GPIO.output(31, False) GPIO.output(29, False) try: # Collect gas resistance burn-in values, then use the average # of the last 50 values to set the upper limit for calculating # gas_baseline. print('Collecting gas resistance burn-in data for 1 mins\n') while curr_time - start_time < burn_in_time: curr_time = time.time()
from twython import Twython import logging #Assigning colour variables to display on sensehat green = (0, 255, 0) red = (255,0,0) amber = (255,191,0) #Devie owners name names = ["Bernard", "Nicola"] #MAC address of bernard and nicola's device macs = ["10:f1:f2:0e:2f:88","4e:4e:fa:86:ab:c6"] #sense python object sense = SenseHat() #wia python object wia = Wia() #Access token needed to connect device with WIA wia.access_token = "d_sk_kNGmSQ57p1NADpytzmhZDN9t" #Access keys and tokens required to work for twitter interaction APP_KEY = 'omlJF10BHvUPukQyQglpry74K' APP_SECRET = 'k42Vu7OFsefCfBwons7TekafL0qTfTAjWiP8U6FsMt8tzrNkXv' OAUTH_TOKEN = '1079070521948540928-DGExLZrQpQVGjg6hVmNeRuSZKhABaX' OAUTH_TOKEN_SECRET = 'xOJYVZWhX04QobhaaopozUMGToNH0jNSyFijMtChfD3PG' #twitter python object twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) logging.basicConfig(filename='bernard_thompson_assignment.log',level=logging.INFO, format='%(asctime)s - %(message)s') logging.info('Variables assigned ready to begin while loop') #Running a while loop #While true gather the data from the sense hat every 60 seconds #This can then graph the weather data while ensuring #The most recent data is available
return acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0) y = round(y, 0) z = round(z, 0) init_val = [x, y, z] wia = Wia() wia.access_token = 'Wia_secret_key' #here I intended to work on a piece of code which activates sound via bluetooth... but due to lack of time related to my newborn I ended up suspending this idea :) timestamp = [0, 0, 0, 0] i = 0 while True: acceleration = sense.get_accelerometer_raw() x = acceleration['x'] y = acceleration['y'] z = acceleration['z'] x = round(x, 0) y = round(y, 0) z = round(z, 0) sens_val = [x, y, z] if (init_val[0] != sens_val[0] or init_val[1] != sens_val[1]