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_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_stream_commands(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": "test-run", "device.id": os.environ['device_id']}) wia.Stream.connect() count = 0 while count <= 10: time.sleep(0.5) count += 1 if wia.Stream.connected: break self.assertTrue(wia.Stream.connected) def test_run(self): wia.Stream.disconnect() count = 0 while count <= 10: time.sleep(0.5) count += 1 if not wia.Stream.connected: break wia.Stream.connected = False wia.access_token = None wia.Command.subscribe(**{"device": os.environ['device_id'], "slug": command.slug, "func": test_run}) time.sleep(2) json = {"slug": command.slug, 'device.id': os.environ['device_id']} headers = {'Authorization': 'Bearer ' + Wia().access_token} r = requests.post("https://api.wia.io/v1/commands/run", json=json, headers=headers) #wia.Command.run(**{"device": os.environ['device_id'], "slug": command.slug}) while wia.Stream.connected: time.sleep(0.5)
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 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_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_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_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_spaces_create_and_retrieve(self): wia = Wia() wia.access_token_create(username=os.environ['WIA_TEST_USERNAME'], password=os.environ['WIA_TEST_PASSWORD']) random_name = str(datetime.date.today()) + str(random.getrandbits(128)) space = wia.Space.create(name=random_name) self.assertTrue(space.name == random_name) space_retrieve = wia.Space.retrieve(space.id) self.assertTrue(space.name == space_retrieve.name)
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 generate_url(path): if path is None: path = '' url = Wia().rest_config['protocol'] + '://' + Wia( ).rest_config['host'] + '/' + Wia().rest_config['basePath'] + '/' + path logging.debug('URL: %s', url) return url
def generate_headers(path): headers = {} if Wia().app_key is not None: headers['x-app-key'] = Wia().app_key if Wia().access_token is not None: headers['Authorization'] = 'Bearer ' + Wia().access_token return headers
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_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_init_app_key_access_token(self): logging.info("Starting test_init_access_token") 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']) self.assertIsInstance(access_token, type(wia.AccessToken)) access_token = None logging.info("Finished test_init_app_key_access_token")
def test_init_app_key(self): logging.info("Starting test_init_access_token") app_key = os.environ['WIA_TEST_APP_KEY'] wia = Wia() wia.username = os.environ['WIA_TEST_USERNAME'] wia.password = os.environ['WIA_TEST_PASSWORD'] wia.app_key = app_key whoami = wia.WhoAmI.retrieve() self.assertIsInstance(whoami, type(wia.WhoAmI)) access_token = None logging.info("Finished test_init_app_token")
def test_init_app_key_access_token(self): logging.info("Starting test_init_access_token") 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']) self.assertIsInstance(access_token, type(wia.AccessToken)) access_token = None logging.info("Finished test_init_app_key_access_token")
def publish(cls, **kwargs): path = 'locations' if Wia().Stream.connected and Wia().client_id is not None: topic = 'devices/' + Wia().client_id + '/' + path Wia().Stream.publish(topic=topic, **kwargs) return cls() else: response = post(path, kwargs) if WiaResource.is_success(response): return cls(**response.json()) else: return WiaResource.error_response(response)
def run(cls, **kwargs): if Wia().Stream.connected and Wia().client_id is not None: command = 'devices/' + Wia().client_id + '/commands/' + ( kwargs['slug'] or kwargs['name']) + '/run' Wia().Stream.run(command=command) return cls() else: response = post('commands/run', kwargs) if WiaResource.is_success(response): return cls(**response.json()) else: return WiaResource.error_response(response)
def publish(cls, **kwargs): path = 'events' if not ('file' in kwargs) and Wia().Stream.connected and Wia( ).client_id is not None: topic = 'devices/' + Wia( ).client_id + '/' + path + '/' + kwargs['name'] Wia().Stream.publish(topic=topic, **kwargs) return cls() else: response = post(path, kwargs) if WiaResource.is_success(response): return cls(**WiaResource.json_converter(response)) else: return WiaResource.error_response(response)
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 connect(self, _async=True): self.__init__() self.client.username_pw_set(Wia().access_token, ' ') self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.client.on_unsubscribe = self.on_unsubscribe self.client.on_message = self.on_message self.client.connect(Wia().stream_config['host'], Wia().stream_config['port'], 60) if _async: self.client.loop_start() self.connected = True time.sleep(1)
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 unsubscribe(**kwargs): device = kwargs['device'] topic = 'devices/' + device + '/events/' if 'name' in kwargs: topic += kwargs['name'] else: topic += '+' Wia().Stream.unsubscribe(topic=topic)
def test_stream_commands(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": "test-run", "device.id": os.environ['device_id'] }) wia.Stream.connect() count = 0 while count <= 10: time.sleep(0.5) count += 1 if wia.Stream.connected: break self.assertTrue(wia.Stream.connected) def test_run(self): wia.Stream.disconnect() count = 0 while count <= 10: time.sleep(0.5) count += 1 if not wia.Stream.connected: break wia.Stream.connected = False wia.access_token = None wia.Command.subscribe( **{ "device": os.environ['device_id'], "slug": command.slug, "func": test_run }) time.sleep(2) json = {"slug": command.slug, 'device.id': os.environ['device_id']} headers = {'Authorization': 'Bearer ' + Wia().access_token} r = requests.post("https://api.wia.io/v1/commands/run", json=json, headers=headers) #wia.Command.run(**{"device": os.environ['device_id'], "slug": command.slug}) while wia.Stream.connected: time.sleep(0.5)
def test_spaces_devices_list_order_asc(self): wia = Wia() spaces = wia.Space.list() testSpace = spaces['spaces'][0] list_return_asc = wia.Device.list(**{ "space.id": testSpace.id, "order": "createdAt", "sort": "asc" }) self.assertTrue('devices' in list_return_asc) self.assertTrue(type(list_return_asc['devices']) == list) self.assertTrue('count' in list_return_asc)
def test_spaces_create_retrieve_update_list_delete_device(self): wia = Wia() spaces = wia.Space.list() testSpace = spaces['spaces'][0] testDevice = wia.Device.create(**{ "name": "testDevice", "space.id": testSpace.id }) self.assertIsInstance(testDevice, type(Wia().Device)) retrieveDevice = wia.Device.retrieve(testDevice.id) self.assertTrue(retrieveDevice.name == "testDevice") deviceUpdated = wia.Device.update(id=retrieveDevice.id, name="testDeviceUpdated") self.assertTrue(deviceUpdated.name == "testDeviceUpdated") list_return = wia.Device.list(**{"space.id": testSpace.id}) self.assertTrue('devices' in list_return) self.assertTrue(type(list_return['devices']) == list) self.assertTrue('count' in list_return) self.assertTrue(wia.Device.delete(deviceUpdated.id))
class Stream: def __init__(self): self.connected = False self.subscribed = None self.subscribed_count = 0 self.client = mqtt.Client() self.function_subscriptions = {} def connect(self, async=True): self.__init__() self.client.username_pw_set(Wia().access_token, ' ') self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_subscribe = self.on_subscribe self.client.on_unsubscribe = self.on_unsubscribe self.client.on_message = self.on_message self.client.connect(Wia().stream_config['host'], Wia().stream_config['port'], 60) if async: self.client.loop_start() self.connected = True time.sleep(1)
os.system('clear') 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]
sensor.set_gas_heater_duration(150) 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:
#!/usr/bin/env python # Publish Arduino connected DHT11 sensors data to wia.io through Rapsberry Pi # Author: Thomas Simon # Date: 20190819 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
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
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
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
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_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
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
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