Exemplo n.º 1
0
class LCDOutput(Output):
    def __init__(self):
        self.lcd = Server()
        self.lcd.start_session()

        idleScreen = self.lcd.add_screen("Idle")
        idleScreen.set_backlight("off")

        self.screen = self.lcd.add_screen("Message")
        self.screen.add_title_widget("title", "pilight Message")
        self.screen.set_duration(5)
        self.screen.set_priority("hidden")
        self.textWidget = self.screen.add_string_widget("message", text="", x=1, y=2)
    def displayMessage(self, message):
        self.textWidget.set_text(message)
        self.screen.set_priority("foreground")
        self.scheduleHide()
    def scheduleHide(self):
        def hide():
            self.screen.set_priority("hidden")
            del self.timer

        if hasattr(self, "timer"): self.timer.cancel()
        self.timer = Timer(5, hide)
        self.timer.start()
Exemplo n.º 2
0
class GeocacheDisplay:
  def __init__(self):
    self.__lcd = Server()
    self.__lcd.start_session()
    self.__screen = self.__lcd.add_screen("cache")
    self.__screen.set_heartbeat("off")
    self.__screen.set_duration(10)
    self.__screen.set_priority("hidden")

    self.__title_widget = self.__screen.add_scroller_widget("title",1,1,12,1,"h",1,"")
    self.__code_widget = self.__screen.add_string_widget("code","",y=2)
    self.__distance_to_cache_widget = self.__screen.add_string_widget("dist","",y=2, x=9)
    self.__bearing_to_cache_widget = self.__screen.add_string_widget("btc","",y=2, x=14)
    self.__bearing_widget = self.__screen.add_string_widget("bearing","",y=1, x=14)

  def update(self, cache_name, code, bearing, bearing_to_cache, distance_to_cache):
    self.__title_widget.set_text(cache_name.encode('ascii'))
    self.__code_widget.set_text(code.encode('ascii'))
    if (distance_to_cache > 1000):
      self.__distance_to_cache_widget.set_text('%0.0fkm' % (distance_to_cache / 1000.0))
    else:
      self.__distance_to_cache_widget.set_text('%0.0fm' % distance_to_cache)
    self.__bearing_widget.set_text(bearing)
    self.__bearing_to_cache_widget.set_text(bearing_to_cache)

  def hide(self):
    self.__screen.set_priority("hidden")

  def show(self, foreground):
    if foreground:
      self.__screen.set_priority("foreground")
    else:
      self.__screen.set_priority("info")
class CommonLCDProc(object):
    """
    Class for interfacing with lcpproc
    """

    def __init__(self, option_config_json):
        self.lcd = Server("media", debug=False)
        self.lcd.start_session()
        self.screens = {}

    def com_lcdproc_add_screen(self, name, heartbeat='off', duration=10):
        self.screens[name] = self.lcd.add_screen(name)
        self.screens[name].set_heartbeat(heartbeat)
        self.screens[name].set_duration(duration)

    def com_lcdproc_add_string(self, screen_name, name, text, x, y):
        string_widget = self.screens[screen_name].add_string_widget(
            name, text=text, x=x, y=y)

    def com_lcdproc_add_scroller(self, screen_name, name, text, speed=2):
        scroller_widget = self.screens[screen_name].add_scroller_widget(name, text=text,
                                                                        speed=speed)

    def com_lcdproc_add_hbar(self, screen_name, name, x, y, length=60):
        hbar_widget = self.screens[screen_name].add_hbar_widget(
            name, x=x, y=y, length=length)

    def com_lcdproc_add_frame(self, screen_name, name):
        frame_widget = self.screens[screen_name].add_frame_widget(name)

    def com_lcdproc_add_number(self, screen_name, name, x, value):
        num1_widget = self.screens[screen_name].add_number_widget(
            name, x=x, value=value)
Exemplo n.º 4
0
class GeocacheLoader(Thread):
  def __init__(self, database_filename, source, pause_func, unpause_func):
    Thread.__init__(self)
    self.daemon = True
    self.__database_filename = database_filename
    self.__source = source
    self.__pause_func = pause_func
    self.__unpause_func = unpause_func
    self.__lcd = Server()
    self.__lcd.start_session()
    self.__screen = self.__lcd.add_screen("loader")
    self.__screen.set_priority("hidden")
    self.__title_widget = self.__screen.add_string_widget("title","",y=1)
    self.__progress_widget = self.__screen.add_hbar_widget("status",y=2,length=0)

  def run(self):
    db = spatialite.connect(self.__database_filename)
    while 1:
      # wait until memory stick is inserted
      while not os.path.exists(self.__source):
        time.sleep(5)

      self.__pause_func()

      cur = db.cursor()

      self.__progress_widget.set_length(0)
      self.__screen.set_priority("foreground")

      # read entire file into memory so we can do nice progress bar
      self.__title_widget.set_text("Reading") 
      f = open(self.__source,"r")
      header = f.readline()
      lines = f.readlines()
      f.close()

      self.__title_widget.set_text("Clearing")
      cur.execute("delete from gc");

      self.__title_widget.set_text("Loading")
      position = 0
      for line in lines:
        position = position + 1
        if position % 20 == 0:
          self.__progress_widget.set_length((float(position)/len(lines)) * (5*16))
        Name,Latitude,Longitude,Description,URL,Type,Container,Diff,Terr = line.split('\t')
        cur.execute("insert into gc (code, description, type, container, diff, terr, location) values (?,?,?,?,?,?,MakePoint(?, ?, 4326))", 
            (Name, Description.replace("'", ""), Type, Container, float(Diff), float(Terr), float(Latitude), float(Longitude)));

      db.commit()
      cur.close()

      self.__screen.set_priority("hidden")

      self.__unpause_func()

      # wait until memory stick is removed
      while os.path.exists(self.__source):
        time.sleep(5)
Exemplo n.º 5
0
class GeocacheLoader(Thread):
  def __init__(self, database_filename, source, pause_func, unpause_func):
    Thread.__init__(self)
    self.daemon = True
    self.__database_filename = database_filename
    self.__source = source
    self.__pause_func = pause_func
    self.__unpause_func = unpause_func
    self.__lcd = Server()
    self.__lcd.start_session()
    self.__screen = self.__lcd.add_screen("loader")
    self.__screen.set_priority("hidden")
    self.__title_widget = self.__screen.add_string_widget("title","",y=1)
    self.__progress_widget = self.__screen.add_hbar_widget("status",y=2,length=0)

  def run(self):
    db = spatialite.connect(self.__database_filename)
    while 1:
      # wait until memory stick is inserted
      while not os.path.exists(self.__source):
        time.sleep(5)

      self.__pause_func()

      cur = db.cursor()

      self.__progress_widget.set_length(0)
      self.__screen.set_priority("foreground")

      # read entire file into memory so we can do nice progress bar
      self.__title_widget.set_text("Reading") 
      f = open(self.__source,"r")
      header = f.readline()
      lines = f.readlines()
      f.close()

      self.__title_widget.set_text("Clearing")
      cur.execute("delete from gc");

      self.__title_widget.set_text("Loading")
      position = 0
      for line in lines:
        position = position + 1
        if position % 20 == 0:
          self.__progress_widget.set_length((float(position)/len(lines)) * (5*16))
        Name,Latitude,Longitude,Description,URL,Type,Container,Diff,Terr = line.split('\t')
        cur.execute("insert into gc (code, description, URL, type, container, diff, terr, location) values (?,?,?,?,?,?,?,MakePoint(?, ?, 4326))", 
            (Name, Description.replace("'", ""), URL, Type, Container, float(Diff), float(Terr), float(Latitude), float(Longitude)));

      db.commit()
      cur.close()

      self.__screen.set_priority("hidden")

      self.__unpause_func()

      # wait until memory stick is removed
      while os.path.exists(self.__source):
        time.sleep(5)
Exemplo n.º 6
0
def write_to_lcd():
    lcd = Server("localhost", debug=False)
    lcd.start_session()

    screen1 = lcd.add_screen("screen1")
    screen1.set_heartbeat("off")

    system_uptime = os.popen('uptime | cut -c 13-19').read()
    system_uptime = system_uptime.rstrip()

    (lan_bytes_rx, lan_bytes_tx, wan_bytes_rx, wan_bytes_tx, lan_state_isup,
     wan_state_isup) = router_stats.interface_stats()
    user_load, system_load, irq_load = router_stats.cpu_load_stats()
    mem_used_percent = router_stats.mem_load_stats()

    string_widget = screen1.add_string_widget("wan_info_title",
                                              text="WAN data (gb):",
                                              x=1,
                                              y=1)

    string_widget = screen1.add_string_widget(
        "wan_info_data",
        text="RX:{0:.2f} ||TX:{1:.2f}".format(wan_bytes_rx / 1073741824,
                                              wan_bytes_tx / 1073741824),
        x=1,
        y=2)

    string_widget = screen1.add_string_widget("lan_info_title",
                                              text="LAN data (gb):",
                                              x=1,
                                              y=3)
    string_widget = screen1.add_string_widget(
        "lan_info_data",
        text="RX:{0:.2f} ||TX:{1:.2f}".format(lan_bytes_rx / 1073741824,
                                              lan_bytes_tx / 1073741824),
        x=1,
        y=4)

    string_widget = screen1.add_string_widget("cpu_info_title",
                                              text="CPU load:",
                                              x=1,
                                              y=5)
    string_widget = screen1.add_string_widget(
        "cpu_info_data",
        text="U: {0:.0f}% S: {1:.0f}% I: {2:.0f}%".format(
            user_load, system_load, irq_load),
        x=1,
        y=6)

    string_widget = screen1.add_string_widget(
        "mem_info",
        text="MEM load: {0:.1f}% used".format(mem_used_percent),
        x=1,
        y=7)

    string_widget = screen1.add_string_widget(
        "sys_uptime", text="Uptime: {0}".format(system_uptime), x=1, y=8)
