示例#1
0
def cmd_communicate_hue_server(msg, ressource, bri):  # pragma: no cover
    pseudo = get_username(msg)
    current_user = User.query.filter_by(username=pseudo).one()
    if "hue_username" in current_user.settings:
        Bridge(HUE_BRIDGE, current_user.settings.hue_username)
    else:
        reply_to_user(
            msg,
            "Pour utiliser les commandes HUE, vous devez faire « hue init »")
示例#2
0
def main():
    global running
    signal.signal(signal.SIGTERM, _handle_signal)
    signal.signal(signal.SIGINT, _handle_signal)

    if not path.exists(CRED_FILE_PATH):
        while True:
            try:
                username = create_new_username(BRIDGE_IP)
                break
            except QhueException as err:
                print "Error occurred while creating a new username: {}".format(
                    err)

        # store the username in a credential file
        with open(CRED_FILE_PATH, "w") as cred_file:
            cred_file.write(username)

    else:
        with open(CRED_FILE_PATH, "r") as cred_file:
            username = cred_file.read()

    b = Bridge(BRIDGE_IP, username)
    wonderwareOnline = WonderwareOnline('https://online.wonderware.com')

    header = ''

    with open(WWO_AUTH_HEADER, "r") as cred_file:
        header = cred_file.read()

    while running:
        startCollectingStates = datetime.datetime.now()
        lights = b.lights

        csv = WonderwareOnlineCSV()

        print 'Lights'
        for light in lights():
            for stateItem in lights[light]()['state']:
                if stateItem == 'xy':
                    continue
                csv.add_value(light + '.' + stateItem,
                              lights[light]()['state'][stateItem])

            print csv.build()

            wonderwareOnline.send_csv(header, csv.build())
            if (running == False):
                break

        endCollectingStates = datetime.datetime.now()
        waitTimeInMilli = (60000000 -
                           (endCollectingStates -
                            startCollectingStates).microseconds) / 1000000.0
        print 'waiting '
        print waitTimeInMilli
        time.sleep(waitTimeInMilli)
 def authenticate(self):
     # Data.Save("hue_username", None)
     if not self.username:
         try:
             self.username = create_new_username(self.hub_ip)
         except:
             pass
         Data.Save("hue_username", self.username)
     self.bridge = Bridge(self.hub_ip, self.username)
示例#4
0
    def on_after_startup(self):
        self._logger.info("Octohue is alive!")
        if self._settings.get(["statusDict"]) == '':
            self._logger.info("Bootstrapping Octohue Status Defaults")
            self._settings.set(
                ["statusDict"], {
                    'Connected': {
                        'colour': '#FFFFFF',
                        'ct': 155,
                        'brightness': 255,
                        'turnoff': False
                    },
                    'Disconnected': {
                        'colour': '',
                        'ct': 155,
                        'brightness': "",
                        'turnoff': True
                    },
                    'PrintStarted': {
                        'colour': '#FFFFFF',
                        'ct': 155,
                        'brightness': 255,
                        'turnoff': False
                    },
                    'PrintResumed': {
                        'colour': '#FFFFFF',
                        'ct': 155,
                        'brightness': 255,
                        'turnoff': False
                    },
                    'PrintDone': {
                        'colour': '#33FF36',
                        'ct': 155,
                        'brightness': 255,
                        'turnoff': False
                    },
                    'PrintFailed': {
                        'colour': '#FF0000',
                        'ct': 155,
                        'brightness': 255,
                        'turnoff': False
                    }
                })
            self._settings.save()

        self._logger.debug(
            "Bridge Address is %s" %
            self._settings.get(['bridgeaddr']) if self._settings.
            get(['bridgeaddr']) else "Please set Bridge Address in settings")
        self._logger.debug(
            "Hue Username is %s" %
            self._settings.get(['husername']) if self._settings.
            get(['husername']) else "Please set Hue Username in settings")
        self.pbridge = Bridge(self._settings.get(['bridgeaddr']),
                              self._settings.get(['husername']))
        self._logger.debug("Bridge established at: %s" % self.pbridge.url)
