Exemplo n.º 1
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Add device specified by serial number. """
    from blinkstick import blinkstick

    stick = blinkstick.find_by_serial(config['serial'])

    add_devices_callback([BlinkStickLight(stick, config['name'])])
Exemplo n.º 2
0
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
    """ Add device specified by serial number. """
    from blinkstick import blinkstick

    stick = blinkstick.find_by_serial(config['serial'])

    add_devices_callback([BlinkStickLight(stick, config['name'])])
Exemplo n.º 3
0
    def __init__(self,
                 name,
                 role,
                 sn=None,
                 max_power=0.1,
                 inversed=False,
                 **kwargs):
        """
        sn (None or str): serial number.
           If None, it will pick the first device found.
        max_power (0<float): maxium power emitted in W.
        """
        model.Emitter.__init__(self, name, role, **kwargs)

        self._sn = sn
        self._max_power = max_power

        # Just find the first BlinkStick led controller
        if sn is None:
            self._bstick = blinkstick.find_first()
        else:
            # Note: doesn't work with v1.1.7:
            # need fix on get_string(), reported here: https://github.com/arvydas/blinkstick-python/pull/35
            logging.warning(
                "Using sn to select the device doesn't currently work")
            self._bstick = blinkstick.find_by_serial(sn)
        if self._bstick is None:
            raise HwError(
                "Failed to find a Blinkstick for component %s. "
                "Check that the device is connected to the computer." %
                (name, ))

        self._bstick.set_inverse(inversed)
        time.sleep(0.1)  # Device apparently needs some time to recover

        self._shape = ()
        # list of 5-tuples of floats
        self.spectra = model.ListVA([(380e-9, 390e-9, 560e-9, 730e-9, 740e-9)],
                                    unit="m",
                                    readonly=True)

        self.power = model.ListContinuous([
            0.,
        ], ((0., ), (max_power, )),
                                          unit="W",
                                          cls=(int, long, float),
                                          setter=self._setPower)
        self.power.subscribe(self._updatePower, init=True)

        self._swVersion = "Blinkstick v%s" % (blinkstick.__version__, )
        # These functions report wrong values on Linux with v1.1.7
        #         man = self._bstick.get_manufacturer()
        #         desc = self._bstick.get_description()
        #         rsn = self._bstick.get_serial()
        man = self._bstick.device.manufacturer
        desc = self._bstick.device.product
        rsn = self._bstick.device.serial_number
        self._hwVersion = "%s %s (s/n: %s)" % (man, desc, rsn)
Exemplo n.º 4
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up Blinkstick device specified by serial number."""

    name = config.get(CONF_NAME)
    serial = config.get(CONF_SERIAL)

    stick = blinkstick.find_by_serial(serial)

    add_entities([BlinkStickLight(stick, name)], True)
Exemplo n.º 5
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Add device specified by serial number."""
    from blinkstick import blinkstick

    name = config.get(CONF_NAME)
    serial = config.get(CONF_SERIAL)

    stick = blinkstick.find_by_serial(serial)

    add_devices([BlinkStickLight(stick, name)])
Exemplo n.º 6
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Add device specified by serial number."""
    from blinkstick import blinkstick

    name = config.get(CONF_NAME)
    serial = config.get(CONF_SERIAL)

    stick = blinkstick.find_by_serial(serial)

    add_devices([BlinkStickLight(stick, name)])
Exemplo n.º 7
0
def setup_platform(
    hass: HomeAssistant,
    config: ConfigType,
    add_entities: AddEntitiesCallback,
    discovery_info: DiscoveryInfoType | None = None,
) -> None:
    """Set up Blinkstick device specified by serial number."""

    name = config[CONF_NAME]
    serial = config[CONF_SERIAL]

    stick = blinkstick.find_by_serial(serial)

    add_entities([BlinkStickLight(stick, name)], True)
