def __init__(self):
     self.con = IPConnection()
     self.master = Master(self.uid_master, self.con)
     self.motion = MotionDetector(self.uid_motion, self.con)
     self.poti_left = RotaryPoti(self.uid_poti_left, self.con)
     self.poti_right = RotaryPoti(self.uid_poti_right, self.con)
     self.io = IO4(self.uid_io, self.con)
     print "---" + str(15^15)
     print "---" + str(15^14)
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, 
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            
            self.log("cb_enumerate() id {} - Found device: ident={}, position={}".format(uid, device_identifier, position))
            if device_identifier == IO4.DEVICE_IDENTIFIER:
                self.log("cb_enumerate() id {} - Creating IO4 device object".format(uid))
                self.io = IO4(uid, self.con) 
                self.io.set_debounce_period(1000)

                if position == 'a':
                    self.log("cb_enumerate() id {} - Configuring IO4 device object at position a (switches).".format(uid))
                    self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch)
                    self.io.set_configuration(15, 'i', True)
                    # Enable interrupt on pin 0 and 1
                    self.io.set_interrupt(1 << 0)
                    self.io.set_interrupt(1 << 1)
                    self.set_ziel_geschlecht(self.io.get_value())
                else:
                    self.log("cb_enumerate() id {} - Configuring IO4 device object at position ? (lights, shutdown).".format(uid))
                    self.io.set_configuration((1 << 0) | (1 << 1), "o", True)

            elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER:
                self.log("cb_enumerate() id {} - Creating RotaryPoti device object".format(uid))
                self.poti_volume = RotaryPoti(uid, self.con) 
                self.poti_volume.set_position_callback_period(100)
                self.poti_volume.register_callback(self.poti_volume.CALLBACK_POSITION, self.poti_volume_changed)
            elif device_identifier == Master.DEVICE_IDENTIFIER:
                self.log("cb_enumerate() id {} - Creating Master device object".format(uid))
                self.master = Master(uid, self.con)
            else: 
                self.log("cb_enumerate() id {} - Could not register unknown device bricklet".format(uid))
class emulate:
	def poti_cb(self,position):
		print(str(position))
		self.device.emit(uinput.ABS_Z, position) #Setzt den Wert des Joysticks auf den Wert des Potis

	def __init__(self):
		#uinput Bereich
		self.events = (
			uinput.BTN_A, #Es wird mindestens ein Button benötigt (seltsam)
			uinput.ABS_Z + (-150, 150, 0, 0), #Erstellt Joystick Achse Z, kleinster Wert des Potis ist -150, größter Wert ist +150
			)

		self.device = uinput.Device(self.events, "TF Virutal HID Joystick")
		
		#TinkerForge Bereich
		ipcon = IPConnection()
		self.poti = RotaryPoti("aBQ", ipcon) #UID ändern!

		ipcon.connect("127.0.0.1", 4223) #IP / Port anpassen
		self.poti.set_position_callback_period(50)
		self.poti.register_callback(self.poti.CALLBACK_POSITION, self.poti_cb) #Sobald der Callback auslöst wird die Funktion poti_cb aufgerufen
Example #4
0
 def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
     if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
         if device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_ONE: #LED-Strip 1
             try:
                 self.led_strip_1 = LEDStrip(uid, self.ipcon)
                 log.info('LED-Strip 1 initialized.')
             except Error as e:
                 log.error('LED-Strip 1 init failed: ' + str(e.description))
                 self.led_strip_1 = None
         elif device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_TWO: #LED-Strip 2
             try:
                 self.led_strip_2 = LEDStrip(uid, self.ipcon)
                 log.info('LED-Strip 2 initialized.')
             except Error as e:
                 log.error('LED-Strip 2 init failed: ' + str(e.description))
                 self.led_strip_2 = None
         elif device_identifier == MultiTouch.DEVICE_IDENTIFIER: # MulitTouch for changing colors etc.
             try:
                 self.multi_touch = MultiTouch(uid, self.ipcon)
                 self.multi_touch.register_callback(self.multi_touch.CALLBACK_TOUCH_STATE, self.cb_buttons)
                 self.multi_touch.set_electrode_config(0x0FFF)
                 self.multi_touch.recalibrate()
                 log.info('Set proximity off.')
                 log.info('Multi-Touch initialized.')
             except Error as e:
                 log.error('Multi-Touch init failed: ' + str(e.description))
                 self.multi_touch = None
         elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER: # Rotary Poti for picking a color or changing the saturation
             try:
                 self.rotary_poti = RotaryPoti(uid, self.ipcon)
                 self.rotary_poti.register_callback(self.rotary_poti.CALLBACK_POSITION, self.cb_position)
                 self.rotary_poti.set_position_callback_period(50)
                 log.info('Rotary Poti initialized.')
             except Error as e:
                 log.error('Rotary Poti init failed: ' + str(e.description))
                 self.rotary_poti = None
# -*- coding: utf-8 -*-  

HOST = "localhost"
PORT = 4223
UID = "2wx" # Change to your UID

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_rotary_poti import RotaryPoti

# Callback function for position callback (parameter has range -150 to 150)
def cb_position(position):
    print('Position: ' + str(position))

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    poti = RotaryPoti(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Set Period for position callback to 0.05s (50ms)
    # Note: The position callback is only called every 50ms if the 
    #       position has changed since the last call!
    poti.set_position_callback_period(50)

    # Register position callback to function cb_position
    poti.register_callback(poti.CALLBACK_POSITION, cb_position)

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.disconnect()
from tinkerforge.brick_dc import DC
from tinkerforge.bricklet_rotary_poti import RotaryPoti

dc = None


# Callback function for position callback (parameter has range -150 to 150)
def cb_position(position):
    velocity = 0xFFFF / 2 * position / 150  # Velocity: -32767/32767
    print('Set Position/Velocity: ' + str(position) + '/' + str(velocity))
    dc.set_velocity(velocity)


if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection

    dc = DC(UID_DC, ipcon)  # Create DC brick device object
    poti = RotaryPoti(UID_POTI, ipcon)  # Create rotary poti device object

    ipcon.connect(HOST, PORT)  # Connect to brickd

    poti.set_position_callback_period(50)  # set callback period to 50ms
    poti.register_callback(poti.CALLBACK_POSITION, cb_position)

    dc.enable()
    dc.set_acceleration(0xFFFF)  # Full acceleration

    raw_input('Press Enter to exit\n')  # Use input() in Python 3
    dc.disable()
    ipcon.disconnect()
class PiTinkerforgeStack:
    host = '192.168.178.27' #raspi
    #host = '127.0.0.1' #localhost
    port = 4223
    uid_master = '6JKxCC'
    uid_motion = 'oRL'
    uid_poti_left = 'ejC'
    uid_poti_right = 'ejm'
    uid_io = 'hcs'
    female = False

    def __init__(self):
        self.con = IPConnection()
        self.master = Master(self.uid_master, self.con)
        self.motion = MotionDetector(self.uid_motion, self.con)
        self.poti_left = RotaryPoti(self.uid_poti_left, self.con)
        self.poti_right = RotaryPoti(self.uid_poti_right, self.con)
        self.io = IO4(self.uid_io, self.con)
        print "---" + str(15^15)
        print "---" + str(15^14)


    def connect(self):
        print "Connecting to host " + self.host + " on port " + str(self.port)
        self.con.connect(self.host, self.port)
        self.set_ziel_geschlecht(self.io.get_value())

    def disconnect(self):
        print "Disconnecting from host " + self.host
        self.con.disconnect()

    def motion_detected(self):
        print "CALLBACK!!"
        self.insult()

    def insult(self):
        ziel_geschlecht = "m"
        if self.female:
            ziel_geschlecht = "f"
        speak_next_insult(ziel_geschlecht, self.poti_left.get_position(), self.poti_right.get_position())

    def motion_cycle_ended(self):
        print "READY for motion detection!"

    def io_switch(self, interrupt_mask, value_mask):
        print "IO4 triggered"
        print('Interrupt by: ' + str(bin(interrupt_mask)))
        print('Value: ' + str(bin(value_mask)))
        #print('Val1: ' + str(value_mask))

        if interrupt_mask == 1:
            print "Sex switched..."
            # button 1 switched
            self.set_ziel_geschlecht(value_mask)
        elif interrupt_mask == 2:
            print "Insult button pressed..."
            button_up = value_mask&2
            print "value_mask =" + str(button_up)
            if button_up == 2:
                self.insult()
        print "io_switch() end"

    def set_ziel_geschlecht(self, value_mask):
        is_on = value_mask^14
        if is_on:
            print "MALE"
            self.female = False
        else:
            print "FEMALE"
            self.female = True


    def register_callbacks(self):
        print "Registering callback to motion detector..."
        #self.motion.register_callback(self.motion.CALLBACK_MOTION_DETECTED, self.motion_detected)
        self.motion.register_callback(self.motion.CALLBACK_DETECTION_CYCLE_ENDED, self.motion_cycle_ended)
        self.io.set_debounce_period(1000)
        self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch)
        # Enable interrupt on pin 0
        self.io.set_interrupt((1 << 0) | (1 << 1))
        #self.io.set_interrupt(1 << 1)
        print "register done"
#!/usr/bin/env python
# -*- coding: utf-8 -*-  

HOST = "localhost"
PORT = 4223
UID = "2wx" # Change to your UID

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_rotary_poti import RotaryPoti

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    poti = RotaryPoti(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Get current position of poti (return value has range -150 to 150)
    position = poti.get_position()

    print('Position: ' + str(position))

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.disconnect()
class PiTinkerforgeStack:
    #host = '192.168.178.36' #raspi
    #host = '127.0.0.1' #localhost
    host = 'brickd'
    port = 4223
    female = False
    io = None
    poti_left = None
    poti_volume = None
    master = None

    def __init__(self):
        syslog.openlog('insultr-tf', 0, syslog.LOG_LOCAL4)

        self.con = IPConnection()

        # Register IP Connection callbacks
        self.con.register_callback(IPConnection.CALLBACK_ENUMERATE, 
                                     self.cb_enumerate)
        self.con.register_callback(IPConnection.CALLBACK_CONNECTED, 
                                     self.cb_connected)
        
        self.insultr = Insultr()
        self.set_volume(50)
        self.log("---" + str(15^15))
        self.log("---" + str(15^14))

    def log(self, msg):
        syslog.syslog(msg)
        print msg

    def connect(self):
        self.log("Connecting to host " + self.host + " on port " + str(self.port))
        self.con.connect(self.host, self.port)
        self.con.enumerate()

    def disconnect(self):
        self.log("Disconnecting from host " + self.host)
        self.con.disconnect()

    # Callback handles device connections and configures possibly lost 
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, 
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            
            self.log("cb_enumerate() id {} - Found device: ident={}, position={}".format(uid, device_identifier, position))
            if device_identifier == IO4.DEVICE_IDENTIFIER:
                self.log("cb_enumerate() id {} - Creating IO4 device object".format(uid))
                self.io = IO4(uid, self.con) 
                self.io.set_debounce_period(1000)

                if position == 'a':
                    self.log("cb_enumerate() id {} - Configuring IO4 device object at position a (switches).".format(uid))
                    self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch)
                    self.io.set_configuration(15, 'i', True)
                    # Enable interrupt on pin 0 and 1
                    self.io.set_interrupt(1 << 0)
                    self.io.set_interrupt(1 << 1)
                    self.set_ziel_geschlecht(self.io.get_value())
                else:
                    self.log("cb_enumerate() id {} - Configuring IO4 device object at position ? (lights, shutdown).".format(uid))
                    self.io.set_configuration((1 << 0) | (1 << 1), "o", True)

            elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER:
                self.log("cb_enumerate() id {} - Creating RotaryPoti device object".format(uid))
                self.poti_volume = RotaryPoti(uid, self.con) 
                self.poti_volume.set_position_callback_period(100)
                self.poti_volume.register_callback(self.poti_volume.CALLBACK_POSITION, self.poti_volume_changed)
            elif device_identifier == Master.DEVICE_IDENTIFIER:
                self.log("cb_enumerate() id {} - Creating Master device object".format(uid))
                self.master = Master(uid, self.con)
            else: 
                self.log("cb_enumerate() id {} - Could not register unknown device bricklet".format(uid))

    # Callback handles reconnection of IP Connection
    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.con.enumerate()    

    def motion_detected(self):
        self.log("CALLBACK!!")
        self.insult()

    def insult(self):
        self.insultr.speak_next_insult()

    def set_volume(self, volume_percent=50):
        set_volume_cmd = 'amixer sset Master {}%'.format(volume_percent)
        self.log("set_volume() Setting volume with command: " + set_volume_cmd)
        os.system(set_volume_cmd)

    def set_volume_from_poti(self):
        if self.poti_volume:
            position = self.poti_volume.get_position()
            self.poti_volume_changed(position)
        else:            
            self.set_volume(50)

    def poti_volume_changed(self, position=0):
        self.log("poti_volume_changed() poti was set to position {}".format(position))
        if position > 150:
            position = 150
        if position < -150:
            position = -150
        MIN_VOLUME = 25.0
        MAX_VOLUME = 90.0
        poti_percent = ((position + 150.0) / 300.0) # between 0.0 and 1.0
        volume_percent = MIN_VOLUME + ((MAX_VOLUME-MIN_VOLUME)*poti_percent)
        self.set_volume(volume_percent)

    def motion_cycle_ended(self):
        self.log("READY for motion detection!")

    def io_switch(self, interrupt_mask, value_mask):
        self.log("io_switch() IO4 triggered")
        self.log("io_switch() Interrupt by {} / {} ".format(str(bin(interrupt_mask)), interrupt_mask))
        self.log('io_switch() Value: ' + str(bin(value_mask)))
        
        try: 
            self.set_volume_from_poti()

            if interrupt_mask == 1:
                self.log("io_switch() Sex switched...")
                # button 1 switched
                self.set_ziel_geschlecht(value_mask)
            elif interrupt_mask == 2:
                self.log("io_switch() Insult button pressed...")
                button_up = value_mask&2
                self.log("io_switch() value_mask =" + str(button_up))
                if button_up == 2:
                    self.insult()
            else: 
                self.log("io_switch() Don't know what to do with interrupt_mask {}".format(interrupt_mask))
        except Error as e:
            self.log("io_switch() ERROR:{}".format(e))
            
        self.log("io_switch() end")

    def set_ziel_geschlecht(self, value_mask):
        is_on = value_mask^14
        if is_on:
            self.log("sex was set to MALE")
            self.female = False
            self.insultr.set_maennlich()
            self.io.set_configuration(1 << 0, "o", True)
            self.io.set_configuration(1 << 1, "o", False)
        else:
            self.log("sex was set to FEMALE")
            self.female = True
            self.insultr.set_weiblich()
            self.io.set_configuration(1 << 0, "o", False)
            self.io.set_configuration(1 << 1, "o", True)


    def register_callbacks(self):
        self.log("Registering callback to motion detector...")
        self.motion.register_callback(self.motion.CALLBACK_MOTION_DETECTED, self.motion_detected)
        self.motion.register_callback(self.motion.CALLBACK_DETECTION_CYCLE_ENDED, self.motion_cycle_ended)
        self.io.set_debounce_period(1000)
        self.io.register_callback(self.io.CALLBACK_INTERRUPT, self.io_switch)
        # Enable interrupt on pin 0
        self.io.set_interrupt((1 << 0) | (1 << 1))
        #self.io.set_interrupt(1 << 1)
        self.log("register done")
Example #10
0
class led_strips:
    HOST = "localhost"
    PORT = 4223

    UID_LED_STRIP_ONE = "jGy"
    UID_LED_STRIP_TWO = "jHE"

    MODE = 0
    MODE_HUE = 1
    MODE_SATURATION = 2
    MODE_VALUE = 3
    MODE_VELOCITY = 4
    MODE_COLOR_GRADIENT = 5
    MODE_COLOR_DOT = 6
    MODE_COLOR_FADING = 7
    MODE_COLOR_RANDOMLY = 8
    MODE_LEDS = 9
    MODE_OFF = 10

    MODE_STRIPS = 0
    MODE_LEFT_STRIP = 1
    MODE_RIGHT_STRIP = 2
    MODE_BOTH_STRIPS = 3

    POSITION_HUE = 1
    POSITION_SATURATION = 1
    POSITION_VALUE = 0.3
    POSITION_VELOCITY = 1

    R = [255]*16
    G = [0]*16
    B = [0]*16
    
    MAX_LEDS = 16
    ACTIVE_LEDS = 16

    ipcon = None
    led_strip_1 = None
    led_strip_2 = None
    multi_touch = None
    rotary_poti = None

    def __init__(self):
        # Create IP Connection
        self.ipcon = IPConnection()
        while True:
            try:
                self.ipcon.connect(led_strips.HOST, led_strips.PORT)
                break
            except Error as e:
                log.error('Connection error: ' + str(e.description))
                time.sleep(1)
            except socket.error as e:
                log.error('Socket error: ' + str(e))
                time.sleep(1)

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected)

        while True:
            try:
                self.ipcon.enumerate()
                break
            except Error as e:
                log.error('Enumerate error: ' + str(e.description))
                time.sleep(1)

    # Callback handels device connections and configures possibly lost configuration
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            if device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_ONE: #LED-Strip 1
                try:
                    self.led_strip_1 = LEDStrip(uid, self.ipcon)
                    log.info('LED-Strip 1 initialized.')
                except Error as e:
                    log.error('LED-Strip 1 init failed: ' + str(e.description))
                    self.led_strip_1 = None
            elif device_identifier == LEDStrip.DEVICE_IDENTIFIER and uid == self.UID_LED_STRIP_TWO: #LED-Strip 2
                try:
                    self.led_strip_2 = LEDStrip(uid, self.ipcon)
                    log.info('LED-Strip 2 initialized.')
                except Error as e:
                    log.error('LED-Strip 2 init failed: ' + str(e.description))
                    self.led_strip_2 = None
            elif device_identifier == MultiTouch.DEVICE_IDENTIFIER: # MulitTouch for changing colors etc.
                try:
                    self.multi_touch = MultiTouch(uid, self.ipcon)
                    self.multi_touch.register_callback(self.multi_touch.CALLBACK_TOUCH_STATE, self.cb_buttons)
                    self.multi_touch.set_electrode_config(0x0FFF)
                    self.multi_touch.recalibrate()
                    log.info('Set proximity off.')
                    log.info('Multi-Touch initialized.')
                except Error as e:
                    log.error('Multi-Touch init failed: ' + str(e.description))
                    self.multi_touch = None
            elif device_identifier == RotaryPoti.DEVICE_IDENTIFIER: # Rotary Poti for picking a color or changing the saturation
                try:
                    self.rotary_poti = RotaryPoti(uid, self.ipcon)
                    self.rotary_poti.register_callback(self.rotary_poti.CALLBACK_POSITION, self.cb_position)
                    self.rotary_poti.set_position_callback_period(50)
                    log.info('Rotary Poti initialized.')
                except Error as e:
                    log.error('Rotary Poti init failed: ' + str(e.description))
                    self.rotary_poti = None

    # Callback handels reconnection of IP Connection
    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:
            log.info('Auto reconnect.')
            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    log.error('Enumerate error:' + str(e.description))
                    time.sleep(1)

    # Check which mode is set: the left LED strip, the right LED strip or both LED strips
    def set_mode(self, mode, i, leds, r, b, g):
        if self.MODE_STRIPS == self.MODE_BOTH_STRIPS:
            self.led_strip_1.set_rgb_values(i, leds, r, b, g)
            self.led_strip_2.set_rgb_values(i, leds, r, b, g)
        elif self.MODE_STRIPS == self.MODE_LEFT_STRIP:
            self.led_strip_1.set_rgb_values(i, leds, r, b, g)
        elif self.MODE_STRIPS == self.MODE_RIGHT_STRIP:
            self.led_strip_2.set_rgb_values(i, leds, r, b, g)
    
    # Turn off the LED strips depending on the given mode
    def leds_off(self):
        r = [0]*self.MAX_LEDS
        g = [0]*self.MAX_LEDS
        b = [0]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    # Some simple color functions to turn the strips to red, green or blue
    def led_strips_red(self):
        r = [255]*self.MAX_LEDS
        g = [0]*self.MAX_LEDS
        b = [0]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    def led_strips_green(self):
        r = [0]*self.MAX_LEDS
        g = [255]*self.MAX_LEDS
        b = [0]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    def led_strips_blue(self):
        r = [0]*self.MAX_LEDS
        g = [0]*self.MAX_LEDS
        b = [255]*self.MAX_LEDS
        self.set_mode(self.MODE_STRIPS, 0, self.MAX_LEDS, r, b, g)

    # Match the hue (color) to the position by the rotary poti.
    def set_hue(self, position):
        # The position returned by the rotary poti (o to +300) must be mapped to 0°-360° in the HSV colorspace
        hue = ((position / 360) * 432)
        # Convert the HSV color (hue,saturation,value) to the RGB color
        # The function expects hue to be in the range 0-1 not 0-360
        r, g, b = colorsys.hsv_to_rgb(hue/360, self.POSITION_SATURATION, self.POSITION_VALUE)
        #print('Hue: {0:.1f}'.format(hue),'Saturation: {0:.2f}'.format(self.POSITION_SATURATION),'Value: {0:.2f}'.format(self.POSITION_VALUE))
        # Build the LED strip
        self.build_led_strip(r, g, b) 
        # Save the value in the variable
        self.POSITION_HUE = hue/360

    # Match the saturation to the position by the rotary poti.
    def set_saturation(self, position):
        # The position returned by the rotary poti must be mapped to 0-1 in the HSV colorspace
        saturation = (position / 300)
        # Convert the HSV color (hue,saturation,value) to the RGB color
        r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, saturation, self.POSITION_VALUE) 
        #print('Hue: {0:.1f}'.format(self.POSITION_HUE*360),'Saturation: {0:.2f}'.format(saturation),'Value: {0:.2f}'.format(self.POSITION_VALUE))
        # Build the LED strip
        self.build_led_strip(r, g, b)
        # Save the value in the variable
        self.POSITION_SATURATION = saturation
    
    # Match the value to the position by the rotary poti.
    def set_value(self, position):
        # The position returned by the rotary poti must be mapped to 0-1 in the HSV colorspace
        value = (position / 300)
        # Convert the HSV color (hue,saturation,value) to the RGB color
        r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, self.POSITION_SATURATION, value)
        #print('Hue: {0:.1f}'.format(self.POSITION_HUE*360),'Saturation: {0:.2f}'.format(self.POSITION_SATURATION),'Value: {0:.2f}'.format(value))
        # Build the LED strip
        self.build_led_strip(r, g, b)
        # Save the value in the variable
        self.POSITION_VALUE = value

    # NOT USED AT THE MOMENT
    # The veolcity for some functions can be adjusted by the rotary poti.
    def set_velocity(self, position):
        velocity = (position / 3)
        #print('Velocity: {0:0.1f}'.format(velocity))
        # Save the velocity in the variable
        self.POSITION_VELOCITY = velocity

    # Function to generate a rainbow gradient. Can be adjusted by the velocity.
    def set_color_gradient(self, position):
        # use all LEDs for the gradient
        active_leds = self.MAX_LEDS
        loop_counter = 0
        r = []
        g = []
        b = []
        for led in list(range(active_leds)):
            rv, gv, bv = colorsys.hsv_to_rgb(1.*led/active_leds, self.POSITION_SATURATION, self.POSITION_VALUE)
            r.append(int(rv*255))
            g.append(int(gv*255))
            b.append(int(bv*255))
        for leds in range(active_leds):
            #print("Loop counter: " + str(loop_counter))
            first_red = r.pop(0)
            r.append(first_red)
            first_green = g.pop(0)
            g.append(first_green)
            first_blue = b.pop(0)
            b.append(first_blue)
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            loop_counter = loop_counter + 1            
            time.sleep(0.075)

    # Fade and change the color for the whole strip
    def set_color_gradient_fading(self):
        # Outer loop for changing the color
        for hue in range(0, 360, 30):
            hue = (hue / 360)
            #print("Hue: " + str(hue))
            # Inner loop for fading the actual color
            for value in range(1, 21):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(hue, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
            for value in reversed(range(1, 21)):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(hue, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
 
    # The LEDs are fading from 0.1 to 1.0 in the value space. The fading can be adjusted by the velocity.
    def set_color_fading(self, position):
        loop_counter = 0
        while loop_counter < 5:
            #print("Loop counter: " + str(loop_counter))
            for value in range(1, 21):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
            for value in reversed(range(1, 21)):
                value = value / 20
                #print("Value: " + str(value))
                r, g, b = colorsys.hsv_to_rgb(self.POSITION_HUE, self.POSITION_SATURATION, value)
                self.build_led_strip(r, g, b)
                time.sleep(0.075)
                loop_counter = loop_counter + 1

    # Only one LED is active and moves from one end to the other end of the strip.
    def set_color_dot(self, position):
        # Build the initial array
        r = self.R[0]
        g = self.G[0]
        b = self.B[0]
        r = [r]
        g = [g]
        b = [b]
        r.extend([0]*15)
        g.extend([0]*15)
        b.extend([0]*15)
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
        # Now get the dot moving
        i = 0
        while i < 15:
            dot_r = r[i]
            dot_g = g[i]
            dot_b = b[i]
            r[i] = 0
            g[i] = 0
            b[i] = 0
            r[i+1] = dot_r
            g[i+1] = dot_g
            b[i+1] = dot_b
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            i = i + 1
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.1)
        while i > 0:
            dot_r = r[i]
            dot_g = g[i]
            dot_b = b[i]
            r[i] = 0
            g[i] = 0
            b[i] = 0
            r[i-1] = dot_r
            g[i-1] = dot_g
            b[i-1] = dot_b
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            i = i - 1
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.1)

    # Build random color values and place them randomly on the strips.
    def set_color_randomly(self, position):
        active_leds = self.ACTIVE_LEDS
        """
        r = []
        g = []
        b = []
        # 1. Variant
        for led in list(range(active_leds)):
            rv = random.randrange(1, 256)
            gv = random.randrange(1, 256)
            bv = random.randrange(1, 256)
            r.append(rv)
            g.append(gv)
            b.append(bv)
        # 2. Variant
        for led in list(range(active_leds)):
            rv, gv, bv = colorsys.hsv_to_rgb(1.*led/active_leds, self.POSITION_SATURATION, self.POSITION_VALUE)
            r.append(int(rv*255))
            g.append(int(gv*255))
            b.append(int(bv*255))
        for leds in range(active_leds):
            random.shuffle(r)
            random.shuffle(g)
            random.shuffle(b)
            print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.075)
        """
        # 3. Variant
        for leds in range(active_leds):
            r = []
            g = []
            b = []
            range_leds = list(range(active_leds))
            random.shuffle(range_leds)
            #print("LEDs: " + str(range_leds))
            for led in range_leds:
                rv, gv, bv = colorsys.hsv_to_rgb(1.*led/active_leds, self.POSITION_SATURATION, self.POSITION_VALUE)
                r.append(int(rv*255))
                g.append(int(gv*255))
                b.append(int(bv*255))
            #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
            self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
            time.sleep(0.1)

    # Extend the LEDs from 1 LED to 16 LEDs per strip. Like the fading, but here the LEDs can be adjusted by the rotary poti.
    def set_leds(self, position):
        # The rotary poti can set the number of LEDs which should be used
        active_leds = (position / 300) * self.MAX_LEDS
        active_leds = int(math.ceil(active_leds))
        #print('Active LEDs: ' + str(active_leds))
        
        # Get the color values from the variables
        r = self.R[0]
        g = self.G[0]
        b = self.B[0]
        #print('R: ' + str(r),'G: ' + str(g),'B: ' + str(b))

        # Now build the list with the active leds
        r = [r]*active_leds
        g = [g]*active_leds
        b = [b]*active_leds
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')

        # Now add the remaining dark leds to the list
        dark_leds = 16 - active_leds
        #print('Dark LEDs: ' + str(dark_leds))
        r.extend([0]*dark_leds)
        g.extend([0]*dark_leds)
        b.extend([0]*dark_leds)          
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')

        # Now get it to the strips
        self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)           

        # Save the value in the variable
        self.ACTIVE_LEDS = active_leds

    # Helper function to generate the output for the LED strips
    def build_led_strip(self, r, g, b):
        r = int(r*255)
        g = int(g*255)
        b = int(b*255)
        #print('R: ' + str(r),'G: ' + str(g),'B: ' + str(b))

        # Get the actual number of LEDs which should be used
        active_leds = self.ACTIVE_LEDS
        r = [r]*active_leds
        g = [g]*active_leds
        b = [b]*active_leds
        
        # Now add the remaining dark leds to the list
        dark_leds = 16 - active_leds
        r.extend([0]*dark_leds)
        g.extend([0]*dark_leds)
        b.extend([0]*dark_leds)
        #print('R: ' + str(r) + '\n','G: ' + str(g) + '\n','B: ' + str(b) + '\n')
        
        # Now get it to the strips
        self.set_mode(self.MODE, 0, self.MAX_LEDS, r, b, g)
        # Save the values in the variables
        self.R = r
        self.G = g
        self.B = b

    # Callback function for position callback (parameter has range -150 to 150)
    def cb_position(self, position):
        # Print the position for debuging
        #print('Position: ' + str(position))
        # Always add +150 to the position value so that it will start on the left by 0 and to the right it will end by 300
        position = position + 150
        # Select in which MODE it is called
        if self.MODE == self.MODE_HUE:
            self.set_hue(position)
        elif self.MODE == self.MODE_SATURATION:
            self.set_saturation(position)
        elif self.MODE == self.MODE_VALUE:
            self.set_value(position)
        elif self.MODE == self.MODE_VELOCITY:
            self.set_velocity(position)
        elif self.MODE == self.MODE_COLOR_GRADIENT:
            self.set_color_gradient(position)
        elif self.MODE == self.MODE_COLOR_DOT:
            self.set_color_dot(position)
        elif self.MODE == self.MODE_COLOR_FADING:
            self.set_color_fading(position)
        elif self.MODE == self.MODE_COLOR_RANDOMLY:
            self.set_color_randomly(position)
        elif self.MODE == self.MODE_LEDS:
            self.set_leds(position)

    # Callback function for button callback
    def cb_buttons(self, button_state):
        for i in range(12):
            if button_state & (1 << i):
                if i == 0:
                    self.MODE_STRIPS = self.MODE_LEFT_STRIP
                elif i == 1:
                    self.MODE = self.MODE_HUE
                elif i == 2:
                    self.MODE = self.MODE_COLOR_GRADIENT
                elif i == 3:
                    self.MODE_STRIPS = self.MODE_BOTH_STRIPS
                elif i == 4:
                    self.MODE = self.MODE_SATURATION
                elif i == 5:
                    self.set_color_gradient_fading()
                elif i == 6:
                    self.MODE_STRIPS = self.MODE_RIGHT_STRIP
                elif i == 7:
                    self.MODE = self.MODE_VALUE
                elif i == 8:
                    self.MODE = self.MODE_COLOR_FADING
                elif i == 9:
                    #self.MODE = self.MODE_OFF
                    self.MODE = self.MODE_COLOR_RANDOMLY
                elif i == 10:
                    self.MODE = self.MODE_LEDS
                elif i == 11:
                    self.MODE = self.MODE_COLOR_DOT