Python – State Machine Code

'''
    COMP-E, reposted as __nero on activestate
    Monday, May 08, 2011
'''

import inspect
import sys
import re

class StateMachineFoo(object):
    '''
        This is a template for a finite state machine that is dynamically built based
        on the function names and docstring for the given functions
    '''

    def __init__(self):
        # find all the states based on the regex
        m = re.compile(r'_state.*',re.I)

        # return a list of matches
        state_names = filter(m.search,dir(self))

        # get the function pointers to all of our states
        state_ptrs = [getattr(self,state) for state in state_names]

        # from the function pointers, suck up our dockstring and get our transitions
        dictm = re.compile(r"{.*}",re.S)
        state_trans = [eval(dictm.search(getattr(state, 'func_doc', '')).group(0)) for state in state_ptrs]

        # use zip to create a tuple containing our state_name/state_transition pairings, and add
        # them to the dictionary as key/value pairs
        self.state_machine = dict(zip(state_names,state_trans))

    def start(self, start_state):
        '''
            you should specify your beginning state
        '''
        if type('') == type(start_state):
            getattr(self,start_state)()
        else:
            self._stateA()

    def stop(self):
        '''
            A state to exit nicely from
        '''
        return

    def _stateA(self):
        '''
            {'SUCCESS': self._stateB,'FAIL':self.error}
        '''
        error = False
        fname = inspect.stack()[0][3]

        print "I'm in '%s'" % fname

        if error:
            self.state_machine[fname]['FAIL']()
        else:
            self.state_machine[fname]['SUCCESS']()

    def _stateB(self):
        '''
            {'SUCCESS': self._stateD,'FAIL':self.error}
        '''
        error = False
        fname = inspect.stack()[0][3]

        print "I'm in '%s'" % fname

        if error:
            self.state_machine[fname]['FAIL']()
        else:
            self.state_machine[fname]['SUCCESS']()

    def _stateC(self):
        '''
            {'SUCCESS': self._stateA,'FAIL':self.error}
        '''
        error = True
        fname = inspect.stack()[0][3]

        print "I'm in '%s'" % fname

        if error:
            self.state_machine[fname]['FAIL']()
        else:
            self.state_machine[fname]['SUCCESS']()

    def _stateD(self):
        '''
            {'SUCCESS': self._stateE,'FAIL':self.error}
        '''
        error = False
        fname = inspect.stack()[0][3]

        print "I'm in '%s'" % fname

        if error:
            self.state_machine[fname]['FAIL']()
        else:
            self.state_machine[fname]['SUCCESS']()

    def _stateE(self):
        '''
            {'SUCCESS': self._stateC,'FAIL':self.error}
        '''
        error = False
        fname = inspect.stack()[0][3]

        print "I'm in '%s'" % fname

        if error:
            self.state_machine[fname]['FAIL']()
        else:
            self.state_machine[fname]['SUCCESS']()

    def error(self):
        print "OH NO, AN ERROR!!! "
        sys.exit(-1)

if __name__ == '__main__':

    my_self     = StateMachineFoo()
    start_state = None

    # this is a really bad way to do this, probably want python argparse module, but for
    # demo purposes, this should allow you to change your start state from the command line
    # the simple/dirty way

    if len(sys.argv) > 1:
        start_state = sys.argv[1]

    my_self.start(start_state)
Posted in Python, regex | 1 Comment

Python – Filter directory contents

short and sweet, this python snippet will return a list containing your filtered directory


import re
import os

filter = ".*" + searchstr + ".*"
m = re.compile(filter,re.I) #if you want to ignore case use re.I, otherwise remove it
filter(m.search,os.listdir(os.getcwd()))

#that's it, you can see that the reason for compiling the regex is so you can use m.search as a function pointer which accepts the list of all items in the directory

Posted in Python, regex | Tagged , | Leave a comment

Python – Use regex to split hyphenated words

I was asked this question on stackoverflow, and figured I’d repost it here since I wrote it after all.


s = "-this is. A - sentence;one-word what's"
re.findall("\w+-\w+|[\w']+",s)

result: ['this', 'is', 'A', 'sentence', 'one-word', "what's"]

make sure you notice that the correct ordering is to look for hypenated words first!

Posted in Python, regex | Tagged , | Leave a comment

Python – Chunk string or data buffer

I was disappointed that there was no good way to chunk up data for string formatting or packetzing UDP data. After a bit of thought, and a desire to avoid using python code to do loops, I came up with a nice simple regex-based solution.

import re
buff = #some data buffer
m = re.compile(r'.{##}|.+',re.S)
chunks = m.findall(buff)

example:
>>> import re
>>> m = re.compile(r'.{5}|.*',re.S)
>>> data = "HELLO_WORLD_HOW_ARE_YOU"
>>> m.findall(data)
['HELLO', '_WORL', 'D_HOW', '_ARE_', 'YOU']

I would assume that this is the most efficient way to do this, as it uses underlying c functions, and there’s nothing better than zippy python : )

Posted in Python, regex | Tagged , | Leave a comment

Python – Convert 16bit image to 24bit image 565 to 888

Doing the following is much better than using putpixel and a for loop, as numpy uses c-functions. The actual execution speed is about .3 seconds faster on a 240×320 RGBA image.


