Exemplo n.º 1
0
def go():
    b = blinkstick.find_first()

    b.set_color(name='blue')

    async def tally():
        while True:
            try:
                async with websockets.connect(config.url) as websocket:
                    await websocket.send(config.me)

                    while True:
                        data = await websocket.recv()
                        data = json.loads(data)

                        if data is None:
                            b.turn_off()

                        else:
                            b.set_color(
                                name='red' if config.me in data else 'white')

            except Exception as e:
                print('network error')
                b.turn_off()
                time.sleep(5)

    asyncio.get_event_loop().run_until_complete(tally())
Exemplo n.º 2
0
def demo_hourly():

    bstick = blinkstick.find_first()

    # Do processing needed to update blinkstick [output how/where?]
    #code goes here with status to [syslog?]
    
    # Get "state" of blinkstick from one of its two [registers?]
    #code goes here with "old state" to [syslog?]
    
    # Turn blinkstick off
    bstick.turn_off()
    
    # Update blinkstick with info from processing done "not long ago"
    for x in range(5):
        bstick.set_random_color()
        print bstick.get_serial() + " " + bstick.get_color(color_format="hex")
        time.sleep(0.5)
    # with "new state" to [syslog?]
        
    # Restore "state" of blinkstick    
    bstick.turn_off()
    
    # Log status
    print bstick.get_serial() + " turned off"    
Exemplo n.º 3
0
 def __init__(self):
     from blinkstick import blinkstick
     self.bstick = blinkstick.find_first()
     if self.bstick is None:
         print "No BlinkSticks found..."
         time.sleep(10)
         sys.exit(1)
Exemplo n.º 4
0
def main():
    color1 = (0.05, 1, 0.98)  # These are in hsv format
    color2 = (0.08, 0.95, 1)
    speed = 10  # Speed of the animation
    width = 15  # Width of the stripes. Lower = wider.
    fps = 50.0  # FPS of the animation. 50 is about the upper limit.

    ### END OPTIONS ###

    stk = blinkstick.find_first()
    cnt = stk.get_led_count()

    while True:
        data = []
        for i in range(cnt):
            fac = math.sin((time.time()) * speed + i * width) / 2 + 0.5
            hue = color1[0] + (color2[0] - color1[0]) * fac
            sat = color1[1] + (color2[1] - color1[1]) * fac
            val = color1[2] + (color2[2] - color1[2]) * fac
            r, g, b = colorsys.hsv_to_rgb(hue, sat, val)
            data = data + [
                int(g * 255),
                int(r * 255),
                int(b * 255),
            ]  # Convert to GRB and add to the frame.
        stk.set_led_data(0, data)  # Send off to the blinkstick
        time.sleep(1 /
                   fps)  # Nap for a bit so we don't overwhelm the blinkstick.
Exemplo n.º 5
0
def process_user_commands():

    working_flag = True

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen(10)
        conn, addr = s.accept()
        with conn:
            print('Connected by', addr)
            while True:
                data = conn.recv(1024)
                if not data:
                    # conn.sendall(b'empty command')
                    break
                syslog.syslog(syslog.LOG_CRIT, 'chainvu_test data: {0}'.format(data))
                command = data.decode("utf-8")
                if (command == 'led'):
                    led = blinkstick.find_first()
                    led.set_color(name = 'red')
                    #working_flag = False
                    #conn.sendall(b'done')
                    #conn.sendto(b'done', addr)
                else:
                    working_flag = True
Exemplo n.º 6
0
    def __init__(self, channel):
        self.animator = threading.Thread(target=self._animate)
        self.channel = channel
        self.iterator = None
        self.running = False
        self.state = None
        self.last_known_state = None
        self.sleep = 0

        self.max_pwm = 100
        GPIO.setup(channel, GPIO.OUT)  # GPIO pin 25 by default
        self.pwm = GPIO.PWM(channel, self.max_pwm)

        # Find the first BlinkStick
        self.max_brightness = 255
        self.bstick = blinkstick.find_first()
        # Set the color red on the 1st LED of G channel to OFF
        self.led_index = 0
        self.led_channel = 1
        # Ensure the LED is OFF after boot
        self.bstick.set_color(
            channel=self.led_channel,
            index=self.led_index,
            name="black")

        # Default LED colour
        self.base_red = 255
        self.base_green = 0
        self.base_blue = 0
 def __new__(cls, *args, **kwargs):
     led = blinkstick.find_first()
     if InternetCheck() is True:
         print("Internet is up!")
         led.set_color(name="green")
     elif InternetCheck() is False:
         print("Internet is down")
         led.set_color("red")