Exemplo n.º 7
0
def main():
    current_isp_index = 0

    try:
        lcd = Server("localhost", debug=False)
        lcd.start_session()

        sc = lcd.add_screen("home")
        sc.set_heartbeat("off")
        sc.set_duration(10)

        line1 = sc.add_string_widget("Line1Widget", text="Init...", x=1, y=1)
        line2 = sc.add_scroller_widget("Line2Widget",
                                       text="",
                                       speed=6,
                                       top=2,
                                       right=16)

        last_calibration = get_calibration()

        update_display(line1, line2, current_isp_index)
        update_shaping(last_calibration, current_isp_index)

        lcd.add_key("Down")
        lcd.add_key("Up")

        last_update_time = time.time()
        while (True):
            key = lcd.poll()
            if key is not None:
                favorites = get_favorites()
                if key == "key Down\n":
                    current_isp_index += 1
                    if current_isp_index == len(favorites):
                        current_isp_index = 0
                elif key == "key Up\n":
                    current_isp_index -= 1
                    if current_isp_index < 0:
                        current_isp_index = len(favorites) - 1
                else:
                    print(("Unknown key: ", key))
                update_display(line1, line2, current_isp_index)
                # reload the calibration, in case it has updated
                last_calibration = get_calibration()
                update_shaping(last_calibration, current_isp_index)
                last_update_time = time.time()
            # watch for file changes on LASTDISPLAY_FULLPATH
            elif os.path.isfile(LASTDISPLAY_FULLPATH) and os.stat(
                    LASTDISPLAY_FULLPATH).st_mtime > last_update_time:
                last_update_time = time.time()
                with open(LASTDISPLAY_FULLPATH) as f:
                    line1.set_text(f.readline().split("\n")[0])
                    line2.set_text(f.readline().split("\n")[0])

            time.sleep(0.2)
    except ConnectionRefusedError:
        print("display: problem connecting to lcdproc, shutting down")
Exemplo n.º 8
0
def main():

    lcd = Server("media", debug=False)
    lcd.start_session()

    screen1 = lcd.add_screen("Screen1")
    screen1.set_heartbeat("off")
    screen1.set_duration(10)

    screen2 = lcd.add_screen("Screen2")
    screen2.set_heartbeat("off")
    screen2.set_duration(2)

    #string_widget = screen.add_string_widget("MyStringWidget", text="TestwWEJIowejioewjio", x=1, y=2)
    #scroller_widget = screen.add_scroller_widget("MyScrollerWidget", text="This Is A Test Message, Yeah, Yeah, Yeah", speed=2)
    #hbar_widget = screen.add_hbar_widget("MyHBarWidget", x=1, y=4, length=60)
    #frame_widget = screen.add_frame_widget("MyFrameWidget")

    num1_widget = screen1.add_number_widget("MyNumber1Widget", x=1, value=0)
    num2_widget = screen1.add_number_widget("MyNumber2Widget", x=5, value=0)
    num3_widget = screen1.add_number_widget("MyNumber3Widget", x=9, value=0)
    num4_widget = screen1.add_number_widget("MyNumber4Widget", x=13, value=0)

    time.sleep(2)

    progress = 0

    while True:

        num1_widget.set_value(progress)
        num2_widget.set_value(progress)
        num3_widget.set_value(progress)
        num4_widget.set_value(progress)

        time.sleep(0.5)

        progress = progress + 1
        if progress > 9: progress = 0
Exemplo n.º 9
0
def main():

    lcd = Server("media", debug=False)
    lcd.start_session()
    
    screen1 = lcd.add_screen("Screen1")
    screen1.set_heartbeat("off")
    screen1.set_duration(10)
    
    screen2 = lcd.add_screen("Screen2")
    screen2.set_heartbeat("off")
    screen2.set_duration(2)

    #string_widget = screen.add_string_widget("MyStringWidget", text="TestwWEJIowejioewjio", x=1, y=2)
    #scroller_widget = screen.add_scroller_widget("MyScrollerWidget", text="This Is A Test Message, Yeah, Yeah, Yeah", speed=2)
    #hbar_widget = screen.add_hbar_widget("MyHBarWidget", x=1, y=4, length=60)
    #frame_widget = screen.add_frame_widget("MyFrameWidget")
    
    num1_widget = screen1.add_number_widget("MyNumber1Widget", x=1, value=0)
    num2_widget = screen1.add_number_widget("MyNumber2Widget", x=5, value=0)
    num3_widget = screen1.add_number_widget("MyNumber3Widget", x=9, value=0)    
    num4_widget = screen1.add_number_widget("MyNumber4Widget", x=13, value=0)    

    time.sleep(2)

    progress = 0
    
    while True:
    
        num1_widget.set_value(progress)
        num2_widget.set_value(progress)
        num3_widget.set_value(progress)
        num4_widget.set_value(progress)                
    
        time.sleep(0.5)
        
        progress = progress + 1
        if progress > 9: progress = 0
Exemplo n.º 10
0
class TracklogExporter(Thread):
    def __init__(self, tracklog_source_dir, tracklog_export_dir):
        Thread.__init__(self)
        self.daemon = True
        self.__tracklog_source_dir = tracklog_source_dir
        self.__tracklog_export_dir = tracklog_export_dir
        self.__lcd = Server()
        self.__lcd.start_session()
        self.__screen = self.__lcd.add_screen("exporter")
        self.__screen.set_priority("hidden")
        self.__title_widget = self.__screen.add_string_widget("title", "", y=1)
        self.__progress_widget = self.__screen.add_hbar_widget("status",
                                                               y=2,
                                                               length=0)

    def __test_lock(self, file):
        f = open(file, 'r')
        try:
            ret = True
        except:
            ret = False
        f.close()
        return ret

    def run(self):
        while 1:
            # wait until memory stick is inserted
            while not os.path.exists(self.__tracklog_export_dir):
                time.sleep(5)

            self.__progress_widget.set_length(0)
            self.__screen.set_priority("foreground")
            self.__title_widget.set_text("Moving Logs")

            files = glob.glob(os.path.join(self.__tracklog_source_dir,
                                           "*.csv"))
            position = 0
            for file in files:
                if self.__test_lock(file):
                    shutil.move(file, self.__tracklog_export_dir)
                self.__progress_widget.set_length(
                    (float(position) / len(files)) * (5 * 16))
                position = position + 1

            self.__screen.set_priority("hidden")

            # wait until memory stick is removed
            while os.path.exists(self.__tracklog_export_dir):
                time.sleep(5)
Exemplo n.º 11
0
class GeocacheDisplay:
  def __init__(self, scroll_speed=3): # Scroll Speed can be customized in cacheberrypi.cfg
    self.__lcd = Server()
    self.__lcd.start_session()
    self.__screen = self.__lcd.add_screen("cache")
    self.__screen.set_heartbeat("off")
    self.__screen.set_duration(10)
    self.__screen.set_priority("hidden")
# Scroller Widget parameters - SCREEN, REF, LEFT, TOP, RIGHT, BOTTOM, DIRECTION, SPEED, TEXT
# Scroll speed increases as the speed setting decreases.  1 is the fastest.
    self.__title_widget = self.__screen.add_scroller_widget("title",1,1,12,1,"h",scroll_speed,"")
    self.__code_widget = self.__screen.add_string_widget("code","",y=2)
    self.__distance_to_cache_widget = self.__screen.add_string_widget("dist","",y=2, x=9)
    self.__bearing_to_cache_widget = self.__screen.add_string_widget("btc","",y=2, x=14)
    self.__bearing_widget = self.__screen.add_string_widget("bearing","",y=1, x=14)

  def update(self, cache_name, code, bearing, bearing_to_cache, distance_to_cache, MEASUREMENT_STANDARD):
    self.__title_widget.set_text(cache_name.encode('ascii'))
    self.__code_widget.set_text(code.encode('ascii'))
    if MEASUREMENT_STANDARD == 'US':
      display_distance = (distance_to_cache / 1609.34) # convert distance_to_cache from meters to miles
      small_display_distance = (display_distance * 5280) # convert display_distance from miles to feet
      units = "Mi"
      small_units = "'" 
      threshold = 1609.34
    elif MEASUREMENT_STANDARD == 'METRIC':
      display_distance = (distance_to_cache / 1000)
      small_display_distance = (distance_to_cache)
      units = 'km'
      small_units = 'm'
      threshold = 1000
    else:
      raise ValueError('MEASUREMENT_STANDARD must be "US" or "METRIC"')
    if (distance_to_cache > threshold): # If distance to cache is less than 1 'units', display small_units
      self.__distance_to_cache_widget.set_text((('%0.0f' % display_distance) + units).rjust(4))
    else:
      self.__distance_to_cache_widget.set_text((('%0.0f' % small_display_distance) + small_units).rjust(5))
    self.__bearing_widget.set_text((bearing).rjust(3))
    self.__bearing_to_cache_widget.set_text((bearing_to_cache).rjust(3))

  def hide(self):
    self.__screen.set_priority("hidden")

  def show(self, foreground):
    if foreground:
      self.__screen.set_priority("foreground")
    else:
      self.__screen.set_priority("info")
Exemplo n.º 12
0
class Dashboard:
  def __init__(self):
    self.__lcd = Server()
    self.__lcd.start_session()
    self.__screen = self.__lcd.add_screen("dashboard")
    self.__screen.set_heartbeat("off")
    self.__screen.set_priority("info")

    self.__clock_widget = self.__screen.add_string_widget("time","")
    self.__speed_widget = self.__screen.add_string_widget("speed","",y=2, x=1)
    self.__bearing_widget = self.__screen.add_string_widget("bearing","",y=2, x=14)

  def update(self, clock, speed, bearing, units):
    if clock:
      self.__clock_widget.set_text(time.strftime('%H:%M:%S  %d-%b', clock))
    self.__bearing_widget.set_text(bearing)
    self.__speed_widget.set_text('%0.0f ' % speed + units)
Exemplo n.º 13
0
class LCDController:
	def __init__(self):
		print "Setting up lcdproc client ..."
		self.__lcdServer = Server(hostname="localhost")
		self.__lcdServer.start_session()
		self.__screen = self.__lcdServer.add_screen("Radio")
		self.__screen.set_heartbeat("off")
		self.__first = self.__screen.add_scroller_widget("artist",text="",left=5, top=1, right=12, bottom=2,speed=5, direction="h")
		self.__last = self.__screen.add_scroller_widget("title",text="",left=5, top=2, right=12, bottom=2,speed=5, direction="h")

	def setFirst(self, text):
		self.__first.set_text(text)
		log.info("LCD - First: " + text)
	
	def setLast(self, text):
		self.__last.set_text(text)
		log.info("LCD -  Last: " + text)
Exemplo n.º 14
0
class TracklogExporter(Thread):
  def __init__(self, tracklog_source_dir, tracklog_export_dir):
    Thread.__init__(self)
    self.daemon = True
    self.__tracklog_source_dir = tracklog_source_dir
    self.__tracklog_export_dir = tracklog_export_dir
    self.__lcd = Server()
    self.__lcd.start_session()
    self.__screen = self.__lcd.add_screen("exporter")
    self.__screen.set_priority("hidden")
    self.__title_widget = self.__screen.add_string_widget("title","",y=1)
    self.__progress_widget = self.__screen.add_hbar_widget("status",y=2,length=0)

  def __test_lock(self, file):
        f = open(file, 'r')
        try:
          ret = True
        except:
          ret = False
        f.close()
        return ret

  def run(self):
    while 1:
      # wait until memory stick is inserted
      while not os.path.exists(self.__tracklog_export_dir):
        time.sleep(5)

      self.__progress_widget.set_length(0)
      self.__screen.set_priority("foreground")
      self.__title_widget.set_text("Moving Logs") 

      files = glob.glob(os.path.join(self.__tracklog_source_dir, "*.csv"))
      position = 0
      for file in files:
        if self.__test_lock(file):
          shutil.move(file, self.__tracklog_export_dir)
        self.__progress_widget.set_length((float(position)/len(files)) * (5*16))
        position = position + 1

      self.__screen.set_priority("hidden")

      # wait until memory stick is removed
      while os.path.exists(self.__tracklog_export_dir):
        time.sleep(5)
Exemplo n.º 15
0
class GeocacheDisplay:
    def __init__(self):
        self.__lcd = Server()
        self.__lcd.start_session()
        self.__screen = self.__lcd.add_screen("cache")
        self.__screen.set_heartbeat("off")
        self.__screen.set_duration(10)
        self.__screen.set_priority("hidden")

        self.__title_widget = self.__screen.add_scroller_widget(
            "title", 1, 1, 12, 1, "h", 1, "")
        self.__code_widget = self.__screen.add_string_widget("code", "", y=2)
        self.__distance_to_cache_widget = self.__screen.add_string_widget(
            "dist", "", y=2, x=9)
        self.__bearing_to_cache_widget = self.__screen.add_string_widget("btc",
                                                                         "",
                                                                         y=2,
                                                                         x=14)
        self.__bearing_widget = self.__screen.add_string_widget("bearing",
                                                                "",
                                                                y=1,
                                                                x=14)

    def update(self, cache_name, code, bearing, bearing_to_cache,
               distance_to_cache):
        self.__title_widget.set_text(cache_name.encode('ascii'))
        self.__code_widget.set_text(code.encode('ascii'))
        if (distance_to_cache > 1000):
            self.__distance_to_cache_widget.set_text(
                '%0.0fkm' % (distance_to_cache / 1000.0))
        else:
            self.__distance_to_cache_widget.set_text('%0.0fm' %
                                                     distance_to_cache)
        self.__bearing_widget.set_text(bearing)
        self.__bearing_to_cache_widget.set_text(bearing_to_cache)

    def hide(self):
        self.__screen.set_priority("hidden")

    def show(self, foreground):
        if foreground:
            self.__screen.set_priority("foreground")
        else:
            self.__screen.set_priority("info")
Exemplo n.º 16
0
def write_to_lcd():
    lcd = Server("localhost", debug=False)
    lcd.start_session()

    screen1 = lcd.add_screen("screen1")
    screen1.set_heartbeat("off")

    system_uptime = os.popen('uptime | cut -c 13-19').read()
    system_uptime = system_uptime.rstrip()

    (lan_bytes_rx, lan_bytes_tx, wan_bytes_rx, wan_bytes_tx,
        lan_state_isup, wan_state_isup) = router_stats.interface_stats()
    user_load, system_load, irq_load = router_stats.cpu_load_stats()
    mem_used_percent = router_stats.mem_load_stats()

    string_widget = screen1.add_string_widget(
        "wan_info_title", text="WAN data (gb):", x=1, y=1)

    string_widget = screen1.add_string_widget("wan_info_data",
        text="RX:{0:.2f} ||TX:{1:.2f}".format(
                                               wan_bytes_rx / 1073741824,
                                               wan_bytes_tx / 1073741824),
                                               x=1, y=2)

    string_widget = screen1.add_string_widget(
        "lan_info_title", text="LAN data (gb):", x=1, y=3)
    string_widget = screen1.add_string_widget("lan_info_data",
        text="RX:{0:.2f} ||TX:{1:.2f}".format(
                                               lan_bytes_rx / 1073741824,
                                               lan_bytes_tx / 1073741824),
                                               x=1, y=4)

    string_widget = screen1.add_string_widget(
        "cpu_info_title", text="CPU load:", x=1, y=5)
    string_widget = screen1.add_string_widget(
        "cpu_info_data", text="U: {0:.0f}% S: {1:.0f}% I: {2:.0f}%".format(
        user_load, system_load, irq_load), x=1, y=6)

    string_widget = screen1.add_string_widget(
        "mem_info", text="MEM load: {0:.1f}% used".format(
        mem_used_percent), x=1, y=7)

    string_widget = screen1.add_string_widget(
        "sys_uptime", text="Uptime: {0}".format(system_uptime), x=1, y=8)
Exemplo n.º 17
0
class Dashboard:
    def __init__(self):
        self.__lcd = Server()
        self.__lcd.start_session()
        self.__screen = self.__lcd.add_screen("dashboard")
        self.__screen.set_heartbeat("off")
        self.__screen.set_priority("info")

        self.__clock_widget = self.__screen.add_string_widget("time", "")
        self.__speed_widget = self.__screen.add_string_widget("speed",
                                                              "",
                                                              y=2,
                                                              x=1)
        self.__bearing_widget = self.__screen.add_string_widget("bearing",
                                                                "",
                                                                y=2,
                                                                x=14)

    def update(self, clock, speed, bearing):
        if clock:
            self.__clock_widget.set_text(
                time.strftime('%H:%M:%S  %d-%b', clock))
        self.__bearing_widget.set_text(bearing)
        self.__speed_widget.set_text('%0.0f km/h' % (speed * 3.6))
Exemplo n.º 18
0
class LCDProcPlugin (GObject.Object, Peas.Activatable):
    BASE_KEY = "org.gnome.rhythmbox.plugins.lcdproc-plugin"
    __gtype_name__ = 'LCDProcPlugin'
    object = GObject.property(type=GObject.Object)

    def __init__ (self):
        GObject.Object.__init__ (self)
        self.scrolling = None
        self.running = False

    def time_callback(self, player, time):
        if not self.running and not self.connect():
            # no connection to LCDd
            print "Could not reconnect to LCDd"
            return
        
        try:
            result, playing = player.get_playing()
            if not (time >= 0 and playing):
                return
            if self.streaming:
                # do not append remaining time or track
                self.scrolling.update_widget(self.time_widget, "Webradio" + ("%2d:%02d" % (time/60,  time % 60)).rjust(12," "))
            else:
                # append remaining time
                self.scrolling.update_widget(self.time_widget, self.track + (("%2d:%02d -" % (time/60,  time % 60)) + self.duration).rjust(13," "))
        except:
            # connection to LCDd is broken
            self.connectionlost("time_callback");

    def change_callback(self, player, entry):
        #print "change callback"
        if not self.running and not self.connect():
            # no connection to LCDd
            print "Could not reconnect to LCDd"
            return
        