import numpy as np
arr = np.fromstring(buff,dtype=np.uint16).astype(np.uint32)
arr = 0xFF000000 + ((arr & 0xF800) >> 8 ) + ((arr & 0x07E0) << 5) + ((arr & 0x001F) << 19)
return Image.frombuffer('RGBA', (xdim,ydim), arr, 'raw', 'RGBA', 0, 1)

While it may seem like an odd bit shift, stuffing the channels into an int requires that it get stuffed as (most significant bit) ABGR (least significant bit). If you were to use the PIL call to putpixel, it would get stuffed as RGBA.

Posted in Image Processing, Python, comp-e | Tagged , , , | Leave a comment

Image Analysis Using Python

/* work inprogress ;p */

While I may be a fan of embedded systems, I have to admit that python has become my new love. Thought taking into account that you can do sweet Matlab style dsp with it, you can’t really blame me. Assuming you have raw data from an image, you can do some awesome stuff with it using python. You will of course need python 2.6 as well as the numPy module installed. The techniques I’m going to discuss are already out there if you look for Matlab references but I thought I’d bring to light that you can do the same things using python as well. You will need to go to http://www.pythonware.com/products/pil/ to get the image module. After installing, I will suggest that you compile your entire python directory. To do that, open the python console and type:

import compileall
compileall.compile_dir(‘C:\python26′,force = True,maxlevels=20)

Now,lets start off simple by doing some masking. However, you should first create a 100×100 maroonish jpg in mspaint

Open your python console and type the following

from numpy import *
import Image

#import the jpg
im = Image.open(“test.jpg”)

#split the image into numpy arrays so we can do all kinds of matrix voodoo on it
[r,g,b] = [array(im.split()[i] for i in range(3)]
image = array([r,g,b])

# create a mask and define the region we will want to keep when we mask our image
mask = zeros((13,13),dtype=int) # make a 100×100 integer array of zeros
mask[0:25,0:25] = 0xFF #define the positive mask region noting that RGB has a max value of FF,FF,FF

The upper corner of your image should now be maroon while the rest of your image is white.
test = array[0:3] & mask

Posted in comp-e | Leave a comment

Verilog Examples For The Spartan 3 / Nexys 2 Boards

Well, I thought I’d be extra generous since I haven’t posted in so long, and have uploaded 4 verilog examples for your viewing pleasure.

I have been a bit busy to comment them but I hope that they may be useful still as just coding examples.

Enjoy

Verilog – 14-bit BCD ( Binary Converted to Decimal)
Verilog – 4 to 1 and 2 to 1 multiplexor
Verilog – Seven Segment Display on Spartan 3 Board
Verilog – Simle PB Debounce Code For Spartan 3 Boards

- comp-e

Posted in Verilog, comp-e, forum | Tagged , , , , | Leave a comment

Pythons in the ‘C’ircus

Spiffy code that is.  Stubby has made a few contributions as of late, so check them out.  I will be ragging on him to put his battleship game up, but alas it seems it’s lacking comments so we’ll see how long that takes.

I on the other hand, appologize for not tossing up any new coding examples.  As of late I’ve been rather busy but fear not for I’ve been dabbling in Python and have some fun stuff to share.  To give a bit of a hint, I’ve been playing with the Numpy module and have found it incredibly useful as it ties in exceptionally well with Matlab.  I also plan on making a mini program to poll USB for those of you who rely on antiquated RS232 and are left without an easy means of switching over : )

Lastly, I encourage more of you to join and contribute well documented examples to the site.  As always, there are no ads and questions will be answered without the arrogant charm of other such code collaborative sites

Posted in C, comp-e, forum | Tagged , , , | Leave a comment

Creating Morse Code Using The HCS08 Microcontroller

Recently I was faced with the task of sending data out of a HCS08 microcontroller wirelessly.  I had only one pin available to me and decided to effectively create Morse Code so that my receiver could decode the signal without having some sort of reference clock to distinguish the 1′s and 0′s.   What took many hours to conceptualize and diagram out on the blackboard, turned out to be a very small bit of code.

On the sender side is a simple function written in C that takes a byte and loops through masking each bit.  This masking is done inside an if / else block and the result determines whether or not you are getting a dit or a dash.

Tied to the RF receiver is another MC9S08QG8 which takes in the signal via interrupts and assembles eight interrupts into eight bytes.  It then does a series of bitwise operations on each of the eight bytes in order to reconstruct the original byte.  You will find that a few parts of the code are subject to change (the time for 0′s and 1′s can be adjusted and must be adjusted if you plan on implementing PLL or have a different desired data rate).  That byte is then sent to a PC vie RS232 serial port and stored using a free program called RS232 Data Logger from Eltima Software.  The code will be posted shortly under the microcontroller section on the COMP-E forum for you to use and enjoy.

- COMP-E

~ ALERT: This post does not return to main !!!

Posted in C, Microcontrollers, forum | Tagged , , , , | Leave a comment

Javascript Examples

In addition to fixing the forum today, I also decided to post a couple ‘fun’ javascript applications that I’ve made.  I’m not the best with java script and these two apps are my first attempts.  However, they are functional and kind of cool.  One is magnetic poetry and the other is a javascript scientific calculator of sorts.   I’m not sure how much more I’ll post for javascript examples, but I encourage you to add your apps or examples to the forum : )

-  COMP-E

Posted in Javascript, forum | Tagged , , | Leave a comment