Exemplo n.º 8
0
 def setup(self):
     """ Setup this sink. Returns True if a BlinkStick is found """
     if not has_blinkstick:
         return False
     self.blinkstick = blinkstick.find_first()
     # TODO support more than one BlinkStick (and configuration)
     if self.blinkstick is not None:
         return True
Exemplo n.º 9
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.º 10
0
 def __init__(self, reader, n, pupdate=None, pcl=None):
     self.lights = []
     for i in range(n):
         self.lights.append(Light(blinkstick.find_first()))
     self.programReader = reader
     if pupdate:
         self.PUPDATE = pupdate
     if pcl:
         self.PCL = pcl
Exemplo n.º 11
0
 def __init__(self):
     """Initializes a BlinkStick controller"""
     try:
         from blinkstick import blinkstick
     except ImportError as e:
         print('Unable to import the blinkstick library')
         print('You can install this library with `pip install blinkstick`')
         raise e
     self.stick = blinkstick.find_first()
Exemplo n.º 12
0
def main():
    ### START OPTIONS ###
    speed = 2  # Overall speed of the animation
    popspeed = 4  # Speed of the flickers/pops
    ### END OPTIONS ###

    # try to find the blinkstick
    try:
        stk = blinkstick.find_first()
        cnt = stk.get_led_count()
        print("It's lit bruv. Press CTRL-C to turn down.")
    # exit if not found
    except:
        print("Blinkstick not detected. Is it plugged in?")
        exit(0)

    #### START MAIN LOOP ####
    errors = 0
    while True:
        data = []
        for i in range(cnt):
            x = time() * speed  # Base speed control
            y = x + i  # For some variation from LED to LED
            z = x * popspeed + i ** 2  # For the sporadic flickering
            hue = (
                (sin(y / 0.4) + sin(y / 0.2) + sin(y / 0.5)) / 6 + 0.5
            ) * 0.06  # Main color
            hueplus = max(
                (sin(z) + sin(z / 3.0) + sin(z / 7.0)) / 5 - 0.4, 0
            )  # Flicker
            r, g, b = hsv_to_rgb(
                min(hue + hueplus, 0.07), 1.0 - hueplus, sin(z) / 8 + 0.875
            )  # Convert to RGB
            # print(hueplus, r, g, b)
            data = data + [
                int(g * 255),
                int(r * 255),
                int(b * 255),
            ]  # Convert to GRB and add to the frame.

        # try to write the colors to the strip
        try:
            stk.set_led_data(0, data)
        # if there's an error, increment the error counter and try again
        except:
            errors += 1
            # if we accumulate more than 10 errors without a successful write,
            # strip is probably unplugged, so exit program
            if errors > 15:
                print("Looks like we've been unplugged!")
                exit(0)
        # else if write successful, reset the error counter
        else:
            errors = 0

        sleep(0.02)  # Nap for a bit so we don't overwhelm the blinkstick.
Exemplo n.º 13
0
def main():
    ### START OPTIONS ###
    speed = 1  # Overall speed of the animation.
    ff_speed = 5  # Speed of the fireflies.
    fps = 50.0  # FPS of the animation. 50 is about the upper limit.
    ### END OPTIONS ###

    # try to find the blinkstick
    try:
        stk = blinkstick.find_first()
        cnt = stk.get_led_count()
        print("It's lit bruv. Press CTRL-C to turn down.")
    # exit if not found
    except:
        print("Blinkstick not detected. Is it plugged in?")
        exit(0)

    #### START MAIN LOOP ####
    errors = 0
    while True:
        data = []
        for i in range(cnt):
            x = time.time() * speed  # Base speed control
            y = x + i  # For a bit of random color for the flies.
            z = x * ff_speed + i**2  # Firefly speed control
            ff_glow = max(
                (sin(z) + sin(z / 3.0) + sin(z / 7.0)) / 5 - 0.4, 0
            )  # Flicker. Honestly with this math I just threw stuff at the wall on desmos.com to see what stuck.
            r, g, b = colorsys.hsv_to_rgb(0.10 + (sin(y) / 32 + 0.03125),
                                          1.0 - ff_glow * 1.3,
                                          ff_glow * 5)  # Convert to RGB.
            # print(hueplus, r, g, b)
            data = data + [
                int(g * 255),
                int(r * 255),
                int(b * 255),
            ]  # Convert to GRB and add to the frame.

        # try to write the colors to the strip
        try:
            stk.set_led_data(0, data)
        # if there's an error, increment the error counter and try again
        except:
            errors += 1
            # if we accumulate more than 10 errors without a successful write,
            # strip is probably unplugged, so exit program
            if errors > 15:
                print("Looks like we've been unplugged!")
                exit(0)
        # else if write successful, reset the error counter
        else:
            errors = 0

        time.sleep(1 /
                   fps)  # Nap for a bit so we don't overwhelm the blinkstick.
def turn_off_sequence(red=0, green=0, blue=255, step=0.1):
    try:
        turn_all_on(red, green, blue)
        led = blinkstick.find_first()
        for i in range(32, -1, -1):
            led.set_color(channel=0, index=i, red=0, green=0, blue=0)
            time.sleep(step)

    except KeyboardInterrupt:
        print("Exiting... Bye!")
        turn_all_off()
 def __init__(self, num_pixels, num_rows=1):
     super().__init__(num_pixels, num_rows)
     """Initializes a BlinkStick controller"""
     try:
         from blinkstick import blinkstick
     except ImportError as e:
         logger.error('Unable to import the blinkstick library')
         logger.error(
             'You can install this library with `pip install blinkstick`')
         raise e
     self.stick = blinkstick.find_first()
def turn_on_sequence(red=0, green=0, blue=255, step=0.1):
    try:
        turn_all_off()
        led = blinkstick.find_first()
        for i in range(1, 32):
            led.set_color(0, i, green, red, blue)
            time.sleep(step)

    except KeyboardInterrupt:
        print("Exiting... Bye!")
        turn_all_off()
Exemplo n.º 17
0
def demo_set_get_block_info(info_block1, info_block2):

    bstick = blinkstick.find_first()

    # set and get device info-block1 here
    bstick.set_info_block1(info_block1)
    print bstick.get_info_block1()

    # set and get device info-block2 here
    bstick.set_info_block2(info_block2)
    print bstick.get_info_block2()
Exemplo n.º 18
0
 def get_blinkstick(self):
     bs = None
     try:
         bs = blinkstick.find_first()
     except:
         # more attempts to get around the blinkstick USB flakiness
         logger.warn('Trying to reset USB device...')
         dev = usb.core.find(find_all=False,
                             idVendor=blinkstick.VENDOR_ID,
                             idProduct=blinkstick.PRODUCT_ID)
         if dev:
             dev.reset()
             logger.warn('Reset USB device')
     return bs
Exemplo n.º 19
0
    def __init__(self):

        try:
            self.bstick = blinkstick.find_first()
        except:
            rospy.logerr('unable to find BlinkStick Square')
            sys.exit(-1)

        rospy.loginfo('connected to BlinkStick Square')

        rospy.Subscriber("set_all_led", ColorRGBA, self.set_all)
        rospy.Subscriber("set_single_led", ColorRGBA, self.set_single)

        self.bstick.morph(channel=0, index=0, red=0, green=40, blue=0)
Exemplo n.º 20
0
 def __init__(self):
     self.cube = blinkstick.find_first()
     self.drawingarea = gtk.DrawingArea()
     self.color = self.drawingarea.get_colormap().alloc_color(0, 255, 0)
     self.colorseldlg = gtk.ColorSelectionDialog("Select Cube Color")
     colorsel = self.colorseldlg.colorsel
     colorsel.set_previous_color(self.color)
     colorsel.set_current_color(self.color)
     colorsel.set_has_palette(True)
     colorsel.set_has_opacity_control(True)
     colorsel.connect("color_changed", self.update_cubecolor)
     colorsel.connect("delete_event", self.bye)
     self.colorseldlg.run()
     self.bye()
Exemplo n.º 21
0
def off():
    if skipBlinkStick:
        if isBlinkStickAttached():
            if resetBlinkStick() is False:
                return
        else:
            return

    bs = blinkstick.find_first()

    if bs is None:
        return False

    for i in range(8):
        bs.set_color(channel=0, index=i, name=None)
Exemplo n.º 22
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.º 23
0
  def __init__(self, bstick=None):
    if not bstick:
      try:
        bstick = blinkstick.find_first()
        print('Blinkstick connected.')
      except IOError as e:
        print('No blinkstick found.')
        raise e
    self.bstick = bstick
    if self.bstick.get_mode() != 2:
      print('Changing to WS2812 mode (mode 2).')
      self.bstick.set_mode(2)

    self.grid = np.zeros((HEIGHT, WIDTH, COLOR_CHANNELS))
    self._update_neopixel()
    print('State initialized.')
Exemplo n.º 24
0
def startup(delay=0.15):
    global startupCompleted

    ping.play()
    bs = blinkstick.find_first()

    if bs is None:
        startupCompleted = True
        #raise BlinkStickNotConnected
        return False

    for i in range(8):
        bs.set_color(channel=0, index=i, name="blue")
        time.sleep(delay)

    startupCompleted = True
Exemplo n.º 25
0
def main():
    fps = 50.0  # How many frames per second. 50 is about the upper limit.
    colorin = Color("#b71500")
    colorout = Color("black")

    ### END OPTIONS ###

    stk = blinkstick.find_first()
    cnt = stk.get_led_count()

    while True:
        mult = 0
        last = colorout
        while (
                last.hex != colorin.hex
        ):  # For some reason if I use anything but .hex, they'll never equal the same color.
            last = Color(rgb=(
                (last.red * 5 + colorin.red) / 6,
                (last.green * 5 + colorin.green) / 6,
                (last.blue * 5 + colorin.blue) / 6,
            ))
            data = [
                int(last.green * 255),
                int(last.red * 255),
                int(last.blue * 255),
            ] * cnt
            stk.set_led_data(0, data)
            sleep(1 / fps)
            print("breathe in", last)
        print("pause", last)
        sleep(1 / fps * 7)
        while (
                last.hex != colorout.hex and last.luminance > 0.004
        ):  # For fading to black, this helps a bit since the blinkstick completely blanks out at low brightness levels.
            last = Color(rgb=(
                (last.red * 6 + colorout.red) / 7,
                (last.green * 6 + colorout.green) / 7,
                (last.blue * 6 + colorout.blue) / 7,
            ))
            data = [
                int(last.green * 255),
                int(last.red * 255),
                int(last.blue * 255),
            ] * cnt
            stk.set_led_data(0, data)
            sleep(1 / fps)
            print("breathe out", last)
Exemplo n.º 26
0
def process_user_commands():

    working_flag = True

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
    sock.bind((IP, PORT))

    while working_flag:
        data = sock.recvfrom(1024)
        syslog.syslog(syslog.LOG_CRIT, 'chainvu_test data: {0}'.format(data))

        command = data[0]

        if (command == 'led'):
            led = blinkstick.find_first()
            led.set_color(name='red')
            working_flag = False
def snake(red=0, green=0, blue=255, size=3, cicles=9, speed=0.1):
    try:
        led = blinkstick.find_first()
        for i in range(cicles):
            head = 0
            while head < 32:
                for j in range(0, 32):
                    if head >= j > head - size:
                        led.set_color(0, j, green, red, blue)
                    else:
                        led.set_color(0, j, 0, 0, 0)
                time.sleep(speed)
                head += 1

    except KeyboardInterrupt:
        print("Exiting... Bye!")
        turn_all_off()
Exemplo n.º 28
0
def main():
    ### START OPTIONS ###
    fps = 50.0  # FPS of the animation. 50 is about the upper limit.
    speed = 1  # Speed of animation
    type = 1.0  # "1" for hard edges on colors, "1.0" for smooth fading.
    brightness = 1.0  # Brightness of animation, from 0 to 1
    ### END OPTIONS ###

    # try to find the blinkstick
    try:
        stk = blinkstick.find_first()
        cnt = stk.get_led_count()
        print("It's lit bruv. Press CTRL-C to turn down.")
    # exit if not found
    except:
        print("Blinkstick not detected. Is it plugged in?")
        exit(0)

    #### START MAIN LOOP ####
    errors = 0
    while True:
        data = []
        # choose and set the colors
        for i in range(1, cnt + 1):
            (r, g, b) = hsv_to_rgb(
                (sin(time() / (8.0 / speed) + i / (4 * type)) + 1) / 2, 1,
                brightness)
            data = data + [int(g * 255), int(r * 255), int(b * 255)]

        # try to write the colors to the strip
        try:
            stk.set_led_data(0, data)
        # if there's an error, increment the error counter and try again
        except:
            errors += 1
            # if we accumulate more than 10 errors without a successful write,
            # strip is probably unplugged, so exit program
            if errors > 250:
                print("Looks like we've been unplugged!")
                exit(0)

        # else if write successful, reset the error counter
        else:
            errors = 0

        sleep(1 / fps)
