Esempio n. 1
0
def turn_off_light():
    time.sleep(1)
    for light in all_the_lights:
        url_to_call = lights_url + light + '/state'
        body = '{ "on" : false }'
        rest.send('PUT', url_to_call, body,
                  {'Content-Type': 'application/json'})
Esempio n. 2
0
def arduinoInput(value):
    base_url = 'http://192.168.1.5:8083'
    username = '******'
    password = '******'

    all_devices = rest.send(url=base_url + '/ZWaveAPI/Data/0', auth=(username, password))

    all_devices = all_devices['devices']


    all_devices.pop('1')
    all_devices.pop('3')
    all_devices.pop('9')

    device_url = base_url + '/ZWaveAPI/Run/devices[{}].instances[{}].commandClasses[{}]'
    switch_binary = '37'

    for device_key in all_devices:

        for instance in all_devices[device_key]['instances']:

            if switch_binary in all_devices[device_key]['instances'][instance]['commandClasses']:
                if (int(value) == 1):
                  print('Turning on device %s...' % device_key)
                  url_to_call = (device_url + '.Set(255)').format(device_key, instance, switch_binary)
                  rest.send(url=url_to_call, auth=(username, password))
                else:
                 print('Turning off device %s...' % device_key)

                 url_to_call = (device_url + '.Set(0)').format(device_key, instance, switch_binary)
                 rest.send(url=url_to_call, auth=(username, password))

    return Response(status=200)
Esempio n. 3
0
def change_light_color(rgb):
    for light in all_the_lights:
        url_to_call = lights_url + light + '/state'
        body = '{"on":true, "transitiontime": 10,"xy":[%f, %f]}' % converter.rgb_to_xy(
            rgb[0], rgb[1], rgb[2])
        rest.send('PUT', url_to_call, body,
                  {'Content-Type': 'application/json'})
Esempio n. 4
0
def reading():

    # the base URL
    base_url = 'http://192.168.0.201'

    username = '******'

    # lights URL
    lights_url = base_url + '/api/' + username + '/lights/'

    # get the Hue lights
    all_the_lights = rest.send(url=lights_url)

    #set a specific color and turn on
    if type(all_the_lights) is dict:
        # iterate over the Hue lights, turn them on with the color loop effect
        light = '3'
        #for light in all_the_lights:
        url_to_call = lights_url + light + '/state'
        body = '{ "on" : true, "hue" : 12750 }'
        time.sleep(1)
        rest.send('PUT', url_to_call, body,
                  {'Content-Type': 'application/json'})
        global value
        value = 3
        check(value)
        return value

    else:
        print('Error:', all_the_lights[0]['error'])
Esempio n. 5
0
 def sendCommand(self, device_id, command, parameters = {}):
     '''
     Sends a command to the dog gateway wrapped by this client, also passing any given parameter
     '''
     #print 'sending: '+self.all_devices_url+'/'+device_id+'/commands/'+command
     rest.send('PUT', self.all_devices_url+'/'+device_id+'/commands/'+command, json.dumps(parameters), 
               {'Accept':'application/json', 'Content-Type':'application/json'})
Esempio n. 6
0
 def setHue(self, light_id, hue):
     #compose the specific light url
     url_to_call = self.lights_url+"/"+str(light_id)+"/state"
     #set the given hue value
     body = '{ "on" : true, "hue" : %d}'%hue
     #send the request
     rest.send('PUT', url_to_call, body, { 'Content-Type':'application/json' })
Esempio n. 7
0
def switchLed(x):
    url = ''
    if (x == 1):
        url = 'http://192.168.1.5/arduino/digital/13/1'
    else:
        url = 'http://192.168.1.5/arduino/digital/13/0'

    rest.send(url=url)