#        try:
        if (entry == None):
            self.title = "No playback"
            self.album = ""
            self.artist = ""
            self.duration = ""
            self.track = ""
            self.streaming = False
        else:
            if entry.get_entry_type().props.category == RB.RhythmDBEntryCategory.STREAM:
                # streaming item - set station name as album and only update artist & title
                self.album = entry.get_string(RB.RhythmDBPropType.TITLE)
                self.artist = ""
                self.title = ""
                self.track = ""
                self.duration = ""
                self.streaming = True
            else:
                # regular item (local DB or LastFM)
                self.artist = entry.get_string(RB.RhythmDBPropType.ARTIST)
                self.album = entry.get_string(RB.RhythmDBPropType.ALBUM)
                self.title = entry.get_string(RB.RhythmDBPropType.TITLE)
                tracknumber = entry.get_ulong(RB.RhythmDBPropType.TRACK_NUMBER)
                if tracknumber > 0 and tracknumber < 100:
                    # valid track number
                    self.track = "Track" + str(tracknumber).rjust(2," ")
                else:
                    # invalid track number
                    self.track = ""
                seconds = entry.get_ulong(RB.RhythmDBPropType.DURATION)
                self.duration = "%2d:%02d" % (seconds/60,  seconds % 60)
                self.streaming = False
        
        self.update_widgets()
#        except:
#            # connection to LCDd is broken
#            self.connectionlost("change_callback");
    
    def update_widgets(self):
        self.scrolling.update_widget(self.title_widget, self.title)
        self.scrolling.update_widget(self.album_widget, self.album)
        self.scrolling.update_widget(self.artist_widget, self.artist)
        self.scrolling.update_widget(self.time_widget, self.duration)
        
    # copied from im-status plugin
    def playing_song_property_changed (self, sp, uri, property, old, new):
        if not self.running and not self.connect():
            # no connection to LCDd
            print "Could not reconnect to LCDd"
            return
        #print "prop callback: old %s new %s uri %s prop %s" % (old, new, uri, property)
#        if not self.streaming:
#            # do not update
#            return
        relevant = False
        if sp.get_playing () and property in (NORMAL_SONG_ARTIST,STREAM_SONG_ARTIST):
            self.artist = new
            relevant = True
        elif sp.get_playing () and property in (NORMAL_SONG_TITLE,STREAM_SONG_TITLE):
            if new.count(" - ") >= 1:
                # contains "Artist - Title"
                fields = new.split(" - ",1)
                self.artist = fields[0]
                self.title = fields[1]
            else:
                # only title
                self.title = new
            relevant = True
        elif sp.get_playing () and property in (NORMAL_SONG_ALBUM,STREAM_SONG_ALBUM):
            self.album = new
            relevant = True
        
        if relevant:
            self.update_widgets()

    def connectionlost(self, source):
        print "in " + source + ": Connection to LCDd lost, disconnecting plugin (will try to reconnect)"
        self.disconnect()
    
    def do_activate(self):
        self.shell = self.object
        self.config = LCDProcPluginConfigureDialog()
        if not self.connect():
             # LCDd not running
            print "LCDd not running, plugin not initialising"
            self.running = False
            self.inited = False
            return
        self.pec_id = self.shell.props.shell_player.connect('playing-song-changed', self.change_callback)
        self.pspc_id = self.shell.props.shell_player.connect ('playing-song-property-changed', self.playing_song_property_changed)
        self.inited = True
        print "Connected to LCDProc, loading plugin"


    def connect(self):
        try:
            self.lcd = Server()
        except:
            # LCDd not running
            self.running = False
            return False

        self.lcd.start_session()
        self.running = True
        
        self.screen1 = self.lcd.add_screen("Screen1")
        self.screen1.set_heartbeat("off")
        self.screen1.set_priority("foreground")
        
        self.counter = 0
        self.title_widget = self.screen1.add_string_widget("Widget1", x = 1, y = 1 , text = "")
        self.artist_widget = self.screen1.add_string_widget("Widget2", x = 1, y = 2 , text = "")
        self.album_widget = self.screen1.add_string_widget("Widget3", x = 1, y = 3 , text = "")
        self.time_widget = self.screen1.add_string_widget("Widget4", x = 1, y = 4 , text = "")
        try:
            scrollmode = Gio.Settings.new(self.BASE_KEY).get_string('scrolling')
        except:
            scrollmode = SCROLL_ROLLING
        self.scrolling = scroll_thread(scrollmode)
        self.scrolling.config([self.title_widget, self.album_widget, self.artist_widget, self.time_widget])
        self.scrolling.start()
        
        self.pec_idd = self.shell.props.shell_player.connect('elapsed-changed', self.time_callback)
        self.change_callback(self.shell.props.shell_player,self.shell.props.shell_player.get_playing_entry())
#        self.time_callback(self.shell.props.shell_player,-1)
        print "(Re-)Connected to LCDProc"
        return True

    def do_deactivate(self):
        self.disconnect()
        if self.inited:
            #plugin was running at some point
            self.shell.props.shell_player.disconnect(self.pec_id)
            self.shell.props.shell_player.disconnect(self.pspc_id)
            del self.pec_id
            del self.pspc_id
        del self.shell
        print "Plugin unloaded"

    def disconnect(self):
        if not self.running:
            # LCDd was not running, nothing to clean up
            return
        
        self.running = False;
        self.scrolling.stop_scrolling()
        self.shell.props.shell_player.disconnect(self.pec_idd)
        del self.pec_idd
        del self.scrolling
        del self.title_widget
        del self.album_widget
        del self.artist_widget
        del self.time_widget
        del self.screen1
        self.lcd.tn.close()
        del self.lcd
        print "Plugin disconnected"
Exemplo n.º 19
0
class LCDProcPlugin (GObject.Object, Peas.Activatable):
    object = GObject.property(type=GObject.Object)
 
    def __init__(self):
        super(LCDProcPlugin, self).__init__()
 
    def do_activate(self):
        print "Activating Plugin"
         
        self.entry = None
        self.duration = 0
        self.artist = " "
        self.title = " "
        self.album = " "
 
        # Initialise LCD
        try:
            self.lcd = Server(LCDPROC_HOST, debug=True)
        except SocketError:
            print "Failed to connect to LCDd"
            return False
        self.lcd.start_session()
        self.screen1 = self.lcd.add_screen("Rhythmbox")
        self.title1_widget = self.screen1.add_title_widget("Title", "Rhythmbox")
        self.label1_widget = self.screen1.add_string_widget("Label", KEY_LABELS, 1, 2)
        self.screen2 = self.lcd.add_screen("Rhythmbox-info")
        self.screen2.set_heartbeat("off")
        self.lcd.output("on")
        width = self.lcd.server_info["screen_width"]
        self.album_widget = self.screen2.add_scroller_widget("AlbumWidget", top = ALBUM_LINE, bottom = ALBUM_LINE, right = width, text = "Album")
        self.artist_widget = self.screen2.add_scroller_widget("ArtistWidget", top = ARTIST_LINE, bottom = ARTIST_LINE, right = width, text = "Artist")
        self.title_widget = self.screen2.add_scroller_widget("TitleWidget", top = TITLE_LINE, bottom = TITLE_LINE, right = width, text = "Title")
        self.progress_bar = self.screen2.add_hbar_widget("HBarWidget", x=1, y=TIME_LINE, length=0)
        self.time_widget = self.screen2.add_string_widget("TimeWidget", "", 1, TIME_LINE)
        self.displayed_lines = 4
        if SHOW_LABELS:
            self.label_widget = self.screen2.add_string_widget("LabelWidget", KEY_LABELS, 1, LABEL_LINE)
            self.displayed_lines += 1
 
        self.bounce_roll_length = width + BOUNCE_ROLL_THRESHOLD
        self.screen_width_pxl = width * self.lcd.server_info["cell_width"]
         
        for key in keyUse.keys():
            self.lcd.add_key(key)
 
        # Connect call-back functions to interesting events.
        sp = self.object.props.shell_player
        self.pc_id = sp.connect('playing-changed', self.playing_changed)
        self.psc_id = sp.connect('playing-song-changed', self.playing_song_changed)
        self.pspc_id = sp.connect('playing-song-property-changed', self.playing_song_property_changed)
        self.ec_id = sp.connect('elapsed-changed', self.elapsed_changed)
        # LCDd processes key input at 32Hz.
        self.pollcbtag = GObject.timeout_add(1000 / 32, self.poll_cb)
        
        print sp.get_playback_state()
        if sp.get_playing():
            print "Activating: playing"
            self.set_entry(sp.get_playing_entry())
            self.screen1.set_priority("background")
            self.screen2.set_priority("foreground")
        else:
            print "Activating: stopped"
            self.screen1.set_priority("info")
            self.screen2.set_priority("background")
        print "Plugin Activated"
 
    def do_deactivate(self):
        print "Deactivating Plugin"
        if not hasattr(self, 'pc_id'):
            return
        sp = self.object.props.shell_player
        sp.disconnect(self.pc_id)
        sp.disconnect(self.psc_id)
        sp.disconnect(self.pspc_id)
        sp.disconnect(self.ec_id)
        GObject.source_remove(self.pollcbtag)
 
        # Disconnect LCD
        del self.title1_widget
        del self.label1_widget
        del self.artist_widget
        del self.album_widget
        del self.title_widget
        del self.progress_bar
        del self.time_widget
        if SHOW_LABELS:
            del self.label_widget
        del self.screen1
        del self.screen2
        self.lcd.tn.close()
        del self.lcd
        print "Plugin Deactivated"
 
    def poll_cb(self):
        response = self.lcd.poll()
        if response:
            print "Poll Response: %s" % (response[:-1])
            bits = (response[:-1]).split(" ")
            if bits[0] == "key":
                action = keyUse[bits[1]]
                sp = self.object.props.shell_player    # Used by some actions.
                print action
                try:
                    exec action
                except GError as e:
                    if e.args[0] in ('Not currently playing', 'No previous song'):
                        print "%s safe to ignore." % e.args[0]
                    else:
                        print "%s unexpected." % e.args
                        raise
                except:
                    print "Blast! Unexpected error:", sys.exc_info()[0]
                    raise
        return True
 
    def playing_changed(self, player, playing):
        if playing:
            print "Playing"
            self.set_entry(player.get_playing_entry())
            self.screen1.set_priority("background")
            self.screen2.set_priority("foreground")
        else:
            print "Not playing"
            self.entry = None
            self.screen1.set_priority("info")
            self.screen2.set_priority("background")
 
    def playing_song_changed(self, player, entry):
        print "Playing song changed %s" % (entry)
        if player.get_playing():
            self.set_entry(entry)
 
    def playing_song_property_changed(self, player, uri, song_property, old, new):
        print "Playing song %s property (%s) changed (%s to %s)" % (uri, song_property, old, new)
        if player.get_playing():
            if song_property in (NORMAL_ALBUM, STREAM_ALBUM):
                self.album = new
            elif song_property in (NORMAL_ARTIST, STREAM_ARTIST):
                self.artist = new
            elif song_property in (NORMAL_TITLE):
                self.title = new
            elif song_property in (STREAM_TITLE):
                if new.count(" - ") >= 1:
                    # contains "Artist - Title"
                    fields = new.split(" - ",1)
                    self.artist = fields[0]
                    self.title = fields[1]
                else:
                    # only title
                    self.title = new
                    self.artist = ""
                self.album = uri
                self.duration = 0
            else:
                return
        else:
            return
        self.set_display()
 
    def elapsed_changed(self, player, time):