Exemplo n.º 29
0
def fail(delay=0.1):

    buzz.play()

    if skipBlinkStick:
        if isBlinkStickAttached():
            if resetBlinkStick() is False:
                return
        else:
            return

    bs = blinkstick.find_first()

    if bs is None:
        return False

    for i in range(8):
        bs.set_color(channel=0, index=i, name="red")
        time.sleep(delay)
Exemplo n.º 30
0
def loop_square():
    call(['sudo', 'amixer', 'cset', 'numid=3', '1'])
    bstick = blinkstick.find_first()
    pygame.init()
    SONG_END = pygame.USEREVENT + 1

    pygame.mixer.music.set_endevent(SONG_END)
    pygame.mixer.music.load('/home/pi/Projects/b_square/TARDIS.mp3')

    pygame.mixer.music.play()

    print 'Playing song'
    while pygame.mixer.music.get_busy() == True:
        for x in range(0, 8):
            if x >= 1: bstick.set_color(channel=0, index=(x - 1))
            if x < 8: bstick.set_color(channel=0, index=x, name="white")
            time.sleep(0.05)
        continue
    turn_off_square()
Exemplo n.º 31
0
def main():
    speed = 1  # 2 is 2x speed, .5 is half speed, you get the idea.
    fps = 50.0  # Frames per second of the animation. 50 is about the upper limit.
    cut = 2  # how much of the spectrum to show. 1 = full spectrum, 2 = 2 full spectrums, .5 is half a spectrum.
    brightness = 1.0  # Brightness of animation from 0 to 1

    stk = blinkstick.find_first()
    cnt = stk.get_led_count()

    while True:
        data = []
        for i in range(1, cnt + 1):
            (r, g,
             b) = hsv_to_rgb(i / float(cnt * (1.0 / cut)) + time() * speed, 1,
                             brightness)
            data = data + [int(g * 255), int(r * 255), int(b * 255)]
            # print(int(r*255), int(g*255), int(b*255), i/32.0,)
        stk.set_led_data(0, data)
        sleep(1 / fps)
Exemplo n.º 32
0
def pingSuccess(hold=0.50):
    global skipBlinkStick

    if skipBlinkStick:
        if isBlinkStickAttached():
            if resetBlinkStick() is False:
                return
        else:
            return
    skipBlinkStick = False
    bs = blinkstick.find_first()

    if bs is None:
        return False

    bs.set_color(channel=0, index=0, name=None)
    time.sleep(hold)
    bs.set_color(channel=0, index=0, name="blue")
    time.sleep(hold)
Exemplo n.º 33
0
    def __init__(self, app=None):
        """
        Sets up everything required, connects with the blinkstick and registers with the app

        :param app: flask-app to register with
        """
        Thread.__init__(self)
        self.daemon = True
        self.queue = Queue()
        self.running = False

        # Find blinckstick and set mode
        self.led = blinkstick.find_first()
        if self.led is not None:
            self.led.set_mode(3)
        else:
            raise Exception('Blinkstick not found')

        if app is not None:
            self.init_app(app)
Exemplo n.º 34
0
    def __init__(self):
        # initialize the blinkstick
        self.vision_led = blinkstick.find_first()

        # set initial states
        self.state = rospy.get_param("~state_init", "Idle")
        self.state_last = ""
        self.cmd_state = rospy.get_param("~cmd_state_init", "Idle")

        # flag that indicates whether haptic tether is enables
        # 0 - Teleoperation
        # 1 - Autonomous
        # 2 - Haptic Tether
        # 3 - Training
        self.follower_mode = 3

        # timer for state machine
        self.cmd_state_timer = rospy.get_time()
        self.cmd_state_period = 0.0

        # time in following mode
        self.dt_following = 0.0

        # loop counters
        self.stuck_count = 0
        self.stuck_backup_count = 0
        self.lost_vision_count = 0
        self.too_fast_count = 0
        self.slow_down_count = 0
        self.too_fast_pause_count = 0

        self.flag_too_fast_check_pause = False

        self.stuck_backup_count_limit = 50
        self.stuck_count_limit = rospy.get_param("~stuck_count_limit", 20)
        self.lost_vision_count_limit = rospy.get_param("~lost_vision_count_limit", 25)
        self.too_fast_count_limit_low = rospy.get_param("~too_fast_count_limit_low", 25)
        self.too_fast_count_limit_high = rospy.get_param("~too_fast_count_limit_high", 45)
        self.too_fast_pause_count_limit = rospy.get_param("~too_fast_pause_count_limit", 65)
        self.slow_down_count_limit = rospy.get_param("~slow_down_count_limit", 25)
        self.turtlebot_vel_max = rospy.get_param("~turtlebot_vel_max", 0.7)
        self.turtlebot_angvel_max = rospy.get_param("~turtlebot_angvel_max", np.pi)

        # a little bit of hysteresis
        self.too_fast_threshold_low = rospy.get_param("~too_fast_threshold_low", self.turtlebot_vel_max * 1.4)
        self.too_fast_threshold_high = rospy.get_param("~too_fast_threshold_high", self.turtlebot_vel_max * 1.5)

        # desired velocity for publish
        self.cmd_vel = Twist()
        self.measured_vel = Twist()

        # teleoperation parameters
        self.tele_vel = Twist()
        self.tele_vel.linear.x = rospy.get_param("~default_teleop_vel_linear", 0.3)
        self.tele_vel_inc_linear = rospy.get_param("~telop_vel_increment_linear", 0.01)

        # bumper variable
        self.bumper_event = BumperEvent()

        # human tracking variables
        self.human_pose = Pose2D()
        self.human_vel = Vector3()
        self.track_status = "Lost"

        # human input variables
        self.human_input_tilt = Vector3()  # roll, pitch, yaw
        self.human_input_gesture = -1  # 10 means no gesture input

        self.flag_button_pressed = False
        self.flag_latch_cmd_vel = False
        self.human_input_mode = rospy.get_param("~human_input_mode", "tilt_control")

        # state machine control
        self.set_state = -1  # < 0 means no set state command
        self.set_cmd_state = -1

        # variables for follower control
        self.dist_desired = rospy.get_param("~dist_desired_follower", 1.0)
        self.kp_linear = rospy.get_param("~kp_linear", 1.0)
        self.kd_linear = rospy.get_param("~kd_linear", 0.1)
        self.kb_linear = rospy.get_param("~kb_linear", 0.1)
        self.kp_angular = rospy.get_param("~kp_angular", 2.0)
        self.kd_angular = rospy.get_param("~kd_angular", 0.2)
        self.kb_angular = rospy.get_param("~kb_angular", 0.2)

        self.dist_range_min = rospy.get_param("~dist_range_min", 0.3)
        self.dist_range_max = rospy.get_param("~dist_range_max", 1.9)

        self.dist_stuck_resume_max = rospy.get_param("~dist_stuck_resume_max", 1.0)

        # variables for tilt control
        self.pitch_to_linear_scale = rospy.get_param("~roll_to_linear_scale", 1.0)
        self.roll_to_angular_scale = rospy.get_param("~pitch_to_angular_scale", -2.0)
        self.pitch_deadband = rospy.get_param("~pitch_deadband", 0.2)
        self.roll_deadband = rospy.get_param("~roll_deadband", 0.2)
        self.pitch_offset = rospy.get_param("~pitch_offset", 0.15)
        self.roll_offset = rospy.get_param("~roll_offset", 0.1)
        self.roll_center_offset = rospy.get_param("~roll_center_offset", 0.0)
        self.pitch_center_offset = rospy.get_param("~pitch_center_offset", 0.0)
        self.flag_reverse_mapping = rospy.get_param("~reverse_mapping", False)

        # variables for the autonomous turning
        self.measured_pose = Odometry()
        self.pos_init_pre_turning = Pose2D()
        self.dist_pre_turning = 0.0
        self.angle_turning = np.pi / 2.0
        self.angle_turning_goal = 0.0
        self.tilt_turning_thresh = 0.75

        # turning direction, 0 - no turning, 1 - turning left, 2 - turning right
        self.dir_turning = 0

        # subscribers to human tracking
        self.human_pose_sub = rospy.Subscriber("tracking/human_pos2d",
                                               Pose2D, self.human_track_pose_cb)
        self.human_vel_sub = rospy.Subscriber("tracking/human_vel2d",
                                              Vector3, self.human_track_vel_cb)
        self.track_status_sub = rospy.Subscriber("tracking/status",
                                                 String, self.human_track_status_cb)
        self.odom_sub = rospy.Subscriber("odom",
                                         Odometry, self.odom_cb)
        # subscribers to human input
        self.human_input_ort_sub = rospy.Subscriber("human_input/tilt",
                                                    Vector3, self.human_input_tilt_cb)
        self.human_input_gesture_sub = rospy.Subscriber("human_input/gesture",
                                                        Int8, self.human_input_gesture_cb)
        self.human_input_mode_sub = rospy.Subscriber("human_input/button",
                                                     Bool, self.human_input_mode_cb)
        self.button_event_sub = rospy.Subscriber("human_input/button_event",
                                                 Int8, self.button_event_cb)

        # subscriber to reverse mapping
        self.reverse_mapping_sub = rospy.Subscriber("human_input/reverse_mapping",
                                                    Bool, self.reverse_mapping_cb)

        # subscriber to state control
        self.state_control_sub = rospy.Subscriber("state_control/set_state",
                                                  Int8, self.set_state_cb)
        self.cmd_state_control_sub = rospy.Subscriber("cmd_state_control/set_state",
                                                      Int8, self.set_cmd_state_cb)
        # subscriber to haptic tether control
        self.follower_mode_control_sub = rospy.Subscriber("state_control/set_follower_mode",
                                                          Int8, self.follower_mode_control_cb)

        # subscribe to the bumper event
        self.bumper_event_sub = rospy.Subscriber("mobile_base/events/bumper",
                                                 BumperEvent, self.bumper_event_cb)

        # publisher to robot velocity
        self.robot_state_pub = rospy.Publisher("robot_follower_state",
                                               Int8, queue_size=1)
        self.robot_vel_pub = rospy.Publisher("cmd_vel",
                                             Twist, queue_size=1)
        self.haptic_msg_pub = rospy.Publisher("haptic_control",
                                              haptic_msg, queue_size=1)

        # publisher to system message
        self.sys_msg_pub = rospy.Publisher("sys_message",
                                           String, queue_size=1)