def start_station_by_IP(IP_address):
    message = {'state': True, 'msg': 'Starting loop'}
    rest.send('POST', IP_address + '/start',
              json.dumps(message, separators=(',', ':')),
              {'Content-Type': 'application/json'})

    # PROBLEMA: SE ASPETTO LA RESPONSE DALLA STAZIONE QUESTA FUNZIONE NON TERMINA FINCHE' LA STAZIONE NON SI FERMA
    '''
Esempio n. 9
0
 def setHue(self, light_id, hue):
     #compose the specific light url
     url_to_call = self.lights_url + "/" + str(light_id) + "/state"
     #set the given hue value
     body = '{ "on" : true, "hue" : %d}' % hue
     #send the request
     rest.send('PUT', url_to_call, body,
               {'Content-Type': 'application/json'})
Esempio n. 10
0
def handle(text, mic, profile):
    
    print "I'm recipes.py"
    apiKey='dvxSvo0rQ069QnGwoB7m67Y572Xl4sm3'
    mic.say("What do you want to cook?")
    nome=mic.activeListen()
    mic.say(nome)
    url="http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw=" + nome + "&api_key="+apiKey
    
    data = rest.send('GET', url, headers= {'Accept':'application/json'})
    
    
    
    for item in data['Results']:
        codice = item['RecipeID']
        
    
        print codice
        apiKey='dvxSvo0rQ069QnGwoB7m67Y572Xl4sm3'
        
        url="http://api.bigoven.com/recipe/" + str(codice) + "?api_key="+apiKey
        data = rest.send('GET', url, headers= {'Accept':'application/json'})
        l=data['Instructions']
        title=data['Title']
        
            
        if ((l.find('http://')) < 0):
    
            mic.say("The recipe for " + title)
            Ingredienti= data['Ingredients']
            
            frase = "You will need these ingredients:"
            mic.say(frase)   
            for item in Ingredienti:
                ingrediente = " "
                nome=item['Name']
                quantita=item['DisplayQuantity'] 
                print quantita
                if (quantita==None):
                    quantita = " "
                
                metric=item['MetricUnit']
                ingrediente += quantita
                ingrediente += metric
                ingrediente += nome
                print nome
                
                mic.say(ingrediente)
               
            mic.say("Now we can start the preparation.")
            l=l.replace("w/", " ")
            for line in l.split('\n'):
                print line
                mic.say(line)
            break  
    return
Esempio n. 11
0
    def sendCommand(self, device_id, command, parameters={}):

        #print 'sending: '+self.all_devices_url+'/'+device_id+'/commands/'+command
        rest.send(
            'PUT',
            self.all_devices_url + '/' + device_id + '/commands/' + command,
            str(parameters), {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            })
Esempio n. 12
0
def start_station_by_IP(IP_address):
    message = {
               'state' : True,
               'msg' : 'Starting loop'
               }
    rest.send( 'POST', IP_address + '/start', json.dumps(message, separators=(',',':')), {'Content-Type': 'application/json'} )
    
    
    # PROBLEMA: SE ASPETTO LA RESPONSE DALLA STAZIONE QUESTA FUNZIONE NON TERMINA FINCHE' LA STAZIONE NON SI FERMA
    
    '''
Esempio n. 13
0
 def sendCommand(self, device_id, command, parameters={}):
     '''
     Sends a command to the dog gateway wrapped by this client, also passing any given parameter
     '''
     #print 'sending: '+self.all_devices_url+'/'+device_id+'/commands/'+command
     rest.send(
         'PUT',
         self.all_devices_url + '/' + device_id + '/commands/' + command,
         json.dumps(parameters), {
             'Accept': 'application/json',
             'Content-Type': 'application/json'
         })
Esempio n. 14
0
 def turn_all_off(self):
     """
     Turn all the lights off
     """
     # get all lights
     all_lights = self.get_all_lights()
     for light in all_lights:
         url_to_call = self.lights_url + '/' + light + '/state'
         # prepare the "turn off" request
         body = '{ "on": false }'
         rest.send('PUT', url_to_call, body,
                   {'Content-Type': 'application/json'})
Esempio n. 15
0
def handle(text, mic, profile):

    print "I'm recipes.py"
    apiKey = 'dvxSvo0rQ069QnGwoB7m67Y572Xl4sm3'
    mic.say("What do you want to cook?")
    nome = mic.activeListen()
    mic.say(nome)
    url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw=" + nome + "&api_key=" + apiKey

    data = rest.send('GET', url, headers={'Accept': 'application/json'})

    for item in data['Results']:
        codice = item['RecipeID']

        print codice
        apiKey = 'dvxSvo0rQ069QnGwoB7m67Y572Xl4sm3'

        url = "http://api.bigoven.com/recipe/" + str(
            codice) + "?api_key=" + apiKey
        data = rest.send('GET', url, headers={'Accept': 'application/json'})
        l = data['Instructions']
        title = data['Title']

        if ((l.find('http://')) < 0):

            mic.say("The recipe for " + title)
            Ingredienti = data['Ingredients']

            frase = "You will need these ingredients:"
            mic.say(frase)
            for item in Ingredienti:
                ingrediente = " "
                nome = item['Name']
                quantita = item['DisplayQuantity']
                print quantita
                if (quantita == None):
                    quantita = " "

                metric = item['MetricUnit']
                ingrediente += quantita
                ingrediente += metric
                ingrediente += nome
                print nome

                mic.say(ingrediente)

            mic.say("Now we can start the preparation.")
            l = l.replace("w/", " ")
            for line in l.split('\n'):
                print line
                mic.say(line)
            break
    return
Esempio n. 16
0
 def set_hue(self, light_id, hue):
     """
     Change the hue value of a given light
     :param light_id: the id of the light to control
     :param hue: the hue value to set
     """
     # compose the specific light URL
     url_to_call = self.lights_url + '/' + str(light_id) + '/state'
     # set the given hue value
     body = '{{ "on" : true, "hue" : {} }}'.format(hue)
     # send the request
     rest.send('PUT', url_to_call, body,
               {'Content-Type': 'application/json'})
Esempio n. 17
0
 def getStatus(self, device_id):
     '''
         provides back the status of a given device
     '''
     #print 'Sending: '+self.all_devices_url+'/'+device_id+'/status'
     return rest.send(url=self.all_devices_url + '/' + device_id +
                      '/status')
Esempio n. 18
0
def initialize_server():
    global converter, lights_url, all_the_lights, \
           host, port, pi_host, pi_port
    # Read configurations
    config = configparser.ConfigParser()
    config.read('config.ini')

    # Initialize Hue Bridge information and RGB_to_XY converter
    if config['LIGHT BRIDGE']['converter'] == "GamutA":
        converter = Converter(GamutA)
    elif config['LIGHT BRIDGE']['converter'] == "GamutB":
        converter = Converter(GamutB)
    elif config['LIGHT BRIDGE']['converter'] == "GamutC":
        converter = Converter(GamutC)

    base_url = config['LIGHT BRIDGE']['base_url']
    username = config['LIGHT BRIDGE']['username']

    lights_url = base_url + '/api/' + username + '/lights/'
    all_the_lights = rest.send(url=lights_url)

    # Initialize Server information
    host = config['SERVER']['host']
    port = int(config['SERVER']['port'])

    # Initialize raspberry IP and PORT
    pi_host = config['SERVER']['pi_host']
    pi_port = int(config['SERVER']['pi_port'])
Esempio n. 19
0
 def change_light_state(self, light_id, state):
     """
     Turn a given lamp on or off
     :param light_id: the light to act on
     :param state: the "on" or "off" string
     """
     # compose the specific light URL
     url_to_call = self.lights_url + '/' + str(light_id) + '/state'
     # set the given on/off value
     if state == 'on':
         state = 'true'
     else:
         state = 'false'
     body = '{{ "on" : {} }}'.format(state)
     # send the request
     rest.send('PUT', url_to_call, body,
               {'Content-Type': 'application/json'})
Esempio n. 20
0
def isUserAtHome():
    # the base url
    base_url = 'http://192.168.0.202:8083'

    # login credentials
    username = '******'
    password = '******'

    # get z-wave devices
    all_devices = rest.send(url=base_url + '/ZWaveAPI/Data/0',
                            auth=(username, password))

    # clean up all_devices dictionary
    all_devices = all_devices['devices']
    # remove the Z-Way controller from the device list
    all_devices.pop('1')

    # "prototype" and base URL for getting/setting device properties
    device_url = base_url + '/ZWaveAPI/Run/devices[{}].instances[{}].commandClasses[{}]'

    # every device has an ID ==> dobbiamo trovare id del sensore di movimento dal sito
    # ogni sensore può avere diverse instances, ad esempio il 4 in 1 ne avra 4, sono le diverse cose che può fare
    # ogni istance ha una command class, che specifica le feature del device:

    # sensore di movimento
    motion_sensor_id = None  # id del nostro sensore
    sensor_binary = '48'  # (command class) per il movimento

    # search for devices to be "operated", in this case power outlets, temperature, and motion sensors
    for device_key in all_devices:
        # iterate over device instances
        for instance in all_devices[device_key]['instances']:
            # search for the SensorBinary (48) command class, e.g., for motion
            if sensor_binary in all_devices[device_key]['instances'][instance][
                    'commandClasses']:
                # debug
                print('Device %s is a sensor binary' % device_key)
                # get motion
                url_to_call = device_url.format(device_key, instance,
                                                sensor_binary)
                # info from devices is in the response
                response = rest.send(url=url_to_call,
                                     auth=(username, password))
                val = response['data']['1']['level']['value']
                print('Motion: ' + str(val))
                return val
Esempio n. 21
0
def light():


    # the base URL
    base_url = 'http://192.168.0.201'

    username = '******'

    # lights URL
    lights_url = base_url + '/api/' + username + '/lights/'

    # get the Hue lights
    all_the_lights = rest.send(url=lights_url)

    #flashing
    for alert in range(0, 2):
    #changing the colors
     colors = [0, 12750, 25500, 46920, 56100, 65280]
     for color in colors:
            if type(all_the_lights) is dict:
                    # iterate over the Hue lights, turn them on with the color loop effect
                    light = '10'
                    #for light in all_the_lights:
                    url_to_call = lights_url + light + '/state'
                    body = '{ "on" : true, "hue" : %s }' %color
                    print(color)
                    rest.send('PUT', url_to_call, body, {'Content-Type': 'application/json'})

                    # wait 2 seconds...
                    for i in range(0, 2):
                        time.sleep(1)
                        print(2-i)

                    # iterate over the Hue lights and turn them off
                    #for light in all_the_lights:
                    #url_to_call = lights_url + light + '/state'
                    body = '{ "on" : false }'
                    rest.send('PUT', url_to_call, body, {'Content-Type': 'application/json'})
                    time.sleep(2)
            else:
                print('Error:', all_the_lights[0]['error'])
Esempio n. 22
0
def get_value(all_devices, device_key, instance):
    """
    :param all_devices: the list of the devices of the system
    :param device_key: the device which we need to access information from
    :param instance: the particular instance of the device we are retrieving information from
    :return: all the values of the different classes the device support, joined inside a list
    """
    if all_devices[device_key]['instances'][instance] is not None:
        data = list()
        if comm_classes["sensor_multi"] in all_devices[device_key]['instances'][instance]['commandClasses']:
            url_to_update = update_url.format(device_key, comm_classes['sensor_multi'], instance)
            # print(device_key + "\t" + instance)
            rest.send(url=url_to_update, auth=(username, password))
            url_to_call = device_url.format(device_key, instance, comm_classes["sensor_multi"])
            response = rest.send(url=url_to_call, auth=(username, password))
            data.append(response['data']['3']['val']['value'])
        if comm_classes["sensor_binary"] in all_devices[device_key]['instances'][instance]['commandClasses']:
            url_to_update = update_url.format(device_key, comm_classes['sensor_binary'], instance)
            # print(device_key + "\t" + instance)
            rest.send(url=url_to_update, auth=(username, password))
            url_to_call = device_url.format(device_key, instance, comm_classes["sensor_binary"])
            response = rest.send(url=url_to_call, auth=(username, password))
            data.append(response['data']['1']['level']['value'])
    else:
        data = None
    # print(data)
    return data
Esempio n. 23
0
def set_devices(all_devices, value):
    """
    Turn the devices on or off
    :param all_devices: the list of devices (entire list) to be switched
    :param value: true for getting on, false for getting off
    :return:
    """
    for device_key in all_devices:
        if all_devices[device_key] is not None:
            instances = all_devices[device_key]['instances']
            if value:
                for instance in instances:
                    for command_class in all_devices[device_key]['instances'][instance]['commandClasses']:
                        # turn it on (255)
                        url_to_call = (device_url + '.Set(255)').format(device_key, instance, command_class)
                        rest.send(url=url_to_call, auth=(username, password))
            else:
                for instance in instances:
                    for command_class in all_devices[device_key]['instances'][instance]['commandClasses']:
                        # turn it off (0)
                        url_to_call = (device_url + '.Set(0)').format(device_key, instance, command_class)
                        rest.send(url=url_to_call, auth=(username, password))
Esempio n. 24
0
def control_music(command, url):
    
    # init json content for PUT requests
    data = '{ }'
    
    # check if I need to play or stop music...
    if command == 'PLAYPAUSE':
        # get the music server status
        status = rest.send(url = base_url + '/api/v1/player')
        
        if status['status'] == 'playing':
            url = url + 'stop'
        else:
            url = url + 'play'
            # read the playlist
            playlist = open('playlist.json')
            data = playlist.read()
    
    # execute the command
    rest.send('PUT', base_url + url, data, { 'Content-Type':'application/json' })
    
    # update the track metadata
    update_metadata()
Esempio n. 25
0
def update_metadata():
    # init
    artist = ""
    title = "No Music Found"
    album = ""
    
    # get current track metadata as string
    queue = rest.send(url = base_url + '/api/v1/player')
    if queue and queue['current']:
        artist = str(queue['current']['artist'])
        title = str(queue['current']['title'])
        album = str(queue['current']['album'])
    
    pebble.set_nowplaying_metadata(title, album, artist)
Esempio n. 26
0
def init(lat,lon,station_id,server_addr):
    message = { 'station_id': station_id, 'lat': lat, 'lon':lon }
    res = rest.send( 'POST', server_addr + '/newstation', json.dumps(message, separators=(',',':')), {'Content-Type': 'application/json'} )
    state = res['state']
    if( state == False ):
        sleep_time = res['sleep']
    else:
        sleep_time = False
    
    f = open("log.txt", "a")
    f.write(time.strftime("%c") + " - " + res['msg'] + "\n")
    f.close()

    return {'state':state,'sleep':sleep_time}
Esempio n. 27
0
def main():
    """
    main function to implement reasoning part
    :return:
    """
    triggered = False
    previous_intervent = False
    last_intervent = ''
    sensors = zway.connect()
    zway.set_devices(sensors, True)
    while True:
        time.sleep(10)
        sensor_lm = zway.get_values(sensors, light_motion_id)
        luminosity = sensor_lm.pop(0)
        motion = sensor_lm.pop(0)
        sensor_door = zway.get_values(sensors, door_id)
        drawer_opened = sensor_door.pop(0)
        triggered = motion or drawer_opened
        if triggered:
            global motion
            if motion:
                intervent ='motion'
            else:
                intervent = 'drawer'
            print(intervent + " detected " + time.asctime(time.localtime(time.time())))
            if not previous_intervent:
                # distract(intervent, luminosity)
            else:
                if intervent == last_intervent:
                    data = {'event' : intervent}
                    rest.send('POST', url=base_url + '/api/danger', data=data)
                else:
                    # distract(intervent, luminosity)
                last_intervent = intervent
        elif not triggered and previous_intervent:
            previous_intervent = False
Esempio n. 28
0
def connect():
    """
    The function initializes the connection to the z-wave controller
    and get the list of all devices connected to it
    :return: list of all devices connected to the controller, exluded the latter
    """

    # get z-wave devices
    all_devices = rest.send(url=base_url + '/ZWaveAPI/Data/0', auth=(username, password))
    # print(all_devices)

    # clean up all_devices and removing the controller
    all_devices = all_devices['devices']
    all_devices.pop('1')
    # print(all_devices)
    return all_devices
Esempio n. 29
0
def init(lat, lon, station_id, server_addr):
    message = {'station_id': station_id, 'lat': lat, 'lon': lon}
    res = rest.send('POST', server_addr + '/newstation',
                    json.dumps(message, separators=(',', ':')),
                    {'Content-Type': 'application/json'})
    state = res['state']
    if (state == False):
        sleep_time = res['sleep']
    else:
        sleep_time = False

    f = open("log.txt", "a")
    f.write(time.strftime("%c") + " - " + res['msg'] + "\n")
    f.close()

    return {'state': state, 'sleep': sleep_time}
Esempio n. 30
0
def fetch_zwavedata():
    sensors_data = {'temperature': -1, 'humidity': -1, 'light': -1}

    # get the ZWave Device (there should be only one)
    all_devices = rest.send(url=base_url + '/ZWaveAPI/Data/0')

    # get temperature
    temperature = all_devices['devices']['2']['instances']['0'][
        'commandClasses']['49']['data']['1']['val']['value']
    # get humidity
    humidity = all_devices['devices']['2']['instances']['0']['commandClasses'][
        '49']['data']['3']['val']['value']
    # get light
    light = all_devices['devices']['2']['instances']['0']['commandClasses'][
        '49']['data']['5']['val']['value']

    sensors_data['temperature'] = float(temperature)
    sensors_data['humidity'] = float(humidity)
    sensors_data['light'] = float(light)

    return sensors_data