示例#5
0
    def __config(self):
        config = ConfigServiceImpl()
        ip = config.getOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.IP_OPTION)
        username = config.getOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.USERNAME_OPTION)

        if(username is None):
            username = self.getUsername(ip)
            config.setOption(ConfigServiceImpl.HUE_SECTION, ConfigServiceImpl.USERNAME_OPTION, username)

        self.bridge = Bridge(ip, username)
示例#6
0
 def __init__(self, bridge_info=None, ttime=None):
     """Initialize a transmitter, but don't start it yet."""
     if bridge_info is None:
         self.bridge, _ = quickstart.quickstart()
     else:
         self.bridge = Bridge(*bridge_info)
     self.lamps = get_lamps(self.bridge)
     if ttime is not None:
         for lamp in self.lamps:
             lamp.ttime = ttime
示例#7
0
 def __init__(self, name, timer, config, logger):
     self.name = name
     self.config = config
     self.logger = logger
     self.mode = HueClass.MOTION
     self.timer = timer
     self.lightState = False
     self.initConfig()
     self.b = Bridge(self.ip, self.user)
     self.logger.info('Init Hue OK')
示例#8
0
 def on_settings_save(self, data):
     octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
     self._logger.debug(
         "Saved Bridge Address: %s" %
         self._settings.get(['bridgeaddr']) if self._settings.
         get(['bridgeaddr']) else "Please set Bridge Address in settings")
     self._logger.debug(
         "Saved Hue Username: %s" %
         self._settings.get(['husername']) if self._settings.
         get(['husername']) else "Please set Hue Username in settings")
     self.pbridge = Bridge(self._settings.get(['bridgeaddr']),
                           self._settings.get(['husername']))
     self._logger.debug("New Bridge established at: %s" % self.pbridge.url)
def main():
    # https://developers.google.com/calendar/quickstart/python
    # Initialize Calendar API
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    # https://developers.meethue.com/develop/hue-api/lights-api/
    # https://github.com/quentinsf/qhue
    # Initialize Philips Hue Bridge
    bridge = Bridge(BRIDGE_IP, BRIDGE_USERNAME)
    lights = bridge.lights

    now_time = datetime.datetime.now().time()

    if now_time < WORK_DAY_END:
        TurnOnLights(lights)

    while now_time < WORK_DAY_END:
        now_time = datetime.datetime.now().time()

        # Identify if there is a GVC coming up or not
        event_type = GetCalendarEvents(service)

        if event_type == 'GVC':
            SetGVCColor(lights)

        elif event_type == 'Ambient':
            SetAmbientColor(lights)

        if LOGGING:
            print(
                'Sleeping for {} seconds \n'.format(LIGHT_CHANGE_INTERVAL_SEC))
        time.sleep(LIGHT_CHANGE_INTERVAL_SEC)

    print('You are done working, now go play!')
    TurnOffLights(lights)
示例#10
0
    def init(self):
        self.host = self.config(BRIDGE_HOST_CONFIG)
        self.username = self.config(BRIDGE_USERNAME_CONFIG)

        if not self.host:
            raise StopAndTalkException(
                "Bridge host not configured. Usage: !config " +
                BRIDGE_HOST_CONFIG + " <host> (e.g. 192.168.1.x, ...)")
        if not self.username:
            raise StopAndTalkException(
                "Username not configured. Usage: !config " +
                BRIDGE_USERNAME_CONFIG + " <username>")

        self.bridge = Bridge(self.host, self.username)
class HueUtil:
    ipAddress = "d780c907.ngrok.io"
    userId = "IbUDZzSJqJwaMEuH3hQzXoZKPzqsy3Qvus2Io8Vr"
    lightId = 2
    b = Bridge(ipAddress, userId)

    def hex(self, hexStr):
        red = int(hexStr[1:3], 16)
        green = int(hexStr[3:5], 16)
        blue = int(hexStr[5:], 16)

        converter = Converter(GamutC)
        xy = converter.rgb_to_xy(red, green, blue)
        print(xy)
        self.b.lights(self.lightId, 'state', xy=xy)
示例#12
0
def __create_bridge_conn(authfile, bridgeIP):
    if path.exists(authfile):
        with open(authfile, "r") as cred_file:
            username = cred_file.read()
    else:
        print("Authfile does not exist! Creating new one...")
        try:
            username = create_new_username(bridgeIP)
        except QhueException as err:
            print(f"Error occurred while creating a new username: {format(err)}")
        # store the username in a credential file
        with open(authfile, "w") as cred_file:
            cred_file.write(username)

    return Bridge(bridgeIP, username)
示例#13
0
    def __init__(self, args, verbose=False):

        self.verbose = verbose

        self.bridgeIP = args.get('bridgeIP')
        self.username = args.get('username')

        try:
            from qhue import Bridge

        except ImportError:
            exit("For using PhilipsHue is necessary to import it's bibliotec\n\
            Please install it with: sudo pip install qhue")

        self.bridge = Bridge(self.bridgeIP, self.username)
        self.lights = self.bridge.lights
示例#14
0
 def __init__(self):
     try:
         with open('.hueusername') as f:
             bridge_data = json.loads(f.read())
     except:
         logger.warn("Bridge not authorised, need to press the button!")
         bridge_data = json.loads(
             requests.get('https://www.meethue.com/api/nupnp').text)[0]
         bridge_data['username'] = create_new_username(
             bridge_data['internalipaddress'])
         with open('.hueusername', 'w') as f:
             f.write(json.dumps(bridge_data))
     self.bridge = Bridge(bridge_data['internalipaddress'],
                          bridge_data['username'])
     logger.info("Successfully connected to Hue Bridge {}".format(
         bridge_data['internalipaddress']))
示例#15
0
 def __init__(self, verbose, fullscreen, transition, interval, ignore_white,
              ignore_black):
     self.config = Config()
     # Get config from config.yaml
     self.config_obj = self.config.get_config()
     self.ip = self.config_obj['bridge']['ip']
     self.user = self.config_obj['bridge']['user']
     self.lights_list = self.config_obj['lights']
     # Use CLI args
     self.verbose = verbose
     self.fullscreen = fullscreen
     self.transition = transition
     self.interval = interval
     self.ignore_white = ignore_white
     self.ignore_black = ignore_black
     # Instantiate qHue Bridge
     self.bridge = Bridge(self.ip, self.user)
示例#16
0
    def __init__(self, bridge_ip=None, user_key=None):

        """ First check to ensure a bridge IP address has been supplied """
        if bridge_ip is None:
            print("Please Supply Bridge IP Address")
            exit()
        else:
            self._bridge_ip = bridge_ip

        """ If a user has not been created, create one """
        if user_key is None:
            self._user_key = create_new_username(bridge_ip)
            print("New user: {} .".format(self._user_key))
        else:
            self._user_key = user_key

        self.bridge = Bridge(self._bridge_ip, self._user_key)
        self.bridge_url = self._bridge_ip + '/api/' + user_key + '/groups/1/action'
示例#17
0
def main():
    temp = None
    if len(argv) == 2:
        temp = int(argv[1])
    else:
        temp = weather.WeatherCom().temperature()

    # check for a credential file
    if not path.exists(CRED_FILE_PATH):

        while True:
            try:
                username = create_new_username(BRIDGE_IP)
                break
            except QhueException as err:
                print(
                    "Error occurred while creating a new username: {}".format(
                        err))

        # store the username in a credential file
        with open(CRED_FILE_PATH, "w") as cred_file:
            cred_file.write(username)

    else:
        with open(CRED_FILE_PATH, "r") as cred_file:
            username = cred_file.read()

    # create the bridge resource, passing the captured username
    bridge = Bridge(BRIDGE_IP, username)

    # create a lights resource
    lights = bridge.lights

    if temp < 30:
        lights[1].state(bri=100, hue=46920)
        #print "Less than 30"
    elif temp <= 70:
        lights[1].state(bri=100, hue=56100)
        #print "Greater than or eq to 30 and <=70"
    elif temp <= 120:
        lights[1].state(bri=100, hue=65280)
        #print "LT or EQ 120"
    else:
        print("Error: Temperature out of Range")
def hue_basic():
    # Connect to the bridge with a particular username
    xy = Color_Extraction_Main.get_artwork_colors()
    print(xy[1])

    from qhue import Bridge
    bridge_obj = Bridge('192.168.0.24',
                        'COB9plogkaqukYuCoOvaO8hkI-ukMgzdL0BQp4MD')

    lights = bridge_obj.lights  # Creates a new Resource with its own URL

    #    for i in range(1, 7):
    #        print('iteration')
    #        print(i)
    #        print(bridge_obj('lights', i))

    bridge_obj.lights[5].state(on=True, bri=175, xy=xy[0])
    bridge_obj.lights[6].state(on=True, bri=175, xy=xy[1])
    bridge_obj.lights[4].state(on=True, bri=175, xy=xy[0])
示例#19
0
def init_config():
    IP = str(input("Please enter your hue bridge IP address: "))
    if IP == "":
        print(
            'Visit https://huetips.com/help/how-to-find-my-bridge-ip-address/ to know how to get your bridge IP address'
        )
        sleep(300)

    username = create_new_username(IP)
    config = {
        'IP': IP,
        'username': username,
        "loops_per_sec": 2.0,
        "m_sat": 185,
        "r_sat": 70,
        "m_bri": 70,
        "r_bri": 50,
        "divider": 5,
        "crop": 1,
        "bezel": 1
    }

    b = Bridge(config['IP'], config['username'])
    print('Please enter the number beside the lamp that you want to use :')
    for lamp in b.lights():
        print(lamp, b.lights()[lamp]['name'])
    print()
    chosen_light = input()
    if chosen_light == "":
        print()
        print()
        print(
            "------- Please enter a number correspond to the desired bulb : -------"
        )
        print()
        chosen_light = input()
        print()
        print()

    config['chosen_light'] = int(chosen_light)

    with open(directory + 'config.json', 'w') as fp:
        json.dump(config, fp)
示例#20
0
def restore_last_known_state_involved_in_scene(scene_name):
    """ Restore the last known state of lights involved in scene 'scene_name'"""
    # Check if the last state has been saved
    try:
        with open(last_known_state_file) as f:
            last_known_state = json.load(f)
    except:
        print("Unknown last state")
        return False

    #Let's restore as it was before the playback
    b = Bridge(bridge_ip, bridge_username)
    for light_id, light in last_known_state.items():
        if light['on'] == True:
            b.lights[light_id].state(on=True, bri=light['bri'], ct=light['ct'])
        else:
            b.lights[light_id].state(on=False)

    return True
示例#21
0
def lightingOn():
	client = MongoClient('mongodb://ec2-52-89-213-104.us-west-2.compute.amazonaws.com:27017/')
	client.Alfr3d_DB.authenticate(db_user,db_pass)
	db = client['Alfr3d_DB']
	devicesCollection = db['devices']

	logger.info("looking for devices")
	for device in devicesCollection.find({"$and":[
											{"type":'lights'},
											{"location.name":socket.gethostname()}
										]}):
		logger.info("device found: "+ str(device))

		if device['name'].startswith("hue"):
			logger.info("looking for apikeys")
			username = config.get("HUE dev", str(device['MAC']).replace(':',''))
			logger.info("found key: "+ str(username))

			bridge = Bridge(device['IP'], username)
			
			logger.info(str(bridge.lights()))
			lights_data = json.loads(json.dumps(bridge.lights()))

			for light in lights_data:
				hue = light_hue()
				hue.number=light
				hue.ip = device['IP']
				hue.username = username

				logger.info("all lights on")
				hue.hue_on()

		elif device['name'].startswith("Lifx"):
			bulb_label = device['name']
			logger.info("looking for apikeys")
			lifx_token = config.get("Lifx", "token")
			logger.info("found key: "+ str(lifx_token))

			headers = {"Authorization": "Bearer %s" % lifx_token,}
			response = requests.put('https://api.lifx.com/v1/lights/label:'+bulb_label+'/state', data={"power": "on"}, headers=headers)
			if response.json()[u'results'][0][u'status'] != u'ok':
				logger.error("failed to turn off the bulb "+str(bulb_label))
