Exemple #1
0
def main():
    msg = "Neopixel WS2812 LED Matrix Demo"
    show_message(device, msg, y_offset=-1, fill="green", font=proportional(TINY_FONT))
    time.sleep(1)

    with canvas(device) as draw:
        text(draw, (0, -1), txt="A", fill="red", font=TINY_FONT)
        text(draw, (4, -1), txt="T", fill="green", font=TINY_FONT)

    time.sleep(1)

    with canvas(device) as draw:
        draw.line((0, 0, 0, device.height), fill="red")
        draw.line((1, 0, 1, device.height), fill="orange")
        draw.line((2, 0, 2, device.height), fill="yellow")
        draw.line((3, 0, 3, device.height), fill="green")
        draw.line((4, 0, 4, device.height), fill="blue")
        draw.line((5, 0, 5, device.height), fill="indigo")
        draw.line((6, 0, 6, device.height), fill="violet")
        draw.line((7, 0, 7, device.height), fill="white")

    time.sleep(4)

    for _ in range(5):
        for intensity in range(16):
            device.contrast(intensity * 16)
            time.sleep(0.1)

    device.contrast(0x80)
    time.sleep(1)

    gfx(device)
Exemple #2
0
def main():
    colors = [
        "red",
        "orange",
        "yellow",
        "green",
        "blue",
        "indigo",
        "violet",
        "white"
    ]

    for color in colors:
        with canvas(device) as draw:
            draw.line(device.bounding_box, fill=color)
        time.sleep(2)

    device.contrast(0x30)
    for _ in range(80):
        with canvas(device) as draw:
            for x, color in enumerate(colors):
                draw.point((x, 0), fill=color)

        colors = rotate(colors)
        time.sleep(0.2)

    time.sleep(4)

    device.contrast(0x80)
    time.sleep(1)
    device.contrast(0x10)
    time.sleep(1)
def ShutdownAndHalt():
    print "Received a Halt - shutting down"
    device.contrast(200)
    Ledallon()
    time.sleep(1)
    with canvas(device) as draw:
        #print "Handling 101-lamp_AUX_FUEL_LOW"
        draw.point((1, 7 ), 1)
        #print "Handling 102-lamp_XMSN_OIL_PRESS"
        draw.point((1, 6 ), 1)
        #print "Handling 103-lamp_XMSN_OIL_HOT"
        draw.point((1, 5 ), 1)
        #print "Handling 104-lamp_HYD_PRESSURE"
        draw.point((1, 4 ), 1)
        #print "Handling 105-lamp_ENGINE_INLET_AIR"
        draw.point((1, 3 ), 1)
        #print "Handling 106-lamp_INST_INVERTER"
        draw.point((1, 2 ), 1)
        #print "Handling 107-lamp_DC_GENERATOR"
        draw.point((1, 1 ), 1)
        #print "Handling 108-lamp_EXTERNAL_POWER"
        draw.point((1, 0 ), 1)
        #print "Handling 109-lamp_CHIP_DETECTOR"
        draw.point((3, 1 ), 1)
        #print "Handling 110-lamp_IFF"
        draw.point((3, 0 ), 1)


    time.sleep(1)
    GPIO.cleanup()       # clean up GPIO on CTRL+C exit
    os.system("shutdown now -h")
    sys.exit(0)
Exemple #4
0
def test_greyscale_display():
    """
    SSD1322_NHD OLED screen can draw and display a greyscale image.
    """
    device = ssd1322_nhd(serial, mode="RGB")
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command.side_effect = command
    serial.data.side_effect = data

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    assert serial.data.called
    assert serial.command.called

    assert recordings == [
        {'command': [21]}, {'data': [28, 91]},
        {'command': [117]}, {'data': [0, 63]},
        {'command': [92]}, {'data': get_json_data('demo_ssd1322_nhd_greyscale')}
    ]
Exemple #5
0
def gfx(device):
    effects = [tunnel, rainbow_search, checker, swirl]

    step = 0
    while True:
        for i in range(500):
            with canvas(device) as draw:
                for y in range(device.height):
                    for x in range(device.width):
                        r, g, b = effects[0](x, y, step)
                        if i > 400:
                            r2, g2, b2 = effects[-1](x, y, step)

                            ratio = (500.00 - i) / 100.0
                            r = r * ratio + r2 * (1.0 - ratio)
                            g = g * ratio + g2 * (1.0 - ratio)
                            b = b * ratio + b2 * (1.0 - ratio)
                        r = int(max(0, min(255, r)))
                        g = int(max(0, min(255, g)))
                        b = int(max(0, min(255, b)))
                        draw.point((x, y), (r, g, b))

            step += 1

            time.sleep(0.01)

        effect = effects.pop()
        effects.insert(0, effect)
Exemple #6
0
def test_settext_nocolor():
    neoseg = neosegment(width=6, device=dummy(width=6, height=7))
    neoseg.text = "888888"
    ref = dummy(width=6, height=7)
    with canvas(ref) as draw:
        draw.rectangle(ref.bounding_box, fill="white")
    assert_identical_image(ref.image, neoseg.device.image)
Exemple #7
0
def test_display():
    """
    SH1106 OLED screen can draw and display an image.
    """
    device = sh1106(serial)
    serial.reset_mock()

    recordings = []

    def data(data):
        recordings.append({'data': data})

    def command(*cmd):
        recordings.append({'command': list(cmd)})

    serial.command = Mock(side_effect=command, unsafe=True)
    serial.data = Mock(side_effect=data, unsafe=True)

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    serial.data.assert_called()
    serial.command.assert_called()

    assert recordings == get_json_data('demo_sh1106')
Exemple #8
0
def test_contrast():
    device = unicornhathd(serial)
    with canvas(device) as draw:
        draw.rectangle(device.bounding_box, outline="white", fill="white")
    serial.reset_mock()
    device.contrast(0x6B)
    serial.data.assert_called_once_with([0x72] + [0x6B] * 256 * 3)
Exemple #9
0
def main():
    # Setup for Banggood version of 4 x 8x8 LED Matrix (https://bit.ly/2Gywazb)
    serial = spi(port=0, device=0, gpio=noop())
    device = max7219(serial, cascaded=4, block_orientation=-90, blocks_arranged_in_reverse_order=True)
    device.contrast(16)

    # The time ascends from the abyss...
    animation(device, 8, 1)

    toggle = False  # Toggle the second indicator every second
    while True:
        toggle = not toggle
        sec = datetime.now().second
        if sec == 59:
            # When we change minutes, animate the minute change
            minute_change(device)
        elif sec == 30:
            # Half-way through each minute, display the complete date/time,
            # animating the time display into and out of the abyss.
            full_msg = time.ctime()
            animation(device, 1, 8)
            show_message(device, full_msg, fill="white", font=proportional(CP437_FONT))
            animation(device, 8, 1)
        else:
            # Do the following twice a second (so the seconds' indicator blips).
            # I'd optimize if I had to - but what's the point?
            # Even my Raspberry PI2 can do this at 4% of a single one of the 4 cores!
            hours = datetime.now().strftime('%H')
            minutes = datetime.now().strftime('%M')
            with canvas(device) as draw:
                text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT))
                text(draw, (15, 1), ":" if toggle else " ", fill="white", font=proportional(TINY_FONT))
                text(draw, (17, 1), minutes, fill="white", font=proportional(CP437_FONT))
            time.sleep(0.5)
Exemple #10
0
def test_display():
    device = neopixel(ws, width=4, height=4)
    ws.reset_mock()

    with canvas(device) as draw:
        draw.rectangle(device.bounding_box, outline="red")

    ws.ws2811_led_set.assert_has_calls([
        call(chan, 0, 0xFF0000),
        call(chan, 1, 0xFF0000),
        call(chan, 2, 0xFF0000),
        call(chan, 3, 0xFF0000),
        call(chan, 4, 0xFF0000),
        call(chan, 5, 0x000000),
        call(chan, 6, 0x000000),
        call(chan, 7, 0xFF0000),
        call(chan, 8, 0xFF0000),
        call(chan, 9, 0x000000),
        call(chan, 10, 0x000000),
        call(chan, 11, 0xFF0000),
        call(chan, 12, 0xFF0000),
        call(chan, 13, 0xFF0000),
        call(chan, 14, 0xFF0000),
        call(chan, 15, 0xFF0000),
    ])
    assert ws.ws2811_render.called
def LedMap():
    print("Walking Led Array")
    for y in range(8):
        for x in range(8):              
             with canvas(device) as draw:
                print x, ' ' , y 
                draw.point((x, y ), 1)
                raw_input("Press Enter to continue:")
Exemple #12
0
 def draw_processing_count(self):
     if not self.display_anim:
         with canvas(self.device) as draw:
             for i in range(0,self.processing_count):
                 if self.show_grec_bool:
                     draw.point((7,7-i), fill="white")
                 else:
                     draw.point((0,i), fill="white")
Exemple #13
0
def stats(oled):
    font = ImageFont.load_default()
    font2 = ImageFont.truetype('c-and-c.ttf', 12)
    with canvas(oled) as draw:
        draw.text((0, 00), myip('wlan0'), font=font2, fill=255)
        draw.text((0, 14), mem_usage(), font=font2, fill=255)
        draw.text((0, 26), disk_usage('/'), font=font2, fill=255)
        draw.text((0, 38), network('wlan0'), font=font2, fill=255)
        draw.text((0, 50), cpu_usage(), font=font2, fill=255)
def Ledallon():
    print("Leds all on")

    for abc in range(1):
        with canvas(device) as draw:
            for y in range(8):
                for x in range(8):
                    draw.point((x, y ), 1)                
    print("Finished Leds all on")   
Exemple #15
0
def test_settext_replacechars():
    neoseg = neosegment(width=6, device=dummy(width=6, height=7))
    neoseg.text = "888888"
    neoseg.text[2:4] = "  "
    ref = dummy(width=6, height=7)
    with canvas(ref) as draw:
        draw.rectangle(ref.bounding_box, fill="white")
        draw.rectangle([2, 0, 3, 6], fill="black")
    assert_identical_image(ref.image, neoseg.device.image)
Exemple #16
0
def test_display_fail():
    device = neopixel(ws, cascaded=7)
    ws.reset_mock()
    ws.ws2811_render = Mock(return_value=-1)

    with pytest.raises(RuntimeError) as ex:
        with canvas(device) as draw:
            draw.rectangle(device.bounding_box, outline="red")

    assert "ws2811_render failed with code -1" in str(ex.value)
def main():
    device = get_device()

    print("Testing basic canvas graphics...")
    for _ in range(2):
        with canvas(device) as draw:
            primitives(device, draw)
    time.sleep(5)

    print("Testing contrast (dim/bright cycles)...")
    for _ in range(5):
        for level in range(255, -1, -10):
            device.contrast(level)
            time.sleep(0.1)
        time.sleep(0.5)

        for level in range(0, 255, 10):
            device.contrast(level)
            time.sleep(0.1)

        time.sleep(1)

    print("Testing display ON/OFF...")
    for _ in range(5):
        time.sleep(0.5)
        device.hide()

        time.sleep(0.5)
        device.show()

    print("Testing clear display...")
    time.sleep(2)
    device.clear()

    print("Testing screen updates...")
    time.sleep(2)
    for x in range(40):
        with canvas(device) as draw:
            now = datetime.datetime.now()
            draw.text((x, 4), str(now.date()), fill="white")
            draw.text((10, 16), str(now.time()), fill="white")
            time.sleep(0.1)
Exemple #18
0
def test_unknown_char():
    neoseg = neosegment(width=6, device=dummy(width=6, height=7))
    neoseg.text = "888888"
    neoseg.text[2:4] = "&\x7f"
    neoseg.color[2:4] = ["orange", "orange"]
    ref = dummy(width=6, height=7)
    with canvas(ref) as draw:
        draw.rectangle(ref.bounding_box, fill="white")
        draw.rectangle([2, 0, 3, 6], fill="black")
        draw.rectangle([2, 1, 3, 1], fill="orange")
    assert_identical_image(ref.image, neoseg.device.image)
def Ledalloff():
    print("Leds all off")

    for abc in range(1):
        with canvas(device) as draw:
            for y in range(8):
                for x in range(8):
                    draw.point((x, y ), 0)
                
        time.sleep(0.1)
                
    print("Finished Leds all off")  
Exemple #20
0
def demo(w, h, block_orientation, rotate):
    # create matrix device
    serial = spi(port=0, device=0, gpio=noop())
    device = max7219(serial, width=w, height=h, rotate=rotate, block_orientation=block_orientation)
    print("Created device")

    with canvas(device) as draw:
        draw.rectangle(device.bounding_box, outline="white")
        text(draw, (2, 2), "Hello", fill="white", font=proportional(LCD_FONT))
        text(draw, (2, 10), "World", fill="white", font=proportional(LCD_FONT))

    time.sleep(300)
Exemple #21
0
 def emotion(self,data):
     emo_type = data.type
     if (emo_type==disp_emotion.POSITIVE):
         with canvas(self.device) as draw:
             text(draw, (0, 0), chr(1), fill="white")
             draw.point((3,4), fill="black")
             draw.point((4,4), fill="black")
     if (emo_type==disp_emotion.NEGATIVE):
         with canvas(self.device) as draw:
             text(draw, (0, 0), chr(1), fill="white")
             draw.point((2,4), fill="black")
             draw.point((5,4), fill="black")
             draw.point((3,5), fill="black")
             draw.point((4,5), fill="black")
             draw.point((2,5), fill="white")
             draw.point((5,5), fill="white")
     if (emo_type==disp_emotion.HAPPY):
         with canvas(self.device) as draw:
             text(draw, (0, 0), chr(1), fill="white")
     rospy.sleep(data.duration)
     self.disable_disp()
Exemple #22
0
def animation(device, from_y, to_y):
    '''Animate the whole thing, moving it into/out of the abyss.'''
    hourstime = datetime.now().strftime('%H')
    mintime = datetime.now().strftime('%M')
    current_y = from_y
    while current_y != to_y:
        with canvas(device) as draw:
            text(draw, (0, current_y), hourstime, fill="white", font=proportional(CP437_FONT))
            text(draw, (15, current_y), ":", fill="white", font=proportional(TINY_FONT))
            text(draw, (17, current_y), mintime, fill="white", font=proportional(CP437_FONT))
        time.sleep(0.1)
        current_y += 1 if to_y > from_y else -1
def LedRandom():
    print "Starting Drawing Random" 

    for abc in range(1):
        with canvas(device) as draw:
            for y in range(8):
                for x in range(8):
                    draw.point((x, y ), randint(0,1))
                
        time.sleep(0.1)
                
    print "Finished Drawing Random"       
Exemple #24
0
    def action(self,data):
        action_type=data.type
        self.stop_disp(False)
        if (action_type==disp_action.MUSIC):
            with canvas(self.device) as draw:
                text(draw, (0, 0), chr(14), fill="white")
        if (action_type==disp_action.SPEAKING):
            self.display_anim=True
            while(self.display_anim):
                with canvas(self.device) as draw:
                    val=self.sin_func(self.shift_counter,self.peak_counter)
                    self.shift_counter+=1
                    if self.shift_counter%2 is 0:
                        self.peak_counter=random.randint(1,3)
                    for i in range(0,7):
                        draw.point((i,int(val[i])), fill="white")
                    rospy.sleep(0.1)
            self.disable_disp()


        if (action_type==disp_action.PROCESSING):
            self.display_anim=True
            while(self.display_anim):
                for image in [1,2,3,2]:
                    with canvas(self.device) as draw:
                        self.shift_counter+=1
                        for shift in range(1,image+1):
                            for i in range(shift,8-shift):
                                draw.point((i,shift-1), fill="white")

                                draw.point((i,8-shift), fill="white")
                                draw.point((shift-1,i), fill="white")
                                draw.point((8-shift,i), fill="white")
                            draw.point((shift,shift), fill="white")
                            draw.point((7-shift,7-shift), fill="white")
                            draw.point((shift,7-shift), fill="white")
                            draw.point((7-shift,shift), fill="white")
                        self.device.contrast(int(round(255*(math.sin(self.shift_counter%6/5.0*2*math.pi)+1))/2))
                        rospy.sleep(0.12*(math.sin(self.shift_counter%6/5.0*2*math.pi)+1)/2+0.10)
            self.disable_disp()
Exemple #25
0
def test_display():
    device = pcd8544(serial)
    serial.reset_mock()

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    # Initial command to reset the display
    serial.command.assert_called_once_with(32, 128, 64)

    # Next 1024 bytes are data representing the drawn image
    serial.data.assert_called_once_with(get_reference_data('demo_pcd8544'))
Exemple #26
0
def binary_clock(device):
    while True:
        now = datetime.now()
        fields = [now.year - YEAR_OFFSET, now.month, now.day, now.hour, now.minute, now.second]
        points = []
        for i, value in zip(COLUMNS, fields):
            for j in range(device.height):
                mask = 2 ** j
                if value & mask:
                    points.append((i, device.height - 1 - j))
        with canvas(device) as draw:
            draw.point(points, fill='white')
        time.sleep(REFRESH_INTERVAL_SECONDS)
Exemple #27
0
def test_mapping():
    num_pixels = 16
    device = neopixel(ws, cascaded=num_pixels, mapping=reversed(list(range(num_pixels))))
    ws.reset_mock()

    with canvas(device) as draw:
        for i in range(device.cascaded):
            draw.point((i, 0), (i, 0, 0))

    expected = [call(chan, num_pixels - i - 1, i << 16) for i in range(num_pixels)]
    ws.ws2811_led_set.assert_has_calls(expected)

    assert ws.ws2811_render.called
Exemple #28
0
def test_display():
    """
    SSD1309 OLED screen can draw and display an image.
    """
    device = ssd1309(serial)
    serial.reset_mock()

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    # Initial command to reset the display
    serial.command.assert_called_once_with(33, 0, 127, 34, 0, 7)

    # Next 1024 bytes are data representing the drawn image
    serial.data.assert_called_once_with(get_json_data('demo_ssd1309'))
Exemple #29
0
def test_monochrome_display():
    """
    SSD1327 OLED screen can draw and display a monochrome image.
    """
    device = ssd1327(serial, mode="1")
    serial.reset_mock()

    # Use the same drawing primitives as the demo
    with canvas(device) as draw:
        primitives(device, draw)

    # Initial command to reset the display
    serial.command.assert_called_once_with(21, 0, 63, 117, 0, 127)

    # Next 4096 bytes are data representing the drawn image
    serial.data.assert_called_once_with(get_json_data('demo_ssd1327_monochrome'))
Exemple #30
0
def test_16bit_rgb_packing(bit, expected_16_bit_color):
    """
    Checks that 8 bit red component is packed into first 5 bits
    Checks that 8 bit green component is packed into next 6 bits
    Checks that 8 bit blue component is packed into remaining 5 bits
    """
    device = ssd1331(serial)
    serial.reset_mock()

    rgb_color = (2 ** bit,) * 3
    expected = expected_16_bit_color * device.width * device.height

    with canvas(device) as draw:
        draw.rectangle(device.bounding_box, outline=rgb_color, fill=rgb_color)

    serial.data.assert_called_once_with(expected)
Exemple #31
0
def demo(n, block_orientation, rotate):
    # create matrix device
    serial = spi(port=0, device=0, gpio=noop())
    device = max7219(serial,
                     cascaded=n or 1,
                     block_orientation=block_orientation,
                     rotate=rotate or 0)

    # start demo
    msg = "MAX7219 LED Matrix Demo"
    print(msg)
    show_message(device, msg, fill="white", font=proportional(CP437_FONT))
    time.sleep(1)

    msg = "Fast scrolling: This is very fast and impossible to read"
    msg = re.sub(" +", " ", msg)
    print(msg)
    show_message(device,
                 msg,
                 fill="white",
                 font=proportional(LCD_FONT),
                 scroll_delay=0)
    time.sleep(1)

    msg = "Slow Scrolling"
    print(msg)
    show_message(device,
                 msg,
                 fill="white",
                 font=proportional(LCD_FONT),
                 scroll_delay=0.1)
    time.sleep(1)

    print("Vertical Scrolling")
    words = [
        "Victor", "Echo", "Romeo", "Tango", "India", "Charlie", "Alpha",
        "Lima", " ", "Sierra", "Charlie", "Romeo", "Oscar", "Lima", "Lima",
        "India", "November", "Golf", " "
    ]

    virtual = viewport(device, width=device.width, height=len(words) * 8)
    with canvas(virtual) as draw:
        for i, word in enumerate(words):
            text(draw, (0, i * 8),
                 word,
                 fill="white",
                 font=proportional(CP437_FONT))

    for i in range(virtual.height - device.height):
        virtual.set_position((0, i))
        time.sleep(0.05)

    msg = "Brightness"
    print(msg)
    show_message(device, msg, fill="white")

    time.sleep(1)
    with canvas(device) as draw:
        text(draw, (0, 0), "A", fill="white")

    time.sleep(1)
    for _ in range(5):
        for intensity in range(16):
            device.contrast(intensity * 16)
            time.sleep(0.1)

    device.contrast(0x80)
    time.sleep(1)

    msg = "Alternative font!"
    print(msg)
    show_message(device, msg, fill="white", font=SINCLAIR_FONT)

    time.sleep(1)
    msg = "Proportional font - characters are squeezed together!"
    print(msg)
    show_message(device, msg, fill="white", font=proportional(SINCLAIR_FONT))
    # http://www.squaregear.net/fonts/tiny.shtml
    time.sleep(1)

    msg = "This is smallest possible font"
    msg = re.sub(" +", " ", msg)
    print(msg)
    show_message(device, msg, fill="white", font=proportional(TINY_FONT))
    time.sleep(1)

    #All the characters present are displayed
    msg = "CP437 Characters"
    print(msg)
    show_message(device, msg)

    time.sleep(1)
    for x in range(256):
        with canvas(device) as draw:
            text(draw, (0, 0), chr(x), fill="white")
            time.sleep(0.1)

    msg = "MAXPI"
    print(msg)
    show_message(device,
                 msg,
                 fill="white",
                 font=proportional(CP437_FONT),
                 scroll_delay=0.1)
    time.sleep(1)
Exemple #32
0
def show(c="^ 3 ^",
         forceSingle=False,
         speed=25,
         timeout=10,
         vibe=None,
         overflow=True,
         font=SMALL_FONT,
         fontPadding=0,
         fill=1,
         quiet=False):
    v = loop(0), loop(0)
    c = str(c)
    d = int(device.size[0] / (font.size - 1 + fontPadding))
    isTwoRows = not forceSingle and font.size - 1 <= device.size[
        1] / 2 and len(c) > d
    overflow = overflow and (font.getsize(c)[0] > device.size[0]
                             if not isTwoRows else
                             font.getsize(c[d:])[0] > device.size[0])
    count = 0
    if overflow:
        if vibe is None:
            vibe = [0, 0]
        if not isTwoRows:
            vibe[0] = font.getsize(c)[0] - device.size[0]
        else:
            vibe[1] = font.getsize(c[d:])[0] - device.size[0]
        v = loop(
            vibe_range(device.size[0],
                       font.getsize(c[:d] if isTwoRows else c)[0], vibe[0]
                       ) if not isTwoRows and overflow else
            int(above(device.size[0] - font.getsize(c)[0], 0) / 2)), loop(
                vibe_range(device.size[0],
                           font.getsize(c[d:])[0], vibe[1]))
    else:
        if isTwoRows:
            if len(c) > d * 2:
                c = c[len(c) - d * (2 if isTwoRows else 1):]
        elif font.getsize(c)[0] > device.size[0]:
            v = loop(device.size[0] - font.getsize(c)[0]), loop(0)
    if not quiet:
        print("\r|" + c[:d] + "|",
              "|" + c[d:][:d] + "|" if isTwoRows and c[d:] else "",
              flush=True,
              end="")
    while True:
        with canvas(device) as draw:
            draw.text(
                (v[0].__next__(), -fontPadding + (0 if isTwoRows else int(
                    (device.size[1] - font.size + 1) / 2))),
                c[:d] if isTwoRows else c,
                fill=fill,
                font=font)
            if isTwoRows and c[d:]:
                draw.text((v[1].__next__(), 4 - fontPadding),
                          c[d:],
                          fill=fill,
                          font=font)
        count += 1
        if (timeout and count * 1 / speed > timeout) or (v[0].isSingle
                                                         and v[1].isSingle):
            break
        time.sleep(1 / speed)
    return "|" + c[:d] + "|", "|" + c[d:][:d] + "|" if isTwoRows and c[
        d:] else ""
Exemple #33
0
    def draw_player(self):
        #while True:

        with canvas(self.device) as draw:
            #basic outline Box and text rendered in portrait mode
            #draw.rectangle(device.bounding_box, outline="white", fill="black")
            D.draw_rectangle(draw, self.device)
            self.Time()
            #date and time
            draw.line((0, 13, 128, 13), fill="white")
            draw.text((2, 1), self.today_date, fill="white")
            draw.text((78, 1), self.today_time, fill="white")
            #info = ctrl.get_music_info()
            #music name, artist and album(may be next music inline)
            if (CF.message):
                draw.text((25, 14),
                          CF.message,
                          font=self.font_basic_8,
                          fill="white")
            else:
                try:
                    draw.text(
                        ((self.device.width / 4.3) - len(CF.music_info[0]),
                         14),
                        CF.music_info[0],
                        font=self.font_basic_8,
                        fill="white")
                    draw.text(
                        ((self.device.width / 3) - len(CF.music_info[1]), 22),
                        CF.music_info[1],
                        font=self.font_basic_8,
                        fill="white")
                    draw.text(((self.device.width / 3) - len(CF.time), 32),
                              CF.time,
                              font=self.font_basic_8,
                              fill="white")
                except:
                    pass

            #text position for music info(can be better) TODO: a Better Scroll
            #c.get_music_info()
            #print(CF.music_info)

            volumetodisplay = str(CF.interval) + "%"
            #print(volumetodisplay)
            volume = CF.interval

            #volume controls status info
            draw.text((25, 50),
                      volumetodisplay,
                      font=self.font_basic_8,
                      fill="white")
            if volume > 1 and volume <= 50:
                draw.text((5, 45),
                          text=self.codes[2],
                          font=self.font_awesome,
                          fill="white")
            if volume > 51 and volume <= 80:
                draw.text((5, 45),
                          text=self.codes[0],
                          font=self.font_awesome,
                          fill="white")
            if volume > 80:
                draw.text((5, 45),
                          text=self.codes[3],
                          font=self.font_awesome,
                          fill="white")
            if volume <= 0:
                draw.text((5, 45),
                          text=self.codes[1],
                          font=self.font_awesome,
                          fill="white")
            if CF.status == "play":
                draw.text((110, 45),
                          text=self.codes[5],
                          font=self.font_awesome,
                          fill="white")
            if CF.status == "pause":
                draw.text((110, 45),
                          text=self.codes[4],
                          font=self.font_awesome,
                          fill="white",
                          contrast=10)
            if CF.second_status == "next":
                draw.text((80, 45),
                          text=self.codes[7],
                          font=self.font_awesome,
                          fill="white",
                          contrast=10)
            if CF.second_status == "prev":
                draw.text((80, 45),
                          text=self.codes[6],
                          font=self.font_awesome,
                          fill="white",
                          contrast=10)
            if CF.random:
                draw.text((50, 45),
                          text=self.codes[8],
                          font=self.font_awesome_small,
                          fill="white",
                          contrast=10)
            if CF.playbackMode == 1:
                draw.text((50, 53),
                          text=self.codes[9],
                          font=self.font_awesome_small,
                          fill="white",
                          contrast=10)
            if CF.playbackMode == 2:
                draw.text((50, 53),
                          text=self.codes[10],
                          font=self.font_awesome_small,
                          fill="white",
                          contrast=10)
            if CF.playbackMode == 0:
                draw.text((50, 53),
                          text="",
                          font=self.font_awesome_small,
                          fill="white",
                          contrast=10)
            if CF.source == 3:
                draw.text((65, 53),
                          text=self.codes[11],
                          font=self.font_awesome_small,
                          fill="white",
                          contrast=10)
            if CF.source == 0:
                draw.text((65, 53),
                          text=self.codes[12],
                          font=self.font_awesome_small,
                          fill="white",
                          contrast=10)
Exemple #34
0
def dispListMenu(device,title,plist,alist,pos,apos=0,vpos=999):
	
	if vpos!=999:
		mlist=plist[vpos:vpos+5]
	else:
		mlist=plist


	#offsets
	xdist=5 #x offset
	yoffset=4
	
	#menu
	width=100 #width of hilight
	#mlist=["list1", "list2","list3","list4","list5"] #will be parameter
	mlistc=["white"]*len(mlist)
	if pos != 0: #setup cursor
		mlistc[pos-1]="black"

	#action menu
	axdist=64
	#alist=["action1", "action2","action3"]
	alistc=["white"]*len(alist)
	if apos != 0:
		alistc[apos-1]="black"



	with canvas(device) as draw:

		#draw title
		draw.rectangle((0,0,128,12), outline="white", fill="white")
		#draw.rectangle((1,10,126,11), outline="black", fill="black")
		draw.text((2,0),title,"black")

		# // STATUS BAR //

		if is_connected()==1:
			draw.rectangle((116,2,124,10), outline="black", fill="black")
		else:
			draw.rectangle((116,2,124,10), outline="black", fill="white")

		# if GPIO.event_detected(lowBat):
		# 	draw.rectangle((96,3,108,9), outline="black", fill="black")
		# else:
		# 	draw.rectangle((96,3,108,9), outline="black", fill="white")




		if pos != 0:
			draw.rectangle((xdist, pos*10+yoffset, xdist+width, (pos*10)+10+yoffset), outline="white", fill="white")
		
		for idx,line in enumerate(mlist):
			#print("idx: ",idx,"line: ",line,"fill: ",flist[idx])
			draw.text((xdist,(idx+1)*10+yoffset),line,mlistc[idx])

		if apos != 0:

			draw.rectangle((60,13,128,64), outline="black", fill="black")
			draw.rectangle((60,13,61,48), outline="white", fill="white")

			draw.rectangle((axdist, apos*10+yoffset, axdist+width, (apos*10)+10+yoffset), outline="white", fill="white")
		
			for idx,line in enumerate(alist):
				#print("idx: ",idx,"line: ",line,"fill: ",flist[idx])
				draw.text((axdist,(idx+1)*10+yoffset),line,alistc[idx])
Exemple #35
0
def staticText(device, msg):
    with canvas(device) as draw:
        text(draw, (0, 0), msg, fill="white")
    time.sleep(2)
Exemple #36
0
def backupTape(device):

	if is_connected():
		forcedir(MOUNT_DIR)
		mountpath = getmountpath()
		print(" > OP-1 device path: %s" % mountpath)
		mountdevice(mountpath, MOUNT_DIR, 'ext4', 'rw')
		print(" > Device mounted at %s" % MOUNT_DIR)
	print is_connected()

	if os.path.exists(op1path)==1:

		# with canvas(device) as draw:
		# 	draw.text((0,0),"op1 connection success","white")
		# 	draw.text((0,10),"backup track?","white")
		# 	draw.text((0,20),"1-back","white")
		# 	draw.text((0,30),"2-yes","white")
		
		# time.sleep(1)
		drawText(device,["op1 connection success","backup tape?"," -yup"," -back"])

			# 			# sh.copy(spath4,dpath)
			# draw.text((0,40),"Track 4 copied","white")


		print "op1 connection success"
		print "Backup Track?"
		print "  1-back"
		print "  2-continue"



		
		#response loop
		while True:
			if GPIO.event_detected(key['key2']):
				print "copying"
				#draw.text((0,10),"copying","white")
				#draw.text((0,20),"Backup tape?","white")
				#Copy Operation
				cdate=datetime.datetime.now()
				dpath='/home/pi/opc/op1-tapebackups/'+str(datetime.date.today())+" "+cdate.strftime("%I:%M%p")
				spath1=op1path+'/tape/track_1.aif'
				spath2=op1path+'/tape/track_2.aif'
				spath3=op1path+'/tape/track_3.aif'
				spath4=op1path+'/tape/track_4.aif'


				if os.path.exists(dpath)==0:
					os.mkdir(dpath)
				
				# if os.path.exists(spath)==1:
				# 	term.println('file exists')
				# 	time.sleep(.5)
				# 	return   					can't check this now. assuming source directory is real

				drawProgress(device,"backing up tape...",0)

				sh.copy(spath1,dpath)
				print 'Track 1 Copied'
				drawProgress(device,"backing up tape...",.2)

				sh.copy(spath2,dpath)
				print 'Track 2 Copied'
				drawProgress(device,"backing up tape...",.4)

				sh.copy(spath3,dpath)
				print 'Track 3 Copied'
				drawProgress(device,"backing up tape...",.6)

				sh.copy(spath4,dpath)
				print 'Track 4 Copied'
				drawProgress(device,"backing up tape...",.8)

				print(" > Unmounting OP-1")
				unmountdevice(MOUNT_DIR)
				print(" > Done.")
				drawProgress(device,'backing up tape...',1)
				time.sleep(.5)

				return

			elif GPIO.event_detected(key['key1']):
				return
	else:
		print "no op1 detcted"
		print "Is your device connected and in disk mode?"
		print "  1-Return to Menu"
		with canvas(device) as draw:
			draw.text((0,10),"no op1 found","white")
			draw.text((0,20),"1-return to menu","white")
		#term.println("  2-Menu")

		wait(keys,'key1')
		return
Exemple #37
0
def drawProgress(device,title,progress):
	with canvas(device) as draw:
		progpix=progress*64
		draw.text((16,8),title,"white")
		draw.rectangle((32,32,96,42), outline="white", fill="black")
		draw.rectangle((32,32,32+progpix,42), outline="white", fill="white")
def morningStageA():
    with canvas(device) as draw:
        draw.line((0, 0, 152, device.height), fill=(0xf4, 0xa0, 0x29, 0x80))
Exemple #39
0
def draw():
    with canvas(device) as draw:
        text(draw, (10,1), str(states[0]), fill="white", font=proportional(LCD_FONT))
        text(draw, (2,1), str(states[1]), fill="white", font=proportional(LCD_FONT))
def blackout():
    with canvas(device) as draw:
        draw.line((0, 0, 152, device.height), fill=(0x00, 0x00, 0x00, 0x80))
def eveningStageA():
    with canvas(device) as draw:
        draw.line((0, 0, 152, device.height), fill=(0xff, 0xfc, 0xaa, 0x80))
Exemple #42
0
        return({'state':state, 'artist':artist, 'title':title, 'eltime':eltime, 'volume':int(vol), 'audio_info':audio_info})

font = ImageFont.truetype('/root/neoplus2/oled/Verdana.ttf', 47)
font2 = ImageFont.truetype('/root/neoplus2/oled/Verdana.ttf', 13)
font3 = ImageFont.truetype('/root/neoplus2/oled/Verdana.ttf', 23)
font4 = ImageFont.truetype('/root/neoplus2/oled/Arial-Bold.ttf', 20)

os.system('echo "199" > /sys/class/gpio/export')
os.system('echo "out" > /sys/class/gpio/gpio199/direction')
os.system('echo "0" > /sys/class/gpio/gpio199/value')
os.system('echo "198" > /sys/class/gpio/export')
os.system('echo "out" > /sys/class/gpio/gpio198/direction')
os.system('echo "0" > /sys/class/gpio/gpio198/value')
os.system('echo "0" > /sys/class/leds/nanopi:green:pwr/brightness')

with canvas(device) as draw:
    device.contrast(0)
    img_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'gdis3.png'))
    logo = Image.open(img_path)
    draw.bitmap((25, 0), logo, fill="white")
for level in range(0, 255, 3):
    device.contrast(level)
    time.sleep(0.1)

with canvas(device) as draw:
    eth = os.popen('ip addr show eth0 | grep "\<inet\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip()
    wlan = os.popen('ip addr show wlan0 | grep "\<inet\>" | awk \'{ print $2 }\' | awk -F "/" \'{ print $1 }\'').read().strip()
    draw.text((5, 0), "Ethernet",  font=font2, fill=255)
    draw.text((5, 15), str(eth),  font=font2, fill=255)
    draw.text((5, 35), "Wireless",  font=font2, fill=255)
    draw.text((5, 50), str(wlan),  font=font2, fill=255)
Exemple #43
0
 def led_matrix(self, msg):
     with canvas(self.ledMat) as draw:
         text(draw, (0, 0), msg, fill="white")
     time.sleep(0.05)
Exemple #44
0
def ascii_char(device, pic):
    with canvas(device) as draw:
        text(draw, (0, 0), chr(pic), fill="white")
    time.sleep(2)
Exemple #45
0
def drawSignage(device, width, height, data):
    global stationRenderCount, pauseCount

    device.clear()

    virtualViewport = viewport(device, width=width, height=height)

    status = "Exp 00:00"
    callingAt = "Calling at:"

    departures, firstDepartureDestinations, departureStation = data

    with canvas(device) as draw:
        w, h = draw.textsize(callingAt, font)

    callingWidth = w
    width = virtualViewport.width

    # First measure the text size
    with canvas(device) as draw:
        w, h = draw.textsize(status, font)
        pw, ph = draw.textsize("Plat 88D", font)

    rowOneA = snapshot(width - w - pw - 5,
                       10,
                       renderDestination(departures[0], fontBold),
                       interval=10)
    rowOneB = snapshot(w, 10, renderServiceStatus(departures[0]), interval=1)
    rowOneC = snapshot(pw, 10, renderPlatform(departures[0]), interval=10)
    rowTwoA = snapshot(callingWidth, 10, renderCallingAt, interval=100)
    rowTwoB = snapshot(width - callingWidth,
                       10,
                       renderStations(", ".join(firstDepartureDestinations)),
                       interval=0.1)

    if (len(departures) > 1):
        rowThreeA = snapshot(width - w - pw,
                             10,
                             renderDestination(departures[1], font),
                             interval=10)
        rowThreeB = snapshot(w,
                             10,
                             renderServiceStatus(departures[1]),
                             interval=1)
        rowThreeC = snapshot(pw,
                             10,
                             renderPlatform(departures[1]),
                             interval=10)

    if (len(departures) > 2):
        rowFourA = snapshot(width - w - pw,
                            10,
                            renderDestination(departures[2], font),
                            interval=10)
        rowFourB = snapshot(w,
                            10,
                            renderServiceStatus(departures[2]),
                            interval=1)
        rowFourC = snapshot(pw, 10, renderPlatform(departures[2]), interval=10)

    rowTime = snapshot(width, 14, renderTime, interval=0.1)

    if len(virtualViewport._hotspots) > 0:
        for hotspot, xy in virtualViewport._hotspots:
            virtualViewport.remove_hotspot(hotspot, xy)

    stationRenderCount = 0
    pauseCount = 0

    virtualViewport.add_hotspot(rowOneA, (0, 0))
    virtualViewport.add_hotspot(rowOneB, (width - w, 0))
    virtualViewport.add_hotspot(rowOneC, (width - w - pw, 0))
    virtualViewport.add_hotspot(rowTwoA, (0, 12))
    virtualViewport.add_hotspot(rowTwoB, (callingWidth, 12))

    if (len(departures) > 1):
        virtualViewport.add_hotspot(rowThreeA, (0, 24))
        virtualViewport.add_hotspot(rowThreeB, (width - w, 24))
        virtualViewport.add_hotspot(rowThreeC, (width - w - pw, 24))

    if (len(departures) > 2):
        virtualViewport.add_hotspot(rowFourA, (0, 36))
        virtualViewport.add_hotspot(rowFourB, (width - w, 36))
        virtualViewport.add_hotspot(rowFourC, (width - w - pw, 36))

    virtualViewport.add_hotspot(rowTime, (0, 50))

    return virtualViewport
Exemple #46
0
def print_text(message, seq, note_length, wait=1.0):
    with canvas(virtual) as draw:
        text(draw, (0, 0), message, fill="white", font=proportional(LCD_FONT))
    time.sleep(wait)
    print_sequencer(seq, seq_length=len(seq[0]), note_length=note_length)
Exemple #47
0
    def run(self, oled):
        self.passing = True

        # open a serial terminal, make sure WFI is off so we have a consistent power measurement
        ser = serial.Serial()
        ser.baudrate = 115200
        ser.port = "/dev/ttyS0"
        ser.stopbits = serial.STOPBITS_ONE
        ser.xonxoff = 0
        try:
            ser.open()
        except:
            print("couldn't open serial port")
            exit(1)

        with canvas(oled) as draw:
            draw.text((0, 0), "Key kill test...", fill="white")

        # ensure the correct config: powering off of battery, high current sense mode
        GPIO.output(GPIO_ISENSE, 1)
        time.sleep(0.25)
        GPIO.output(GPIO_BSIM, 1)
        time.sleep(0.5)
        GPIO.output(GPIO_VBUS, 1)

        time.sleep(9.0)

        ibus_nom = read_i_vbus()
        #print("pre-kill: {} {}".format(ibat_nom, read_i_vbus()))

        # switch to battery power
        GPIO.output(GPIO_VBUS, 0)
        time.sleep(0.5)

        self.console = fdspawn(ser)
        self.try_cmd("test kill\r", "|TSTR|KILL")
        self.console.close()

        with canvas(oled) as draw:
            draw.text((0, 1), "A red light should be turned on.", fill="white")

        time.sleep(2.0)
        destruct_current = read_i_bat(high_range=True)
        if destruct_current > 0.095:
            self.passing = False
            self.add_reason("SD shutdown current too high {:.4f}A".format(
                destruct_current))
            if self.logfile:
                self.logfile.write(
                    "Self destruct shutdown current: {:.4f}mA\n".format(
                        destruct_current * 1000))

        # print("post-kill: {} {}".format(read_i_bat(high_range=True), read_i_vbus()))

        GPIO.output(GPIO_VBUS, 1)
        time.sleep(2.0)
        ibus_kill = read_i_vbus()

        if ibus_kill > (
                ibus_nom - 0.055
        ):  # one working unit with exactly 0.060; 0.055 gives some margin
            self.passing = False
            self.add_reason("Self Destruct fail Q22F/Q21F")
        if self.logfile:
            self.logfile.write(
                "Self destruct vbus current: {:.4f}mA / baseline: {:.4f}\n".
                format(ibus_kill * 1000, ibus_nom * 1000))

        # print("post-vbus: {} {}".format(read_i_bat(high_range=True), read_i_vbus()))

        with canvas(oled) as draw:
            draw.text((0, 1), "Key kill test complete", fill="white")

        # disconnect everything so the system can boot again
        GPIO.output(GPIO_VBUS, 0)
        time.sleep(0.5)
        GPIO.output(GPIO_BSIM, 0)
        GPIO.output(GPIO_ISENSE, 1)
        time.sleep(2.0)

        self.has_run = True
        return self.passing
Exemple #48
0
def print_sequencer(sequencer, seq_length=32, note_length=16):
    max = 64
    if seq_length > max:
        print("ERROR - Can't show sequence lengths longer then '%s'." % max)
    elif seq_length <= 32:
        with canvas(device) as draw:
            text(draw, (0, 0),
                 "Bar's:",
                 fill="white",
                 font=proportional(LCD_FONT))
            if note_length == 4:
                text(draw, (32, 0),
                     "1 3 5 7",
                     fill="white",
                     font=proportional(TINY_FONT))
            elif note_length == 8:
                text(draw, (32, 0),
                     "1 2 3 4",
                     fill="white",
                     font=proportional(TINY_FONT))
            elif note_length == 16:
                text(draw, (32, 0),
                     "1   2   ",
                     fill="white",
                     font=proportional(TINY_FONT))
            else:
                return

            # display sequencer values
            for y in range(len(sequencer) - 2):
                for x in range(len(sequencer[y])):
                    if sequencer[y][x] != 0:
                        point = x + 64, y
                        draw.point(point, fill="white")
    elif seq_length <= 64:
        with canvas(device) as draw:
            if note_length == 4:
                text(draw, (0, 0),
                     "1 3 5 7",
                     fill="white",
                     font=proportional(TINY_FONT))
                text(draw, (64, 0),
                     "9 111315",
                     fill="white",
                     font=proportional(TINY_FONT))
            elif note_length == 8:
                text(draw, (0, 0),
                     "1 2 3 4",
                     fill="white",
                     font=proportional(TINY_FONT))
                text(draw, (64, 0),
                     "5 6 7 8",
                     fill="white",
                     font=proportional(TINY_FONT))
            elif note_length == 16:
                text(draw, (0, 0),
                     "1   2   ",
                     fill="white",
                     font=proportional(TINY_FONT))
                text(draw, (64, 0),
                     "3   4   ",
                     fill="white",
                     font=proportional(TINY_FONT))
            else:
                return

            # display sequencer values
            for y in range(len(sequencer) - 2):
                for x in range(len(sequencer[y])):
                    if sequencer[y][x] != 0:
                        if x > 31:
                            point = x + 64, y
                        else:
                            point = x + 32, y
                        draw.point(point, fill="white")
Exemple #49
0
def drawSplash(device):
	with canvas(device) as draw:
		draw.rectangle((18,12,108,52), outline="white", fill="black")
		draw.text((0,16),'         OPC         ',"white")
		draw.text((0,38),'     tink3rtanker    ',"white")
Exemple #50
0
import time
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306
from PIL import ImageFont

serial = i2c(port=1, address=0x3C)
device = ssd1306(serial, rotate=0)
font = ImageFont.truetype("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 17)

Weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
while True:
    Time = time.localtime()
    Date = '{}年{:0>2d}月{:0>2d}日'.format(Time.tm_year, Time.tm_mon,
                                        Time.tm_mday)
    Clock = '{:0>2d}:{:0>2d}:{:0>2d}'.format(Time.tm_hour, Time.tm_min,
                                             Time.tm_sec)
    with canvas(device, dither=False) as draw:
        draw.text((-2, 2), Date, fill="white", font=font)
        draw.text((40, 23), Weekdays[Time.tm_wday], fill="white", font=font)
        draw.text((30, 44), Clock, fill="white", font=font)
    time.sleep(1)
Exemple #51
0
def drawText(device,textlist):
	with canvas(device) as draw:
		for idx,text in enumerate(textlist):
			#print text, ", ", idx
			draw.text((0,idx*10),text,"white")
Exemple #52
0
 def scrollingChar(self):
     self.scrollPos -= 1
     with canvas(self.device) as draw:
         text(draw, (self.scrollPos, 0), chr(self.scrollChar), fill='white')
     if self.scrollPos == -8:
         self.scrollPos = 16
Exemple #53
0
def give_info(sequencer):
    with canvas(virtual) as draw:
        text(draw, (0, 0),
             "Sequ",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (32, 0),
             "encer",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (64, 0),
             "leng",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (96, 0),
             "ths:",
             fill="white",
             font=proportional(SINCLAIR_FONT))
    time.sleep(3)

    with canvas(virtual) as draw:
        text(draw, (0, 0),
             str(sequencer.bars),
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (32, 0),
             "bars,",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (64, 0),
             str(sequencer.note_length),
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (96, 0),
             "notes",
             fill="white",
             font=proportional(SINCLAIR_FONT))
    time.sleep(3)

    with canvas(virtual) as draw:
        text(draw, (0, 0),
             "Chann",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (32, 0),
             "els:",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (64, 0),
             str(sequencer.max_channels) + ",",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (96, 0),
             "order:",
             fill="white",
             font=proportional(SINCLAIR_FONT))
    time.sleep(3)

    with canvas(virtual) as draw:
        text(draw, (0, 0),
             "Kick",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (32, 0),
             "Snare",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (64, 0),
             "HiHat",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (96, 0),
             "Bass",
             fill="white",
             font=proportional(SINCLAIR_FONT))
    time.sleep(3)

    with canvas(virtual) as draw:
        text(draw, (0, 0),
             "Let's",
             fill="white",
             font=proportional(SINCLAIR_FONT))
        text(draw, (32, 0),
             "go!",
             fill="white",
             font=proportional(SINCLAIR_FONT))
    time.sleep(3)

    print_sequencer(sequencer.seq,
                    seq_length=sequencer.sequence_length,
                    note_length=sequencer.note_length)
Exemple #54
0
def main():
  client = MPDConnect()
  client.connect()

  while True:

    info = client.fetch()
    state = info['state']
    vol = info['volume']
    eltime = info['eltime']
    artist = info['artist']
    title = info['title']
    audio = info['audio_info']

    if '1' in open('/sys/class/gpio/gpio198/value').read():
      if '0' in open('/sys/class/gpio/gpio199/value').read():
        with canvas(device) as draw:
             draw.text((15,15),"Optical 1", font=font3, fill=255)

    if '1' in open('/sys/class/gpio/gpio198/value').read():
      if '1' in open('/sys/class/gpio/gpio199/value').read():
        with canvas(device) as draw:
             draw.text((15,15),"Optical 2", font=font3, fill=255)

    if '0' in open('/sys/class/gpio/gpio198/value').read():
      if '0' in open('/sys/class/gpio/gpio199/value').read():

        if (state == 'stop'):
          with canvas(device) as draw:

           if vol>0 and vol<100:
             draw.text((0,13),str(vol), font=font, fill=255)
           if vol==100:
             draw.text((0,13),"--", font=font, fill=255)

        if state == 'play':
          with canvas(device) as draw:

           if vol>0 and vol<100:
             draw.text((35,0), audio, font=font2, fill=255)
             draw.text((0,13),str(vol), font=font, fill=255)
             draw.text((80,50),str(eltime), font=font2, fill=255)
             draw.text((87,20),">>", font=font4, fill=255)
           if vol==100:
             draw.text((35,0), audio, font=font2, fill=255)
             draw.text((0,13),"--", font=font, fill=255)
             draw.text((80,50),str(eltime), font=font2, fill=255)
             draw.text((87,20),">>", font=font4, fill=255)

        if state == 'pause':
          with canvas(device) as draw:
           if vol>0 and vol<100:

             draw.text((35,0), audio, font=font2, fill=255)
             draw.text((0,13),str(vol), font=font, fill=255)
             draw.text((80,50),str(eltime), font=font2, fill=255)
             draw.text((87,20)," ||", font=font4, fill=255)
           if vol==100:
             draw.text((35,0), audio, font=font2, fill=255)
             draw.text((0,13),"--", font=font, fill=255)
             draw.text((80,50),str(eltime), font=font2, fill=255)
             draw.text((87,20)," ||", font=font4, fill=255)
Exemple #55
0
def demo(photo_count, countdown_from):

    # create matrix device
    serial = spi(port=0, device=0, gpio=noop())
    device = max7219(serial, cascaded=4, block_orientation=-90, rotate=0)
    print("Created device")

    # setup button on Raspberry Pi Pin 18

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    while True:
        print("PUSH THE BUTTON!")
        with canvas(device) as draw:
            text(draw, (1, 0),
                 "Ready",
                 fill="white",
                 font=proportional(LCD_FONT))

        GPIO.wait_for_edge(18, GPIO.FALLING)

        print('Button Pressed')

        # Start by creating a folder for all the photos, with a folder inside called minis for gif-based

        time_now = time.strftime("%Y-%m-%d_%H-%M-%S", time.gmtime())
        pi_folder = os.path.join('/home/pi/wedding_photos/', time_now)
        minis_folder = os.path.join(pi_folder, 'minis')
        os.makedirs(minis_folder)

        gif_folder = os.path.join('/home/pi/wedding_photos/gifs/')
        # os.makedirs(gif_folder)

        # Start looping and taking photos!

        for index in range(photo_count):
            msg = ""
            for i in range(countdown_from):

                msg += "%s... " % (countdown_from - i)

            show_message(device,
                         msg,
                         fill="white",
                         font=proportional(LCD_FONT),
                         scroll_delay=0.05)

            with canvas(device) as draw:
                text(draw, (2, 0),
                     "Smile!",
                     fill="white",
                     font=proportional(LCD_FONT))

        # GPHOTO

            logging.basicConfig(format='%(levelname)s: %(name)s: %(message)s',
                                level=logging.WARNING)
            gp.check_result(gp.use_python_logging())
            camera = gp.check_result(gp.gp_camera_new())
            gp.check_result(gp.gp_camera_init(camera))
            print('Capturing image')
            file_path = gp.check_result(
                gp.gp_camera_capture(camera, gp.GP_CAPTURE_IMAGE))
            print('Camera file path: {0}/{1}'.format(file_path.folder,
                                                     file_path.name))

            # save image to pi
            target = os.path.join(
                pi_folder,
                time.strftime("%Y%m%d%H%M%S", time.gmtime()) + file_path.name)

            print('Copying image to', target)
            camera_file = gp.check_result(
                gp.gp_camera_file_get(camera, file_path.folder, file_path.name,
                                      gp.GP_FILE_TYPE_NORMAL))
            gp.check_result(gp.gp_file_save(camera_file, target))

            # subprocess.call(['xdg-open', target]) # Commented out as no need to open

            gp.check_result(gp.gp_camera_exit(camera))

            ## GPHOTO END

            device.clear()

        # OK, let's create a gif! First, let's create some smaller images

        for filename in os.listdir(pi_folder):
            if filename.endswith(".jpg"):
                img = Image(filename=os.path.join(pi_folder, filename))
                img.sample(780, 540)
                img.save(filename=os.path.join(minis_folder, filename))
            else:
                continue

        # Create a gif from them smaller images

        with Image() as wand:
            for filename in os.listdir(minis_folder):
                if filename.endswith(".jpg"):
                    with Image(filename=os.path.join(minis_folder,
                                                     filename)) as photo:
                        wand.sequence.append(photo)
                else:
                    continue
            for cursor in range(len(wand.sequence)):
                with wand.sequence[cursor] as frame:
                    frame.delay = 50
            wand.type = 'optimize'
            wand.save(
                filename=os.path.join(gif_folder, "{0}.gif".format(time_now)))
Exemple #56
0
    def run(self, oled):
        self.passing = True

        # open a serial terminal, make sure WFI is off so we have a consistent power measurement
        ser = serial.Serial()
        ser.baudrate = 115200
        ser.port = "/dev/ttyS0"
        ser.stopbits = serial.STOPBITS_ONE
        ser.xonxoff = 0
        try:
            ser.open()
        except:
            print("couldn't open serial port")
            exit(1)

        with canvas(oled) as draw:
            draw.text((0, 0), "Post-test current...", fill="white")

        # ensure the correct config: powering off of battery, high current sense mode
        GPIO.output(GPIO_ISENSE, 1)
        time.sleep(0.25)
        GPIO.output(GPIO_BSIM, 1)
        time.sleep(0.5)
        GPIO.output(GPIO_VBUS, 1)
        time.sleep(0.5)
        GPIO.output(GPIO_VBUS, 0)

        time.sleep(10.0)  # total time required from boot to command acceptance
        self.console = fdspawn(ser)
        self.try_cmd("test wfioff\r", "|TSTR|WFIOFF")
        self.console.close()

        vbus = read_vbus()

        # demonstrate that vbus is at 0
        if vbus > 1.0:
            self.passing = False
            self.add_reason("VBUS did not drop: {:.3f}V".format(vbus))

        oled.clear()
        line = 0
        ibat_max = 0.250
        ibat_min = 0.180

        ibat_avg = 0.0
        for x in range(10, 0, -1):
            if x == 10 or x == 5 or x == 1:
                with canvas(oled) as draw:
                    draw.text((0, FONT_HEIGHT * line),
                              "Measuring current... {}".format(int(x / 5)),
                              fill="white")
            time.sleep(0.2)
            # sample
            ibat_avg += read_i_bat(high_range=True)

        ibat_avg /= 10.0

        if ibat_avg > ibat_max:
            self.passing = False
            self.add_reason("IBAT too high: {:.3f}mA".format(ibat_avg * 1000))
        if ibat_avg < ibat_min:
            self.passing = False
            self.add_reason("IBAT too low: {:.3f}mA".format(ibat_avg * 1000))

        with canvas(oled) as draw:
            line = 0
            draw.text((0, FONT_HEIGHT * line),
                      "Post-test current measurement:")
            line += 1
            draw.text((0, FONT_HEIGHT * line), "VBUS: {:.3f}V".format(vbus))
            line += 1
            draw.text((0, FONT_HEIGHT * line),
                      "IBAT: {:.3f}mA".format(ibat_avg * 1000))

        if self.logfile:
            self.logfile.write("Post-test current measured at {}\n".format(
                str(datetime.now())))
            self.logfile.write("VBUS: {:.3f}V\n".format(vbus))
            self.logfile.write("IBAT: {:.3f}mA\n".format(ibat_avg * 1000))

        time.sleep(1.0)

        GPIO.output(GPIO_BSIM, 0)
        GPIO.output(GPIO_VBUS,
                    0)  # should already be off, doesn't hurt to check

        self.has_run = True
        return self.passing
Exemple #57
0
 def setScrollChar(self, char):
     self.scrollPos = 16
     self.scrollChar = char
     with canvas(self.device) as draw:
         text(draw, (self.scrollPos, 0), chr(char), fill='white')
Exemple #58
0
    def run(self, oled):
        self.passing = True
        self.has_run = True

        with canvas(oled) as draw:
            draw.text((0, 0), "Audio / Battery on...", fill="white")
        GPIO.output(GPIO_BSIM, 1)
        time.sleep(0.5)
        
        with canvas(oled) as draw:
            draw.text((0, 0), "Audio / Power on...", fill="white")
        GPIO.output(GPIO_VBUS, 1)

        time.sleep(9) # give a little time for the device to boot

        # open a serial terminal
        ser = serial.Serial()
        ser.baudrate = 115200
        ser.port="/dev/ttyS0"
        ser.stopbits=serial.STOPBITS_ONE
        ser.xonxoff=0
        try:
            ser.open()
        except:
            print("couldn't open serial port")
            exit(1)
        self.console = fdspawn(ser)        

        # setup for left feed
        GPIO.output(GPIO_AUD_HPR, 0)
        GPIO.output(GPIO_AUD_HPL, 1)
        GPIO.output(GPIO_AUD_SPK, 0)
        
        with canvas(oled) as draw:
            draw.text((0, 0), "Test left audio channel...", fill="white")
        self.try_cmd("test astart 261.63 left\r", "|TSTR|ASTART")
        time.sleep(3)
        self.try_cmd("test astop\r", "|TSTR|ASTOP")

        results = self.console.before.decode('utf-8', errors='ignore')
        for line in results.split('\r'):
            if 'TSTR|' in line:
                if self.logfile:
                    self.logfile.write(line.rstrip() + '\n')
                #print(line.rstrip())
                test_output = line.split('|')
                if test_output[2] == 'ARESULT':
                    if test_output[3] == 'FAIL':
                        self.passing = False
                        self.add_reason("Left audio fail")
        

        # setup for right feed
        GPIO.output(GPIO_AUD_HPR, 1)
        GPIO.output(GPIO_AUD_HPL, 0)
        GPIO.output(GPIO_AUD_SPK, 0)
        
        with canvas(oled) as draw:
            draw.text((0, 0), "Test right audio channel...", fill="white")
        self.try_cmd("test astart 329.63 right\r", "|TSTR|ASTART")
        time.sleep(3)
        self.try_cmd("test astop\r", "|TSTR|ASTOP")

        results = self.console.before.decode('utf-8', errors='ignore')
        for line in results.split('\r'):
            if 'TSTR|' in line:
                if self.logfile:
                    self.logfile.write(line.rstrip() + '\n')
                #print(line.rstrip())
                test_output = line.split('|')
                if test_output[2] == 'ARESULT':
                    if test_output[3] == 'FAIL':
                        self.passing = False
                        self.add_reason("Right audio fail")
        
                        
        # setup for speaker feed
        GPIO.output(GPIO_AUD_HPR, 0)
        GPIO.output(GPIO_AUD_HPL, 0)
        GPIO.output(GPIO_AUD_SPK, 1)
        
        with canvas(oled) as draw:
            draw.text((0, 0), "Test speaker...", fill="white")
        self.try_cmd("test astart 440 speaker\r", "|TSTR|ASTART")
        time.sleep(3)
        self.try_cmd("test astop\r", "|TSTR|ASTOP")

        results = self.console.before.decode('utf-8', errors='ignore')
        for line in results.split('\r'):
            if 'TSTR|' in line:
                if self.logfile:
                    self.logfile.write(line.rstrip() + '\n')
                #print(line.rstrip())
                test_output = line.split('|')
                if test_output[2] == 'ARESULT':
                    if test_output[3] == 'FAIL':
                        self.passing = False
                        self.add_reason("Speaker fail")

        # setup for right/left crosstalk
        GPIO.output(GPIO_AUD_HPR, 0)
        GPIO.output(GPIO_AUD_HPL, 1)
        GPIO.output(GPIO_AUD_SPK, 0)
        
        with canvas(oled) as draw:
            draw.text((0, 0), "Test crosstalk...", fill="white")
        self.try_cmd("test astart 523.25 right\r", "|TSTR|ASTART")
        time.sleep(3)
        self.try_cmd("test astop\r", "|TSTR|ASTOP")

        results = self.console.before.decode('utf-8', errors='ignore')
        for line in results.split('\r'):
            if 'TSTR|' in line:
                if self.logfile:
                    self.logfile.write(line.rstrip() + '\n')
                #print(line.rstrip())
                test_output = line.split('|')
                if test_output[2] == 'ARESULT':
                    if test_output[3] == 'PASS': # we expect this test to FAIL; should be silence in this config
                        self.passing = False
                        self.add_reason("L/R isolation fail")
                        

        # isolate all
        GPIO.output(GPIO_AUD_HPR, 0)
        GPIO.output(GPIO_AUD_HPL, 0)
        GPIO.output(GPIO_AUD_SPK, 0)
                        
        with canvas(oled) as draw:
            draw.text((0, 0), "Audio test complete!", fill="white")
        time.sleep(1)
        with canvas(oled) as draw:
            oled.clear()

        self.console.close()
        return self.passing
Exemple #59
0
def update_display(display, msg):
    with canvas(display) as draw:
        draw.text((0, 0), msg, fill='white')
Exemple #60
0
    def draw_menu(self):
        #while CF.source == 1:
        self.Time()
        with canvas(self.device) as draw:
            #basic outline Box and text rendered in portrait mode
            #draw.rectangle(device.bounding_box, outline="white", fill="black")
            D.draw_rectangle(draw, self.device)

            #date and time
            draw.line((0, 13, 128, 13), fill="white")
            draw.text((2, 1), self.today_date, fill="white")
            draw.text((78, 1), self.today_time, fill="white")
            #updateMusic()
            #ler controle de volume! Depois, ler primeito configuração inicial!
            p = self.menu_position()
            #musicInfo()
            #MP3
            if (p[0] == 1):
                draw.rectangle((4, 14, 122, 24), outline="white", fill="white")
                draw.text((4, 14),
                          "1 - Internal MP3",
                          font=self.font_menu,
                          fill="black")
            else:
                draw.text((4, 14),
                          "1 - Internal MP3",
                          font=self.font_menu,
                          fill="white")
            #Bluetooth
            if (p[1] == 1):
                draw.rectangle((4, 26, 122, 36), outline="white", fill="white")
                draw.text((4, 26),
                          "2 - Bluetooth",
                          font=self.font_menu,
                          fill="black")
            else:
                draw.text((4, 26),
                          "2 - Bluetooth",
                          font=self.font_menu,
                          fill="white")
            #USB
            if (p[2] == 1):
                draw.rectangle((4, 38, 122, 49), outline="white", fill="white")
                draw.text((4, 38),
                          "3 - USB",
                          font=self.font_menu,
                          fill="black")
            else:
                draw.text((4, 38),
                          "3 - USB",
                          font=self.font_menu,
                          fill="white")
            #settings
            if (p[3] == 1):
                draw.rectangle((4, 51, 122, 62), outline="white", fill="white")
                draw.text((4, 50),
                          "4 - Settings",
                          font=self.font_menu,
                          fill="black")
            else:
                draw.text((4, 50),
                          "4 - Settings",
                          font=self.font_menu,
                          fill="white")