Beispiel #1
0
def _get_bridge():
  bridge = clique.context('bridge')
  if not bridge:
    bridge = Bridge()
    bridge.get_ip_address(set_result=True)
    try:
      bridge.connect()
    except:
      logging.exception("Failed to connect bridge.")
      return

    clique.context('bridge', bridge)

  return bridge
Beispiel #2
0
def initial_setup(config, guided_setup=False):
    """Initial setup to be called when Alfred Flask app is run"""

    # (TODO) Should not respond to numbers it does not recognize
    # (TODO) Complete action for one light when light name is mentioned

    # add <number>:<name> key pair values to have Alfred respond using your name
    # callers = {}
    print('[INFO] Setting up...')

    ## SETUP
    # if setup flag is passed, run guided setup loop
    if guided_setup:
        guided_setup()

    # parse and store config file
    config = configurations(config)

    ## PHILIPS HUE
    hue_config = config['lights']
    if hue_config['bridgeIP'] != 'None':
        # create the Bridge object with correct IP
        print(
            "[INFO] Make sure you have pressed the button on the Hue Bridge within 30 seconds of running this script!"
        )
        print('[INFO] Connecting to Philips Hue Bridge with IP {}'.format(
            hue_config['bridgeIP']))
        philips_bridge = Bridge(hue_config['bridgeIP'])
        # warn user about connect process with hub
        print("[INFO] Your bridge ip is {}".format(
            philips_bridge.get_ip_address()))
    else:
        philips_bridge = None

    ## WOLFRAM TODO
    wolfram = None

    ## WEATHER
    weather_config = config['weather']
    if weather_config['OWMKey'] != 'None':
        print('[INFO] Setting up pyowm with API key {}'.format(
            weather_config['OWMKey']))
        owm = pyowm.OWM(weather_config['OWMKey'])
    else:
        owm = None

    return philips_bridge, owm, wolfram
Beispiel #3
0
import os 


print('starting[PiLamp]')
try:
  IP_ADDRESS_BRIDGE = '10.0.0.102'
  PHUE_CONFIG_FILE  =  os.path.dirname(os.path.realpath(__file__))+'/.python_hue'
  PI_LIGHT          = '3.14 Lamp'
  HUE               = 'Hue'
  SATURATION        = 'Saturation'
  colorMode         = HUE     
 
  done = False
  while not done:
    try:
      IP_ADDRESS_BRIDGE = Bridge.get_ip_address( None )
      bridge = Bridge (ip = IP_ADDRESS_BRIDGE, config_file_path = PHUE_CONFIG_FILE )
      done = True
    except OSError as e:
      # an IOError exception occurred (socket.error is a subclass)
      if e.errno == 101: #Network is unreachable
        print('Network unreachable, going to try again')
      else: 
        raise            #all is lost

  #get list of lights
  done = False
  while not done:
    try:
      IP_ADDRESS_BRIDGE = Bridge.get_ip_address( None )
      print( IP_ADDRESS_BRIDGE )
Beispiel #4
0
class HueClass():
	def __init__(self, Hue_IP):
		self.isFound = False # 是否已经找到
		self.isConnect = False # 是否已经连接
		self.lights_info = None # 用来记录网桥上所有lights的信息
		self.isSame = True
		self.reachable_lights_ids = [] # 用来记录网桥上在线的lights的id号
		self.b = None

		# 开启两个线程分别尝试用配置文件的IP和参数传过来的IP来连接网桥
		ip = read_HueIp_from_file()
		t1 = threading.Thread(target=self.thread_func_to_search, args=(ip,))
		t2 = threading.Thread(target=self.thread_func_to_search, args=(Hue_IP,))
		t1.setDaemon(True)
		t2.setDaemon(True)
		t1.start()
		t2.start()
		count = 300
		# 等待连接或者线程结束
		while count:
			# 当有其中一个线程连接上网桥就退出等待
			if self.isFound is True and self.isConnect is True:
				break
			# 当两个线程都结束就退出等待
			elif t1.isAlive() is False and not t2.isAlive() is False:
				time.sleep(1)
				break
			else:
				count -= 1
				time.sleep(0.1)

		# 当还没发现网桥并且没有连接上网桥就开始搜索参数传过来的Hue_IP整个网段的IP进行尝试连接
		# 可以考虑搜索本地IP的整个网段
		if self.isFound is False and self.isConnect is False:
			ipList = Hue_IP.split('.')[:-1]
			preIp = ''
			for i in ipList:
				preIp += i + '.'
			for i in xrange(1,256):
				if self.isFound is False:
					ip = '%s%s' % (preIp, i)
					print ip
					t = thread.start_new_thread(self.thread_func_to_search, (ip,))
					time.sleep(0.05)
		count = 30

		# 当搜索到网桥但还没连接上就等待连接
		if self.isFound is True and self.isConnect is False:
			while count:
				if self.isConnect is True:
					break
				else:
					count -= 1
					time.sleep(1)

		self.get_lights()

	def thread_func_to_search(self, ip):
		"""
		搜索网桥的线程函数
		"""
		try:
			if ip is None or ip is '':
				self.b = Bridge()
			else:
				self.b = Bridge(ip)
			if self.b is not None:
				if ip is None or ip is '':
					try:
						ip = self.b.get_ip_address()
					except:
						pass
				if self.isSame is True:
					self.isSame = False
					logger.info("Hue_IP: %s" % ip)
				self.isFound = True
				self.isConnect = True
				write_HueIp_to_file(ip)
				
		except PhueRegistrationException as e:
			self.isFound = True
			if self.isSame is True:
				self.isSame = False
				logger.info('请按一下网桥按键进行连接')
			while True:
				try:
					self.b = Bridge(ip)
					if self.isSame is True:
						self.isSame = False
						logger.info("Hue_IP: %s" % ip)
					self.isConnect = True		
					write_HueIp_to_file(ip)
					break
				except:
					time.sleep(2)
		except Exception,e:
			pass
Beispiel #5
0
    try:
        while not resolved:
            ready = select.select([resolve_sdRef], [], [], timeout)
            if resolve_sdRef not in ready[0]:
                print 'Resolve timed out'
                break
            pybonjour.DNSServiceProcessResult(resolve_sdRef)
        else:
            resolved.pop()
    finally:
        resolve_sdRef.close()


bridge = Bridge()
bridge.get_ip_address(True)

groupId = bridge.get_group_id_by_name(room)

browse_sdRef = pybonjour.DNSServiceBrowse(regtype = regtype,
                                          callBack = browse_callback)

try:
    try:
        while True:
            ready = select.select([browse_sdRef], [], [])
            if browse_sdRef in ready[0]:
                pybonjour.DNSServiceProcessResult(browse_sdRef)
    except KeyboardInterrupt:
        pass
finally:
Beispiel #6
0
class LavaLamp:

    switch_colors = False
    was_On = False

    def __init__(self, lights, alexa_light, transition_time, dev_output):
        if isinstance(dev_output, bool):
            self.dev_output = dev_output
        else:
            self.dev_output = False

        self.b = Bridge()
        print '[STATUS]{} Connected to Hue Bridge with IP {}'.format(
            self.get_time_string(), self.b.get_ip_address())

        self.light_names = self.b.get_light_objects('name')
        self.used_lights = lights
        self.alexa_light = alexa_light
        self.transition_time = transition_time
        self.last_hues = []
        self.initial_hues = []
        self.initial_saturation = []
        self.initial_brightness = []
        self.used_lights_without_alexa_light = []

        print '[STATUS]{} Used lights for LavaLamp:\n'.format(
            self.get_time_string())
        for light in self.used_lights:
            self.last_hues.append(self.light_names[light].hue)
            if not light == self.alexa_light:
                self.initial_hues.append(self.light_names[light].hue)
                self.initial_saturation.append(
                    self.light_names[light].saturation)
                self.initial_brightness.append(
                    self.light_names[light].brightness)
                self.used_lights_without_alexa_light.append(light)
            print light

    # generate time string for status messages
    def get_time_string(self):
        return datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")

    # turn on all used lights
    def turn_On(self):
        for l in self.used_lights:
            self.light_names[l].on = True
        print '[STATUS]{} Turned on LavaLamp'.format(self.get_time_string())

    # set brightness of all used lights to specific value
    def set_brightness(self, brightness):
        if isinstance(brightness, int) and 0 <= brightness <= 254:
            for l in self.used_lights:
                self.light_names[l].brightness = brightness
        else:
            if self.dev_output:
                print '[DEV]{} Brightness have to be a value between 0 and 254'.format(
                    self.get_time_string())

    # set saturation of all used lights to specific value
    def set_saturation(self, saturation):
        if isinstance(saturation, int) and 0 <= saturation <= 254:
            for l in self.used_lights:
                self.light_names[l].saturation = saturation
        else:
            if self.dev_output:
                print '[DEV]{} Saturation have to be a value between 0 and 254'.format(
                    self.get_time_string())

    # generate new random colors for the used lights and change them to the new colors
    def new_random_colors(self):
        if len(self.used_lights) == 2:
            if self.switch_colors:
                self.last_hues[0], self.last_hues[1] = self.last_hues[
                    1], self.last_hues[0]
                self.switch_colors = False
            else:
                for index, light in enumerate(self.used_lights):
                    self.last_hues[index] = random.randint(0, 65535)
                self.switch_colors = True

            for index, light in enumerate(self.used_lights):
                self.light_names[light].hue = self.last_hues[index]
                self.light_names[
                    light].transitiontime = 10 * self.transition_time
                if self.dev_output:
                    print '[DEV]{} Light: {} -> New hue: {}'\
                        .format(self.get_time_string(), light, self.last_hues[index])
        else:
            print '[ERROR]{} Not implemented yet!'.format(
                self.get_time_string())

    # check if all of the lights are turned on
    def is_On(self):
        all_lights_on = True
        for light in self.used_lights:
            if not self.light_names[light].on:
                all_lights_on = False
                break
        return all_lights_on

    # match the brightness of all lights to the currently darkest one
    def match_brightness(self):
        brightness_values = []
        for l in self.used_lights:
            brightness_values.append(self.light_names[l].brightness)
        self.set_brightness(min(brightness_values))

    # reset transitiontime, hue, brightness and saturation of every light except for the alexa light
    def restore_original_state(self):
        for index, light in enumerate(self.used_lights_without_alexa_light):
            self.light_names[light].transitiontime = 4
            self.light_names[light].hue = self.initial_hues[index]
            self.light_names[light].saturation = self.initial_saturation[index]
            self.light_names[light].brightness = self.initial_brightness[index]

    # script loop - menu 1
    def loop_random(self):
        if raw_input('Start Color Loop now? (y/n) > ') in ['y', 'Y']:
            while True:
                if self.is_On():
                    if not self.was_On:
                        print '[STATUS]{} Starting color loop ...'.format(
                            self.get_time_string())
                        for index, light in enumerate(
                                self.used_lights_without_alexa_light):
                            self.initial_hues[index] = self.light_names[
                                light].hue
                            self.initial_saturation[index] = self.light_names[
                                light].saturation
                            self.initial_brightness[index] = self.light_names[
                                light].brightness
                        self.set_saturation(254)
                        self.match_brightness()
                    self.was_On = True

                    t = Timer(self.transition_time, self.new_random_colors)
                    t.start()
                    t.join()
                else:
                    if self.was_On:
                        self.was_On = False
                        t = Timer(self.transition_time,
                                  self.restore_original_state)
                        t.start()
                        t.join()
                        print "[STATUS]{} Stopped color loop! Waiting for all lights to be turned on again ..." \
                            .format(self.get_time_string())
                    else:
                        time.sleep(1)

    def loop_same_colors(self):
        print "You've successfully entered loop_same_colors"

    def loop_custom_colors(self):
        print "You've successfully entered loop_custom_colors"

    def menu(self):
        options = {
            1: self.loop_random,
            2: self.loop_same_colors,
            3: self.loop_custom_colors
        }

        while True:
            print '\n----------------------------------------------'
            print '1 -- Random Loop'
            print '2 -- Random Loop with same Colors'
            print '3 -- Custom Color Loop'
            print '----------------------------------------------'
            num = int(raw_input('> '))
            if num in options:
                options[num]()
            else:
                print '[ERROR]{} Your choice is not a part of the menu!'.format(
                    self.get_time_string())