#         print "Elapsed changed %d" % time
        if (time >= 0 and self.duration > 0):
            progress = self.screen_width_pxl * time / self.duration
            self.progress_bar.set_length(progress)
            progress_str  = "%d:%02d" % (time/60, time%60)
            if (time < self.duration / 2):
                self.time_widget.set_x(self.lcd.server_info["screen_width"] - len(progress_str) + 1)
            else:
                self.time_widget.set_x(1)
            self.time_widget.set_text(progress_str)
        else:
            self.progress_bar.set_length(0)
            self.time_widget.set_text("")

    def set_entry(self, entry):
        if rb.entry_equal(entry, self.entry):
            return
        self.entry = entry
        if entry is None:
            return
        self.album = entry.get_string(RB.RhythmDBPropType.ALBUM)
        self.artist = entry.get_string(RB.RhythmDBPropType.ARTIST)
        self.title = entry.get_string(RB.RhythmDBPropType.TITLE)
        self.duration = entry.get_ulong(RB.RhythmDBPropType.DURATION)
#         sp = self.object.props.shell_player
#         self.duration = sp.get_playing_song_duration()
        self.rating = entry.get_double(RB.RhythmDBPropType.RATING)
        print "Song rating %g" % self.rating
        db = self.object.get_property("db")
        if entry.get_entry_type().props.category == RB.RhythmDBEntryCategory.STREAM:
            if not self.album:
                self.album = db.entry_request_extra_metadata(entry, STREAM_ALBUM)
            if not self.artist:
                self.artist = db.entry_request_extra_metadata(entry, STREAM_ARTIST)
            if not self.title:
                self.title = db.entry_request_extra_metadata(entry, STREAM_TITLE)
        self.set_display()
 
    def set_display(self):
        album_text = self.album
        if DONT_SCROLL:
            album_text = album_text[0:self.lcd.server_info["screen_width"]]
        elif len(album_text) < self.bounce_roll_length:
            self.album_widget.set_direction("h")    # Bounce text to show characters that don't fit
        else:
            self.album_widget.set_direction("m")    # Roll text to show characters that don't fit
            album_text += " * "
        self.album_widget.set_text(album_text)
 
        artist_text = self.artist
        if DONT_SCROLL:
            artist_text = artist_text[0:self.lcd.server_info["screen_width"]]
        elif len(artist_text) < self.bounce_roll_length:
            self.artist_widget.set_direction("h")
        else:
            self.artist_widget.set_direction("m")
            artist_text += " * "
        self.artist_widget.set_text(artist_text)
 
        title_text = self.title
        if DONT_SCROLL:
            title_text = title_text[0:self.lcd.server_info["screen_width"]]
        elif len(title_text) < self.bounce_roll_length:
            self.title_widget.set_direction("h")
        else:
            self.title_widget.set_direction("m")
            title_text += " * "
        self.title_widget.set_text(title_text)

    def new_line(self, current, step):
        print "newline %d,%d" % (current, step)
        current += step
        if current > self.displayed_lines:
            return 1
        if current == 0:
            current = self.displayed_lines
        return current
 
    def scroll(self, step):
        self.album_widget.set_top(self.new_line(self.album_widget.top, step))
        self.album_widget.set_bottom(self.new_line(self.album_widget.bottom, step))
        self.artist_widget.set_top(self.new_line(self.artist_widget.top, step))
        self.artist_widget.set_bottom(self.new_line(self.artist_widget.bottom, step))
        self.title_widget.set_top(self.new_line(self.title_widget.top, step))
        self.title_widget.set_bottom(self.new_line(self.title_widget.bottom, step))
        self.progress_bar.set_y(self.new_line(self.progress_bar.y, step))
        self.time_widget.set_y(self.new_line(self.time_widget.y, step))
        if SHOW_LABELS:
            self.label_widget.set_y(self.new_line(self.label_widget.y, step))
Exemplo n.º 20
0
def main():
    # pin setup
    temp_pin = 4
    door_pin = 23
    io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP)  # activate input with PullUp

    # lcd setup
    lcd = Server("127.0.0.1", debug=False)
    lcd.start_session()

    screen1 = lcd.add_screen("Screen1")
    screen1.set_heartbeat("off")
    screen1.set_duration(5)

    # lcd strings
    error = "log err"

    # Account details for google docs
    email       = environment.email
    password    = environment.password
    spreadsheet = environment.spreadsheet

    try:
        # Login with your Google account
        gc = gspread.login(email, password)
        # Open a worksheet from your spreadsheet using the filename
        worksheet = gc.open(spreadsheet).sheet1
    except:
        network_status = error

    # lcd widgets
    display_temperature = screen1.add_string_widget("MyTempWidget", x=1, y=1)
    display_humidity = screen1.add_string_widget("MyHumiWidget", x=1, y=2)
    display_network = screen1.add_string_widget("MyNetworkWidget", x=10, y=1)
    display_alarm = screen1.add_string_widget("MyStringWidget", x=13, y=2)

    while True:
        # get door status
        if io.input(door_pin):
            door_status = "open"
        else:
            door_status = "shut"

        # get temperature and humidity status
        output = subprocess.check_output(["Adafruit-Raspberry-Pi-Python-Code/Adafruit_DHT_Driver/Adafruit_DHT", "2302", str(temp_pin)]);
        # matches_temp, matches_hum = uniform( 36, 37), uniform( 75, 80)
        try:
            matches_temp = re.search("Temp =\s+([0-9.]+)", output)
            matches_hum = re.search("Hum =\s+([0-9.]+)", output)
            temperature = float(matches_temp.group(1))
            humidity = float(matches_hum.group(1))
            temperature_status = str(temperature)+chr(223)+"C"
            humidity_status = str(humidity)+"%RH"
        except:
            temperature_status = "--.-"+chr(223)+"C"
            humidity_status = "--.-%RH"


        # get network status
        if internet_on():
            network_status = "   wifi"
            if matches_temp and matches_hum:
                try:
                    values = [datetime.datetime.now(), temperature, humidity]
                    worksheet.append_row(values)
                except:
                    network_status = error
        else:
            network_status = "no wifi"
        
        display_temperature.set_text(temperature_status)
        display_humidity.set_text(humidity_status)
        display_network.set_text(network_status)
        display_alarm.set_text(door_status)
        time.sleep(10)
Exemplo n.º 21
0
class DmxUi():
    def __init__(self,color_list):
        self.color_list=color_list
        self.lcd = Server("127.0.0.1", debug=False)
        self.lcd.start_session()
        self.lcd.add_key("Up",mode="exclusively")
        self.lcd.add_key("Down",mode="exclusively")
        self.lcd.add_key("Enter",mode="exclusively")

        #Allocate the screen
        self.screen = self.lcd.add_screen("DMX")
        self.screen.set_heartbeat("off")

        #Add a widget for the label
        self.label_widget = self.screen.add_string_widget("label_widget",
                                                          text="",x=1,y=1)
        #Add a widget for the color
        self.color_widget = self.screen.add_string_widget("color_widget",
                                                          text="",x=7,y=1)
        #Add a widget to display the "selected" status
        self.not_set_widget = self.screen.add_string_widget("not_set_widget",
                                                            text="",x=16,y=1)
        #Set the label text
        self.label_widget.set_text("Color:")

        self.color_idx=0
        self.current_color_idx=0
        self.color_widget.set_text(self.color_list[self.color_idx][0])    
        self.num_colors = len(self.color_list)

    # Get a key from LCDproc
    def get_key(self):
        resp = self.lcd.poll()
        if (resp == None):
            return None

        return resp[4:-1]

    # UI processing
    # -get keyinput
    # -update display
    # -return the current selection
    def ui_process(self):

        key_press = self.get_key()

        if (key_press==None):
            return None
        
        if (key_press == "Up"):
            self.color_idx -= 1

        if (key_press == "Down"):
            self.color_idx += 1

        self.color_idx %= self.num_colors

        if (key_press == "Enter"):
            self.current_color_idx = self.color_idx

        if (self.color_idx != self.current_color_idx):
            self.not_set_widget.set_text("*")
        else:
            self.not_set_widget.set_text("")

        self.color_widget.set_text(self.color_list[self.color_idx][0])

        return self.current_color_idx
Exemplo n.º 22
0
def main():
    logInfo("Starting up...")
    while True:
        try:
            lcd = Server("localhost", debug=False)
            lcd.start_session()
            logInfo("Connected to LCDd")

            lcd.add_key("Up")
            lcd.add_key("Down")

            screen1 = lcd.add_screen("Screen1")
            screen1.set_heartbeat("off")

            line1_widget = screen1.add_scroller_widget("line1", left=1, top=1, right=20, bottom=1, speed=10, text="")
            line2_widget = screen1.add_scroller_widget("line2", left=1, top=2, right=20, bottom=2, speed=10, text="")

            currentIndex = 0

            logInfo("Entering endless loop...")
            while True:

                interfaceNames = sorted(netifaces.interfaces())

                interfaceNames = filter (lambda name:
                                             not name in ["lo"],
                                         interfaceNames)

                currentIndex = max(0, min(currentIndex, len(interfaceNames) - 1))
                currentInterfaceName = interfaceNames[currentIndex]

                line1 = currentInterfaceName + ": "
                line2 = ""
                addresses = netifaces.ifaddresses(currentInterfaceName)

                if netifaces.AF_INET in addresses:
                    line1 += addresses[netifaces.AF_INET][0]['addr']

                if netifaces.AF_INET6 in addresses:
                    line2 += addresses[netifaces.AF_INET6][0]['addr']

                line1_widget.set_text(line1)
                line2_widget.set_text(line2)

                time.sleep(0.1)

                while True:
                    event = lcd.poll()
                    if not event:
                        break
                    event = string.strip(event)
                    if event == "key Up":
                        currentIndex = currentIndex + 1
                    elif event == "key Down":
                        currentIndex = currentIndex - 1
        # probably it's better to just quit together with LCDd, therefore it's commented out...
        #except socket.error, EOFError:
        #    logWarn("Error connecting to LCDd, retrying in 30 seconds...")
        #    time.sleep(30)
        except Exception as e:
            logError(e, "Error reached toplevel, exiting with exit code 42")
            sys.exit(42)
Exemplo n.º 23
0
def main():
    logInfo("Starting up...")
    while True:
        try:
            lcd = Server("localhost", debug=False)
            lcd.start_session()
            logInfo("Connected to LCDd")

            lcd.add_key("Up")
            lcd.add_key("Down")

            screen1 = lcd.add_screen("Screen1")
            screen1.set_heartbeat("off")

            line1_widget = screen1.add_scroller_widget("line1",
                                                       left=1,
                                                       top=1,
                                                       right=20,
                                                       bottom=1,
                                                       speed=10,
                                                       text="")
            line2_widget = screen1.add_scroller_widget("line2",
                                                       left=1,
                                                       top=2,
                                                       right=20,
                                                       bottom=2,
                                                       speed=10,
                                                       text="")

            currentIndex = 0

            logInfo("Entering endless loop...")
            while True:

                interfaceNames = sorted(netifaces.interfaces())

                interfaceNames = filter(lambda name: not name in ["lo"],
                                        interfaceNames)

                currentIndex = max(0, min(currentIndex,
                                          len(interfaceNames) - 1))
                currentInterfaceName = interfaceNames[currentIndex]

                line1 = currentInterfaceName + ": "
                line2 = ""
                addresses = netifaces.ifaddresses(currentInterfaceName)

                if netifaces.AF_INET in addresses:
                    line1 += addresses[netifaces.AF_INET][0]['addr']

                if netifaces.AF_INET6 in addresses:
                    line2 += addresses[netifaces.AF_INET6][0]['addr']

                line1_widget.set_text(line1)
                line2_widget.set_text(line2)

                time.sleep(0.1)

                while True:
                    event = lcd.poll()
                    if not event:
                        break
                    event = string.strip(event)
                    if event == "key Up":
                        currentIndex = currentIndex + 1
                    elif event == "key Down":
                        currentIndex = currentIndex - 1
        # probably it's better to just quit together with LCDd, therefore it's commented out...
        #except socket.error, EOFError:
        #    logWarn("Error connecting to LCDd, retrying in 30 seconds...")
        #    time.sleep(30)
        except Exception as e:
            logError(e, "Error reached toplevel, exiting with exit code 42")
            sys.exit(42)
Exemplo n.º 24
0
class LCDProcPlugin (rb.Plugin):
    def __init__(self):
        rb.Plugin.__init__(self)
        self.scrolling = None
        self.running = False

    def time_callback(self, player, time):
        if not self.running and not self.connect():
            # no connection to LCDd
            print "Could not reconnect to LCDd"
            return
        
        try:
            if not (time >= 0 and player.get_playing()):
                return
            if self.streaming:
                # do not append remaining time or track
                self.scrolling.update_widget(self.time_widget, "Webradio" + ("%2d:%02d" % (time/60,  time % 60)).rjust(12," "))
            else:
                # append remaining time
                self.scrolling.update_widget(self.time_widget, self.track + (("%2d:%02d -" % (time/60,  time % 60)) + self.duration).rjust(13," "))
        except:
            # connection to LCDd is broken
            self.connectionlost("time_callback");

    def change_callback(self, player, entry):
        #print "change callback"
        if not self.running and not self.connect():
            # no connection to LCDd
            print "Could not reconnect to LCDd"
            return
        
        try:
            if (entry == None):
                self.title = "No playback"
                self.album = ""
                self.artist = ""
                self.duration = ""
                self.track = ""
                self.streaming = False
            else:
                if entry.get_entry_type().props.category == rhythmdb.ENTRY_STREAM:
                    # streaming item - set station name as artist and only update artist (in album row) & title
                    self.artist = self.shell.props.db.entry_get(entry, rhythmdb.PROP_TITLE)
                    self.album = ""
                    self.title = ""
                    self.track = ""
                    self.duration = ""
                    self.streaming = True
                else:
                    # regular item (local DB or LastFM)
                    self.artist = self.shell.props.db.entry_get(entry, rhythmdb.PROP_ARTIST)
                    self.album = self.shell.props.db.entry_get(entry, rhythmdb.PROP_ALBUM)
                    self.title = self.shell.props.db.entry_get(entry, rhythmdb.PROP_TITLE)
                    tracknumber = self.shell.props.db.entry_get(entry, rhythmdb.PROP_TRACK_NUMBER)
                    if tracknumber > 0 and tracknumber < 100:
                        # valid track number
                        self.track = "Track" + str(tracknumber).rjust(2," ")
                    else:
                        # invalid track number
                        self.track = ""
                    seconds = self.shell.props.db.entry_get(entry, rhythmdb.PROP_DURATION)
                    self.duration = "%2d:%02d" % (seconds/60,  seconds % 60)
                    self.streaming = False
            
            self.update_widgets()
        except:
            # connection to LCDd is broken
            self.connectionlost("change_callback");
    
    def update_widgets(self):
        self.scrolling.update_widget(self.title_widget, self.title)
        self.scrolling.update_widget(self.album_widget, self.album)
        self.scrolling.update_widget(self.artist_widget, self.artist)
        self.scrolling.update_widget(self.time_widget, self.duration)
        
    # copied from im-status plugin
    def playing_song_property_changed (self, sp, uri, property, old, new):
        if not self.running and not self.connect():
            # no connection to LCDd
            print "Could not reconnect to LCDd"
            return
        #print "prop callback: old %s new %s uri %s prop %s" % (old, new, uri, property)
#        if not self.streaming:
#            # do not update
#            return
        relevant = False
        if sp.get_playing () and property in (NORMAL_SONG_ARTIST,STREAM_SONG_ARTIST):
            self.artist = new
            relevant = True
        elif sp.get_playing () and property in (NORMAL_SONG_TITLE,STREAM_SONG_TITLE):
            if new.count(" - ") >= 1:
                # contains "Artist - Title" - store artist in album
                fields = new.split(" - ",1)
                self.album = fields[0]
                self.title = fields[1]
            else:
                # only title
                self.title = new
            relevant = True
        elif sp.get_playing () and property in (NORMAL_SONG_ALBUM,STREAM_SONG_ALBUM):
            self.album = new
            relevant = True
        
        if relevant:
            self.update_widgets()

    def connectionlost(self, source):
        print "in " + source + ": Connection to LCDd lost, disconnecting plugin (will try to reconnect)"
        self.disconnect()
    
    def activate(self, shell):
        self.shell = shell
        if not self.connect():
             # LCDd not running
            print "LCDd not running, plugin not initialising"
            self.running = False
            self.inited = False
            return
        self.pec_id = self.shell.get_player().connect('playing-song-changed', self.change_callback)
        self.pspc_id = self.shell.get_player().connect ('playing-song-property-changed', self.playing_song_property_changed)
        self.inited = True
        print "Connected to LCDProc, loading plugin"


    def connect(self):
        try:
            self.lcd = Server()
        except:
            # LCDd not running
            self.running = False
            return False

        self.lcd.start_session()
        self.running = True
        
        self.screen1 = self.lcd.add_screen("Screen1")
        self.screen1.set_heartbeat("off")
        self.screen1.set_priority("foreground")
        
        self.counter = 0
        self.title_widget = self.screen1.add_string_widget("Widget1", x = 1, y = 1 , text = "")
        self.album_widget = self.screen1.add_string_widget("Widget2", x = 1, y = 2 , text = "")
        self.artist_widget = self.screen1.add_string_widget("Widget3", x = 1, y = 3 , text = "")
        self.time_widget = self.screen1.add_string_widget("Widget4", x = 1, y = 4 , text = "")
        scrollmode = gconf.client_get_default().get_string(LCDProcPluginConfigureDialog.gconf_keys['scrolling'])
        if not scrollmode:
            scrollmode = SCROLL_ROLLING
        self.scrolling = scroll_thread(scrollmode)
        self.scrolling.config([self.title_widget, self.album_widget, self.artist_widget, self.time_widget])
        self.scrolling.start()
        
        self.pec_idd = self.shell.get_player().connect('elapsed-changed', self.time_callback)
        self.change_callback(self.shell.get_player(),self.shell.get_player().get_playing_entry())
        self.time_callback(self.shell.get_player(),-1)
        print "(Re-)Connected to LCDProc"
        return True

    def deactivate(self, shell):
        self.disconnect()
        if self.inited:
            #plugin was running at some point
            self.shell.get_player().disconnect(self.pec_id)
            del self.pec_id
            del self.pspc_id
        del self.shell
        print "Plugin unloaded"

    def disconnect(self):
        if not self.running:
            # LCDd was not running, nothing to clean up
            return
        
        self.running = False;
        self.scrolling.stop_scrolling()
        self.shell.get_player().disconnect(self.pec_idd)
        del self.pec_idd
        del self.scrolling
        del self.title_widget
        del self.album_widget
        del self.artist_widget
        del self.time_widget
        del self.screen1
        self.lcd.tn.close()
        del self.lcd
        print "Plugin disconnected"
        
    def create_configure_dialog(self, dialog=None):
        if not dialog:
            builder_file = self.find_file("config_dlg.glade")
            dialog = LCDProcPluginConfigureDialog(builder_file).get_dialog()
            dialog.present()
        return dialog
Exemplo n.º 25
0
def main():
	# initialize the connection
	lcd = Server(debug=False)
    	lcd.start_session()

	# setup a screen
	screen1 = lcd.add_screen("Screen1")
	screen1.set_heartbeat("off")
	screen1.set_duration(10)
	screen1.set_priority("info")

	# add fields to the screen - in this case we're just going to use scrolling text fields
	title = screen1.add_title_widget("Title", text = "Airplay")
	line1 = screen1.add_scroller_widget("Line1", top = 2, direction = "m",  speed=3, text = "")
	line2 = screen1.add_scroller_widget("Line2", top = 3, direction = "m",  speed=3, text = "")
	line3 = screen1.add_scroller_widget("Line3", top = 4, direction = "m",  speed=3, text = "")



	path = "/tmp/shairport-sync-metadata"
	fifo = open(path, "r")
	wholeelement = ""
	title = ""
	album = ""
	artist = ""
	info = ""
	updateflag = False

	with fifo as f:
		while True:
			line = f.readline()
			line = line.strip()
			logger.debug("Got " + line)
			wholeelement += line
			if line.endswith("</item>"):
				logger.debug("end of item")
				logger.debug("element = " + wholeelement)

				# Now that we've got a whole xml element, we can process it
				doc = xml.etree.ElementTree.fromstring(wholeelement)

				# get the type and convert to ascii
				type = doc.findtext('type')
				type = ascii_integers_to_string(type)
				# get the code and convert to ascii
				code = doc.findtext('code')
				code = ascii_integers_to_string(code)

				# get the data out, if there is any
				data = doc.findtext('data')
				if data != None:
					data = base64.b64decode(data)
				else:
					data = ""
				if type == "ssnc":
					#if code == "pfls":
						#title = ""
						#album = ""
						#artist = ""
						#updateflag = True

					if code == "pend":
						logger.info("Playback finished...")
						screen1.clear()
						title = ""
						album = ""
						artist = ""
						info = ""
						updateflag = True
						screen1.set_backlight("off")

					if code == "pbeg":
						screen1.set_backlight("on")
						logger.info("Playback started...")
						# device.lcd_clear()
					if code == "snua":
						logger.info("User agent received")
						info = data
						updateflag = True
					if code == "pvol":
						# set up the volume screen
						vol_screen = lcd.add_screen("Volume")
						vol_screen.set_heartbeat("off")
						vol_title = vol_screen.add_title_widget("vol_title", text = "Volume")
						vol_screen.set_priority("foreground")
						vol_screen.set_timeout(2)


						logger.info("volume information received")
				if type == "core":
					#process the codes that we're interested in
					if code == "assn":
						if ((title != data) and (data !="")):
							title = data
							updateflag = True
					if code == "minm":
						if ((title != data) and (data !="")):
							title = data
							updateflag = True
					if code == "asar":
						if artist != data:
							artist = data
							updateflag = True
					if code == "asal":
						if album != data:
							album = data
							updateflag = True
					if code == "asbr":
						logger.info("Bitrate:")
						logger.info(int("0x" + ''.join([hex(ord(x))[2:] for x in data]), base=16))


				if data != "":
					logger.info("Type: " + type + ", Code: " + code + ", Data: " + data)
				else:
					logger.info("Type: " + type + ", Code: " + code)

				wholeelement = ""
			if updateflag:
				logger.info("\nTitle: " + title + "\nArtist: " + artist + "\nAlbum: " + album)
				# update the lines with the new contents of the variables
				line1.set_text(pad_string(title))
				line2.set_text(pad_string(artist))
				line3.set_text(pad_string(album))
				updateflag = False
	fifo.close()
Exemplo n.º 26
0
class AmpiOled:
    def __init__(self):
        self.oledLines = 4
        self.oledCols = 20
        self.timeoutVolScreen = 0
        self.timeoutMsgScreen = 0
        self.visibletime = 3
        self.blank = False

        self.tStop = threading.Event()

        self.init_oled()

        self.initVolScreen()
        self.initMsgScreen()

        #self.msgScreenT = threading.Thread(target=self.setMsgScreen, args=(1, self.tStop))
        #self.msgScreenT.start()

        self.clearScreenT = threading.Thread(target=self.clearScreen,
                                             args=(1, self.tStop))
        self.clearScreenT.setDaemon(True)
        self.clearScreenT.start()

        logger.debug("Leaving set_lcd")

    def __del__(self):
        self.tStop.set()  #Threads ordnungsgemäss beenden

    def init_oled(self):
        self.oled_reset = 13
        self.reset_oled()
        import dbus
        service = "LCDd.service"
        bus = dbus.SystemBus()
        systemd = bus.get_object('org.freedesktop.systemd1',
                                 '/org/freedesktop/systemd1')
        manager = dbus.Interface(systemd, 'org.freedesktop.systemd1.Manager')
        manager.RestartUnit(service, 'replace')

        run = False
        while run != True:
            try:
                self.lcd = Server("127.0.0.1", debug=False)
                self.lcd.start_session()
                run = True
            except:
                logger.info("Waiting for LDCd ...")
                time.sleep(.1)
                run = False

        self.screenVol = self.lcd.add_screen("Screen_vol")
        self.screenVol.set_heartbeat("off")
        self.screenVol.set_priority("background")

        self.screenMsg = self.lcd.add_screen("Screen_msg")
        self.screenMsg.set_heartbeat("off")
        self.screenMsg.set_priority("background")

        self.screenClear = self.lcd.add_screen("Screen_clear")
        self.screenClear.set_heartbeat("off")
        self.screenClear.set_priority("background")

    def reset_oled(self):
        try:
            GPIO
        except NameError:
            import RPi.GPIO as GPIO
            GPIO.setwarnings(False)
            GPIO.setmode(
                GPIO.BOARD)  # Nutzung der Pin-Nummerierung, nicht GPIO-Nummegn
        GPIO.setup(self.oled_reset,
                   GPIO.OUT)  # EXT1 -> for control of external Relais etc.
        GPIO.output(self.oled_reset, GPIO.LOW)  # Drive oled reset pin low
        time.sleep(.5)
        GPIO.output(self.oled_reset,
                    GPIO.HIGH)  # Drive oled reset pin high again

    def clearScreen(self, dummy, stop_event):
        while (not stop_event.is_set()):
            if self.blank == 1:
                self.screenClear.set_priority("input")
            else:
                self.screenClear.set_priority("hidden")

            if (self.timeoutVolScreen > self.visibletime - 1):
                self.screenVol.set_priority("background")
                self.timeoutVolScreen = 0
            else:
                self.timeoutVolScreen = self.timeoutVolScreen + 1

            if (self.timeoutMsgScreen > self.visibletime - 1):
                self.screenMsg.set_priority("background")
                self.timeoutMsgScreen = 0
            else:
                self.timeoutMsgScreen = self.timeoutMsgScreen + 1

            #print(self.timeoutVolScreen)
            stop_event.wait(1)

    def toggleBlankScreen(
        self
    ):  # Toggle screen blanking, takes effect with next run of clearScreen thread loop
        self.blank = not self.blank
        return (self.blank)

    def getBlankScreen(
        self
    ):  # Toggle screen blanking, takes effect with next run of clearScreen thread loop
        return (self.blank)

    def findX(self, s):
        l = self.oledCols - len(s)
        return (l // 2)

    def initVolScreen(self):
        self.screenVolNum1 = self.screenVol.add_number_widget("Num1Wid",
                                                              x=8,
                                                              value=4)
        self.screenVolNum2 = self.screenVol.add_number_widget("Num2Wid",
                                                              x=11,
                                                              value=2)
        self.screenVol.set_priority("input")

    def initMsgScreen(self):
        self.screenMsg.set_priority("alert")
        line1 = "Los geht's"
        line2 = "schon wieder"
        line3 = "Du"
        line4 = "Aff"
        self.screenMsgL1 = self.screenMsg.add_string_widget(
            "string_widget_l1", line1, x=self.findX(line1), y=1)
        self.screenMsgL2 = self.screenMsg.add_string_widget(
            "string_widget_l2", line2, x=self.findX(line2), y=2)
        self.screenMsgL3 = self.screenMsg.add_string_widget(
            "string_widget_l3", line3, x=self.findX(line3), y=3)
        self.screenMsgL4 = self.screenMsg.add_string_widget(
            "string_widget_l4", line4, x=self.findX(line4), y=4)

    def setVolScreen(self, value):
        self.timeoutVolScreen = 0
        if (value == "mute"):
            zehner = 6
            einer = 3
        else:
            try:
                zehner = value // 10
                einer = value % 10
            except:
                return
        self.screenVol.set_priority("input")
        self.screenVolNum1.set_value(zehner)
        self.screenVolNum2.set_value(einer)

    def setMsgScreen(self, l1="", l2="", l3="", l4=""):
        self.timeoutMsgScreen = 0
        self.screenMsg.set_priority("alert")
        self.screenMsgL1.set_x(self.findX(l1))
        self.screenMsgL2.set_x(self.findX(l2))
        self.screenMsgL3.set_x(self.findX(l3))
        self.screenMsgL4.set_x(self.findX(l4))
        self.screenMsgL1.set_text(l1)
        self.screenMsgL2.set_text(l2)
        self.screenMsgL3.set_text(l3)
        self.screenMsgL4.set_text(l4)
Exemplo n.º 27
0
def main():

    lcd = Server("localhost", debug=False)
    lcd.start_session()
    
    screen1 = lcd.add_screen("Screen1")
    screen1.set_heartbeat("off")

    # hostname/time
    uname = os.uname()[1]
    uname = uname.ljust(10)
    text1 = uname + time.strftime("%H:%M:%S")
    line1 = screen1.add_string_widget("String1", text=text1, x=1, y=1)

    # load
    load = os.getloadavg()
    text2 = "Load %.2f/%.2f/%.2f" % (load[0], load[1], load[2])
    line2 = screen1.add_string_widget("String2", text=text2, x=1, y=2)

    # CPU usage
    text3 = "CPU "
    usage = commands.getoutput("vmstat | tail -1 | awk '{print $15 \" \" $14 \" \" $13}'")
    usage = usage.split(" ")
    text3 = "CPU %s%%u %s%%i %s%%s" % (usage[2], usage[0], usage[1])
    line3 = screen1.add_string_widget("String3", text=text3, x=1, y=3)

    # mem/swap
    mem = commands.getoutput("free | grep '^Mem:' | awk '{print $4 \" \" $2}'")
    mem = mem.split(" ") # 0 = free 1 = total
    mem = (float(mem[0]) / float(mem[1])) * 100.0
    swap = commands.getoutput("free | grep '^Swap:' | awk '{print $4 \" \" $2}'")
    swap = swap.split(" ") # 0 = free 1 = total
    swap = (float(swap[0]) / float(swap[1])) * 100.0
    text4 = "free M:%.1f S:%.1f" % (mem, swap)
    line4 = screen1.add_string_widget("String4", text=text4, x=1, y=4)

    sep = ":"

    while True:
        text1 = uname + time.strftime("%H:%M:%S")
        line1.set_text(text1)

        load = os.getloadavg()
        text2 = "Load" + sep + "%.2f/%.2f/%.2f" % (load[0], load[1], load[2])
        line2.set_text(text2)

        usage = commands.getoutput("vmstat | tail -1 | awk '{print $15 \" \" $14 \" \" $13}'")
        usage = usage.split(" ")
        text3 = "CPU" + sep + "%s%%u %s%%i %s%%s" % (usage[2], usage[0], usage[1])
        line3.set_text(text3)

        mem = commands.getoutput("free | grep '^Mem:' | awk '{print $4 \" \" $2}'")
        mem = mem.split(" ") # 0 = free 1 = total
        mem = (float(mem[0]) / float(mem[1])) * 100.0
        swap = commands.getoutput("free | grep '^Swap:' | awk '{print $4 \" \" $2}'")
        swap = swap.split(" ") # 0 = free 1 = total
        swap = (float(swap[0]) / float(swap[1])) * 100.0
        text4 = "free" + sep + "M:%.1f%% S:%.1f%%" % (mem, swap)
        line4.set_text(text4)

        if sep == ":":
            sep = " "
        else:
            sep = ":"

        time.sleep(1)
Exemplo n.º 28
0
class LCD(object):
    def __init__(self, server = "localhost", debug = False):
        self._logger = logging.getLogger(__name__)
        self.__lcd = Server(server, debug=debug)
        self.__lcd.start_session()
        self.__screen = self.__lcd.add_screen("screen")
        self.__screen.set_heartbeat("off")
        self.__screen.set_priority("foreground")
        self.__line1 = self.__screen.add_string_widget("line1", text="", x=1, y=1)
        self.__line2 = self.__screen.add_string_widget("line2", text="", x=1, y=2)
        self.__line3 = self.__screen.add_string_widget("line3", text="", x=1, y=3)
        self.__line4 = self.__screen.add_string_widget("line4", text="", x=1, y=4)

    def clear(self):
        self.write()

    def write(self, line1 = "", line2 = "", line3 = "", line4 = ""):
        self.__line1.set_text(line1)
        self.__line2.set_text(line2)
        self.__line3.set_text(line3)
        self.__line4.set_text(line4)

        self._logger.info(line1 + ' | ' + line2 + ' | ' + line3 + ' | ' + line4)

    def setup(self):
        self.write("Fnordload booting", "", "Please stand by...")

    def show_accepted_values(self, values):
        accepted = [str(x) for x in values]

        if (len(accepted) == 0):
            self.write("Sorry!","No change available", "", "             The MGT")
        else:
            self.write("Giving Change", "Accepting (Euro):", ", ".join(accepted),"        Insert money")

    def out_of_order(self):
        self.write("Sorry!","Fnordload is currently", "out of order.", "             The MGT")
        self.__screen.set_backlight("off")

    def reading_note(self, value = 0):
        self.__screen.set_backlight("on")

        if value == 0:
            self.write("Reading note...")
        else:
            self.write(value + " Euro note read")

    def cashed_note(self, value):
        self.__screen.set_backlight("on")

        self.write("Cashed " + value + " Euro")

    def payout_in_progress(self):
        self.write("Payout in Progress", "", "", "Please stand by")

    def rejected_note(self):
        #self.__screen.set_backlight("flash")
        self.write("Sorry, this note", "cannot be accepted" , "at this time.")

    def thinking(self):
        self.write("Thinking...", "", "", "Please stand by")
Exemplo n.º 29
0
def main():

    lcd = Server("localhost", debug=False)
    lcd.start_session()

    screen1 = lcd.add_screen("Screen1")
    screen1.set_heartbeat("off")

    # hostname/time
    uname = os.uname()[1]
    uname = uname.ljust(10)
    text1 = uname + time.strftime("%H:%M:%S")
    line1 = screen1.add_string_widget("String1", text=text1, x=1, y=1)

    # load
    load = os.getloadavg()
    text2 = "Load %.2f/%.2f/%.2f" % (load[0], load[1], load[2])
    line2 = screen1.add_string_widget("String2", text=text2, x=1, y=2)

    # CPU usage
    text3 = "CPU "
    usage = commands.getoutput(
        "vmstat | tail -1 | awk '{print $15 \" \" $14 \" \" $13}'")
    usage = usage.split(" ")
    text3 = "CPU %s%%u %s%%i %s%%s" % (usage[2], usage[0], usage[1])
    line3 = screen1.add_string_widget("String3", text=text3, x=1, y=3)

    # mem/swap
    mem = commands.getoutput("free | grep '^Mem:' | awk '{print $4 \" \" $2}'")
    mem = mem.split(" ")  # 0 = free 1 = total
    mem = (float(mem[0]) / float(mem[1])) * 100.0
    swap = commands.getoutput(
        "free | grep '^Swap:' | awk '{print $4 \" \" $2}'")
    swap = swap.split(" ")  # 0 = free 1 = total
    swap = (float(swap[0]) / float(swap[1])) * 100.0
    text4 = "free M:%.1f S:%.1f" % (mem, swap)
    line4 = screen1.add_string_widget("String4", text=text4, x=1, y=4)

    sep = ":"

    while True:
        text1 = uname + time.strftime("%H:%M:%S")
        line1.set_text(text1)

        load = os.getloadavg()
        text2 = "Load" + sep + "%.2f/%.2f/%.2f" % (load[0], load[1], load[2])
        line2.set_text(text2)

        usage = commands.getoutput(
            "vmstat | tail -1 | awk '{print $15 \" \" $14 \" \" $13}'")
        usage = usage.split(" ")
        text3 = "CPU" + sep + "%s%%u %s%%i %s%%s" % (usage[2], usage[0],
                                                     usage[1])
        line3.set_text(text3)

        mem = commands.getoutput(
            "free | grep '^Mem:' | awk '{print $4 \" \" $2}'")
        mem = mem.split(" ")  # 0 = free 1 = total
        mem = (float(mem[0]) / float(mem[1])) * 100.0
        swap = commands.getoutput(
            "free | grep '^Swap:' | awk '{print $4 \" \" $2}'")
        swap = swap.split(" ")  # 0 = free 1 = total
        swap = (float(swap[0]) / float(swap[1])) * 100.0
        text4 = "free" + sep + "M:%.1f%% S:%.1f%%" % (mem, swap)
        line4.set_text(text4)

        if sep == ":":
            sep = " "
        else:
            sep = ":"

        time.sleep(1)