#!/usr/bin/env python
import socket
import sys

# This program opens two sockets to the dpserver, one
# to listen for button press events and one to update
# the LED display.  This code uses a blocking read but
# a select() implementation would work too.
#
# Pressing button 1 increments the count, button 2
# clears the count and button 3 decrements the count.
# Buttons are represented as hex values 1, 2, and 4.

# Global state information
count = 0

try:
    sock_cmd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_cmd.connect(('localhost', 8870))
    sock_button = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_button.connect(('localhost', 8870))
    sock_button.send('dpcat bb4io buttons\n')
    # loop forever getting button presses and updating the count
    while True:
        display_count = count
        if display_count < 0:
            display_count = count + 256
        sock_cmd.send('dpset bb4io leds ' "%x" '\n' % display_count)
        key = sock_button.recv(6)
        keyint = int(key[:3])
        if keyint == 1:
            count = (count + 1) % 256
        elif keyint == 2:
            count = 0;
        elif keyint == 4:
            count = (count - 1) % 256

except KeyboardInterrupt:
    # exit on Ctrl^C
    sock_cmd.close()
    sock_button.close()
    sys.exit()

except socket.error:
    print "Couldn't connect to dpdaemon"
    sys.exit()