Exemplo n.º 35
0
class BothMode(BlinkstickNanoMode):
    def inbox_item_received(self, inbox_item):
        r, g, b = image_helper.get_random_rgb()

        for led in range(2):
            _blinkstick.set_color(channel=0, index=led, red=r, green=g, blue=b)

    def lights(self):
        r, g, b = image_helper.get_random_rgb()

        for led in range(2):
            _blinkstick.set_color(channel=0, index=led, red=r, green=g, blue=b)
        time.sleep(1)


_blinkstick = blinkstick.find_first()

for led in range(2):
    _blinkstick.set_color(channel=0, index=led, red=0, green=0, blue=0)

_modes = itertools.cycle([
    AlternateMode(),
    BothMode()
])
_mode = next(_modes)


def lights():
    _mode.lights()

#! /usr/bin/python
import re
import signal
import sys
import time
import requests
from threading import Event, Thread
from jenkinsapi.jenkins import Jenkins
from jenkinsapi.utils.requester import Requester
from blinkstick import blinkstick

# preset configuration
JENKINS_URL = 'https://jenkins.midvale.leedsdev.net/'
DISABLE_SSL_VERIFY = True

led = blinkstick.find_first()
current_time = lambda: int(time.time())
found_running_job = False
thread_status_stop = thread_status = None


def get_server_instance():
    jenkins_url = JENKINS_URL
    while True:
        try:
            if DISABLE_SSL_VERIFY == True:
                requests.packages.urllib3.disable_warnings()
                return Jenkins(jenkins_url,requester=Requester("","",baseurl=jenkins_url,ssl_verify=False))
            else:
                return Jenkins(jenkins_url)
        except ConnectionError: