Beispiel #1
0
 def __init__(self, IP):
     self.IP = IP
     self.bridge = Bridge(self.IP)
     self.connect = self.bridge.connect()
     self.lights = self.bridge.get_light_objects('name')
     self.colors = {}
Beispiel #2
0
        return "2000"


# Main Code
if len(sys.argv) == 1:
    quit("Call as: " + sys.argv[0] +
         " <scenename|color temp> [transition time in minues]")

if len(sys.argv) > 2:
    xyTransitionTime = briTransitionTime = int(sys.argv[2]) * 600
else:
    xyTransitionTime = briTransitionTime = 4  # This is the hue default (0.4 seconds)

with open('/root/hue/bridgeip.txt', 'r') as f:
    bridgeIP = f.readline().strip()
b = Bridge(bridgeIP)

target = sys.argv[1]
if target == 'calculate':
    target = colortemp()

if target.isdigit():
    tempk = int(target)
    tempm = int(1000000 / tempk)

    for i in range(0, len(names)):
        if not b.get_light(
                names[i],
                'on'):  # Change the color immediately if the light was off
            xyTransitionTime = 0
            b.set_light(names[i], 'on', True)
#!/usr/bin/python
from phue import Bridge
import random

b = Bridge("192.168.10.196")  # Enter bridge IP here.

#If running for the first time, press button on bridge and run with b.connect() uncommented
#b.connect()

lights = b.get_light_objects()

for light in lights:
    light.brightness = 254
    light.xy = [random.random(), random.random()]
Beispiel #4
0
from flask import Flask
from phue import Bridge
import random
import socket
import requests

app = Flask(__name__)
bridge = Bridge('192.168.86.110')
bridge.connect()
#print(bridge.get_api())


@app.route('/')
def index():
    return 'Hello world'


@app.route('/counter-lights-off', methods=['GET', 'POST'])
def turn_coutner_ligths_off():
    print('Turning the counter lights off')
    led_setting = {"red": 0, "green": 0, "blue": 0}
    r = requests.post("http://192.168.86.130", json=dict(led_setting))
    return 'Turned the counter lights off'


@app.route('/counter-lights-on', methods=['GET', 'POST'])
def turn_counter_lights_on():
    print('Turning the counter lights on')
    led_setting = {"red": 255, "green": 180, "blue": 40}
    r = requests.post("http://192.168.86.130", json=dict(led_setting))
    return 'Turned the counter lights on'
Beispiel #5
0
"""
A better candle scene
"""

import numpy as np
from phue import Bridge
from math import ceil

b = Bridge('192.168.1.64')  # your bridge IP here
b.connect()

lr_lamp = [1, 4]
b.set_light(lr_lamp, 'on', True)
b.set_light(lr_lamp, 'ct', 380, transitiontime=0)  # set color temp.

m = 2  # brightness multiplier

while True:

    pchance = np.random.uniform(0, 1)

    if pchance <= 0.001:  # one percent chance of gusty breeze
        n = 0
        n_flickers = np.random.randint(2, 6)

        while n < n_flickers:  # simulate disturbed air around a candle
            t0 = np.random.randint(0.5, 2)
            t1 = np.random.randint(0.5, 2)
            bri_val_f0 = np.random.randint(60, 110)
            bri_val_f1 = np.random.randint(60, 120)
Beispiel #6
0
#!/usr/bin/python
#-*- coding:Utf-8 -*-
import sys  #,getopt
#import re
from phue import Bridge
import json
import ast

b = Bridge(sys.argv[2])
lang = sys.argv[1]
TOSAY = ""

lbl = {
    'fr': {
        'on': 'allumé',
        'off': 'éteinte',
        'lamp': 'lumière',
        'unknow': 'inconnue',
        'error': 'erreur',
        'command': 'commande',
    },
    'en': {
        'on': 'on',
        'off': 'off',
        'lamp': 'lamp',
        'unknow': 'unknow',
        'error': 'error',
        'command': 'command',
    }
}
'''from socket import *
import sys
import json
import unicodedata
s = socket(AF_INET, SOCK_DGRAM)
host = "192.168.100.181"
port = 5000
buf = 1024
data= b"Hello"
addr = (host, port)
num = 1'''
#end
lightnumber = 4
#light control code
from phue import Bridge
b = Bridge(ip='192.168.100.103')
b.connect()
b.get_api()
#lights = b.lights
lights = b.get_light_objects('id')
if (lights[lightnumber].on == False):
    lights[lightnumber].on = True
    lights[lightnumber].brightness = 220
    lights[lightnumber].saturation = 200
else:
    lights[lightnumber].brightness = 220
    lights[lightnumber].saturation = 200

#lights[lightnumber].hue = 0
#end
Beispiel #8
0
        else:
            log.error("topic: "+msg.topic + "size not matching")
    except Exception as e:
        log.error("mqtt_on_message> Exception :%s"%e)
    return

# -------------------- main -------------------- 
config = cfg.configure_log(__file__)

# -------------------- Philips Hue Client -------------------- 
log.info("Check Bridge Presence")

if(cfg.ping(config["bridges"]["LivingRoom"])):
    file_path=config["bridges"]["username_config"]
    log.info(f"Bridge Connection using config '{file_path}'")
    b = Bridge(ip=config["bridges"]["LivingRoom"],config_file_path=file_path)
    b.connect()
    log.info("Light Objects retrieval")
    lights = b.get_light_objects('name')
    log.info("Hue Lights available :")
    for name, light in lights.items():
        log.info(name)
    
else:
    log.info("Bridge ip not responding")


# -------------------- Mqtt Client -------------------- 
#will start a separate thread for looping
clientMQTT = mqtt_start(config,mqtt_on_message,True)
Beispiel #9
0
    # convert rgb to xyz
    x = red * 0.649926 + green * 0.103455 + blue * 0.197109
    y = red * 0.234327 + green * 0.743075 + blue * 0.022598
    z = green * 0.053077 + blue * 1.035763

    # convert xyz to xy
    x = x / (x + y + z)
    y = y / (x + y + z)

    # TODO check color gamut if known

    return [x, y]


b = Bridge('192.168.7.154')
b.connect()

lights = b.lights

# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error 
def start(update: Update, context: CallbackContext) -> None:
    update.message.reply_text('Hi! we have 4 command!')
    update.message.reply_text("You can turn on Philips hue : /turn on <light's index(0, 1, 2)>")
    update.message.reply_text("Also, you can turn off Philips hue : /turn off <light's index(0, 1, 2)>")
    update.message.reply_text("You can change light's color : /color <light's index> <red, blue, green>")
    update.message.reply_text("Othere way : /color <light's index> <3 color codes(0~1)>")
    update.message.reply_text("example : /color 1 0.5 0.5 0.5")

def alarm(context):
Beispiel #10
0
def get_hsv(hsv, x, y):
    return [
        int((hsv[y, x][0] / 179) * 65535),
        int(hsv[y, x][1]),
        int(hsv[y, x][2])
    ]


def set_hsv(light, hsv_val):
    light.hue = hsv_val[0]
    light.saturation = hsv_val[1]
    light.brightness = 255


# Connect to Philips Hue
b = Bridge('192.168.2.44')
b.connect()
study_light = b.lights[2]

# Read frames from built-in camera
cap = cv2.VideoCapture(0)
while (True):
    ret, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    cv2.imshow('frame', frame)
    set_hsv(study_light, get_hsv(hsv, 100, 400))
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
#!/usr/bin/python
from phue import Bridge
import random

b = Bridge('192.168.1.23') # Enter bridge IP here.

#If running for the first time, press button on bridge and run with b.connect() uncommented
#b.connect()


lights = b.get_light_objects('id')


for light in lights:
    print("id=%d name=%s" %(light, b.get_light(light, 'name')))
Beispiel #12
0
else:
    HUE_IP = '192.168.1.101'
POLL_INTERVAL = 3  # seconds

MQTT_ADDRESS = 'mosquitto'

MQTT_USER = '******'
MQTT_PASSWORD = '******'
MQTT_CLIENT_ID = 'philips_hue_driver'

print("Connecting to Philips Hue Hub, IP: {}".format(HUE_IP))

retry = True
while retry:
    try:
        b = Bridge(HUE_IP, config_file_path='/data/config_file.config')
        retry = False

    except PhueRegistrationException as e:
        print("The link button has not been pressed (on hub IP:{}) in the last "
              "30 seconds, please press and pairing will begin".format(HUE_IP))
        sleep(3)
    except JSONDecodeError as e:
        print("Error decoding HUE Hub response, is the hub IP ({}) correct?".format(HUE_IP))

# If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single time)
b.connect()

# Get the bridge state (This returns the full dictionary that you can explore)
# print(b.get_api())
Beispiel #13
0
 def __init__(self, ip, username=None, config=None):
     self.bridge = Bridge(ip, username, config)
     self.bridge.connect()
Beispiel #14
0
        elif (name == "cube"):
            aqara_cube(msg.payload)
        elif (name == "night leds button"):
            night_leds_button(msg.payload)
    else:
        log.error("topic: " + msg.topic + "size not matching")


# -------------------- main --------------------
config = cfg.configure_log(__file__)

# -------------------- Philips Hue Client --------------------
log.info("Check Bridge Presence")

if (cfg.ping(config["bridges"]["LivingRoom"])):
    b = Bridge(config["bridges"]["LivingRoom"])
    log.info("Bridge Connection")
    b.connect()
    log.info("Light Objects retrieval")
    lights = b.get_light_objects('name')
    print("_________________________")
    print(lights["Bed Leds Cupboard"])
    print("_________________________")

    log.info("Hue Lights available :")
    for name, light in lights.items():
        log.info(name)

else:
    log.info("Bridge ip not responding")
Beispiel #15
0
#!/usr/bin/python
# -*- coding: utf8 -*-import sys
import Tkinter
from phue import Bridge
import random
import json, urllib2
import time
import urllib2
from bs4 import BeautifulSoup

b = Bridge('192.168.2.2')
b.connect()

root = Tkinter.Tk()
root.title(u"Software Title")
root.geometry("400x300")


def Tenki(event):
    url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=070030'
    try:
        r = urllib2.urlopen(url)
        root = json.loads(r.read())
        print 'title=' + root['title']
        description = root['description']
        print 'publicTime=' + description['publicTime']

        forecasts = root['forecasts']
        print '    dateLabel=' + forecasts[0][
            'dateLabel'] + ',telop=' + forecasts[0][
                'telop'] + ',date=' + forecasts[0]['date']
Beispiel #16
0
from phue import Bridge
import cv2
from time import sleep

#Turn on the light
b = Bridge('192.168.86.21')
b.connect()

#Take a picture each hour

name = 0
while True:
    b.set_light(3, 'on', True)
    cap = cv2.VideoCapture(0)
    ret, frame = cap.read()
    name += 1
    final_name = 'C:/geomsb/' + str(name) + '.jpg'
    cv2.imwrite(final_name, frame)
    cap.release()
    b.set_light(3, 'on', False)
    sleep(30)
        if os.path.exists(FLAGS.save_file):
            pass
        else:
            with open(FLAGS.save_file, 'w') as writeFile:
                writer = csv.writer(writeFile)
                if FLAGS.recording_directory:
                    row = ['Date', 'filepath', 'laugh_score', 'volume']
                    writer.writerow(row)
                else:
                    row = ['Date', 'laugh_score', 'volume']
                    writer.writerow(row)

    if FLAGS.hue_lights:
        from phue import Bridge

        b = Bridge(FLAGS.hue_IP)
        lights = b.lights[:2]

        blue_xy = [0.1691, 0.0441]
        white_xy = [0.4051, 0.3906]

    #need to investigate what this window is used for, taking half of the window length
    window = [0.5]*FLAGS.avg_window

    #using MicrophoneStream as context class, using stream object to process the data
    with MicrophoneStream(RATE, CHUNK) as stream:
        #stream.generator() function automatically processes the 10 second chunks and puts them in a generator
        audio_generator = stream.generator()
        for chunk in audio_generator:
            try:
                arr = np.frombuffer(chunk, dtype=np.int16)
Beispiel #18
0
from phue import Bridge

b = Bridge('192.168.1.188')
b.connect()

#b.set_light(1,'xy', (.45,.22))

print(b.get_light(1, 'xy'))
#print(b.get_api())
Beispiel #19
0
from phue import Bridge
import time
import datetime
import sys

# Get light object
light = Bridge('192.168.0.190')["Jessi's Lamp"]
brightnessStart = light.brightness
print('Initial brightness: %d.' % brightnessStart)

countdownMinutes = float(
    sys.argv[1])  # How long the timer should run, in minutes
countdownSeconds = countdownMinutes * 60

startTime = time.time()
endTime = startTime + countdownSeconds

print('Start: ' + str(datetime.datetime.fromtimestamp(startTime)) + '\tEnd: ' +
      str(datetime.datetime.fromtimestamp(endTime)))

divisions = 60
divisionTime = (endTime - startTime) / divisions

nextDivisionTime = startTime + divisionTime
print('First update: %s' %
      str(datetime.datetime.fromtimestamp(nextDivisionTime)))

# TODO: remove after testing
firstFraction = (nextDivisionTime - endTime) / (startTime - endTime)
firstBrightness = int(
    (nextDivisionTime - endTime) / (startTime - endTime) * brightnessStart)
Beispiel #20
0
def access_lights(hue_bridge):
    b = Bridge(hue_bridge)
    light_names_list = b.get_light_objects("name")
    return light_names_list
Beispiel #21
0
import logging
from unicodedata import normalize as norm
from phue import Bridge
from subprocess import run, PIPE
logging.basicConfig()
b = Bridge('192.168.1.15')

# If the app is not registered and the button is not pressed, press the button and call connect() (this only needs to be run a single time)
b.connect()
lights = b.get_light_objects('name')
logging.info("Detected {} lights:".format(len(lights)))
for l in lights: logging.info("\t{}".format(l))

room = run("whereami predict", shell=True, stdout=PIPE)
room = room.stdout.decode('UTF-8').strip().split('\n')[-1]
room_lights = [l for l in lights if norm("NFKD",room.casefold()) in norm("NFKD",l.casefold())]
print("Detected room {}.\nTurn on {} ? (Y/n)".format(room, room_lights))
if not input().lower() == 'n':
    print("Turning lights on")
    for l in room_lights:
        lights[l].on = True
print("Turn off all other lights ? (Y/n)")
if not input().lower() == 'n':
    print("Turning lights off")
    for n, l in lights.items():
        if not n in room_lights:
            l.on = False
Beispiel #22
0
 def __init__(self, bridge_ip):
     b = Bridge(bridge_ip)
     b.connect()
     self.bridge = b
Beispiel #23
0
from socket import *
from phue import Bridge

port_num = 6667
servername = 'chat.freenode.net'

sock = socket(AF_INET, SOCK_STREAM)
sock.connect((servername, port_num))
b = Bridge('192.168.1.139')
b.connect()
lights = b.lights


def hue_set(num, status, light, color_x, color_y):
    num = int(num)
    light = int(light)
    color_x = float(color_x)
    color_y = float(color_y)

    if num == 1:
        if status == 'on':
            lights[0].on = True
            lights[0].brightness = light
            lights[0].xy = [color_x, color_y]
        else:
            lights[0].on = False
    if num == 2:
        if status == 'on':
            lights[1].on = True
            lights[1].brightness = light
            lights[1].xy = [color_x, color_y]
Beispiel #24
0
#coding:utf-8

from tkinter import *
from distutils import command
from phue import Bridge, Light


def switch():
    print('Light switch {}'.format(check_on.get()))
    test_light.on = check_on.get()


b = Bridge('10.0.0.2')
lights = b.lights
test_light = Light(b, 5)

root = Tk()
check_on = BooleanVar()
b1 = Button(root, text='On / Off', command=switch).pack()
b2 = Checkbutton(root,
                 text='check',
                 command=switch,
                 onvalue=True,
                 offvalue=False,
                 variable=check_on,
                 image='off_button.png',
                 selectimage='on_button.png').pack()

root.mainloop()
 def __init__(self,ip_addr,mode,inputdevice,left_light_no=None,right_light_no=None):
     self.__b=Bridge(ip_addr)
     self.__mode=mode
     sd.default.device=inputdevice,None
     self.__left_light_no=left_light_no
     self.__right_light_no=right_light_no
Beispiel #26
0
from flask import Flask, render_template, redirect,url_for, request
from flask_bootstrap import Bootstrap
#.station_ip = "192.168.1.20"  # Your base station IP
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
BROWN = "#eabf9f"
from phue import Bridge
B = Bridge('192.168.1.20')
B.connect()

app = Flask(__name__)
Bootstrap(app)
light_numbers=[]
lights_in_the_room=[]
rooms = B.groups
brightness=127
@app.route("/")
def home():
    return render_template("index.html" , rooms=rooms)

@app.route("/edit/<int:room_id>")
def edit(room_id):
    light_numbers=[]
    light_numbers = B.get_group(room_id,'lights')

    for l in light_numbers:
        light_number = int(l)
        light_name = B.get_light(light_number, 'name')
        light_status = B.get_light(light_number, 'on')
Beispiel #27
0
 def __init__(self):
     self.bridge = Bridge("192.168.0.73")
     self.bridge.connect()
     self.turnLightOn()
     self.setDefaultHue()
Beispiel #28
0
# Setup
# ==============================================================================================
touchphat.all_off()

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# Stuff you need to change!
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# The IP address of the Hue bridge and a list of lights you want to use
bridgeip = '192.168.0.241'  # <<<<<<<<<<<
lights = ['Desk', 'Ikea']  # <<<<<<<<<<<

# -----------------------------------------------------------------------------------------------
# Do some internal setup
# -----------------------------------------------------------------------------------------------
# Connect to the bridge
b = Bridge(bridgeip)

# IMPORTANT: If running for the first time:
#    Uncomment the b.connect() line
#    Ppress button on bridge
#    Run the code
# This will save your connection details in /home/pi/.python_hue
# Delete that file if you change bridges
# b.connect() # <<<<<<<<<<
# b = Bridge('192.168.0.241')
# An array of the light name and the light type.
# Expand if you have something different - please let me know if you do!
lighttype = []
lighttypecolour = 'Extended color light'
lighttypedimmable = 'Dimmable light'
# Get the type of lights that are connected
Beispiel #29
0
def lights_shift(hermes, intent_message):
    # type: (Hermes, IntentMessage) -> None
    ip, user, no = read_configuration_file(CONFIG_FILE)
    bridge = Bridge(ip, user)
    slot_map = to_slot_map(intent_message)
    brightness = bridge.get_light(no, "bri")
    print "brightness", brightness
    house_room = slot_map.get("house_room", None)
    if house_room is not None:
        house_room = house_room[0].raw_value
        message = u"%sのライトを" % house_room.decode("utf-8")
    else:
        message = u"ライトを"

    up_down = slot_map.get("up_down")[0]
    print dir(up_down.slot_value.value.value)
    if up_down.slot_value.value.value == "up":
        up = True
    else:
        up = False

    intensity_number = slot_map.get("intensity_number", None)
    if intensity_number is None:
        intensity_percentage = slot_map.get("intensity_percentage", None)

        if intensity_percentage is None:
            if up:
                brightness = brightness + 25
                if brightness > 254:
                    brightness = 254
                    message += u"最大値でつけました"
                else:
                    message += u"明るくしました"
                print bridge.set_light(no, command(bri=brightness))
            else:
                brightness = brightness - 25
                if brightness < 0:
                    brightness = 0
                    message += u"消しました"
                else:
                    message += u"暗くしました"
                print bridge.set_light(no, command(bri=brightness))

        else:
            percentage = intensity_percentage[0].slot_value.value
            print "percentage", percentage
            brightness_delta = int(254 * float(0.01 * percentage))
            print "delta", brightness_delta
            if up:
                brightness += brightness_delta
                print "brightness up", brightness
                if brightness > 254:
                    brightness = 254
                    message += u"最大値でつけました"
                else:
                    message += u"%d%%明るくしました" % percentage
            else:
                brightness -= brightness_delta
                print "brightness down", brightness
                if brightness < 0:
                    brightness = 0
                    message += u"暗くしました"
                else:
                    message += u"%d%%暗くしました" % percentage
            print brightness
            print bridge.set_light(no, command(bri=int(brightness)))
            message += u"%dでつけました" % percentage
    else:
        intensity_number = intensity_number[0]
        if u"割" in intent_message.input:
            percentage = intensity_number.slot_value.value * 0.1
            if percentage > 1:
                print bridge.set_light(no, command(bri=254))
                message += u"最大値でつけました"
            else:
                print bridge.set_light(no, command(bri=254 * percentage))
                message += u"%dでつけました" % percentage
        else:
            value = intensity_number.slot_value.value
            if value > 254 or value < 0:
                message = "0から254で指定してください"
            else:
                if up:
                    brightness += value
                    if brightness > 254:
                        brightness = 254
                    message += u"明るくしました"
                else:
                    brightness -= value
                    if brightness < 0:
                        brightness = 0
                    message += u"暗くしました"

                print bridge.set_light(no, command(bri=brightness))

    hermes.publish_end_session(intent_message.session_id,
                               message.encode("utf-8"))
Beispiel #30
0
#!/usr/bin/python
from phue import Bridge
import random

b = Bridge('10.0.0.11', 'pi')  # Enter bridge IP here.

#If running for the first time, press button on bridge and run with b.connect() uncommented
b.connect()

lights = b.get_light_objects()

for light in lights:
    light.brightness = 254
    light.xy = [random.random(), random.random()]