Exemplo n.º 8
0
    def __init__(self, name, role, sn=None, max_power=0.1, inversed=False, **kwargs):
        """
        sn (None or str): serial number.
           If None, it will pick the first device found.
        max_power (0<float): maxium power emitted in W.
        """
        model.Emitter.__init__(self, name, role, **kwargs)

        self._sn = sn
        self._max_power = max_power

        # Just find the first BlinkStick led controller
        if sn is None:
            self._bstick = blinkstick.find_first()
        else:
            # Note: doesn't work with v1.1.7:
            # need fix on get_string(), reported here: https://github.com/arvydas/blinkstick-python/pull/35
            logging.warning("Using sn to select the device doesn't currently work")
            self._bstick = blinkstick.find_by_serial(sn)
        if self._bstick is None:
            raise HwError("Failed to find a Blinkstick for component %s. "
                          "Check that the device is connected to the computer."
                          % (name,))

        self._bstick.set_inverse(inversed)
        time.sleep(0.1)  # Device apparently needs some time to recover

        self._shape = ()
        # TODO: allow to change the power also via emissions? Or just make it a choice
        self.emissions = model.ListVA([0], unit="", setter=self._setEmissions)
        self.emissions.subscribe(self._updatePower)
        # list of 5-tuples of floats
        self.spectra = model.ListVA([(380e-9, 390e-9, 560e-9, 730e-9, 740e-9)],
                                    unit="m", readonly=True)

        self.power = model.FloatContinuous(0., (0., self._max_power), unit="W",
                                           setter=self._setPower)
        self.power.subscribe(self._updatePower, init=True)

        self._swVersion = "Blinkstick v%s" % (blinkstick.__version__,)
        # These functions report wrong values on Linux with v1.1.7
#         man = self._bstick.get_manufacturer()
#         desc = self._bstick.get_description()
#         rsn = self._bstick.get_serial()
        man = self._bstick.device.manufacturer
        desc = self._bstick.device.product
        rsn = self._bstick.device.serial_number
        self._hwVersion = "%s %s (s/n: %s)" % (man, desc, rsn)
Exemplo n.º 9
0
    def __init__(self):
        # Check the hardware is present
        self._stick = blinkstick.find_by_serial('BS015264-2.2')
        if self._stick == None:
            raise ZeroOneException(
                "Unable to find BlinkStick, is it plugged in?")

        self._stick.set_error_reporting(False)

        mode = self._stick.get_mode()
        if mode == None:
            raise ZeroOneException(
                "BlinkStick is not set to mode 2, we're f****d")

        # Put the LEDs off
        self.led_off(Led.LED_RED)
        self.led_off(Led.LED_GREEN)
Exemplo n.º 10
0
def main():
    stick = blinkstick.find_by_serial('BS015264-2.2')

    # stick.open_device()
    # stick.set_mode(2)
    stick.set_error_reporting(True)
    # stick.set_led_count(4)
    mode = stick.get_mode()
    print(mode)

    stick.morph(0, 0, name='red', duration=200)
    stick.morph(0, 0, name='green', duration=200)
    stick.morph(0, 0, name='blue', duration=200)

    stick.morph(1, 0, name='red', duration=200)
    stick.morph(1, 0, name='green', duration=200)
    stick.morph(1, 0, name='blue', duration=200)

    stick.morph(2, 0, name='red', duration=200)
    stick.morph(2, 0, name='green', duration=200)
    stick.morph(2, 0, name='blue', duration=200)

    pass
Exemplo n.º 11
0
def main():
    global options
    global sticks

    parser = OptionParser(
        formatter=IndentedHelpFormatterWithNL()
    )

    parser.add_option("-i", "--info",
                      action="store_true", dest="info",
                      help="display BlinkStick info")

    parser.add_option("-s", "--serial",
                      dest="serial",
                      help="select device by serial number. If unspecified, action will be performed on all BlinkSticks.")

    parser.add_option("--inverse",
                      action="store_true", dest="inverse",
                      help="control BlinkSticks in inverse mode")

    parser.add_option("--channel",
                      default=0, dest="channel",
                      help="Select channel")

    parser.add_option("--index",
                      default=0, dest="index",
                      help="Select index")

    parser.add_option("--set-color",
                      dest="color",
                      help="set the color for the device. The value can either be a named color, hex value, 'random' or 'off'.\n\n"
                           "CSS color names are defined http://www.w3.org/TR/css3-color/ e.g. red, green, blue."
                           "Specify color using hexadecimal color value e.g. '#FF3366'")

    parser.add_option("--duration",
                      dest="duration",
                      default=1000,
                      help="Set duration of transition in milliseconds (use with --morph and --pulse).")

    parser.add_option("--delay",
                      dest="delay",
                      default=500,
                      help="Set time in milliseconds to light LED for (use with --blink).")

    parser.add_option("--repeats",
                      dest="repeats",
                      default=1,
                      help="Number of repetitions (use with --blink and --pulse).")

    parser.add_option("--blink",
                      dest="blink",
                      action='store_true',
                      help="Blink LED (requires --set-color, and optionally --delay)")

    parser.add_option("--pulse",
                      dest="pulse",
                      action='store_true',
                      help="Pulse LED (requires --set-color, and optionally --duration).")

    parser.add_option("--morph",
                      dest="morph",
                      action='store_true',
                      help="Morph to specified color (requires --set-color, and optionally --duration).")

    parser.add_option("--set-infoblock1",
                      dest="infoblock1",
                      help="set the first info block for the device.")

    parser.add_option("--set-infoblock2",
                      dest="infoblock2",
                      help="set the second info block for the device.")

    if sys.platform != "win32":
        parser.add_option("--cpu-usage",
                          dest="cpu_usage", action="store_true",
                          help="Use BlinkStick to display CPU usage.")

    parser.add_option("--connect",
                      dest="access_code",
                      help="Connect to blinkstick.com and control the device remotely.")

    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose",
                      help="Display debug output")

    parser.add_option("--add-udev-rule",
                      action="store_true", dest="udev",
                      help="Add udev rule to access BlinkSticks without root permissions. Must be run as root.")

    (options, args) = parser.parse_args()

    print("BlinkStick control script {0}".format(blinkstick.get_blinkstick_package_version()))
    print("(c) Agile Innovative Ltd 2013")
    print("")

    if options.serial is None:
        sticks = blinkstick.find_all()
    else:
        sticks = [blinkstick.find_by_serial(options.serial)]

        if len(sticks) == 0:
            print("BlinkStick with serial number " + options.device + " not found...")
            return 64

    #Global action
    if options.udev:

        try:
            filename = "/etc/udev/rules.d/85-blinkstick.rules"
            file = open(filename, 'w')
            file.write('SUBSYSTEM=="usb", ATTR{idVendor}=="20a0", ATTR{idProduct}=="41e5", MODE:="0666"')
            file.close()

            print("Rule added to {0}").format(filename)
        except IOError as e:
            print(str(e))
            print("Make sure you run this script as root: sudo blinkstick --add-udev-rule")
            return 64

        print("Reboot your computer for changes to take effect")
        return 0

    for stick in sticks:
        if options.inverse:
            stick.set_inverse(True)

    #Actions here work only on the first BlinkStick found
    if sys.platform != "win32" and options.cpu_usage:
        show_cpu_usage(sticks[0])
    elif options.access_code:
        while True:
            connect()
            print("Attempting to reconnect in 15s")
            time.sleep(15)

    #Actions here work on all BlinkSticks
    for stick in sticks:
        if options.infoblock1:
            stick.set_info_block1(options.infoblock1)

        if options.infoblock2:
            stick.set_info_block2(options.infoblock2)

        if options.info:
            print_info(stick)
        elif options.color:
            # determine color
            args = {}
            if options.color.startswith('#'):
                args['hex'] = options.color
            elif options.color == "random":
                args['name'] = 'random'
            elif options.color == "off":
                args['hex'] = "#000000"
            else:
                args['name'] = options.color

            args['index'] = options.index
            args['channel'] = options.channel

            # handle blink/pulse/morph
            func = stick.set_color
            if options.blink:
                func = stick.blink
                args['delay'] = options.delay
                args['repeats'] = int(options.repeats)
            elif options.pulse:
                func = stick.pulse
                args['duration'] = options.duration
                args['repeats'] = int(options.repeats)
            elif options.morph:
                func = stick.morph
                args['duration'] = options.duration

            func(**args)


        else:
            parser.print_help()

    return 0
Exemplo n.º 12
0
def main_blinkstick_util():
    global options
    global sticks

    parser = OptionParser(usage="usage: %prog [options] [color]",
                          formatter=IndentedHelpFormatterWithNL())

    parser.add_option("-i",
                      "--info",
                      action="store_true",
                      dest="info",
                      help="Display BlinkStick info")

    parser.add_option(
        "-s",
        "--serial",
        dest="serial",
        help=
        "Select device by serial number. If unspecified, action will be performed on all BlinkSticks."
    )

    parser.add_option("-v",
                      "--verbose",
                      action="store_true",
                      dest="verbose",
                      help="Display debug output")

    group = OptionGroup(parser, "Change color",
                        "These options control the color of the device  ")

    group.add_option("--channel",
                     default=0,
                     dest="channel",
                     help="Select channel. Applies only to BlinkStick Pro.")

    group.add_option("--index",
                     default=0,
                     dest="index",
                     help="Select index. Applies only to BlinkStick Pro.")

    group.add_option("--brightness",
                     default=100,
                     dest="limit",
                     help="Limit the brightness of the color 0..100")

    group.add_option("--limit",
                     default=100,
                     dest="limit",
                     help="Alias to --brightness option")

    group.add_option(
        "--set-color",
        dest="color",
        help=
        "Set the color for the device. This can also be the last argument for the script. "
        "The value can either be a named color, hex value, 'random' or 'off'.\n\n"
        "CSS color names are defined http://www.w3.org/TR/css3-color/ e.g. red, green, blue. "
        "Specify color using hexadecimal color value e.g. 'FF3366'")
    group.add_option("--inverse",
                     action="store_true",
                     dest="inverse",
                     help="Control BlinkSticks in inverse mode")

    group.add_option(
        "--set-led-count",
        dest="led_count",
        help="Set the number of LEDs to control for supported devices.")

    parser.add_option_group(group)

    group = OptionGroup(
        parser, "Control animations",
        "These options will blink, morph or pulse selected color.  ")

    group.add_option(
        "--blink",
        dest="blink",
        action='store_true',
        help=
        "Blink LED (requires --set-color or color set as last argument, and optionally --delay)"
    )

    group.add_option(
        "--pulse",
        dest="pulse",
        action='store_true',
        help=
        "Pulse LED (requires --set-color or color set as last argument, and optionally --duration)."
    )

    group.add_option(
        "--morph",
        dest="morph",
        action='store_true',
        help=
        "Morph to specified color (requires --set-color or color set as last argument, and optionally --duration)."
    )

    group.add_option(
        "--duration",
        dest="duration",
        default=1000,
        help=
        "Set duration of transition in milliseconds (use with --morph and --pulse)."
    )

    group.add_option(
        "--delay",
        dest="delay",
        default=500,
        help="Set time in milliseconds to light LED for (use with --blink).")

    group.add_option(
        "--repeats",
        dest="repeats",
        default=1,
        help="Number of repetitions (use with --blink and --pulse).")

    parser.add_option_group(group)

    group = OptionGroup(
        parser, "Device data and behaviour",
        "These options will change device mode and data stored internally.  ")

    group.add_option(
        "--set-mode",
        default=0,
        dest="mode",
        help=
        "Set mode for BlinkStick Pro:\n\n    0 - default\n\n    1 - inverse\n\n    2 - ws2812\n\n    3 - ws2812 mirror"
    )

    group.add_option("--set-infoblock1",
                     dest="infoblock1",
                     help="Set the first info block for the device.")

    group.add_option("--set-infoblock2",
                     dest="infoblock2",
                     help="Set the second info block for the device.")

    parser.add_option_group(group)

    group = OptionGroup(parser, "Advanced options", "")

    group.add_option(
        "--add-udev-rule",
        action="store_true",
        dest="udev",
        help=
        "Add udev rule to access BlinkSticks without root permissions. Must be run as root."
    )

    parser.add_option_group(group)

    (options, args) = parser.parse_args()

    if options.serial is None:
        sticks = blinkstick.find_all()
    else:
        sticks = [blinkstick.find_by_serial(options.serial)]

        if len(sticks) == 0:
            print("BlinkStick with serial number " + options.device +
                  " not found...")
            return 64

    #Global action
    if options.udev:

        try:
            filename = "/etc/udev/rules.d/85-blinkstick.rules"
            file = open(filename, 'w')
            file.write(
                'SUBSYSTEM=="usb", ATTR{idVendor}=="20a0", ATTR{idProduct}=="41e5", MODE:="0666"'
            )
            file.close()

            print("Rule added to {0}").format(filename)
        except IOError as e:
            print(str(e))
            print(
                "Make sure you run this script as root: sudo blinkstick --add-udev-rule"
            )
            return 64

        print("Reboot your computer for changes to take effect")
        return 0

    for stick in sticks:
        if options.inverse:
            stick.set_inverse(True)

        stick.set_max_rgb_value(int(float(options.limit) / 100.0 * 255))

        stick.set_error_reporting(False)

    #Actions here work on all BlinkSticks
    for stick in sticks:
        if options.infoblock1:
            stick.set_info_block1(options.infoblock1)

        if options.infoblock2:
            stick.set_info_block2(options.infoblock2)

        if options.mode:
            if options.mode == "0" or options.mode == "1" or options.mode == "2" or options.mode == "3":
                stick.set_mode(int(options.mode))
            else:
                print("Error: Invalid mode parameter value")

        elif options.led_count:
            led_count = int(options.led_count)

            if led_count > 0 and led_count <= 32:
                stick.set_led_count(led_count)
            else:
                print("Error: Invalid led-count parameter value")

        elif options.info:
            print_info(stick)
        elif options.color or len(args) > 0:
            if options.color:
                color = options.color
            else:
                color = args[0]

            # determine color
            fargs = {}
            if color.startswith('#'):
                fargs['hex'] = color
            elif color == "random":
                fargs['name'] = 'random'
            elif color == "off":
                fargs['hex'] = "#000000"
            else:
                if len(color) == 6:
                    # If color contains 6 chars check if it's hex
                    try:
                        int(color, 16)
                        fargs['hex'] = "#" + color
                    except:
                        fargs['name'] = color
                else:
                    fargs['name'] = color

            fargs['index'] = int(options.index)
            fargs['channel'] = int(options.channel)

            # handle blink/pulse/morph
            func = stick.set_color
            if options.blink:
                func = stick.blink
                fargs['delay'] = options.delay
                fargs['repeats'] = int(options.repeats)
            elif options.pulse:
                func = stick.pulse
                fargs['duration'] = options.duration
                fargs['repeats'] = int(options.repeats)
            elif options.morph:
                func = stick.morph
                fargs['duration'] = options.duration

            func(**fargs)

        else:
            parser.print_help()
            return 0

    return 0
# Prints upcoming vehicle IDs and how many minutes away they are from a given station
from urllib2 import urlopen
import xml.etree.ElementTree as ET
import collections  # Used for sorted dictionary
import sys
from blinkstick import blinkstick
import time
import datetime

# Find Blinkstick
bstick = blinkstick.find_by_serial("BS016770-3.0")

agency = 'sf-muni'

line1 = '45'
stopNum1 = '6757'  #45 stop at Union & Gough

line2 = '47'
stopNum2 = '6814'  #47 stop at Van Ness & Jackson

line3 = '49'
stopNum3 = '6814'  #49 stop at Van Ness & Jackson

trains = ['E', 'F', 'J', 'KT', 'L', 'M', 'N']

# Sleep timer variables
z = 25  #Steady
z1 = 1  #Slow blink
z2 = .5  #Medium blink
z3 = .1  #Fast blink