Advertisement
ap5Lj9rB2AMoQ7

upb hass code

Feb 18th, 2018
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.14 KB | None | 0 0
  1. """
  2. DEVVVVVVVV Support for UPB lights
  3.  
  4.  
  5. Improvements:
  6. - ditch upb-cli and do everything natively
  7. - listen for status changes in real time on the network
  8. - optionally poll all the devices in the network every x minutes for their
  9.  status
  10. - instead of recreating the light config in configuration.yaml, read the config
  11.  from the upstart export file
  12.  
  13. """
  14. import asyncio
  15. import logging
  16. import time
  17. from subprocess import check_output, CalledProcessError, STDOUT
  18.  
  19. import voluptuous as vol
  20.  
  21.  
  22. from homeassistant.components.light import (
  23.     ATTR_BRIGHTNESS, ATTR_BRIGHTNESS_PCT, SUPPORT_BRIGHTNESS, Light,
  24.     PLATFORM_SCHEMA)
  25.  
  26. from homeassistant.const import (CONF_NAME, CONF_ID, CONF_DEVICES)
  27.  
  28. import homeassistant.helpers.config_validation as cv
  29.  
  30.  
  31. serial_port = ''
  32. network_id = ''
  33.  
  34. _LOGGER = logging.getLogger(__name__)
  35.  
  36. CONF_SERIAL_PORT = 'serial_port'
  37. CONF_NETWORK_ID = 'network_id'
  38. UPB_LIGHTS = 'upb_lights'
  39.  
  40. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  41.     vol.Required(CONF_DEVICES): vol.All(cv.ensure_list, [
  42.         {
  43.             vol.Required(CONF_ID): cv.string,
  44.             vol.Required(CONF_NAME): cv.string,
  45.         }
  46.     ]),
  47.     vol.Required(CONF_SERIAL_PORT): cv.string,
  48.     vol.Required(CONF_NETWORK_ID): cv.string,
  49.  
  50. })
  51.  
  52. # Initialize a list / array
  53. upb_dev_bright_time = [None]*100
  54. upb_dev_bright_lvl = [None]*100
  55. upb_dev_bright_lvl[33] = 88
  56. upb_dev_bright_lvl[4] = 4
  57. upb_dev_bright_lvl[83] = 83
  58.  
  59. def dump(obj):
  60.     for attr in dir(obj):
  61.         if hasattr( obj, attr ):
  62.             print( "obj.%s = %s" % (attr, getattr(obj, attr)))
  63.  
  64.  
  65.  
  66. def setup_platform(hass, config, add_devices, discovery_info=None):
  67.     """Set up the UPB Light platform"""
  68.    
  69.     global serial_port, network_id
  70.  
  71.  
  72.     serial_port = config.get(CONF_SERIAL_PORT)
  73.     network_id = config.get(CONF_NETWORK_ID)
  74.    
  75.     try:
  76.         upb_command('-V')
  77.     except CalledProcessError as err:
  78.         _LOGGER.error(err.output)
  79.         return False
  80.  
  81.     for l in config[CONF_DEVICES]:
  82.         print(l)        # OrderedDict([('id', '83'), ('name', 'Office Lamp')])
  83.         #add_devices(l)
  84.     #    hass.data[UPB_LIGHTS][light] = light
  85.        
  86.     add_devices(UPBLight(light) for light in config[CONF_DEVICES])       # add_devices returns None
  87.    
  88.  
  89.     # devs = []
  90.     # for (area_name, device) in hass.data[LUTRON_DEVICES]['light']:
  91.     #     dev = LutronLight(area_name, device, hass.data[LUTRON_CONTROLLER])
  92.     #     devs.append(dev)
  93.  
  94.     # light_devices = bridge.get_devices_by_domain(DOMAIN)
  95.     # for light_device in light_devices:
  96.     #     print(light_device)
  97.  
  98.     """Handle when an entity is about to be added to Home Assistant."""
  99.     #self._serial_loop_task = self.hass.loop.create_task(
  100.         #self.serial_read(self._port, self._baudrate))
  101.     myloop = hass.loop.create_task(serial_read(hass, '/dev/ttyS1', 4800))
  102.  
  103. class UPBLight(Light):
  104.     """Representation of an UPB Light"""
  105.  
  106.     def __init__(self, light):
  107.         """Initialize an UPB Light"""
  108.         self._light = light
  109.         self._name = 'upb_' + light['name']
  110.         self._id = light['id']
  111.         self._brightness = None
  112.         self._state = None
  113.  
  114.     @property
  115.     def name(self):
  116.         """Return the display name of this light"""
  117.         return self._name
  118.  
  119.     @property
  120.     def supported_features(self):
  121.         """Flag supported features"""
  122.         return SUPPORT_BRIGHTNESS
  123.  
  124.     @property
  125.     def brightness(self):
  126.         """Return the brightness of the light"""
  127.         global upb_dev_bright_lvl
  128.         #return self._brightness
  129.         return upb_dev_bright_lvl[int(self._id)]
  130.  
  131.     @property
  132.     def is_on(self):
  133.         """Return true if light is on"""
  134.         return self._state
  135.  
  136.  
  137.     def turn_on(self, **kwargs):
  138.         """Instruct the light to turn on"""  
  139.         global upb_dev_bright_lvl, upb_dev_bright_time
  140.        
  141.         bright_pct = int((kwargs.get(ATTR_BRIGHTNESS,255)/255)*100)
  142.         #self._brightness = bright_pct
  143.         upb_dev_bright_lvl[int(self._id)] = bright_pct
  144.  
  145.         #print(str(self._id)) ## This is the id value from the configutaion.yaml
  146.         #upb_command('-n 99 -i 83 -t device -c goto -l 100 --send -p /dev/ttyS1' )
  147.         #upb_command(' -i ' + self._id + ' -t device -c goto -l ' + str(bright_pct) + ' --send' )
  148.        
  149.         print("turn_on: " + "id: " + self._id + " brightness: " + str(bright_pct))
  150.         #print(kwargs)
  151.         self._state = True
  152.         self._brightness = bright_pct
  153.  
  154.     def turn_off(self, **kwargs):
  155.         """Instruct the light to turn off"""
  156.         # upb_command(' -i ' + self._id + ' -t device -c goto -l 0 --send' )
  157.         # time.sleep(1)
  158.         # upb_command(' -i ' + self._id + ' -t device -c goto -l 0 --send' )
  159.         self._state = False
  160.  
  161.     def update(self, **kwargs):
  162.         """Update light"""
  163.         global upb_dev_bright_lvl
  164.         print('update kwargs: '+ str(kwargs))
  165.         print("update for id: " + str(self._id) + " brightness: " + str(upb_dev_bright_lvl[int(self._id)]))
  166.         self._brightness = upb_dev_bright_lvl[int(self._id)]
  167.         #self._brightness = upb_dev_bright_lvl[self._id]
  168.         #print(upb_dev_bright_lvl)
  169.         #self._state = bool(get_unit_status(self._id))
  170.         #self._light.update()
  171.         #self._state = self._light.is_on()
  172.         #self._brightness = self._light.brightness
  173.         #self._brightness = self._light.brightness
  174.        
  175.  
  176.  
  177.  
  178.  
  179.  
  180. @asyncio.coroutine
  181. def serial_read(hass, device, rate, **kwargs):
  182.     """Read the stream of light statuses from the serial port"""
  183.     import serial_asyncio
  184.     global upb_dev_bright_lvl
  185.  
  186.     print('serial_read kwargs: ' + str(kwargs))
  187.     print('serial read method')
  188.    
  189.     reader, _ = yield from serial_asyncio.open_serial_connection(
  190.         url=device, baudrate=rate, **kwargs)
  191.     print('after reader 3')
  192.  
  193.     #hass.core.set('light.upb_office_lamp', 'on')
  194.     #hass.states.async_set('light.upb_office_lamp', 'on')
  195.     #self.hass.states.async_set(entity_id, STATE_CONFIGURE, data)
  196.  
  197.     while True:
  198.         print('before readuntil')
  199.         line = yield from reader.readuntil(separator=b'\r')
  200.         line = line.decode('utf-8').strip()
  201.         print('my line: '+  line)
  202.         #id, brightness = decode_line(line)
  203.         brightness = 77
  204.         id = 4
  205.         #hass.states.async_set('light.upb_office_lamp', 'on')
  206.         upb_dev_bright_lvl[4] = 77
  207.         print(str(upb_dev_bright_lvl))
  208.  
  209.         # create light object here currentlight = hass.data[UPB_LIGHTS][id]
  210.         # lightobject.brightness(lightobject)
  211.        
  212.        
  213.  
  214.         # try:
  215.         #     data = json.loads(line)
  216.         #     if isinstance(data, dict):
  217.         #         self._attributes = data
  218.         # except ValueError:
  219.         #     pass
  220.  
  221.  
  222.  
  223.         _LOGGER.debug("Received: %s", line)
  224.         #self._state = line
  225.         #self.async_schedule_update_ha_state()
  226.  
  227.  
  228.  
  229. def upb_command(command):
  230.     """Execute UPB command and check output"""
  231.     #print("config: " + config[CONF_SERIAL_PORT])
  232.     # print("serial: "+ serial_port)
  233.     # print("upbnet: "+ network_id)
  234.     return check_output(['upb-cli','-p',serial_port,'-n',network_id] + command.split(' '), stderr=STDOUT)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement