Esempio n. 1
0
def send():
    params = bottle.request.query

    if 'text' not in params:
        raise HTTPError(400, 'Need text to send!')

    if 'label' in params:
        label = params.label.lower()
    else:
        label = 'A'

    text = params.text
    color = constants.get_color(params.get('color', 'NONE'))
    mode = constants.get_mode(params.get('mode', 'COMPRESSED_ROTATE'))

    text = color + text
    text = general.parse_colors(text)

    if label == 'A':
        text = parse_labels(text)

    memory_entry = sign.find_entry(read_raw_memory_table(), label)
    if len(text) >= memory_entry['size']:
        raise HTTPError(
            400, 'Not enough space allocated. Need at least %s bytes.' %
            (len(text) + 1))

    if label == 'A':
        sign.write(alphasign.Text(text, label=label, mode=mode))
    else:
        sign.write(alphasign.String(text, label=label))

    return {'result': 'Sucessfully sent text'}
Esempio n. 2
0
 def get_text(self):
     # fixed width to allow matching things up across the two lines
     return alphasign.Text(alphasign.charsets.FIXED_WIDTH_ON + self.top +
                           self.bot,
                           mode=alphasign.modes.AUTOMODE,
                           position=alphasign.positions.FILL,
                           label=self.label)
Esempio n. 3
0
def reset():
    params = bottle.request.query

    text_length = params.get('textsize', 256, type=int)
    string_length = params.get('stringsize', 256, type=int)

    text = alphasign.Text(
        '%sREADY FOR DEAD-SIMPLE. TRY HITTING %s/dead-simple/send?text=%s<text>'
        % (alphasign.colors.RED, alphasign.colors.YELLOW,
           alphasign.colors.GREEN),
        label='A',
        size=text_length,
        mode=alphasign.modes.COMPRESSED_ROTATE)

    strings = [
        alphasign.String(label=label, size=string_length)
        for label in constants.dead_simple_string_labels
    ]

    sign.allocate(chain([text], strings))
    sign.set_run_sequence([text])
    sign.write(text)
    for string in strings:
        sign.write(string)
    read_raw_memory_table.clear_cache()

    return {'result': 'Successfully reset sign for dead-simple API'}
Esempio n. 4
0
    def __init__(self, usb_port=USB_PORT, max_size=10):
        self.messages = []
        self.sign = alphasign.Serial(USB_PORT)
        # where in the queue are we?
        self.index = 0
        # where do we start
        self.start_index = 0

        self.sign.connect()
        self.sign.clear_memory()

        # how many 'live' messages do we have?
        self.size = 0
        self.max_size = max_size
        label_num = 0
        for i in range(self.max_size):
            msg = {}

            msg["str"] = alphasign.String(size=125,
                                          label=chr(ord('A') + label_num))
            label_num = label_num + 1
            msg["txt"] = alphasign.Text(
                "%s%s" % (alphasign.colors.GREEN, msg["str"].call()),
                chr(ord('A') + label_num),
                mode=alphasign.modes.ROTATE)
            label_num = label_num + 1
            self.messages.append(msg)
            self.sign.allocate((msg["str"], msg["txt"]))
            self.sign.write(msg["str"])
            self.sign.write(msg["txt"])
            print "alloc'ed: %s string, %s text" % (msg["str"], msg["txt"])
Esempio n. 5
0
    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        logging.info("{} wrote: {}".format(self.client_address[0], self.data))
        msg = alphasign.Text(self.data)
        sign.write(msg)

        # ack
        self.request.sendall("sign set to %s" % self.data)
Esempio n. 6
0
def show_text(data):
    label = data['label']
    memory_entry = sign.find_entry(read_raw_memory_table(), label)
    if memory_entry['type'] != 'TEXT':
        raise HTTPError(
            400,
            'The data at label %s must be of type TEXT. It is of type %s' %
            (label, memory_entry['type']))
    sign.set_run_sequence([alphasign.Text(label=label)])
    return {'result': 'Sign showing text at %s' % label}
Esempio n. 7
0
def write_file(request, label):
    memory_table = read_raw_memory_table()

    if 'type' in request:
        general.validate_label(label, request['type'], memory_table)

    memory_entry = sign.find_entry(memory_table, label)
    memory_table = sign.parse_raw_memory_table(memory_table)

    file_type = memory_entry['type']

    if file_type == 'TEXT' or file_type == 'STRING':
        data = request['text']

        #Prepend color. Ignore invalid colors.
        data = constants.get_color(request.get('color', 'NO_COLOR')) + data

        #parse colors
        data = general.parse_colors(data)

        #text-specific processing
        if file_type == 'TEXT':
            data = general.parse_labels(data, memory_table)

        #check size
        if len(data) > memory_entry['size']:
            raise HTTPError(
                400,
                'Not enough memory allocated. Requires %s, only %s allocated.'
                % (len(data), memory_entry['size']))

        if file_type == 'TEXT':
            mode = constants.get_mode(request.get('mode', 'HOLD'))
            obj = alphasign.Text(data, label=label, mode=mode)
        elif file_type == 'STRING':
            obj = alphasign.String(data, label=label)

    elif file_type == 'DOTS':
        data = request['data']
        rows = memory_entry['rows']
        columns = memory_entry['columns']

        obj = alphasign.Dots(rows, columns, label=label)

        for i, row in enumerate(data[:rows]):
            obj.set_row(i, row)

    sign.write(obj)
    return {'result': 'memory written successfully'}
Esempio n. 8
0
def make_objects(clump, names=None):
    '''Given a clump, generate the objects to be written to the sign.
    '''
    labels = iter(constants.sign_controller_labels)
    text_label = next(labels)
    fields = clump['fields']
    text = clump['text']
    
    label_map = {name: (next(labels), 'STRING' if 'text' in field else 'DOTS')
                 for name, field in sorted(fields.iteritems())}
    
    #parse colors
    text = general.parse_colors(text)
    
    #parse labels
    def label_replacer(flag):
        if flag in label_map:
            label, type = label_map[flag]
            if type == 'STRING':
                return alphasign.String(label=label).call()
            elif type == 'DOTS':
                return alphasign.Dots(label=label).call()
        return None
    text = general.parse_generic(text, label_replacer)
    
    yield alphasign.Text(text, text_label,
                         mode=constants.get_mode(clump['mode']))
    
    if names is not None:
        label_map = {name: val for name, val in label_map.iteritems() if name in names}
        
    #Run through each named subfield
    for fieldname, (label, fieldtype) in label_map.iteritems():
        field = fields[fieldname]
        
        if fieldtype == 'DOTS':
            rows = field['rows']
            num_rows = len(rows)
            num_columns = max(len(row) for row in rows)
            dots = alphasign.Dots(num_rows, num_columns, label=label)
            for i, row in enumerate(rows):
                dots.set_row(i, str(row))
            yield dots
        elif fieldtype == 'STRING':
            text = field['text']
            text = general.parse_colors(text)
            yield alphasign.String(text, label=label)
Esempio n. 9
0
def update_sign():

        sign = alphasign.Serial(device='/dev/ttyUSB0')
        sign.connect()
        sign.clear_memory()

        # create an empty alphasign.String
        alpha_str = alphasign.String(size=64)

        # create a single alphasign.Text object with a placeholder for our alphasign.String
        alpha_txt = alphasign.Text(alpha_str.call(),mode=alphasign.modes.COMPRESSED_ROTATE)

        # allocate memory for these objects on the sign
        sign.allocate((alpha_str,alpha_txt))

        # tell sign to only display the text part
        sign.set_run_sequence((alpha_txt,))

        # write objects
        for obj in (alpha_str,alpha_txt):
            sign.write(obj)

        # This gives time for the serial write to complete before we issue the next write.
        time.sleep(5)

        last_payload = ''

        while True:

            try:
                # fetch new-line separated plain text from Interweb
                payload = urllib2.urlopen("https://server.appletonmakerspace.org/wiki/doku.php?id=sign_text&do=export_raw").read()
            except Exception as e:
                payload = 'net err: '+str(e)

            # alert bystanders with beep when we update
            if payload != last_payload:
                sign.beep(frequency=20, duration=1)
                last_payload = payload

            # loop over each line of plain text, displaying for 10 seconds
            for line in payload.splitlines():
                alpha_str.data = line
                sign.write(alpha_str)
                time.sleep(10)
Esempio n. 10
0
    def __init__(self, channel, nickname, password=''):
        self.channel = channel
        self.nickname = nickname
        self.password = password
        self.sign = alphasign.Serial(USB_PORT)
        self.sign.connect()
        self.sign.clear_memory()
        self.message_str = alphasign.String(size=140, label="2")
        self.message_txt = alphasign.Text("%s" % self.message_str.call(),
                                          label="B",
                                          mode=alphasign.modes.TWINKLE)
        #message_txt = alphasign.Text("%s%s" % (alphasign.colors.GREEN,message_str.call()), label="B", mode = alphasign.modes.ROTATE)
        self.message_str.data = "Make me say things!"
        # allocate memory for these objects on the sign
        self.sign.allocate((self.message_str, self.message_txt))
        self.sign.set_run_sequence((self.message_txt, ))

        self.sign.write(self.message_txt)
        self.sign.write(self.message_str)
Esempio n. 11
0
def set_allocation_table(request):
    table = request['table']
    allocation_objects = []
    used_labels = []
    for entry in table:
        try:
            label = entry['label']
            object_type = entry['type'].upper()

            general.validate_label(label)

            if label in used_labels:
                raise HTTPError(400, 'Label %s has already appeared in entry')

            #TODO: check sizes
            if object_type == 'TEXT':
                obj = alphasign.Text(label=label, size=entry['size'])
            elif object_type == 'STRING':
                obj = alphasign.String(label=label, size=entry['size'])
            elif object_type == 'DOTS':
                obj = alphasign.Dots(entry['rows'],
                                     entry['columns'],
                                     label=label)
            else:
                raise HTTPError(400, '%s is not a valid type' % object_type)
            allocation_objects.append(obj)
            used_labels.append(label)
        except KeyError as e:
            raise HTTPError(
                400, 'Missing Field %s in entry\nEntry:\n%s' %
                (e.message, entry)), None, sys.exc_traceback
        except HTTPError as e:
            e.output += '\nEntry:\n%s' % entry
            raise

    sign.allocate(allocation_objects)
    read_raw_memory_table.clear_cache()

    return {'result': 'Memory allocated successfully'}
Esempio n. 12
0
def updateLED(list):
  
    sign = alphasign.Serial(0)
    sign.connect()
    print "Clearing sign memory"
    #sign.clear_memory()
    #sign.beep(frequency=0,duration=0.1,repeat=0)
    

    #create the sequence
    messages = []
    for position, item in enumerate(list):
        messageData = item
        #cleanup the message a bit
        #messageData = "%s" + "        " + messageData + "        "
        messageData = "%s" + messageData

        
        label = position + 1
        messageText = alphasign.Text((messageData % alphasign.charsets.TEN_HIGH_STD),label=str(label),mode=checkMode(messageData),position=checkPosition(messageData))
        #messageText = alphasign.Text(messageData % alphasign.charsets.SEVEN_SHADOW,label=str(label))
        #messageText = alphasign.Text((messageData % alphasign.charsets.SEVEN_HIGH_FANCY),label="A")
        print "Message Data: %s" % messageData
        print str(position)
        print "Position: %s" % position
        
        messages.append(messageText)        
     
    # allocate memory for these objects on the sign
    print "Allocating sign text"    
    sign.allocate((messages))
    #print "Updating Sequence"
    #sign.set_run_sequence((messages))
    print "Writing messages"
    for obj in (messages):
        sign.write(obj)
Esempio n. 13
0
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        logging.info("{} wrote: {}".format(self.client_address[0], self.data))
        msg = alphasign.Text(self.data)
        sign.write(msg)

        # ack
        self.request.sendall("sign set to %s" % self.data)

if __name__ == "__main__":

    public_ip = subprocess.check_output(['hostname', '-I']).strip()
    logging.info("starting server on %s:%s" % (HOST, PORT))

    sign = alphasign.interfaces.local.Serial(device='/dev/ttyUSB0', baudrate=38400)
    sign.connect()
    sign.clear_memory()

    msg = alphasign.Text("%sserver %s:%s" % (alphasign.colors.RED, public_ip, PORT),
        label="A",
        mode=alphasign.modes.HOLD)

    sign.write(msg)

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
Esempio n. 14
0
 def get_text(self):
     return alphasign.Text(alphasign.speeds.SPEED_5 + self.text,
                           mode=alphasign.modes.SCROLL,
                           label=self.label)
Esempio n. 15
0
import os
import json
import time
import datetime

import alphasign

sign = alphasign.Serial(device=os.environ["MZ_SIGN_PORT"])
sign.connect()
sign.clear_memory()

name_str = alphasign.String(size=50, label="1")
time_str = alphasign.String(size=20, label="2")
playing_text = alphasign.Text(
        "Now Playing: {}    {}".format(name_str.call(), time_str.call()),
        label="A",
        mode=alphasign.mode.ROLL_LEFT
)

sign_objs = (name_str, time_str, playing_text)
sign.allocate(objs)
sign.set_run_sequence((playing_text,))

for obj in sign_objs:
    sign.write(obj)

redis = redis.Redis()

while True:
    quent = redis.lindex("musicaqueue", 0)
    if quent is None:
Esempio n. 16
0
 def get_text(self):
     return alphasign.Text(self.text,
                           mode=alphasign.modes.AUTOMODE,
                           label=self.label)
Esempio n. 17
0
def sign_loop(sign, module):
    """Main worker loop that feeds sequences to the sign.
    """
    # there are 93 valid labels (see p. 50 of docs)
    valid_labels = iter(
        [chr(x) for x in range(0x20, 0x7E + 1) if x != 0x30 and x != 0x3F])

    textfiles = []
    for i in range(NUM_TEXTFILES):
        textfiles.append(
            alphasign.Text("",
                           size=125,
                           label="%s" % (valid_labels.next(), ),
                           mode=get_mode("HOLD")))

    sign.allocate(textfiles)

    run_sequence = textfiles[0:1]

    sign.set_run_sequence(run_sequence)

    for t in textfiles:
        sign.write(t)

    is_active = getattr(module, "is_active", lambda: True)

    active = True

    while not SHUTDOWN:
        try:
            # sleep and then skip to next iteration if not active
            active = check_if_active(active, is_active, sign, textfiles)
            if not active:
                continue

            try:
                sequence = SEQUENCE_QUEUE.get(True, 1)
            except Queue.Empty:
                sequence = None

            ctx = {'message_queue': MESSAGE_QUEUE}
            if not sequence:
                try:
                    sequence = module.sign_sequence(ctx)
                except Exception as e:
                    LOG.error("Error running sign_sequence(): %s" % (str(e), ))
                if not sequence:
                    sequence = {}

            sleeptime = 60

            messages = []
            if sequence:
                messages = sequence.get('messages', [])
                num_msgs = len(messages)
                if num_msgs > NUM_TEXTFILES:
                    LOG.info(
                        "WARNING: Got %d messages, which exceeds limit of %d. Truncating."
                        % (len(messages), NUM_TEXTFILES))
                # modify run_sequence if necessary
                if num_msgs != len(run_sequence):
                    LOG.debug("Re-setting run sequence")
                    run_sequence = textfiles[0:num_msgs]
                    sign.set_run_sequence(run_sequence)

                sleeptime = int(sequence.get('duration', 60))

            i = 0
            for textfile in textfiles:
                log = True
                if i < len(messages):
                    msg = messages[i]
                else:
                    msg = {'mode': 'HOLD', 'text': ''}
                    log = False
                display_message(sign, msg, textfile, log=log)
                i += 1

            # let it display for given duration
            sleep_for(sleeptime)

        except KeyboardInterrupt:
            LOG.info("Stopping...")
            keep_going = False

    LOG.info("Exiting sign loop")