Пример #1
0
def main(argv):
    """main program - display list of images"""
    dir_path = os.path.dirname(os.path.realpath(__file__))
    subprocess.call(shlex.split(dir_path + '/speedtest2.sh'))
    x = 0
    with open('graph.txt') as f:
        lines = f.readlines()
        y = [line.split()[0] for line in lines]

    with open('graph2.txt') as f2:
        lines = f2.readlines()
        y2 = [line.split()[0] for line in lines]
        #x = [x++1 for line in lines]

    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.set_title("Speed Test")
    ax1.plot(y, c='r', label='Down')
    ax1.plot(y2, c='b', label='Up')
    leg = ax1.legend()
    fig.set_size_inches(3.8, 2.5)
    fig.savefig('temp.png', dpi=75)

    epd = Papirus()

    epd.clear()

    #print('panel = {p:s} {w:d} x {h:d}  version={v:s} COG={g:d} FILM={f:d}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version, g=epd.cog, f=epd.film))

    display_file(epd, 'temp.png')
def main():
    global SIZE
    global PapirusDevice
    global CurrentTime

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    PapirusDevice = Papirus(rotation=0)

    # Use smaller font for smaller displays
    if PapirusDevice.height <= 96:
        SIZE = 18

    PapirusDevice.clear()

    write_text(PapirusDevice, "Ready... SW1 + SW2 to exit.", SIZE)
    sleep(5.0)

    print("Starting...")

    while True:
        CurrentTime = datetime.now()
        forceRefresh = False
        try:
            # Exit when SW1 and SW2 are pressed simultaneously
            if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False):
                write_text(PapirusDevice, "Exiting ...", SIZE)
                sleep(0.2)
                PapirusDevice.clear()
                sys.exit()

            if GPIO.input(SW1) == False:
                # Press twice to shutdown
                handleShutdown()
                forceRefresh = True
            elif GPIO.input(SW2) == False:
                # Press twice to reboot
                handleReboot()
                forceRefresh = True
            elif GPIO.input(SW3) == False:
                # switch to next usb network interface
                use_next_usb_tether_device()
                forceRefresh = True
            elif GPIO.input(SW4) == False:
                # do nothing...
                forceRefresh = True

            clear_pending_states(False)
            refresh_dashboard(forceRefresh)
        except Exception as ex:
            write_text(PapirusDevice, str(ex), SIZE)
        sleep(0.1)
Пример #3
0
def main(argv):
    global SIZE

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus(rotation = int(argv[0]) if len(sys.argv) > 1 else 0)

    # timestamp to be set when this program is initiated.. used for the location file
    # and remains the same for the rest of the duration of the program. If the program
    # is restarted the location file's name changes.

    location_file = '/home/pi/location'+datetime.now().strftime('%Y%m%d%H%M%S')+'.txt'

    # Use smaller font for smaller displays
    if papirus.height <= 96:
        SIZE = 18

    papirus.clear()

    write_text(papirus, "Ready... SW1 + SW2 to exit.", SIZE)

    while True:
        # Exit when SW1 and SW2 are pressed simultaneously
        if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False) :
            write_text(papirus, "Exiting ...", SIZE)
            sleep(0.2)
            papirus.clear()
            sys.exit()

        if GPIO.input(SW1) == False:
            write_text(papirus, "One", SIZE)

        if GPIO.input(SW2) == False:
            write_text(papirus, "Two", SIZE)

        if GPIO.input(SW3) == False:
            write_text(papirus, "Track Motion", SIZE)
            lt = gl.get_loc_time()
            write_text(papirus,str(lt['Alt'])+","+str(lt['Lat'])+","+str(lt['Lon'])+","+str(lt['Time']), SIZE)
            with open(location_file,'a+') as lf:
                lf.write(str(lt['Alt'])+","+str(lt['Lat'])+","+str(lt['Lon'])+","+str(lt['Time'])+"\n") 
        if GPIO.input(SW4) == False:
            write_text(papirus, "Rebooting...", SIZE)
            os.system("sudo reboot") 

        if (SW5 != -1) and (GPIO.input(SW5) == False):
            write_text(papirus, "Shutting Down at\n" + str(datetime.now()), SIZE)
            os.system("sudo shutdown now -h") 
 
        sleep(0.1)
Пример #4
0
def main(argv):
    """main program - draw and display time and date"""

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)

    # print('panel = {p:s} {w:d} x {h:d}  version={v:s} COG={g:d} FILM={f:d}'.format(p=papirus.panel, w=papirus.width, h=papirus.height, v=papirus.version, g=papirus.cog, f=papirus.film))

    papirus.clear()

    timer(papirus, 10)
Пример #5
0
    class PapirusDisplay:
        def __init__(self):
            self.papirus = Papirus(rotation=180)
            self.papirus.clear()
            self.first_draw = True

        def update(self, im):
            self.papirus.display(im)
            if self.first_draw:
                self.papirus.update()
                self.first_draw = False
            else:
                self.papirus.partial_update()
Пример #6
0
def main():
    """main program - draw and display time and date"""

    papirus = Papirus()

    print('panel = {p:s} {w:d} x {h:d}  version={v:s} COG={g:d} FILM={f:d}'.
          format(p=papirus.panel,
                 w=papirus.width,
                 h=papirus.height,
                 v=papirus.version,
                 g=papirus.cog,
                 f=papirus.film))
    print("Test")
    papirus.clear()

    demo(papirus)
Пример #7
0
def main(argv):
    """main program - draw and display time and date"""

    setup_gpio()

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)

    # print('panel = {p:s} {w:d} x {h:d}  version={v:s} COG={g:d} FILM={f:d}'.format(p=papirus.panel, w=papirus.width, h=papirus.height, v=papirus.version, g=papirus.cog, f=papirus.film))

    papirus.clear()

    while True:
        if GPIO.input(SW1) == False:
            timer(papirus, 10)
        if GPIO.input(SW2) == False:
            timer(papirus, 64)
Пример #8
0
def main(argv):
    global SIZE

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)

    # Use smaller font for smaller displays
    if papirus.height <= 96:
        SIZE = 18

    papirus.clear()

    write_text(papirus, "Ready... SW1 + SW2 to exit.", SIZE)

    while True:
        # Exit when SW1 and SW2 are pressed simultaneously
        if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False):
            write_text(papirus, "Exiting ...", SIZE)
            sleep(0.2)
            papirus.clear()
            sys.exit()

        if GPIO.input(SW1) == False:
            write_text(papirus, "One", SIZE)

        if GPIO.input(SW2) == False:
            write_text(papirus, "Two", SIZE)

        if GPIO.input(SW3) == False:
            write_text(papirus, "Three", SIZE)

        if GPIO.input(SW4) == False:
            write_text(papirus, "Four", SIZE)

        if (SW5 != -1) and (GPIO.input(SW5) == False):
            write_text(papirus, "Five", SIZE)

        sleep(0.1)
Пример #9
0
def main(argv):
    """main program - draw and display a test image"""

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(SW1, GPIO.IN)

    papirus = Papirus()

    print('panel = {p:s} {w:d} x {h:d}  version={v:s} COG={g:d} FILM={f:d}'.
          format(p=papirus.panel,
                 w=papirus.width,
                 h=papirus.height,
                 v=papirus.version,
                 g=papirus.cog,
                 f=papirus.film))

    papirus.clear()

    demo(papirus)
Пример #10
0
class PapirusPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.ProgressPlugin):
    def on_after_startup(self):
        self._logger.info("Hello World!")
        self.papirus = Papirus()
        self.font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMono.ttf', 14)
        self.papirus.clear()
        self.last_update = datetime.now()
    
    def on_print_progress(self, storage, path, progress):
        pass

    def on_slicing_progress(self, slicer, source_location, source_path, dest_location, dest_path, progress):
        if progress == 0 or progress == 100 or (datetime.now() - self.last_update).total_seconds() > 3:
            width, height = self.papirus.size
            self.last_update = datetime.now()
            image = Image.new('1', (width, height), 1)
            
            draw = ImageDraw.Draw(image)
            
            #Draw progress
            start_x = width / 10
            end_x = width - start_x
            start_y = height / 2
            end_y = start_y + 20
            draw.rectangle((start_x, start_y, end_x, end_y), 1, 0)
            fillWidth = (end_x - start_x) * progress / 100
            try:
                self._logger.info("On slicing progress : ({}, {}, {}, {}, {})".format(start_x, end_x, start_y, end_y, fillWidth))
            except:
                self._logger.info("Error writing log")
            draw.rectangle((start_x, start_y, start_x + fillWidth, end_y), 0, 0)
            
            # Draw text
            draw.text((0, 0), dest_path, font=self.font, fill=0)

            del draw

            self.papirus.display(image)
            self.papirus.update()
Пример #11
0
def main(argv):
    global SIZE
    global FIAT
    global SATS

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)

    # Use smaller font for smaller displays
    if papirus.height <= 96:
        SIZE = 18

    papirus.clear()

    while True:

        if GPIO.input(SW1) == False:
            update_img_screen(papirus)

        if GPIO.input(SW2) == False:
            pass

        if GPIO.input(SW3) == False:
            pass

        if GPIO.input(SW4) == False:
            pass

        if (GPIO.input(SW5) == False):
            pass

        sleep(0.1)
Пример #12
0
class PapirusDisplay():

    config = None
    papirus = None

    def __init__(self, config):

        self.config = config

        if _SENSOR_DISPLAY:
            self.papirus = Papirus(rotation=180)
            self.clear()

    def clear(self):
        self.papirus.clear()

    def update(self, image):
        self.papirus.display(image)
        self.papirus.fast_update()

    def quit(self):
        if _SENSOR_DISPLAY:
            self.clear()
Пример #13
0
def main(argv):
    global SIZE

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)

    # Use smaller font for smaller displays
    if papirus.height <= 96:
        SIZE = 12

    papirus.clear()

    loc_time = gl.get_loc_time()
    write_text(
        papirus, "Booted up at: \nLat: " + str(loc_time['Lat']) + "\nLon: " +
        str(loc_time['Lon']) + "\nTime: " + loc_time['Time'], SIZE)
Пример #14
0
def main():
    global SIZE
    global FLAG

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus()
    screen = PapirusImage()

    # Use smaller font for smaller dislays
    if papirus.height <= 96:
        SIZE = 18

    papirus.clear()

    # Initialize Screen
    screen.write('./images/light1.bmp')
    while True:
        # Exit when SW1 and SW2 are pressed simultaneously
        if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False):
            write_text(papirus, "Exiting ...", SIZE)
            sleep(0.2)
            papirus.clear()
            sys.exit()

        # Up Arrow
        if GPIO.input(SW1) == False:
            if FLAG == 4:
                FLAG = 1
            else:
                FLAG += 1
            write_text(papirus, "placeholder", SIZE, FLAG)

        # Down Arrow
        if GPIO.input(SW2) == False:
            if FLAG == 1:
                FLAG = 4
            else:
                FLAG -= 1
            write_text(papirus, "placeholder", SIZE, FLAG)

        # Function 3
        if GPIO.input(SW3) == False:
            function_three(FLAG)

        # Function 2
        if GPIO.input(SW4) == False:
            function_two(FLAG)

        # Function 1
        if (SW5 != -1) and (GPIO.input(SW5) == False):
            function_one(FLAG)

        sleep(0.05)
Пример #15
0
class PapirusTextPos(object):
    def __init__(self, autoUpdate=True, rotation=0):
        # Set up the PaPirus and dictionary for text
        self.papirus = Papirus(rotation=rotation)
        self.allText = dict()
        self.image = Image.new('1', self.papirus.size, WHITE)
        self.autoUpdate = autoUpdate
        self.partialUpdates = False

    def AddText(self,
                text,
                x=0,
                y=0,
                size=20,
                Id=None,
                invert=False,
                fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf',
                maxLines=100):
        # Create a new Id if none is supplied
        if Id == None:
            Id = str(uuid.uuid4())

        # If the Id doesn't exist, add it  to the dictionary
        if Id not in self.allText:
            self.allText[Id] = DispText(text, x, y, size, invert)
            # add the text to the image
            self.addToImageText(Id, fontPath, maxLines)
            #Automatically show?
            if self.autoUpdate:
                self.WriteAll()

    def UpdateText(self,
                   Id,
                   newText,
                   fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf',
                   maxLines=100):
        # If the ID supplied is in the dictionary, update the text
        # Currently ONLY the text is update
        if Id in self.allText:
            self.allText[Id].text = newText

            # Remove from the old text from the image (that doesn't use the actual text)
            self.removeImageText(Id)
            # Add the new text to the image
            self.addToImageText(Id, fontPath, maxLines)
            #Automatically show?
            if self.autoUpdate:
                self.WriteAll()

    def RemoveText(self, Id):
        # If the ID supplied is in the dictionary, remove it.
        if Id in self.allText:
            self.removeImageText(Id)
            del self.allText[Id]

            #Automatically show?
            if self.autoUpdate:
                self.WriteAll()

    def removeImageText(self, Id):
        # prepare for drawing
        draw = ImageDraw.Draw(self.image)
        # Draw over the top of the text with a rectangle to cover it
        draw.rectangle([
            self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx,
            self.allText[Id].endy
        ],
                       fill="white")

    def addToImageText(
            self,
            Id,
            fontPath='/usr/share/fonts/truetype/freefont/FreeMono.ttf',
            maxLines=100):
        # Break the text item back in to parts
        size = self.allText[Id].size
        x = self.allText[Id].x
        y = self.allText[Id].y
        fontColor = BLACK
        backgroundColor = WHITE

        if self.allText[Id].invert:
            fontColor = WHITE
            backgroundColor = BLACK

        # prepare for drawing
        draw = ImageDraw.Draw(self.image)

        # Grab the font to use, fixed at the moment
        font = ImageFont.truetype(fontPath, size)

        # Calculate the max number of char to fit on line
        # Taking in to account the X starting position
        lineWidth = self.papirus.width - x

        # Starting vars
        currentLine = 0
        # Unicode by default
        textLines = [u""]

        # Split the text by \n first
        toProcess = self.allText[Id].text.splitlines()

        # Go through the lines and add them
        for line in toProcess:
            # Add in a line to add the words to
            textLines.append(u"")
            currentLine += 1
            # Compute each line
            for word in line.split():
                # Always add first word (even it is too long)
                if len(textLines[currentLine]) == 0:
                    textLines[currentLine] += word
                elif (draw.textsize(textLines[currentLine] + " " + word,
                                    font=font)[0]) < lineWidth:
                    textLines[currentLine] += " " + word
                else:
                    # No space left on line so move to next one
                    textLines.append(u"")
                    if currentLine < maxLines:
                        currentLine += 1
                        textLines[currentLine] += word

        # Remove the first empty line
        if len(textLines) > 1:
            del textLines[0]

        # Go through all the lines as needed, drawing them on to the image

        # Reset the ending position of the text
        self.allText[Id].endy = y
        self.allText[Id].endx = x

        # Start at the beginning, calc all the end locations
        currentLine = 0
        for l in textLines:
            # Find out the size of the line to be drawn
            textSize = draw.textsize(l, font=font)
            # Adjust the x end point if needed
            if textSize[0] + x > self.allText[Id].endx:
                self.allText[Id].endx = textSize[0] + x
            # Add on the y end point
            self.allText[Id].endy += size
            # If next line does not fit, quit
            currentLine += 1
            if self.allText[Id].endy > (self.papirus.height - size - 3):
                del textLines[currentLine:]
                break

        # Little adjustment to make sure the text gets covered
        self.allText[Id].endy += 3

        # If the text is wanted inverted, put a rectangle down first
        if self.allText[Id].invert:
            draw.rectangle([
                self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx,
                self.allText[Id].endy
            ],
                           fill=backgroundColor)

        # Start at the beginning, add all the lines to the image
        currentLine = 0
        for l in textLines:
            # Draw the text to the image
            yline = y + size * currentLine
            draw.text((x, yline), l, font=font, fill=fontColor)
            currentLine += 1

    def WriteAll(self, partialUpdate=False):
        # Push the image to the PaPiRus device, and update only what's needed
        # (unless asked to do a full update)
        self.papirus.display(self.image)
        if partialUpdate or self.partialUpdates:
            self.papirus.partial_update()
        else:
            self.papirus.update()

    def Clear(self):
        # Clear the image, clear the text items, do a full update to the screen
        self.image = Image.new('1', self.papirus.size, WHITE)
        self.allText = dict()
        self.papirus.clear()
Пример #16
0
class Screen:
    def __init__(self):
        # Check EPD_SIZE is defined
        EPD_SIZE = 0.0
        if os.path.exists('/etc/default/epd-fuse'):
            exec(open('/etc/default/epd-fuse').read())
        if EPD_SIZE == 0.0:
            print(
                "Please select your screen size by running 'papirus-config'.")

        self.papirus = Papirus(rotation=0)
        self.papirus.clear()

        # Setting the screen color
        self.BLACK = 0
        self.WHITE = 1

        # Initally set all white background
        self.image = Image.new('1', self.papirus.size, self.WHITE)

        # Prepare for drawing
        self.draw = ImageDraw.Draw(self.image)
        self.width, self.height = self.image.size

        # Setting the size/font for the name
        self.nameSize = int((self.width - 4) / (8 * 0.65))
        self.nameFont = ImageFont.truetype(nameFont, self.nameSize)

        # Setting the size/font for the data
        self.dataSize = int(
            (self.width - MAX_DATA_SIZE) / (MAX_DATA_SIZE * 0.65))
        self.dataFont = ImageFont.truetype(dataFont, self.dataSize)

        # Setting the size/font for time and date
        self.clockSize = int((self.width - 4) / (8 * 0.65))
        self.clockFont = ImageFont.truetype(
            '/usr/share/fonts/truetype/freefont/FreeMonoOblique.ttf',
            self.clockSize)
        self.dateSize = int((self.width - 10) / (10 * 0.65))
        self.dateFont = ImageFont.truetype(
            '/usr/share/fonts/truetype/freefont/FreeMono.ttf', self.dateSize)

    def updateScreen(self, n, d, s):
        self.image = Image.new('1', self.papirus.size, self.WHITE)
        self.draw = ImageDraw.Draw(self.image)

        # Display the data first
        self.draw.rectangle((0, 0, self.papirus.size[0], self.papirus.size[1]),
                            fill=self.WHITE,
                            outline=self.WHITE)
        self.draw.text((5, self.dataSize + MAX_DATA_SIZE), ('%s' % d),
                       fill=self.BLACK,
                       font=self.dataFont)

        # Display the name second
        self.draw.rectangle((3, 3, self.width - 3, self.nameSize),
                            fill=self.WHITE,
                            outline=self.WHITE)
        self.nameFont = ImageFont.truetype(nameFont, self.nameSize)
        self.draw.text((5, 5), ('%s:' % n),
                       fill=self.BLACK,
                       font=self.nameFont)

        if s:
            axis_y = self.dataSize + MAX_DATA_SIZE
            while axis_y > ((-96 * 2) + (len(d) / 2)):
                self.draw.text((5, axis_y), ('%s' % d),
                               fill=self.BLACK,
                               font=self.dataFont)
                self.displayScreen()
                if axis_y == self.dataSize + MAX_DATA_SIZE:
                    sleep(3)
                axis_y -= 5
                sleep(0.05)
                self.draw.rectangle(
                    (0, 0, self.papirus.size[0], self.papirus.size[1]),
                    fill=self.WHITE,
                    outline=self.WHITE)

        self.displayScreen()
        sleep(3)

    # Update the screen
    def displayScreen(self):
        self.papirus.display(self.image)
        self.papirus.partial_update()

    # Display the time and date
    def displayTime(self):
        self.image = Image.new('1', self.papirus.size, self.WHITE)
        self.draw = ImageDraw.Draw(self.image)

        now = datetime.today()
        self.draw.text((10, self.dateSize + 10),
                       '{d:02d}.{m:02d}.{y:04d}'.format(y=now.year,
                                                        m=now.month,
                                                        d=now.day),
                       fill=self.BLACK,
                       font=self.dateFont)
        self.draw.text((40, 10),
                       '{h:02d}:{m:02d}'.format(h=now.hour, m=now.minute),
                       fill=self.BLACK,
                       font=self.clockFont)
        self.displayScreen()

    # Set the size of the name
    # Either 37 or 25
    def setNameSize(self, ns):
        self.nameSize = ns

    def getNameSize(self):
        return self.nameSize

    def clearScreen(self):
        self.papirus.clear()
Пример #17
0
    weekday = date.today()
    day_Name = date.strftime(weekday, '%A')
    day_month_year = date.strftime(weekday, '%Y %b %-d')

    weekday2 = datetime.date.today() + datetime.timedelta(days=1)
    day2 = date.strftime(weekday2, '%A')

    try:
        screen.clear()
        print("Summary: "+currentCondFormatted+"\nTemperture: "+temp+" ")
        text.AddText((day_Name) + ' ' + (day_month_year), 0, 0, 18, Id="Line1", fontPath='/home/pi/weather-pi-data/fonts/Roboto-Black.ttf')
        text.AddText((temp) + ' ' + (humidity) + '\n' + (tempsToday), 0, 19, 14, Id="Line2", fontPath='/home/pi/weather-pi-data/fonts/Roboto-Bold.ttf')
        text.AddText((daily_conditions) + '\n' + (day2) + ' - ' + (tempsTomorrow) + ' ' + (summary2), 0, 53, 10, Id="Lin3", fontPath='/home/pi/weather-pi-data/fonts/ElecSign.ttf')

    except:
        text.UpdateText("Line1", "Connection Error!")

try:
    while True:
        display()
        sleep(300)  # 5 minutes
        text.Clear()
except (KeyboardInterrupt, SystemExit):
    text.RemoveText("Line2")
    text.RemoveText("Line3")
    screen.clear()
    text.UpdateText("Line1", "Exiting...\nGoodbye!")
    sleep(2)
    screen.clear()
    os._exit(1)
Пример #18
0
class PapirusTextPos(object):
    def __init__(self, autoUpdate = True, rotation = 0):
        # Set up the PaPirus and dictionary for text
        self.papirus = Papirus(rotation = rotation)
        self.allText = dict()
        self.image = Image.new('1', self.papirus.size, WHITE)
        self.autoUpdate = autoUpdate
	self.partial_updates = False

    def AddText(self, text, x=0, y=0, size = 20, Id = None, invert=False, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'):
        # Create a new Id if none is supplied
        if Id == None:
            Id = str(uuid.uuid4())

        # If the Id doesn't exist, add it  to the dictionary
	if Id not in self.allText:
            self.allText[Id] = DispText(text, x, y, size, invert)
            # add the text to the image
            self.addToImageText(Id, font_path)
            #Automatically show?
            if self.autoUpdate:
                self.WriteAll()

    def UpdateText(self, Id, newText, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'):
        # If the ID supplied is in the dictionary, update the text
        # Currently ONLY the text is update
        if Id in self.allText:
            self.allText[Id].text = newText

            # Remove from the old text from the image (that doesn't use the actual text)
            self.removeImageText(Id)
            # Add the new text to the image
            self.addToImageText(Id, font_path)
            #Automatically show?
            if self.autoUpdate:
                self.WriteAll()

    def RemoveText(self, Id):
        # If the ID supplied is in the dictionary, remove it.
        if Id in self.allText:
            self.removeImageText(Id)
            del self.allText[Id]

            #Automatically show?
            if self.autoUpdate:
                self.WriteAll()

    def removeImageText(self, Id):
        # prepare for drawing
        draw = ImageDraw.Draw(self.image)
        # Draw over the top of the text with a rectangle to cover it
        draw.rectangle([self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy], fill="white")


    def addToImageText(self, Id, font_path='/usr/share/fonts/truetype/freefont/FreeMono.ttf'):
        # Break the text item back in to parts
        size = self.allText[Id].size
        x =  self.allText[Id].x
        y =  self.allText[Id].y
        font_col = BLACK
        back_col = WHITE

        if self.allText[Id].invert:
            font_col = WHITE
            back_col = BLACK

        # prepare for drawing
        draw = ImageDraw.Draw(self.image)

        # Grab the font to use, fixed at the moment
        font = ImageFont.truetype(font_path, size)

        # Calculate the max number of char to fit on line
        # Taking in to account the X starting position
        line_size = ((self.papirus.width - x) / (size*0.65))

        # Starting vars
        current_line = 0
        # unicode by default
        text_lines = [u""]

        # Split the text by \n first
        toProcess = self.allText[Id].text.splitlines()

        # Go through the lines and add them
        for line in toProcess:
            # Add in a line to add the words to
            text_lines.append("")
            # Compute each line
            for word in line.split():
                # If there is space on line add the word to it
                if (len(text_lines[current_line]) + len(word)) < line_size:
                    # Only add a space if there`s something on the line
                    if len(text_lines[current_line]) > 0:
                        text_lines[current_line] += " "
                    text_lines[current_line] += word
                else:
                    # No space left on line so move to next one
                    text_lines.append("")
                    current_line += 1
                    text_lines[current_line] += " " + word
            # Move the pointer to next line
            current_line +=1

        #  Go through all the lines as needed, drawing them on to the image

        # Reset the ending position of the text
        self.allText[Id].endy = y
        self.allText[Id].endx = x

        # Start at the beginning, calc all the end locations
        current_line = 0
        for l in text_lines:
            current_line += 1
            # Find out the size of the line to be drawn
            textSize = draw.textsize(l, font=font)
            # Adjust the x end point if needed
            if textSize[0]+x > self.allText[Id].endx:
                self.allText[Id].endx = textSize[0] + x
            # Add on the y end point
            self.allText[Id].endy += textSize[1]

        # Little adjustment to make sure the text gets covered
        self.allText[Id].endy += 3

        # If the text is wanted inverted, put a rectangle down first
        if self.allText[Id].invert:
            draw.rectangle([self.allText[Id].x, self.allText[Id].y, self.allText[Id].endx, self.allText[Id].endy], fill=back_col)

        # Start at the beginning, add all the lines to the image
        current_line = 0
        for l in text_lines:
            current_line += 1
            # Draw the text to the image
            draw.text( (x, ((size*current_line)-size) + y) , l, font=font, fill=font_col)

    def WriteAll(self, partial_update=False):
        # Push the image to the PaPiRus device, and update only what's needed
        # (unless asked to do a full update)
        self.papirus.display(self.image)
        if partial_update or self.partial_updates:
            self.papirus.partial_update()
        else:
            self.papirus.update()

    def Clear(self):
        # Clear the image, clear the text items, do a full update to the screen
        self.image = Image.new('1', self.papirus.size, WHITE)
        self.allText = dict()
        self.papirus.clear()
Пример #19
0
class HomeHub():
    def __init__(self):
        #button setup
        self.SW1 = 21
        self.SW2 = 16
        self.SW3 = 20
        self.SW4 = 19
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.SW1, GPIO.IN)
        GPIO.setup(self.SW2, GPIO.IN)
        GPIO.setup(self.SW3, GPIO.IN)
        GPIO.setup(self.SW4, GPIO.IN)

        #config file
        self.Config = ConfigParser.ConfigParser()
        self.Config.read('./config.ini')

        rotation = int(self.Config.get('PAPIRUS', 'rotation'))
        fontPath = self.Config.get('PAPIRUS', 'fontPath')
        self.fontSize = int(self.Config.get('PAPIRUS', 'fontSize'))
        backgroundPath = self.Config.get('PAPIRUS', 'backgroundPath')
        self.defaultDisplayOption = self.Config.get('HOMEHUB',
                                                    'defaultDisplayOption')
        self.url = self.Config.get('HOMEHUB', 'url')

        self.currentLightGroup = 0
        self.ResetLightGroups(True)

        #papirus setup
        self.initX = 15
        self.initY = 40

        self.papirusDisplay = Papirus(rotation=rotation)
        self.papirusDisplay.clear()

        #papirus screen setup
        rsimg = Image.open(backgroundPath)
        self.image = Image.new('1', self.papirusDisplay.size, 1)
        self.image.paste(rsimg, (0, 0))

        self.draw = ImageDraw.Draw(self.image)
        self.font = ImageFont.truetype(fontPath, self.fontSize)
        self.CreateTextObject(self.lightGroups[self.currentLightGroup])

        self.ButtonRead()

    def ResetLightGroups(self, init):
        print 'resetLightGroup'
        self.jsonLightGroups = self.QueryLightList(self.url)
        self.lightGroups = self.JsonLightToLightGroupNames(
            self.jsonLightGroups, self.defaultDisplayOption, init)
        print 'powerTest:' + str(self.jsonLightGroups[self.lightGroups[
            self.currentLightGroup]][0]['power'])

    #initial homehub query to retrieve light list
    def QueryLightList(self, url):
        print 'QueryLightList'
        queryParams = {
            self.Config.get('HOMEHUB', 'queryValue'):
            self.Config.get('HOMEHUB', 'paramValue')
        }
        page = requests.get(url, queryParams)

        #light group setup
        return json.loads(page.text)

    def JsonLightToLightGroupNames(self, jsonObject, default, init):
        lightGroups = []
        print 'jsonToNames'
        for key in jsonObject:
            lightGroups.append(key)
            if key == default and init:
                self.currentLightGroup = len(lightGroups) - 1

        return lightGroups

    def CreateTextObject(self, textToDisplay):
        self.draw.text((self.initX, self.initY),
                       textToDisplay,
                       font=self.font,
                       fill=0)
        self.papirusDisplay.display(self.image)
        self.papirusDisplay.update()
        self.TextCleanupForFutureDelete(textToDisplay)

    def TextCleanupForFutureDelete(self, textToDisplay):
        #calculate some text values for when we want to clear this object
        textSize = self.draw.textsize(textToDisplay, font=self.font)
        self.endX = self.initX + textSize[0]
        self.endY = self.initY + self.fontSize

    def ClearExistingTextNoUpdate(self):
        self.draw.rectangle([self.initX, self.initY, self.endX, self.endY],
                            fill='white')

    def UpdateText(self, textToDisplay):
        self.ClearExistingTextNoUpdate()
        self.draw.text((self.initX, self.initY),
                       textToDisplay,
                       font=self.font,
                       fill=0)

        self.papirusDisplay.display(self.image)
        self.papirusDisplay.partial_update()

    def ButtonRead(self):
        while True:
            if GPIO.input(self.SW1) == False and GPIO.input(self.SW2) == False:
                sleep(0.2)
                self.papirusDisplay.clear()
                break

            if GPIO.input(self.SW1) == False:
                self.currentLightGroup -= 1
                if self.currentLightGroup < 0:
                    self.currentLightGroup = len(self.lightGroups) - 1
                self.UpdateText(self.lightGroups[self.currentLightGroup])
                sleep(0.1)

            if GPIO.input(self.SW2) == False:
                self.currentLightGroup += 1
                if self.currentLightGroup >= len(self.lightGroups):
                    self.currentLightGroup = 0
                self.UpdateText(self.lightGroups[self.currentLightGroup])
                sleep(0.1)

            if GPIO.input(self.SW3) == False:
                sleep(0.1)

            if GPIO.input(self.SW4) == False:
                currentLightStatus = self.jsonLightGroups[self.lightGroups[
                    self.currentLightGroup]][0]['power']
                newLightStatus = 'true'
                if currentLightStatus:
                    newLightStatus = 'false'
                print 'lightStatus:' + newLightStatus
                updateParams = {
                    self.Config.get('HOMEHUB', 'queryValue'):
                    self.Config.get('HOMEHUB', 'updateParamValue'),
                    self.Config.get('HOMEHUB', 'updateGroupQueryValue'):
                    self.lightGroups[self.currentLightGroup],
                    self.Config.get('HOMEHUB', 'updateStatusQueryValue'):
                    newLightStatus
                }
                toggle = requests.get(self.url, updateParams, timeout=5)
                sleep(0.1)
                self.ResetLightGroups(False)
                sleep(0.1)

            sleep(0.1)
Пример #20
0
def main(argv):
    """main program - draw and display time and date"""

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)
    papirus.clear()
    demo(papirus)
Пример #21
0
def main(argv):
    global SIZE

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus(rotation=int(argv[0]) if len(sys.argv) > 1 else 0)

    # Use smaller font for smaller displays
    if papirus.height <= 96:
        SIZE = 12

    papirus.clear()

    write_text(
        papirus,
        "Ready... 1 + 2 to exit.\n1 to start GPS\n2 to stop GPS\n4 to restart\n5 to shutdown",
        SIZE)
    TRACKING = False
    while True:
        # Exit when SW1 and SW2 are pressed simultaneously
        if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False):
            write_text(papirus, "Exiting ...", SIZE)
            sleep(0.2)
            papirus.clear()
            sys.exit()

        if GPIO.input(SW1) == False:
            if TRACKING:
                write_text(papirus, "GPS already logging.\nPress 2 to stop",
                           SIZE)
            else:
                # Start tracking
                g = threading.Thread(target=collect_gps,
                                     args=(
                                         papirus,
                                         SIZE,
                                     ),
                                     daemon=True)
                g.start()
                TRACKING = True
        if GPIO.input(SW2) == False:
            if TRACKING:
                # Stop tracking
                g.join()
                TRACKING = False
                write_text(papirus, "Tracking ended.", SIZE)
            else:
                write_text(papirus,
                           "No current GPS logging.\nPress 1 to start", SIZE)
        if GPIO.input(SW3) == False:
            write_text(papirus, "Three", SIZE)

        if GPIO.input(SW4) == False:
            write_text(papirus, "Rebooting...", SIZE)
            os.system("sudo reboot")

        if (SW5 != -1) and (GPIO.input(SW5) == False):
            write_text(papirus, "Shutting Down at\n" + str(datetime.now()),
                       SIZE)
            os.system("sudo shutdown now -h")

        sleep(0.1)
Пример #22
0
def main():
    global SIZE
    global FLAG

    heading = []
    roll = []
    pitch = []

    GPIO.setmode(GPIO.BCM)

    GPIO.setup(SW1, GPIO.IN)
    GPIO.setup(SW2, GPIO.IN)
    GPIO.setup(SW3, GPIO.IN)
    GPIO.setup(SW4, GPIO.IN)
    if SW5 != -1:
        GPIO.setup(SW5, GPIO.IN)

    papirus = Papirus()
    screen = PapirusImage()

    # Use smaller font for smaller dislays
    if papirus.height <= 96:
        SIZE = 18

    papirus.clear()

    # Initialize Screen
    screen.write('../final_project_code/images/light1.bmp')
    while True:
        # Exit when SW1 and SW2 are pressed simultaneously
        if (GPIO.input(SW1) == False) and (GPIO.input(SW2) == False):
            write_text(papirus, "Exiting ...", SIZE)
            sleep(0.2)
            papirus.clear()
            sys.exit()

        if GPIO.input(SW1) == False:
            if FLAG == 4:
                FLAG = 1
            else:
                FLAG += 1
            write_text(papirus, "placeholder", SIZE, FLAG)

        if GPIO.input(SW2) == False:
            if FLAG == 1:
                FLAG = 4
            else:
                FLAG -= 1
            write_text(papirus, "placeholder", SIZE, FLAG)

        input_state = GPIO.input(18)
        if input_state == False:
            # print('Button Pressed')
            # Read the Euler angles for heading, roll, pitch (all in degrees).
            heading_temp, pitch_temp, roll_temp = bno.read_euler()
            # store orientation angles into list arrays
            heading.append(heading_temp)
            roll.append(roll_temp)
            pitch.append(pitch_temp)
            # Read the calibration status, 0=uncalibrated and 3=fully calibrated.
            sys, gyro, accel, mag = bno.get_calibration_status()
            sleep(.01)

        elif len(heading) != 0:
            # Print everything out.

            if debug == 1:
                print "heading list: "

            rounded_heading = []
            rounded_pitch = []

            rounded_heading = round_angles(heading)
            rounded_pitch = round_angles(pitch)

            rounded_heading = np.array(rounded_heading)
            rounded_pitch = np.array(rounded_pitch)

            # Center heading
            centered_heading = rounded_heading[:] - rounded_heading[1]

            if debug == 1:
                print "Centered heading data: "
                print centered_heading
                print "Pitch data: "
                print rounded_pitch

            # Convert heading data to project position data
            position_array_length = len(centered_heading[:])

            if debug == 1:
                print "Array Length: "
                print position_array_length

            pitch_array_length = len(rounded_pitch[:])

            if debug == 1:
                print "pitch array length: "
                print pitch_array_length

            heading_array_length = len(rounded_heading[:])

            if debug == 1:
                print "heading array length: "
                print heading_array_length

            #Convert heading and pitch angles into cartesion coordinates
            #y_length was arbitrarily set to 10
            y_length = 10
            x_position = y_length * np.tan(np.deg2rad(centered_heading[:]))
            y_position = y_length * np.tan(np.deg2rad(rounded_pitch[:]))

            if debug == 1:
                print "x_position array: "
                print x_position

                print "y_position array: "
                print y_position

            data_points = np.vstack((x_position, y_position))

            if debug == 1:
                print "data points: "
                print data_points

            #generate vectors from data_points
            vectors = np.zeros((position_array_length, 3))

            #create vectors connecting each points
            for k in range(0, position_array_length - 2):
                vectors[k, 0] = data_points[0, k + 1] - data_points[0, k]
                vectors[k, 1] = data_points[1, k + 1] - data_points[1, k]

            #creates final vector between starting and ending points
            vectors[position_array_length - 1,
                    0] = data_points[0, position_array_length -
                                     1] - data_points[0, 0]
            vectors[position_array_length - 1,
                    1] = data_points[1, position_array_length -
                                     1] - data_points[1, 0]

            if debug == 1:
                print "Vectors Array: "
                print vectors

            #remove duplicate vectors from array
            vectors = vectors[~(vectors == 0).all(1)]

            if debug == 1:
                print "Vectors with duplicates removed: "
                print vectors

            #generate array of vector angles by reference vector array to a zero degree reference vector
            ref_vector = [1, 0, 0]
            cross_variable = np.cross(ref_vector, vectors)
            vector_array_length = len(vectors)

            vector_angles = []

            for k in range(0, vector_array_length - 1):
                dot_product = np.dot(ref_vector, vectors[k])
                np.arctan2(cross_variable[:, 2],
                           np.dot(ref_vector, vectors[k]))
                vector_angles.append(
                    np.arctan2(cross_variable[k, 2],
                               np.dot(ref_vector, vectors[k])) * 180 / pi)

            if debug == 1:
                print "Vector Angles List: "
                print np.around(vector_angles)

            #replace negative angles to form unit circle values from 0 to 360 degrees
            for k in range(0, vector_array_length - 1):
                if vector_angles[k] <= 0:
                    vector_angles[k] = 360 + vector_angles[k]

            if debug == 1:
                print "Vector Angles List: "
                print np.around(vector_angles)

            #bin vector angles for frequency analysis
            edges = np.linspace(0, 360, 73)  #0 5 10 ...360
            frequency_hist = np.histogram(vector_angles, edges)

            if debug == 1:
                print "Freqency Bins: "
                print frequency_hist[0]

            frequency_hist = np.array(frequency_hist[0])

            #generate shape charactersistics that can be used to identify drawn shape
            dominant_angle_number = len(
                frequency_hist[np.where(frequency_hist > 4)])
            dominant_angle_index = np.argmax(frequency_hist)
            dominant_angle_value = 5 * dominant_angle_index

            print "Dominant Angle: "
            print dominant_angle_value

            #Use frequency analysis to determine shape drawn
            choices = {1: 'line', 3: 'triangle', 4: 'square', 0: 'none'}
            result = choices.get(dominant_angle_number,
                                 'Sorry no ID made! Try again...')

            print "Shape Matched: "
            print result

            if result == 'line':
                if dominant_angle_value < 15 or dominant_angle_value > 345:
                    result = 'right_swipe'
                elif dominant_angle_value < 60 and dominant_angle_value > 15:
                    result = 'quad_diagonal_1'
                elif dominant_angle_value > 135 and dominant_angle_value < 225:
                    result = 'left_swipe'
                elif dominant_angle_value > 60 and dominant_angle_value < 135:
                    result = 'up_swipe'
                elif dominant_angle_value > 235 and dominant_angle_value < 345:
                    result = 'down_swipe'

            print "Shape Matched: "
            print result

            shapes.append(result)
            logic.roku_command(shapes)
            shapes.remove(result)

            # Reset heading list
            heading = []
            pitch = []

        sleep(0.1)
Пример #23
0
    return


#main entry

#edit the fake temperature value to change the frame rate, or
#'echo 25 > /dev/epd/temperature' in another console whilst running.
#fastest is with temperature set to 50, but ghosting is evident.
#lower the value for blacker updates, with less ghosting.
#temp:   50, 48, 42, 38, 35, 32, 30, 28, 27, 26...
#factor:  2,  3,  4,  5,  6,  7,  8,  9, 10, 11...

call(["echo 50 > /dev/epd/temperature"], shell=True)

epd.clear()
counter = 0
#set to initial non-zero value
frametime = 80
#ensure we enter the loop busy, to avoid a 1st frametime measurement error
thread.start_new_thread(epd_update, (counter, ))

try:
    while (True):
        prev = datetime.now()

        epd_draw(frametime, counter)

        while update_status & 2 == 0:  #wait for last update to finish if necessary
            time.sleep(0.001)
        update_status &= ~2
Пример #24
0
import socket

# Fonts
hatdir = '/proc/device-tree/hat'
ipFont = '/usr/share/fonts/truetype/freefont/FreeMonoOblique.ttf'

if __name__ == "__main__":
    # Check EPD_SIZE is defined
    EPD_SIZE = 0.0
    if os.path.exists('/etc/default/epd-fuse'):
        exec(open('/etc/default/epd-fuse').read())
    if EPD_SIZE == 0.0:
        print("Please select your screen size by running 'papirus-config'.")

    papirus = Papirus(rotation=180)
    papirus.clear()

    # Setting the screen color
    BLACK = 0
    WHITE = 1

    # Set the background to white
    image = Image.new('1', papirus.size, WHITE)
    draw = ImageDraw.Draw(image)

    # Grabbing the width and height of the screen
    width, height = image.size

    # Setting the size/font for the IP Address
    ipSize = int((width - 4) / (8 * 0.65))
    ipFont = ImageFont.truetype(ipFont, ipSize)