示例#22
0
    def get_bridge(self):
        if not os.path.exists(CRED_FILE_PATH):
            while True:
                try:
                    username = create_new_username(BRIDGE_IP)
                    break
                except QhueException as err:
                    print("Error occurred while creating new user: {}".format(
                        err))
                    return

            with open(CRED_FILE_PATH, "w") as cred_file:
                cred_file.write(username)

        else:
            with open(CRED_FILE_PATH, "r") as cred_file:
                username = cred_file.read()

        bridge = Bridge(BRIDGE_IP, username)
        return bridge
示例#23
0
    def bridge_connect(self):
        """
        Connects to the Hue Bridge
        """

        access_token, ip = fetch_phillips_active_bridge(self.conn)

        if access_token and ip is not None:
            try:
                b = Bridge(ip, access_token)
                return b
            except:
                raise
        else:
            self.log.error(f"[ERROR]: Error connecting to Phillips Bridge")
            try:
                self.scan_for_bridge()
                return
            except:
                raise
示例#24
0
def activate_scene(scene_name):
    """ Activate a specific scene if the lights are already on """
    b = Bridge(bridge_ip, bridge_username)
    scenes = b.scenes()
    for scene_id, scene in scenes.items():
        if scene['name'] == scene_name:
            # Variable to store the current light state
            current_lightstates = {}

            status = b.scenes[scene_id](http_method='get')
            lightstates = status['lightstates']
            # Check the current status of the lights
            # If every lights involved in this scene
            # are already off, don't change anything
            # It might means it is the day
            everything_is_off = True
            for light_id, light in lightstates.items():
                light_status = b.lights[light_id](http_method='get')

                # Save the status of this light buble
                current_lightstates[light_id] = light_status['state']

                if light_status['state']['on'] == True:
                    everything_is_off = False

            if everything_is_off:
                # Save the current state (with everything off)
                save_current_state(current_lightstates)
                return False

            for light_id, light in lightstates.items():
                if light['on'] == True:
                    b.lights[light_id].state(on=True,
                                             bri=light['bri'],
                                             ct=light['ct'])
                else:
                    b.lights[light_id].state(on=False)

    # Let's save the current state of the lights involved in this scene
    save_current_state(current_lightstates)
    return True
示例#25
0
 def process(self, inport, msg):
     hueUser = "******"
     bridge = Bridge("10.0.0.159", hueUser)
     converter = Converter()
     # Convert farbgeber to Hue xy
     v1xy = converter.rgb_to_xy(msg.data['v1'][0], msg.data['v1'][1],
                                msg.data['v1'][2])
     cxy = converter.rgb_to_xy(msg.data['c'][0], msg.data['c'][1],
                               msg.data['c'][2])
     contrasted = True
     # Send to all lights. First light found gets contrast color
     for lightId in bridge.lights():
         if contrasted:
             bridge.lights[lightId].state(xy=v1xy)
             contrasted = False
         else:
             contrasted = True
             bridge.lights[lightId].state(xy=cxy)
     # Send light status out
     self.send('out', bridge.lights())
     self.ack(msg)
示例#26
0
def hue_basic(hue_count):
    # Connect to the bridge with a particular username
    from qhue import Bridge
    b = Bridge('192.168.0.24', 'COB9plogkaqukYuCoOvaO8hkI-ukMgzdL0BQp4MD')

    # This should give you something familiar from the API docs:
    print(b.url)

    lights = b.lights  # Creates a new Resource with its own URL
    print(lights.url)  # Should have '/lights' on the end

    # Get the bridge's configuration info as a dict,
    # and print the ethernet MAC address
    #print(b.config()['mac'])

    # Get information about light 1
    for i in range(5, 5):
        print(b('lights', i))

    #Attributes:
    # bri max = 254
    # sat max = 254
    # hue range = 0 to 65535
    #for j in range(1, 5):
    #    b.lights[j].state(on = True, bri=254, hue=10000)

    switch = 0

    while switch == 0:
        for j in range(1, 6):
            b.lights[j].state(on=True, bri=254, sat=254, hue=hue_count)


#            b.lights[j].state(on = True, bri=254, xy = get_artwork_colors())
        time.sleep(100)

    while switch == 1:
        for j in range(1, 6):
            b.lights[j].state(on=True, bri=254, sat=254, hue=hue_count)
        time.sleep(100)
示例#27
0
def main():

    # check for a credential file
    if not path.exists(CRED_FILE_PATH):

        print('Please enter the IP adress of the bridge')
        regex = re.compile(IP_REG, flags=re.IGNORECASE)
        BRIDGE_IP = input('> ')

        while not regex.match(BRIDGE_IP):
            print('You did not enter a valid IP adress, please try again')
            BRIDGE_IP = input('> ')

        while True:
            try:
                username = create_new_username(BRIDGE_IP)
                break
            except QhueException as err:
                print("Error occurred while creating a new username: {}".format(err))

        # store the username in a credential file
        with open(CRED_FILE_PATH, "w") as cred_file:
            cred_file.write(username+'\n')
            cred_file.write(BRIDGE_IP)

    else:
        with open(CRED_FILE_PATH, "r") as cred_file:
            lines = cred_file.read().split('\n')
            username = lines[0]
            BRIDGE_IP = lines[1]

    # create the bridge resource, passing the captured username
    bridge = Bridge(BRIDGE_IP, username)

    # create a lights resource
    light = bridge.lights
    scheduler(light)
import configparser

from qhue import Bridge

config = configparser.ConfigParser()
config.read('config.txt')
hue = Bridge(config.get('hue', 'bridge_ip'), config.get('hue', 'user_token'))


def lights_on():
    if hue.lights[1]()['state']['on']:
        # Lights are already on
        return False
    else:
        hue.groups[1].action(on=True)
        return True


def lights_off():
    if not hue.lights[1]()['state']['on']:
        # Lights are already off
        return False
    else:
        hue.groups[1].action(on=False)
        return True
示例#29
0
import requests
import threading
import json
import time
from qhue import Bridge

b = Bridge("bride_ip_address_here", "hashed_valid_username_here").lights
url = 'https://api.coinmarketcap.com/v2/ticker/'
lampe = 8  # light id number
varia = 5
loopTime = 300
CMCid = 1975  #This ID is for Chainlink, put 1 if you want Bitcoin


def daemonizer(fName):
    try:
        daemon = threading.Thread(target=fName)
        daemon.daemon = True
        daemon.start()
    except Exception as e:
        pass


def getCoins(id):
    try:
        coins = requests.get(url + str(id)).json()
        with open('./coins.json', 'w') as fp:
            json.dump(coins, fp)
        return coins
    except Exception as e:
        time.sleep(60)
示例#30
0
#hue_queue = deque(hue_order)
#hue_queue.rotate(3)


def setlight(lightid='14', on=True, hue=200, bri=128):
    bridge.lights[lightid].state(on=on)
    if on:
        bridge.lights[lightid].state(bri=bri, hue=hue)


if username is None:
    username = create_new_username(BRIDGE_IP)
    print("New user: {} . Put this in the username variable above.".format(
        username))

bridge = Bridge(BRIDGE_IP, username)
lights = bridge.lights()
for num, info in lights.items():
    print("{:16} {}".format(info['name'], num))

v = random.randint(0, 255)


def work_lights():
    for light in hue_order:
        lightid = str(light)
        bridge.lights[lightid].state(on=True)

        bridge.lights[lightid].state(effect="none")
        bridge.lights[lightid].state(sat=15)
        bridge.lights[lightid].state(ct=315)