Browse Source

move to the Adafruit-LED-Backpack module, update documentation accordingly

Helmut Pozimski 7 years ago
parent
commit
64a50c3fa4
8 changed files with 24 additions and 387 deletions
  1. 1 0
      README.md
  2. 0 0
      adafruit_7segment/__init__.py
  3. 0 194
      adafruit_7segment/i2c.py
  4. 0 97
      adafruit_7segment/ledbackpack.py
  5. 0 69
      adafruit_7segment/sevensegment.py
  6. 2 6
      doc/stdd.1
  7. 1 1
      setup.py
  8. 20 20
      stdd

+ 1 - 0
README.md

@@ -17,6 +17,7 @@ stov depends on the following software to be installed:
 	* python 2.7 or higher (lower 2.x versions might work but are not tested 3.x is not supported)
 	* python-smbus
 	* python-pcrtl (optional)
+	* Adafruit-LED-Backpack module from pypi
 
 ## COPYING
 

+ 0 - 0
adafruit_7segment/__init__.py


+ 0 - 194
adafruit_7segment/i2c.py

@@ -1,194 +0,0 @@
-# -*- coding: utf-8-*-
-#
-# This file is part of stdd, the simple time display daemon,
-# written by Helmut Pozimski <helmut@pozimski.eu>,
-# licensed under the 3-clause BSD license
-# This file was originally written by Written by Limor Fried, Kevin Townsend
-# and Mikey Sklar for Adafruit Industries. BSD license,
-# all text above must be included in any redistribution
-
-"""
-===========================================================================
-AdafruitI2c Class
-===========================================================================
-"""
-
-from __future__ import print_function
-
-from smbus import SMBus
-
-
-class AdafruitI2c(object):
-    """ This class provides low level i2c access.
-    """
-    @staticmethod
-    def get_pi_revision():
-        """Gets the version number of the Raspberry Pi board"""
-        # Courtesy quick2wire-python-api
-        # https://github.com/quick2wire/quick2wire-python-api
-        try:
-            with open('/proc/cpuinfo', 'r') as file_obj:
-                for line in file_obj:
-                    if line.startswith('Revision'):
-                        return 1 if line.rstrip()[-1] in ['1', '2'] else 2
-        except IOError:
-            return 0
-
-    @staticmethod
-    def get_pi_i2c_bus_number():
-        """ Gets the I2C bus number /dev/i2c# """
-        return 1 if AdafruitI2c.get_pi_revision() > 1 else 0
-
-    def __init__(self, address, busnum=-1, debug=False):
-        self.address = address
-        # By default, the correct I2C bus is auto-detected using /proc/cpuinfo
-        # Alternatively, you can hard-code the bus version below:
-        # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's)
-        # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's)
-        self.bus = SMBus(
-            busnum if busnum >= 0 else AdafruitI2c.get_pi_i2c_bus_number())
-        self.debug = debug
-
-    @staticmethod
-    def reverse_byte_order(data):
-        """Reverses the byte order of an int (16-bit) or long (32-bit) value"""
-        # Courtesy Vishal Sapre
-        byte_count = len(hex(data)[2:].replace('L', '')[::2])
-        val = 0
-        for i in range(byte_count):
-            val = (val << 8) | (data & 0xff)
-            data >>= 8
-        return val
-
-    @staticmethod
-    def err_msg():
-        """Raises an exception."""
-        raise Exception("cannot connect to device, check hardware address!")
-
-    def write8(self, reg, value):
-        """Writes an 8-bit value to the specified register/address"""
-        try:
-            self.bus.write_byte_data(self.address, reg, value)
-            if self.debug:
-                print("I2C: Wrote 0x%02X to register 0x%02X" % (value, reg))
-        except IOError:
-            return self.err_msg()
-
-    def write16(self, reg, value):
-        """Writes a 16-bit value to the specified register/address pair"""
-        try:
-            self.bus.write_word_data(self.address, reg, value)
-            if self.debug:
-                print("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" %
-                      (value, reg, reg+1))
-        except IOError:
-            return self.err_msg()
-
-    def write_list(self, reg, w_list):
-        """Writes an array of bytes using I2C format"""
-        try:
-            if self.debug:
-                print("I2C: Writing list to register 0x%02X:" % reg)
-                print(w_list)
-            self.bus.write_i2c_block_data(self.address, reg, w_list)
-        except IOError:
-            return self.err_msg()
-
-    def read_list(self, reg, length):
-        """Read a list of bytes from the I2C device"""
-        try:
-            results = self.bus.read_i2c_block_data(self.address, reg, length)
-            if self.debug:
-                print ("I2C: Device 0x % 02X returned the following from \
-                       reg 0x % 02X" % (self.address, reg))
-                print(results)
-            return results
-        except IOError:
-            return self.err_msg()
-
-    def read_u8(self, reg):
-        """Read an unsigned byte from the I2C device"""
-        try:
-            result = self.bus.read_byte_data(self.address, reg)
-            if self.debug:
-                print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
-                      (self.address, result & 0xFF, reg))
-            return result
-        except IOError:
-            return self.err_msg()
-
-    def read_s8(self, reg):
-        """Reads a signed byte from the I2C device"""
-        try:
-            result = self.bus.read_byte_data(self.address, reg)
-            if result > 127:
-                result -= 256
-            if self.debug:
-                print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
-                      (self.address, result & 0xFF, reg))
-            return result
-        except IOError:
-            return self.err_msg()
-
-    def read_u16(self, reg):
-        """Reads an unsigned 16-bit value from the I2C device"""
-        try:
-            hibyte = self.read_u8(reg)
-            lobyte = self.read_u8(reg+1)
-            result = (hibyte << 8) + lobyte
-            if self.debug:
-                print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (
-                    self.address, result & 0xFFFF, reg))
-            return result
-        except IOError:
-            return self.err_msg()
-
-    def read_s16(self, reg):
-        """Reads a signed 16-bit value from the I2C device"""
-        try:
-            hibyte = self.read_s8(reg)
-            lobyte = self.read_u8(reg+1)
-            result = (hibyte << 8) + lobyte
-            if self.debug:
-                print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" %
-                      (self.address, result & 0xFFFF, reg))
-            return result
-        except IOError:
-            return self.err_msg()
-
-    def read_u16_rev(self, reg):
-        """Reads an unsigned 16-bit value from the I2C device with rev byte
-        order.
-        """
-        try:
-            lobyte = self.read_u8(reg)
-            hibyte = self.read_u8(reg+1)
-            result = (hibyte << 8) + lobyte
-            if self.debug:
-                print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" %
-                      (self.address, result & 0xFFFF, reg))
-            return result
-        except IOError:
-            return self.err_msg()
-
-    def read_s16_rev(self, reg):
-        """Reads a signed 16-bit value from the I2C device with rev byte
-        order.
-        """
-        try:
-            lobyte = self.read_s8(reg)
-            hibyte = self.read_u8(reg+1)
-            result = (hibyte << 8) + lobyte
-            if self.debug:
-                print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (
-                    self.address, result & 0xFFFF, reg))
-            return result
-        except IOError:
-            return self.err_msg()
-
-if __name__ == '__main__':
-    try:
-        BUS = AdafruitI2c(address=0)
-        print("Default I2C bus is accessible")
-    except:
-        print("Error accessing default I2C bus")