Esempio n. 31
0
    def getAllDevices(self):

        return rest.send(url=self.all_devices_url,
                         headers={'Accept': 'application/json'})
Esempio n. 32
0
        state = init(lat,lon,station_id,server_addr)
    
    # getting data from the station for the first time
    # TODO: Set the time to 5 AM to 23 AM for station's startup
    old_data = sensors.fetch_data()
    
    while(True):        # too much power consuption with this instruction
                        # Solution: using a semaphore
        
        while( state ):
            # getting data from the sensors
            data = sensors.fetch_data()

            if( data!=old_data ): # check if something changed
                # sending data to the server
                res = rest.send('POST', server_addr + '/stations/'+station_id, json.dumps(data, separators=(',',':')), {'Content-Type': 'application/json'})

                state = res['state']
                if( state == False ):
                    sleep_time = res['sleep']
                else:
                    sleep_time = 0
                
                # writing on log.txt
                f = open("log.txt", "a")
                f.write(time.strftime("%c") + " - " + res['msg'] + "\n")
                f.close()
                
                old_data = data.copy()

        # TODO: Think a smart thing to do before sending another request
Esempio n. 33
0
 def getAllLights(self):
     '''
     Provides a dictionary of all available devices and capabilities
     '''
     return rest.send(url = self.lights_url, headers = {'Accept':'application/json'})
Esempio n. 34
0
 def get_all_lights(self):
     """
     Provide a dictionary of all available lamps and capabilities
     """
     return rest.send(url=self.lights_url)
Esempio n. 35
0
if __name__ == '__main__':

    # the base URL
    base_url = 'http://192.168.0.201'
    # if you are using the emulator, probably the base_url will be:
    # base_url = 'http://localhost:8000'

    # example username, generated by following https://www.developers.meethue.com/documentation/getting-started
    username = '******'
    # if you are using the emulator, the username is:
    # username = '******'

    # lights URL
    lights_url = base_url + '/api/' + username + '/lights/'

    # get the Hue lights
    all_the_lights = rest.send(url=lights_url)
    print(all_the_lights)

    #if (all_the_lights) is dict:
    light_id = input()
    url_to_call = lights_url + light_id + '/state'
    body = '{ "on" : true, "hue" : 0 }'
    # to set the red color
    # body = '{ "hue" : 0 }'
    # more colors: https://www.developers.meethue.com/documentation/core-concepts
    rest.send('PUT', url_to_call, body, {'Content-Type': 'application/json'})
    time.sleep(5)
    body = '{ "on" : false, "hue" : 0 }'
    rest.send('PUT', url_to_call, body, {'Content-Type': 'application/json'})
Created on Apr 10, 2014

@author: bonino
'''
import rest,time

if __name__ == '__main__':
    
    # the base url of the Dog gateway
    base_url = 'http://192.168.1.17:8080/api/v1/'
    
    #the url of all devices
    all_devices_url = base_url+'devices'
    
    #get the list of available devices in JSON format
    all_devices = rest.send(url = all_devices_url, headers = {'Accept':'application/json'})
    
    # iterate over all devices
    for device in all_devices:
        #debug
        #print device
        
        # iterate over all devices
        for i in range(0, len(all_devices[device])):
            #get the device class
            device_class =  all_devices[device][i]['class']
            #print the device class
            print device_class
            #get the device id
            device_id = all_devices[device][i]['id']
            #print the device id
Esempio n. 37
0
    def getStatus(self, device_id):

        #print 'Sending: '+self.all_devices_url+'/'+device_id+'/status'
        return rest.send(url=self.all_devices_url + '/' + device_id +
                         '/status')
Esempio n. 38
0
'''
import rest,time

if __name__ == '__main__':
    
    # the base url
    base_url = 'http://192.168.0.101'
    
    # the username
    username = '******'
    
    # lights URL
    lights_url = base_url+'/api/'+username+'/lights/'
    
    #get the hue lights
    all_the_lights =  rest.send(url = lights_url)
    
    # iterate over the hue lights, turn them on with the color loop effect
    for light in all_the_lights:
        url_to_call = lights_url+light+"/state"
        body = '{ "on" : true, "effect" : "colorloop" }'
        rest.send('PUT', url_to_call, body, { 'Content-Type':'application/json' })
    
    # wait 10 seconds...
    for i in range(0,10):    
        time.sleep(1)
        print 10-i
    
    # iterate over the hue lights and turn them off
    for light in all_the_lights:
        url_to_call = lights_url+light+"/state"
def main():
    
    # the serial port to attach to
    port = ""
    # the baudrate to use
    rate = 0
    # optional 
    device_service_endpoint = None
    device_id = None
    brightness = 125
    on = False
    
    # parse arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h:p:r:a:d:", ["help", "port=", "rate=", "address=", "device="])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
        
    # handle command-line options
    for o, a in opts:
        # handle help
        if o in ("-h", "--help"):
            
            # show usage
            usage()
            
            # exit with success code
            sys.exit(0)
            
        # handle configuration data
        elif o in ("-p", "--port"):
            
            # store the port value
           port = a
        
        elif o in ("-r", "--rate"):
            
           # store the rate
           rate = a
            
        elif o in ("-a", "--address"):
            
           # store the dog address
           device_service_endpoint = a;
        
        elif o in ("-d", "--device"):
            
           # store the dog device
           device_id = a;
            
         # handle not supported options
        else:
            assert False, "unhandled option"

    if((port != "") and (rate > 0)):
            
        # open the serial port
        ser = serial.Serial(port, rate)
        ser.setStopbits(1)
        ser.setByteSize(8)
        ser.setParity(serial.PARITY_NONE)
        
    
        # set the running flag at true
        can_run = True
        printed = False  
        message_bytes = []
        message_chars = []
        
        # sampling cycle
        while can_run:

            try:  
                       
                if(ser.inWaiting() > 0):    
                    # read a line from the serial port
                    byte = ser.read()
            
                    # debug / log print the read line
                    byte_value = byte.encode('hex')
                    if(byte_value == "55"):
                        # print the current message value
                        print("%s\n---------") % message_bytes
                        sys.stdout.flush()
                        
                        # interpret the data
                        action = decode_message(message_chars)
                        if (action == 0):
                            print "Button 1 OFF"
                            if((device_id != None) and (device_service_endpoint != None)):
                                device_url = ("%s%s") % (device_service_endpoint, device_id)
                                rest.send("POST", device_url, json.dumps({"commandName":"changeRGBColor", "params" : {"R": random.randint(0, 255), "G": random.randint(0, 255), "B": random.randint(0, 255)}}), {'Content-Type':'application/json'})
                            
                        elif(action == 1):
                            print "Button1 ON"
                            if((device_id != None) and (device_service_endpoint != None)):
                                device_url = ("%s%s") % (device_service_endpoint, device_id)
                                
                                if(not on):
                                    rest.send("POST", device_url, json.dumps({"commandName":"turnOn"}), {'Content-Type':'application/json'})
                                    on = True
                                else:    
                                    rest.send('POST', device_url, json.dumps({"commandName":"turnOff"}), {'Content-Type':'application/json'})
                                    on = False
                        elif (action == 2):
                            print "Button 2 OFF"
                            if((device_id != None) and (device_service_endpoint != None)):
                                device_url = ("%s%s") % (device_service_endpoint, device_id)
                                if(brightness >= 5):
                                    brightness = brightness - 5
                                print brightness
                                rest.send("POST", device_url, json.dumps({"commandName":"changeBrightness", "params" : {"brightness": brightness}}), {'Content-Type':'application/json'})
                        elif(action == 3):
                            print "Button 2 ON"
                            if((device_id != None) and (device_service_endpoint != None)):
                                device_url = ("%s%s") % (device_service_endpoint, device_id)
                                if(brightness <= 245):
                                    brightness = brightness + 5
                                print brightness
                                rest.send("POST", device_url, json.dumps({"commandName":"changeBrightness", "params" : {"brightness": brightness}}), {'Content-Type':'application/json'})
                                
                        # reset buffers
                        message_bytes = []
                        message_chars = []
                        
                    # append content to buffers    
                    message_bytes.append(byte_value);
                    message_chars.append(byte);
                    
                    
                else:
                    # sleep a bit                       
                    time.sleep(.1)
                        
                        
            except KeyboardInterrupt:
                can_run = False
            
                # debug
                print "stopped"
                sys.stdout.flush()
        
            except :
               pass
Esempio n. 40
0
import rest
import time

if __name__ == '__main__':

    # the base url
    base_url = 'http://192.168.0.202:8083'

    # login credentials, to be replaced with the right ones
    # N.B. authentication may be disabled from the configuration of the 'Z-Wave Network Access' app
    # from the website available at 'base_url'
    username = '******'
    password = '******'

    # get z-wave devices
    all_devices = rest.send(url=base_url + '/ZWaveAPI/Data/0',
                            auth=(username, password))
    # without auth, omit the last parameter
    # all_devices = rest.send(url=base_url + '/ZWaveAPI/Data/0')

    # clean up all_devices
    all_devices = all_devices['devices']
    # remove the Z-Way controller from the device list
    all_devices.pop('1')

    # "prototype" and base URL for getting/setting device properties
    device_url = base_url + '/ZWaveAPI/Run/devices[{}].instances[{}].commandClasses[{}]'

    # some useful command classes
    switch_binary = '37'
    sensor_binary = '48'
    sensor_multi = '49'
# Most of the code credits to Miguel Grinberg, except that I made a small tweak. Thanks!
# Credits: http://blog.miguelgrinberg.com/post/video-streaming-with-flask
#
# Usage:
# 1. Install Python dependencies: cv2, flask. (wish that pip install works like a charm)
# 2. Run "python main.py".
# 3. Navigate the browser to the local webpage.

from flask import Flask, render_template, Response
import rest
import json
import os

if __name__ == '__main__':

    server_url = 'http://127.0.0.1:8081'
    kod = 'aaaa'

    stream_url = server_url+'/get_ip'
    podaci = {"kod":kod}
    p = json.dumps(podaci)
    provera = rest.send('POST', stream_url, p, {'Content-Type': 'application/json'})
    print(provera)
    if 'status' in provera and provera['status'] == 'ok':
        ip = provera['ip']
        print(ip)
        os.system(r'"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" %s' % ip)
    else:
        print('neuspesno')

    #app.run(host='0.0.0.0', debug=True)
Esempio n. 42
0
 def getStatus(self,device_id):
     '''
         provides back the status of a given device
     '''
     #print 'Sending: '+self.all_devices_url+'/'+device_id+'/status'
     return rest.send(url = self.all_devices_url+'/'+device_id+'/status')
Esempio n. 43
0
lat = None
lon = None
station_id = None
server_addr = 'http://10.15.3.164:5000'
station_addr = 'http://10.15.3.164:8000'
'''
Main
'''
if __name__ == '__main__':

    # Opening/closing info.txt file
    f = open("info.txt", "r")
    raw_info = f.read()
    f.close()

    # Fetching data from raw_info
    info = raw_info.split()

    # Basic information about the station
    lat = info[0]
    lon = info[1]
    station_id = info[2]
    server_addr = info[3]

    # getting data from the sensors
    data = fetch_data()

    # sending data to the server
    res = rest.send('POST', server_addr + '/stations/' + station_id,
                    json.dumps(data, separators=(',', ':')),
                    {'Content-Type': 'application/json'})
Esempio n. 44
0
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
'''
import rest,time
        

if __name__ == '__main__':
            
    # the base url
    base_url = 'http://192.168.0.102:8083'

    
    #get the zwave devices
    all_devices =  rest.send(url = base_url+'/ZWaveAPI/Data/0')

    #search switches
    for device_key in all_devices['devices']:
        #iterate over device instances
        for instance in all_devices['devices'][device_key]['instances']:
            #search for the 37 (SwitchBinary) command class
            if ('37' in all_devices['devices'][device_key]['instances'][instance]['commandClasses'].keys()):
                #debug
                print "device %s is a switch"%device_key
                #turn it on
                url_to_call = base_url+"/ZWaveAPI/run/devices["+device_key+"].instances["+instance+"].commandClasses[37].Set(255)"
                rest.send(url = url_to_call)
    
    #reverse count to off           
    for i in range(0,10):