+ 0 - 97
adafruit_7segment/ledbackpack.py

@@ -1,97 +0,0 @@
-# -*- coding: utf-8-*-
-#
-# This file is part of stdd, the simple time display daemon,
-# written by Helmut Pozimski <helmut@pozimski.eu>,
-# licensed under the 3-clause BSD license
-# This file was originally written by Written by Limor Fried, Kevin Townsend
-# and Mikey Sklar for Adafruit Industries. BSD license,
-# all text above must be included in any redistribution
-
-"""
-============================================================================
-LEDBackpack Class
-============================================================================
-"""
-
-from copy import copy
-from adafruit_7segment.i2c import AdafruitI2c
-
-
-class LEDBackpack(object):
-    """Represents the LED backpack and allows access to it. """
-    i2c = None
-
-    # Registers
-    __HT16K33_REGISTER_DISPLAY_SET = 0x80
-    __HT16K33_REGISTER_SYSTEM_SETUP = 0x20
-    __HT16K33_REGISTER_DIMMING = 0xE0
-
-    # Blink rate
-    __HT16K33_BLINKRATE_OFF = 0x00
-    __HT16K33_BLINKRATE_2HZ = 0x01
-    __HT16K33_BLINKRATE_1HZ = 0x02
-    __HT16K33_BLINKRATE_HALFHZ = 0x03
-
-    # Display buffer (8x16-bits)
-    __buffer = [0x0000, 0x0000, 0x0000, 0x0000,
-                0x0000, 0x0000, 0x0000, 0x0000]
-
-    # Constructor
-    def __init__(self, address=0x70, debug=False):
-        self.i2c = AdafruitI2c(address)
-        self.address = address
-        self.debug = debug
-
-        # Turn the oscillator on
-        self.i2c.write8(self.__HT16K33_REGISTER_SYSTEM_SETUP | 0x01, 0x00)
-
-        # Turn blink off
-        self.set_blink_rate(self.__HT16K33_BLINKRATE_OFF)
-
-        # Set maximum brightness
-        self.set_brightness(15)
-
-        # Clear the screen
-        self.clear()
-
-    def set_brightness(self, brightness):
-        """Sets the brightness level from 0..15"""
-        if brightness > 15:
-            brightness = 15
-        self.i2c.write8(self.__HT16K33_REGISTER_DIMMING | brightness, 0x00)
-
-    def set_blink_rate(self, blink_rate):
-        """Sets the blink rate"""
-        if blink_rate > self.__HT16K33_BLINKRATE_HALFHZ:
-            blink_rate = self.__HT16K33_BLINKRATE_OFF
-        self.i2c.write8(self.__HT16K33_REGISTER_DISPLAY_SET | 0x01
-                        | (blink_rate << 1), 0x00)
-
-    def set_buffer_row(self, row, value, update=True):
-        """Updates a single 16-bit entry in the 8*16-bit buffer"""
-        if row > 7:
-            return                    # Prevent buffer overflow
-        self.__buffer[row] = value  # value # & 0xFFFF
-        if update:
-            self.write_display()       # Update the display
-
-    def get_buffer(self):
-        """Returns a copy of the raw buffer contents"""
-        buffer_copy = copy(self.__buffer)
-        return buffer_copy
-
-    def write_display(self):
-        """Updates the display memory"""
-        byte_list = []
-        for item in self.__buffer:
-            byte_list.append(item & 0xFF)
-            byte_list.append((item >> 8) & 0xFF)
-        self.i2c.write_list(0x00, byte_list)
-
-    def clear(self, update=True):
-        """Clears the display memory"""
-        self.__buffer = [0, 0, 0, 0, 0, 0, 0, 0]
-        if update:
-            self.write_display()
-
-LED = LEDBackpack(0x70)

+ 0 - 69
adafruit_7segment/sevensegment.py

@@ -1,69 +0,0 @@
-# -*- coding: utf-8-*-
-#
-# This file is part of stdd, the simple time display daemon,
-# written by Helmut Pozimski <helmut@pozimski.eu>,
-# licensed under the 3-clause BSD license
-# This file was originally written by Written by Limor Fried, Kevin Townsend
-# and Mikey Sklar for Adafruit Industries. BSD license,
-# all text above must be included in any redistribution
-
-"""
-===========================================================================
- 7-Segment Display
-===========================================================================
-
- This class is meant to be used with the four-character, seven segment
- displays available from Adafruit.
-"""
-
-
-from __future__ import print_function
-from adafruit_7segment.ledbackpack import LEDBackpack
-
-
-class SevenSegment(object):
-    """This class represents the seven segment display and allows to access and
-    write data to it.
-    """
-    disp = None
-
-    # Hexadecimal character lookup table (row 1 = 0..9, row 2 = A..F)
-    digits = [0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F,
-              0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71]
-
-    # Constructor
-    def __init__(self, address=0x70, debug=False):
-        if debug:
-            print("Initializing a new instance of LEDBackpack at \
-            0x%02X" % address)
-        self.disp = LEDBackpack(address=address, debug=debug)
-
-    def write_digit_raw(self, char_number, value):
-        """Sets a digit using the raw 16-bit value"""
-        if char_number > 7:
-            return
-        # Set the appropriate digit
-        self.disp.set_buffer_row(char_number, value)
-
-    def write_digit(self, char_number, value, dot=False):
-        """Sets a single decimal or hexademical value (0..9 and A..F)"""
-        if char_number > 7:
-            return
-        if value > 0xF:
-            return
-        # Set the appropriate digit
-        self.disp.set_buffer_row(char_number, self.digits[value] | (dot << 7))
-
-    def set_colon(self, state=True):
-        """Enables or disables the colon character"""
-        # Warning: This function assumes that the colon is character '2',
-        # which is the case on 4 char displays, but may need to be modified
-        # if another display type is used
-        if state:
-            self.disp.set_buffer_row(2, 0xFFFF)
-        else:
-            self.disp.set_buffer_row(2, 0)
-
-    def set_brightness(self, brightness):
-        """ Sets the brightness. """
-        self.disp.set_brightness(brightness)

+ 2 - 6
doc/stdd.1

@@ -1,4 +1,4 @@
-.TH STDD 1 "28 July, 2013" 0.9.5 stdd
+.TH STDD 1 "03 December, 2016" 0.9.6 stdd
 .SH NAME
 stdd \- a daemon to display the current time on a 7 segment display
 .SH SYNOPSIS
@@ -74,8 +74,4 @@ sample code used in this project
 .SH AUTHOR
 Helmut Pozimski
 .SH COPYRIGHT
-2013-2015,  Helmut  Pozimski, 3-Clause BSD license
-.P
-some parts written by Limor Fried, Kevin Townsend and Mikey Sklar for Adafruit Industries
-.P
-please look at the license header in the files for details
+2013-2016,  Helmut  Pozimski, 3-Clause BSD license

+ 1 - 1
setup.py

@@ -12,7 +12,7 @@ from distutils.core import setup
 
 setup(
     name="stdd",
-    version="0.9.5",
+    version="0.9.6",
     author_email="helmut@pozimski.eu",
     description="stdd, simple time display daemon",
     long_description=("stdd is a small daemon written in python which displays"

+ 20 - 20
stdd

@@ -18,9 +18,9 @@ import logging
 import logging.handlers
 from optparse import OptionParser
 
-import stddlib.daemon
 import stddlib.configuration
-from adafruit_7segment.sevensegment import SevenSegment
+from stddlib import daemon
+from Adafruit_LED_Backpack import SevenSegment
 
 
 PARSER = OptionParser(prog="stdd", version="%prog 0.9.2", add_help_option=True)
@@ -43,12 +43,12 @@ def sighandler(signum, frame):
         LOGGER.info("received SIGINT, stopping daemon")
     elif signum == 15:
         LOGGER.info("received SIGTERM, stopping daemon")
-    DISPLAY.write_digit(0, 0)
-    DISPLAY.write_digit(1, 0)
-    DISPLAY.write_digit(3, 0)
-    DISPLAY.write_digit(4, 0)
-    if OPTIONS.daemon is True:
-        if DAEMON.stop() is True:
+    DISPLAY.set_digit(0, 0)
+    DISPLAY.set_digit(1, 0)
+    DISPLAY.set_digit(3, 0)
+    DISPLAY.set_digit(4, 0)
+    if OPTIONS.daemon:
+        if DAEMON.stop():
             sys.exit(0)
         else:
             LOGGER.error("stopping daemon failed, PID file was not deleted!")
@@ -95,16 +95,16 @@ FORMATTER = logging.Formatter("%(name)s[" + str(os.getpid()) +
 SYSLOG_HANDLER.setFormatter(FORMATTER)
 CONSOLE_HANDLER.setFormatter(FORMATTER)
 
-if OPTIONS.daemon is True:
+if OPTIONS.daemon:
     LOGGER.addHandler(SYSLOG_HANDLER)
 else:
     LOGGER.addHandler(CONSOLE_HANDLER)
 
-if OPTIONS.daemon is True:
-    if os.access("/run", os.F_OK & os.W_OK) is True:
-        DAEMON = stddlib.daemon.Daemon("/run/stdd", "stdd.pid")
+if OPTIONS.daemon:
+    if os.access("/run", os.F_OK & os.W_OK):
+        DAEMON = daemon.Daemon("/run/stdd", "stdd.pid")
     else:
-        DAEMON = stddlib.daemon.Daemon("/var/run/stdd", "stdd.pid")
+        DAEMON = daemon.Daemon("/var/run/stdd", "stdd.pid")
     DAEMON.daemonize()
     DAEMON.start()
     LOGGER.info("daemon started")
@@ -123,7 +123,7 @@ if OPTIONS.daemon is True:
                      " and group" + OPTIONS.group)
 
 # Initialize the display object
-DISPLAY = SevenSegment(CONFIG.hw_address)
+DISPLAY = SevenSegment.SevenSegment(CONFIG.hw_address)
 LOGGER.debug("opened hardware address")
 
 # Set the brightness according to the configuration
@@ -135,8 +135,8 @@ else:
     LOGGER.debug("setting display brightness low")
     DISPLAY.set_brightness(CONFIG.brightness_low)
 
-# Define the main loop
 
+# Define the main loop
 def main():
     """ Main loop of the daemon.  """
     minute_written = 61
@@ -145,7 +145,7 @@ def main():
         LOGGER.debug("got datetime: " + str(date_now))
         minute = date_now.minute
         hour = date_now.hour
-        if CONFIG.blink_colon is True:
+        if CONFIG.blink_colon:
             LOGGER.debug("blinking middle colon")
             DISPLAY.set_colon(date_now.second % 2)
         else:
@@ -177,10 +177,10 @@ def main():
             else:
                 position3 = str(minute)[0]
             LOGGER.debug("writing time to display")
-            DISPLAY.write_digit(0, int(position1))
-            DISPLAY.write_digit(1, int(position2))
-            DISPLAY.write_digit(3, int(position3))
-            DISPLAY.write_digit(4, int(position4))
+            DISPLAY.set_digit(0, int(position1))
+            DISPLAY.set_digit(1, int(position2))
+            DISPLAY.set_digit(3, int(position3))
+            DISPLAY.set_digit(4, int(position4))
             minute_written = minute
         time.sleep(1)