<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nessy&#039;s Blog</title>
	<atom:link href="http://newblog.flip-edesign.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://newblog.flip-edesign.com</link>
	<description></description>
	<lastBuildDate>Tue, 03 Apr 2012 18:49:55 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4-alpha-20343</generator>
		<item>
		<title>Python libvirt and XML domain configuration</title>
		<link>http://newblog.flip-edesign.com/?p=290</link>
		<comments>http://newblog.flip-edesign.com/?p=290#comments</comments>
		<pubDate>Tue, 03 Apr 2012 18:46:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=290</guid>
		<description><![CDATA[So in my last article I talked a little bit about using libvirt to start and stop QEMU domains, if you didn&#8217;t get a chance to read that you may want to check it out here. In this article I would like to go over how domains are created. QEMU uses XML files for each [...]]]></description>
			<content:encoded><![CDATA[<p>So in my last article I talked a little bit about using libvirt to start and stop QEMU domains,<br />
if you didn&#8217;t get a chance to read that you may want to check it out <a href="http://newblog.flip-edesign.com/?p=284">here</a>.</p>
<p>In this article I would like to go over how domains are created.</p>
<p>QEMU uses XML files for each domain configuration, and using<br />
libvirt we can access that data.</p>
<p>First off lets connect to our local running QEMU instance:</p>
<pre class="brush:py">&gt;&gt;&gt; import libvirt
&gt;&gt;&gt; conn = libvirt.open('qemu:///system')</pre>
<p>Next lets look for and link to a running domain:</p>
<pre class="brush:py">&gt;&gt;&gt; conn.listDomainsID()
[35, 36, 37, 41, 38, 39]

&gt;&gt;&gt; domain = conn.lookupByID(35)</pre>
<p>The libvirt domain object gives os a function called <strong>XMLDesc()</strong> which we can<br />
use to see our running configuration:</p>
<pre class="brush:py">&gt;&gt;&gt; raw_xml = domain.XMLDesc(0)
&gt;&gt;&gt; print raw_xml
&lt;domain type='kvm' id='35'&gt;
  &lt;name&gt;build01-dev&lt;/name&gt;
  &lt;uuid&gt;c5c698cc-95bb-188d-3b5a-625asdj128sd&lt;/uuid&gt;
  &lt;memory&gt;1048576&lt;/memory&gt;
  &lt;currentMemory&gt;1048576&lt;/currentMemory&gt;
  &lt;vcpu&gt;2&lt;/vcpu&gt;
  &lt;os&gt;
    &lt;type arch='x86_64' machine='fedora-13'&gt;hvm&lt;/type&gt;
    &lt;boot dev='hd'/&gt;
  &lt;/os&gt;
  &lt;features&gt;
    &lt;acpi/&gt;
    &lt;apic/&gt;
    &lt;pae/&gt;
  &lt;/features&gt;
  &lt;clock offset='utc'/&gt;
  &lt;on_poweroff&gt;destroy&lt;/on_poweroff&gt;
  &lt;on_reboot&gt;restart&lt;/on_reboot&gt;
  &lt;on_crash&gt;restart&lt;/on_crash&gt;
  &lt;devices&gt;
    &lt;emulator&gt;/usr/bin/qemu-kvm&lt;/emulator&gt;
    &lt;disk type='file' device='disk'&gt;
      &lt;driver name='qemu' type='qcow2'/&gt;
      &lt;source file='/mnt/data/libvirt/datastore01/data01-dev-clone-2.img'/&gt;
      &lt;target dev='vda' bus='virtio'/&gt;
      &lt;alias name='virtio-disk0'/&gt;
      &lt;address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/&gt;
    &lt;/disk&gt;
    &lt;disk type='file' device='cdrom'&gt;
      &lt;driver name='qemu' type='raw'/&gt;
      &lt;target dev='hdc' bus='ide'/&gt;
      &lt;readonly/&gt;
      &lt;alias name='ide0-1-0'/&gt;
      &lt;address type='drive' controller='0' bus='1' unit='0'/&gt;
    &lt;/disk&gt;
    &lt;controller type='ide' index='0'&gt;
      &lt;alias name='ide0'/&gt;
      &lt;address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/&gt;
    &lt;/controller&gt;
    &lt;interface type='bridge'&gt;
      &lt;mac address='50:00:00:00:00:00'/&gt;
      &lt;source bridge='br1'/&gt;
      &lt;target dev='vnet0'/&gt;
      &lt;model type='e1000'/&gt;
      &lt;alias name='net0'/&gt;
      &lt;address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/&gt;
    &lt;/interface&gt;
    &lt;serial type='pty'&gt;
      &lt;source path='/dev/pts/0'/&gt;
      &lt;target port='0'/&gt;
      &lt;alias name='serial0'/&gt;
    &lt;/serial&gt;
    &lt;console type='pty' tty='/dev/pts/0'&gt;
      &lt;source path='/dev/pts/0'/&gt;
      &lt;target type='serial' port='0'/&gt;
      &lt;alias name='serial0'/&gt;
    &lt;/console&gt;
    &lt;input type='tablet' bus='usb'&gt;
      &lt;alias name='input0'/&gt;
    &lt;/input&gt;
    &lt;input type='mouse' bus='ps2'/&gt;
    &lt;graphics type='vnc' port='5900' autoport='yes'/&gt;
    &lt;video&gt;
      &lt;model type='cirrus' vram='9216' heads='1'/&gt;
      &lt;alias name='video0'/&gt;
      &lt;address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/&gt;
    &lt;/video&gt;
    &lt;memballoon model='virtio'&gt;
      &lt;alias name='balloon0'/&gt;
      &lt;address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/&gt;
    &lt;/memballoon&gt;
  &lt;/devices&gt;
&lt;/domain&gt;</pre>
<p>Now say you are interested in working with this XML data,<br />
we can do just that using the <strong>xml</strong> module.</p>
<pre class="brush:py">&gt;&gt;&gt; from xml.dom import minidom
&gt;&gt;&gt; xml = minidom.parseString(raw_xml)</pre>
<p>And something that may be useful in the XML above is the <strong>type</strong> <strong>tag</strong>, so lets grab that data:</p>
<pre class="brush:py">&gt;&gt;&gt; domainTypes = xml.getElementsByTagName('type')
&gt;&gt;&gt; for domainType in domainTypes:
...   print domainType.getAttribute('machine')
...   print domainType.getAttribute('arch')
...
fedora-13
x86_64</pre>
<p>And there you have it, we can easily pull out data from this XML using the <strong>minidom</strong> function.</p>
<p>Using this data it should be pretty easy to deploy a new guest domain using the <strong>createXML</strong> function:</p>
<pre class="brush:plain">Help on method createXML in module libvirt:

createXML(self, xmlDesc, flags) method of libvirt.virConnect instance
    Launch a new guest domain, based on an XML description similar
    to the one returned by virDomainGetXMLDesc()
    This function may require privileged access to the hypervisor.
    The domain is not persistent, so its definition will disappear when it
    is destroyed, or if the host is restarted (see virDomainDefineXML() to
    define persistent domains).

    If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain
    will be started, but its CPUs will remain paused. The CPUs
    can later be manually started using virDomainResume.

    If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
    domain will be automatically destroyed when the virConnectPtr
    object is finally released. This will also happen if the
    client application crashes / loses its connection to the
    libvirtd daemon. Any domains marked for auto destroy will
    block attempts at migration, save-to-file, or snapshots.</pre>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=290</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with libvirt using Python</title>
		<link>http://newblog.flip-edesign.com/?p=284</link>
		<comments>http://newblog.flip-edesign.com/?p=284#comments</comments>
		<pubDate>Thu, 15 Mar 2012 21:59:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=284</guid>
		<description><![CDATA[Today I decide to toy around with a KVM server we have running in house for testing. I started by using the libvirt Documentation, but it was very limited and I had to do some trial and error. I will go over a few basic things I learned using the libvirt Python module: Normally we us virt-manger [...]]]></description>
			<content:encoded><![CDATA[<p>Today I decide to toy around with a KVM server we have running in house for testing.<br />
I started by using the <a href="http://libvirt.org/python.html">libvirt Documentation</a>, but it was very limited and I had to do some<br />
trial and error. I will go over a few basic things I learned using the libvirt Python module:</p>
<p>Normally we us <a href="http://virt-manager.org/">virt-manger</a> to connect to our KVM instances,<br />
and the authentication is tunnled over SSH (using SSH Keys) and QEMU.<br />
First things first I had to learn how to connect with the same method we used in virt-manager</p>
<pre class="brush:py">&gt;&gt;&gt; import libvirt
&gt;&gt;&gt; conn = libvirt.open("qemu+ssh://root@192.168.1.2/system")
&gt;&gt;&gt; conn
&lt;libvirt.virConnect instance at 0x2b518c0&gt;</pre>
<p>Using the open function I was able to successfully connect to our Hypervisor:</p>
<pre class="brush:py">&gt;&gt;&gt; conn.getHostname()
'kvm01.company.com'</pre>
<p>From here I need only see our running virtual machines, and how to interact with them.<br />
I noticed two separate function  the <strong>listDefinedDomains()</strong> and <strong>listDomainsID().<br />
</strong></p>
<p>These two functions do two separate things, first lets go over <strong>listDefinedDomains(),<br />
</strong>this function will return a list of <strong>offline</strong> guest by name:</p>
<pre class="brush:py">&gt;&gt;&gt; conn.listDefinedDomains()
['rawhide', 'el4-i386', 'el5-64', 'el6-64', ....]</pre>
<p>Where as <strong>listDomainsID() </strong>will return a list of <strong>online</strong> devices by ID:</p>
<pre class="brush:py">&gt;&gt;&gt; conn.listDomainsID()
[1, 2, 10, 3, 17, 7, 9, 8, 5, 6]</pre>
<p>Once connected to the Domain you can get its name:</p>
<pre class="brush:py">&gt;&gt;&gt; for i in conn.listDomainsID():
...     print conn.lookupByID(i).name()
...     
... 
build01-dev
data01-dev
build02-dev
CentOS6-x86_64-dev
..</pre>
<p>And as you would expect you can connect to either offline or online domains<br />
by using their name:</p>
<pre class="brush:py">&gt;&gt;&gt; dom = conn.lookupByName('build01-dev')
&gt;&gt;&gt; dom
&lt;libvirt.virDomain instance at 0x2b82c68&gt;
&gt;&gt;&gt; dom.name()
'build01-dev'</pre>
<p>Now that we understand the process of connecting to our Hypervisor and<br />
parsing our Domains, lets go over how to start and stop these Domains,<br />
or as libvirt calls it create and destroy.</p>
<p>Lets start out with a offline (or destroyed) domain:</p>
<pre class="brush:py">&gt;&gt;&gt; dom = conn.lookupByName('rawhide')
&gt;&gt;&gt; dom.isActive()
0</pre>
<p>To bring this Domain online we need to use the <strong>create</strong> function:</p>
<pre class="brush:py">&gt;&gt;&gt; dom.create()
0
&gt;&gt;&gt; dom.isActive()
1</pre>
<p>And to power it down you would <strong>destroy</strong> it:</p>
<pre class="brush:py">&gt;&gt;&gt; dom.destroy()
0
&gt;&gt;&gt; dom.isActive()
0</pre>
<p>I hope this helped out a few of you out there, I know this was rather<br />
confusion when I first started messing around with it.</p>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=284</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MagTek USB Card Reader Hacking with Python 2</title>
		<link>http://newblog.flip-edesign.com/?p=265</link>
		<comments>http://newblog.flip-edesign.com/?p=265#comments</comments>
		<pubDate>Thu, 22 Dec 2011 20:04:42 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=265</guid>
		<description><![CDATA[So back at it, now with some code to decode the common financial card: Let start out by showing the end results of scanning my Freebirds card: # ./main.py Please swipe your card now: Raw String: %B6000107737331611^FANATIC/FREEBIRDS^4211?;6000107737331611=4211101563867? Card Holder: FANATIC/FREEBIRDS Card Number: 6000-1077-3733-1611 Expiration Date: 11/42 As you can see we still have our raw [...]]]></description>
			<content:encoded><![CDATA[<p>So back at it, now with some code to decode the common <a href="http://en.wikipedia.org/wiki/Magnetic_stripe_card#Financial_cards">financial</a> card:</p>
<p><img class="alignnone size-medium wp-image-266" title="Photo on 2011-12-22 at 13.46" src="http://newblog.flip-edesign.com/wp-content/uploads/2011/12/Photo-on-2011-12-22-at-13.46-300x231.jpg" alt="" width="300" height="231" /></p>
<p>Let start out by showing the end results of scanning my <a href="http://freebirds.com/">Freebirds</a> card:</p>
<pre class="brush:plain"># ./main.py 
Please swipe your card now:

Raw String: %B6000107737331611^FANATIC/FREEBIRDS^4211?;6000107737331611=4211101563867?

Card Holder: FANATIC/FREEBIRDS
Card Number: 6000-1077-3733-1611
Expiration Date: 11/42</pre>
<p>As you can see we still have our raw string, this is being decoded from the code I used <a href="http://newblog.flip-edesign.com/?p=253">last time</a>.<br />
However now I have the Card Holder&#8217;s name, Card Number, and Expiration date, this format<br />
was all outlined quite well on <a href="http://en.wikipedia.org/wiki/Magnetic_stripe_card#Financial_cards">Wikipedia</a>.</p>
<ul>
<li><strong>Start sentinel</strong> — one character (generally &#8216;%&#8217;)</li>
<li><strong>Format code=&#8221;B&#8221;</strong> — one character (alpha only)</li>
<li><strong>Primary account number</strong> (PAN) — up to 19 characters. Usually, but not always, matches the <a title="Credit card number" href="http://en.wikipedia.org/wiki/Credit_card_number">credit card number</a> printed on the front of the card.</li>
<li><strong>Field Separator</strong> — one character (generally &#8216;^&#8217;)</li>
<li><strong>Name</strong> — two to 26 characters</li>
<li><strong>Field Separator</strong> — one character (generally &#8216;^&#8217;)</li>
<li><strong>Expiration date</strong> — four characters in the form YYMM.</li>
<li><strong>Service code</strong> — three characters</li>
<li><strong>Discretionary data</strong> — may include Pin Verification Key Indicator (PVKI, 1 character), PIN Verification Value (PVV, 4 characters), <a title="Card Verification Value" href="http://en.wikipedia.org/wiki/Card_Verification_Value#CVC_.2F_CVV">Card Verification Value or Card Verification Code</a> (CVV or CVC, 3 characters)</li>
<li><strong>End sentinel</strong> — one character (generally &#8216;?&#8217;)</li>
</ul>
<p>Once I had this format it was just a matter of using some Python magic to make it happen:</p>
<pre class="brush:py"># attempt to identify data types
start_sentinel = sdata[0]
format_code = sdata[1]

## FORMAT TYPE B
if start_sentinel + format_code == '%B':
    track1 = sdata[2:].split(';')[0]
    data = track1.split('^')

    # financial card
    try:
        card_no = data[0]
        name = data[1].strip()
        expyear = data[2][0:2]
        expmon = data[2][2:4]
        print 'Card Holder: %s' % name
        print 'Card Number: %s' % prettycard(card_no)
        print 'Expiration Date: %s/%s' % (expmon, expyear)
    except:
        pass</pre>
<p>I also found a small bug in how I was handeling the card reader, you see the card reader has built in memory<br />
which will hold all swipes not yet processed. If for some reason a card was swiped when not expected (lets say when not running the script),<br />
it would be stored in memory and wait for next read (this would pile up with the new swipe).</p>
<p>To resolve this I run through the device loop just to clear the buffer:</p>
<pre class="brush:py">def cleardevice():
    '''Clear the devices memory'''
    while True:
        try:
            results = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
        except usb.core.USBError as e:
            if e.args[1] == 'Operation timed out' :
                break # timeout and swiped means we are done</pre>
<p>I also noticed the device I have places a <strong>E</strong> in the format type if it had issues reading the card.</p>
<p>If a error is returned in track 1 I request a re-swipe:</p>
<pre class="brush:py"># A format type of E is a error
while sdata[1] == 'E':
    print 'Failed to read card..'
    sdata = swipeme()</pre>
<p>And the full code I wrote looks something like this (very sloppy I know):</p>
<pre class="brush:py">#!/usr/bin/env python

# MagTek MSR100 Mini Swipe Card Reader
# Written By: Jeffrey Ness
# 
# Some Thanks need to go out to
# http://www.micahcarrick.com/credit-card-reader-pyusb.html
# for helping me get on the right track

import usb.core
import usb.util
from re import findall

# MagTek Device MSR100 Mini Swipe
vendorid = 0x0801
productid = 0x0001

# Small function to return card numbers in blocks of 4
def prettycard(card_no):
    card = '-'.join(findall("[0-9][0-9][0-9][0-9]", card_no))
    return card

# Define our Character Map per Reference Manual
# http://www.magtek.com/documentation/public/99875206-17.01.pdf

chrMap = {
    4:  'a',
    5:  'b',
    6:  'c',
    7:  'd',
    8:  'e',
    9:  'f',
    10: 'g',
    11: 'h',
    12: 'i',
    13: 'j',
    14: 'k',
    15: 'l',
    16: 'm',
    17: 'n',
    18: 'o',
    19: 'p',
    20: 'q',
    21: 'r',
    22: 's',
    23: 't',
    24: 'u',
    25: 'v',
    26: 'w',
    27: 'x',
    28: 'y',
    29: 'z',
    30: '1',
    31: '2',
    32: '3',
    33: '4',
    34: '5',
    35: '6',
    36: '7',
    37: '8',
    38: '9',
    39: '0',
    40: 'KEY_ENTER',
    41: 'KEY_ESCAPE',
    42: 'KEY_BACKSPACE',
    43: 'KEY_TAB',
    44: ' ',
    45: '-',
    46: '=',
    47: '[',
    48: ']',
    49: '\\',
    51: ';',
    52: '\'',
    53: '`',
    54: ',',
    55: '.',
    56: '/',
    57: 'KEY_CAPSLOCK'
}

shiftchrMap = {
    4:  'A',
    5:  'B',
    6:  'C',
    7:  'D',
    8:  'E',
    9:  'F',
    10: 'G',
    11: 'H',
    12: 'I',
    13: 'J',
    14: 'K',
    15: 'L',
    16: 'M',
    17: 'N',
    18: 'O',
    19: 'P',
    20: 'Q',
    21: 'R',
    22: 'S',
    23: 'T',
    24: 'U',
    25: 'V',
    26: 'W',
    27: 'X',
    28: 'Y',
    29: 'Z',
    30: '!',
    31: '@',
    32: '#',
    33: '$',
    34: '%',
    35: '^',
    36: '&amp;',
    37: '*',
    38: '(',
    39: ')',
    40: 'KEY_ENTER',
    41: 'KEY_ESCAPE',
    42: 'KEY_BACKSPACE',
    43: 'KEY_TAB',
    44: ' ',
    45: '_',
    46: '+',
    47: '{',
    48: '}',
    49: '|',
    51: ':',
    52: '"',
    53: '~',
    54: '&lt;',
    55: '&gt;',
    56: '?',
    57: 'KEY_CAPSLOCK'
}

# find our device by id
device = usb.core.find(idVendor=vendorid, idProduct=productid)
if device is None:
    raise Exception('Could not find USB Card Reader')

# remove device from kernel, this should stop
# reader from printing to screen and remove /dev/input
if device.is_kernel_driver_active(0):
    try:
        device.detach_kernel_driver(0)
    except usb.core.USBError as e:
        raise Exception("Could not detatch kernel driver: %s" % str(e))

# load our devices configuration
try:
    device.set_configuration()
    device.reset()
except usb.core.USBError as e:
    raise Exception("Could not set configuration: %s" % str(e))

# get device endpoint information
endpoint = device[0][(0,0)][0]

def cleardevice():
    '''Clear the devices memory'''
    while True:
        try:
            results = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
        except usb.core.USBError as e:
            if e.args[1] == 'Operation timed out' :
                break # timeout and swiped means we are done

def swipeme():
    '''Swipe function'''
    swiped = False
    datalist = []
    cleardevice()

    print 'Please swipe your card now:'
    while True:
        try:
            results = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
            datalist.append(results)
            swiped = True

        except usb.core.USBError as e:
            if e.args[1] == 'Operation timed out' and swiped:
                break # timeout and swiped means we are done

    # create a list of 8 bit bytes and remove
    # empty bytes
    ndata = []
    for d in datalist:
        if d.tolist() != [0, 0, 0, 0, 0, 0, 0, 0]:
            ndata.append(d.tolist())

    # parse over our bytes and create string to final return
    sdata = ''
    for n in ndata:
        # handle non shifted letters
        if n[2] in chrMap and n[0] == 0:
            sdata += chrMap[n[2]]
        # handle shifted letters
        elif n[2] in shiftchrMap and n[0] == 2:
            sdata += shiftchrMap[n[2]]

    return sdata

# run first swipe
sdata = swipeme()

# A format type of E is a error
while sdata[1] == 'E':
    print 'Failed to read card..'
    sdata = swipeme()

# print raw string always
print '\nRaw String: %s\n' % sdata

# attempt to identify data types
start_sentinel = sdata[0]
format_code = sdata[1]

## FORMAT TYPE B
if start_sentinel + format_code == '%B':
    track1 = sdata[2:].split(';')[0]
    data = track1.split('^')

    # financial card
    try:
        card_no = data[0]
        name = data[1].strip()
        expyear = data[2][0:2]
        expmon = data[2][2:4]
        print 'Card Holder: %s' % name
        print 'Card Number: %s' % prettycard(card_no)
        print 'Expiration Date: %s/%s' % (expmon, expyear)
    except:
        pass</pre>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=265</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MagTek USB Card Reader Hacking with Python</title>
		<link>http://newblog.flip-edesign.com/?p=253</link>
		<comments>http://newblog.flip-edesign.com/?p=253#comments</comments>
		<pubDate>Wed, 21 Dec 2011 19:54:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=253</guid>
		<description><![CDATA[So just the other day I received my MagTek MSR100 in the mail, this unit only cost me about $20 and I have to say I&#8217;m very satisfied with it. After opening the box it was delivered in I quickly noticed no documentation was provided. No worries I figured, this will make hacking at it that much more [...]]]></description>
			<content:encoded><![CDATA[<p>So just the other day I received my <a href="http://www.amazon.com/dp/B004IATGGM/ref=as_li_ss_til?tag=flipedesig-20&amp;camp=213381&amp;creative=390973&amp;linkCode=as4&amp;creativeASIN=B004IATGGM&amp;adid=0QEYZYFTKYV7BTN58SZD&amp;&amp;ref-refURL=http%3A%2F%2Frcm.amazon.com%2Fe%2Fcm%3Flt1%3D_blank%26bc1%3D000000%26IS2%3D1%26bg1%3DFFFFFF%26fc1%3D000000%26lc1%3D0000FF%26t%3Dflipedesig-20%26o%3D1%26p%3D8%26l%3Das4%26m%3Damazon%26f%3Difr%26ref%3Dss_til%26asins%3DB004IATGGM">MagTek MSR100</a> in the mail, this unit only cost me about $20<br />
and I have to say I&#8217;m very satisfied with it.</p>
<p><img class="alignnone size-medium wp-image-254" title="cardreader" src="http://newblog.flip-edesign.com/wp-content/uploads/2011/12/cardreader-300x225.jpg" alt="" width="300" height="225" /></p>
<p>After opening the box it was delivered in I quickly noticed no documentation was provided.<br />
No worries I figured, this will make hacking at it that much more fun.</p>
<p>I started out by connecting the USB device to my Gentoo Linux laptop and swiped a card,<br />
I noticed on my console prompt the card data was spewed out. That is because this device<br />
acts like a <a href="http://en.wikipedia.org/wiki/Human_interface_device">HID</a> Keyboard:</p>
<pre class="brush:plain"># lsusb -vv | grep "Mag-Tek Mini Swipe" -A50 | grep bInterfaceProtocol
      bInterfaceProtocol      1 Keyboard</pre>
<p>With this information confirmed I figured I would approach it with the same method<br />
used in one my older post <strong><a href="http://newblog.flip-edesign.com/?p=200">Python Device Hacking (Keyboard)</a></strong>.</p>
<p>Using the k() function outlined in the Keyboard hacking post mentioned above,<br />
I received the following while scanning my <a href="http://pluckers.com/">Pluckers</a> card:</p>
<pre class="brush:plain">&gt;&gt;&gt; k()
KEY_LEFTSHIFT
KEY_5
KEY_LEFTSHIFT
KEY_B
KEY_7
KEY_2
KEY_3
KEY_1
KEY_5
KEY_3
KEY_7
KEY_7
KEY_1
KEY_0
KEY_5
KEY_6
KEY_6
KEY_2
KEY_3
KEY_2
KEY_5
KEY_0
KEY_4
KEY_7
KEY_6
KEY_7
KEY_9
KEY_1
KEY_3
KEY_9
KEY_7
KEY_0
KEY_3
KEY_8
KEY_LEFTSHIFT
KEY_SLASH
KEY_SEMICOLON
KEY_2
KEY_2
KEY_1
KEY_6
KEY_5
KEY_0
KEY_0
KEY_1
KEY_1
KEY_1
KEY_6
KEY_2
KEY_3
KEY_6
KEY_7
KEY_6
KEY_EQUAL
KEY_1
KEY_LEFTSHIFT
KEY_SLASH</pre>
<p>This data looked similar to the results I seen on screen, but not quite..<br />
and printing on the screen at the same time was pretty ugly:</p>
<pre class="brush:plain">%B723153771056623250476791397038?;2216500111623676=1?</pre>
<p>At that point I figured it was time for a better approach, and where best to look than our friend Google?<br />
A quick search brought up a article <a href="http://www.micahcarrick.com/credit-card-reader-pyusb.html">describing a similar project</a>, unfortunately our devices must differ<br />
as his code didn&#8217;t quite work with my device. However this article showed me the <a href="http://pyusb.sourceforge.net/docs/1.0/tutorial.html">PyUSB module</a>.</p>
<p>Using the PyUSB module I whipped up a quick script:</p>
<pre class="brush:py">&gt;&gt;&gt; import usb.core
&gt;&gt;&gt; import usb.util
&gt;&gt;&gt; 
&gt;&gt;&gt; vendorid = 0x0801
&gt;&gt;&gt; productid = 0x0001
&gt;&gt;&gt; device.detach_kernel_driver(0)
&gt;&gt;&gt; endpoint = device[0][(0,0)][0]
&gt;&gt;&gt;
&gt;&gt;&gt; device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=5000)
array('B', [2, 0, 34, 0, 0, 0, 0, 0])
&gt;&gt;&gt; device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=5000)
array('B', [0, 0, 0, 0, 0, 0, 0, 0])
&gt;&gt;&gt; device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=5000)
array('B', [2, 0, 5, 0, 0, 0, 0, 0])
&gt;&gt;&gt; device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=5000)
array('B', [0, 0, 0, 0, 0, 0, 0, 0])
&gt;&gt;&gt; device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=5000)
array('B', [0, 0, 36, 0, 0, 0, 0, 0])</pre>
<p>At this point I got stuck for a bit, you see the data above was not in ASCII format and did not match<br />
my earlier keyboard map. I did figure out the results by comparing onscreen output to my PyUSB output:</p>
<p>I took the known good data (from on screen):</p>
<pre class="brush:plain">%B723153771056623250476791397038?;2216500111623676=1?</pre>
<p>Comparing against PyUSB I noticed the 3rd column appeared to be<br />
the bits of data I needed:</p>
<pre class="brush:plain">[2, 0, 34, 0, 0, 0, 0, 0] = %
[2, 0, 5, 0, 0, 0, 0, 0]  = B
[0, 0, 36, 0, 0, 0, 0, 0] = 7
[0, 0, 31, 0, 0, 0, 0, 0] = 2
[0, 0, 32, 0, 0, 0, 0, 0] = 3
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[0, 0, 34, 0, 0, 0, 0, 0] = 5
[0, 0, 32, 0, 0, 0, 0, 0] = 3
[0, 0, 36, 0, 0, 0, 0, 0] = 7
[0, 0, 36, 0, 0, 0, 0, 0] = 7
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[0, 0, 39, 0, 0, 0, 0, 0] = 0
[0, 0, 34, 0, 0, 0, 0, 0] = 
[0, 0, 35, 0, 0, 0, 0, 0]
[0, 0, 35, 0, 0, 0, 0, 0]
[0, 0, 31, 0, 0, 0, 0, 0]
[0, 0, 32, 0, 0, 0, 0, 0]
[0, 0, 31, 0, 0, 0, 0, 0]
[0, 0, 34, 0, 0, 0, 0, 0]
[0, 0, 39, 0, 0, 0, 0, 0]
[0, 0, 33, 0, 0, 0, 0, 0]
[0, 0, 36, 0, 0, 0, 0, 0]
[0, 0, 35, 0, 0, 0, 0, 0]
[0, 0, 36, 0, 0, 0, 0, 0]
[0, 0, 38, 0, 0, 0, 0, 0]
[0, 0, 30, 0, 0, 0, 0, 0]
[0, 0, 32, 0, 0, 0, 0, 0]
[0, 0, 38, 0, 0, 0, 0, 0]
[0, 0, 36, 0, 0, 0, 0, 0]
[0, 0, 39, 0, 0, 0, 0, 0]
[0, 0, 32, 0, 0, 0, 0, 0]
[0, 0, 37, 0, 0, 0, 0, 0]
[2, 0, 56, 0, 0, 0, 0, 0] = ?
[0, 0, 51, 0, 0, 0, 0, 0] = ;
[0, 0, 31, 0, 0, 0, 0, 0] = 2
[0, 0, 31, 0, 0, 0, 0, 0] = 2
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[0, 0, 35, 0, 0, 0, 0, 0] = 6
[0, 0, 34, 0, 0, 0, 0, 0] = 5
[0, 0, 39, 0, 0, 0, 0, 0] = 0
[0, 0, 39, 0, 0, 0, 0, 0] = 0
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[0, 0, 35, 0, 0, 0, 0, 0] = 6
[0, 0, 31, 0, 0, 0, 0, 0] = 2
[0, 0, 32, 0, 0, 0, 0, 0] = 3
[0, 0, 35, 0, 0, 0, 0, 0] = 6
[0, 0, 36, 0, 0, 0, 0, 0] = 7
[0, 0, 35, 0, 0, 0, 0, 0] = 6
[0, 0, 46, 0, 0, 0, 0, 0] = =
[0, 0, 30, 0, 0, 0, 0, 0] = 1
[2, 0, 56, 0, 0, 0, 0, 0] = ?
[0, 0, 88, 0, 0, 0, 0, 0]</pre>
<p>After trying everything I could think I finally gave up and searched for a <a href="http://www.magtek.com/documentation/public/99875206-17.01.pdf">Developers Manual</a> for the device.<br />
The PDF above gave me a keycode map which made complete sense on the above output (see snippet below):</p>
<p><a href="http://newblog.flip-edesign.com/wp-content/uploads/2011/12/keycode.jpg"><img class="alignnone size-full wp-image-260" title="keycode" src="http://newblog.flip-edesign.com/wp-content/uploads/2011/12/keycode.jpg" alt="" width="688" height="525" /></a></p>
<p>This last piece of information was all I needed to decipher data from my device,<br />
and this was the code I ended up with:</p>
<pre class="brush:py">#!/usr/bin/env python

# MagTek MSR100 Mini Swipe Card Reader
# Written By: Jeffrey Ness
# 
# Some Thanks need to go out to
# http://www.micahcarrick.com/credit-card-reader-pyusb.html
# for helping me get on the right track

import usb.core
import usb.util

# MagTek Device MSR100 Mini Swipe
vendorid = 0x0801
productid = 0x0001

# Define our Character Map per Reference Manual
# http://www.magtek.com/documentation/public/99875206-17.01.pdf

chrMap = {
    4:  'a',
    5:  'b',
    6:  'c',
    7:  'd',
    8:  'e',
    9:  'f',
    10: 'g',
    11: 'h',
    12: 'i',
    13: 'j',
    14: 'k',
    15: 'l',
    16: 'm',
    17: 'n',
    18: 'o',
    19: 'p',
    20: 'q',
    21: 'r',
    22: 's',
    23: 't',
    24: 'u',
    25: 'v',
    26: 'w',
    27: 'x',
    28: 'y',
    29: 'z',
    30: '1',
    31: '2',
    32: '3',
    33: '4',
    34: '5',
    35: '6',
    36: '7',
    37: '8',
    38: '9',
    39: '0',
    40: 'KEY_ENTER',
    41: 'KEY_ESCAPE',
    42: 'KEY_BACKSPACE',
    43: 'KEY_TAB',
    44: ' ',
    45: '-',
    46: '=',
    47: '[',
    48: ']',
    49: '\\',
    51: ';',
    52: '\'',
    53: '`',
    54: ',',
    55: '.',
    56: '/',
    57: 'KEY_CAPSLOCK'
}

shiftchrMap = {
    4:  'A',
    5:  'B',
    6:  'C',
    7:  'D',
    8:  'E',
    9:  'F',
    10: 'G',
    11: 'H',
    12: 'I',
    13: 'J',
    14: 'K',
    15: 'L',
    16: 'M',
    17: 'N',
    18: 'O',
    19: 'P',
    20: 'Q',
    21: 'R',
    22: 'S',
    23: 'T',
    24: 'U',
    25: 'V',
    26: 'W',
    27: 'X',
    28: 'Y',
    29: 'Z',
    30: '!',
    31: '@',
    32: '#',
    33: '$',
    34: '%',
    35: '^',
    36: '&amp;',
    37: '*',
    38: '(',
    39: ')',
    40: 'KEY_ENTER',
    41: 'KEY_ESCAPE',
    42: 'KEY_BACKSPACE',
    43: 'KEY_TAB',
    44: ' ',
    45: '_',
    46: '+',
    47: '{',
    48: '}',
    49: '|',
    51: ':',
    52: '"',
    53: '~',
    54: '&lt;',
    55: '&gt;',
    56: '?',
    57: 'KEY_CAPSLOCK'
}

# find our device by id
device = usb.core.find(idVendor=vendorid, idProduct=productid)
if device is None:
    raise Exception('Could not find USB Card Reader')

# remove device from kernel, this should stop
# reader from printing to screen and remove /dev/input
if device.is_kernel_driver_active(0):
    try:
        device.detach_kernel_driver(0)
    except usb.core.USBError as e:
        raise Exception("Could not detatch kernel driver: %s" % str(e))

# load our devices configuration
try:
    device.set_configuration()
    device.reset()
except usb.core.USBError as e:
    raise Exception("Could not set configuration: %s" % str(e))

# get device endpoint information
endpoint = device[0][(0,0)][0]

swiped = False
data = []
datalist = []
print 'Swipe Card:'
while True:
    try:
        results = device.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, timeout=5)
        data += results
        datalist.append(results)
        swiped = True

    except usb.core.USBError as e:
        if e.args[1] == 'Operation timed out' and swiped:
            break # timeout and swiped means we are done

# create a list of 8 bit bytes and remove
# empty bytes
ndata = []
for d in datalist:
    if d.tolist() != [0, 0, 0, 0, 0, 0, 0, 0]:
        ndata.append(d.tolist())

# parse over our bytes and create string to final return
sdata = ''
for n in ndata:
    # handle non shifted letters
    if n[2] in chrMap and n[0] == 0:
        sdata += chrMap[n[2]]
    # handle shifted letters
    elif n[2] in shiftchrMap and n[0] == 2:
        sdata += shiftchrMap[n[2]]

print sdata</pre>
<p>I&#8217;ve went ahead and uploaded this source to Github in case anyone likes to clone it<br />
<a href="https://github.com/jness/magtek_cardreader/blob/master/main.py">https://github.com/jness/magtek_cardreader/blob/master/main.py </a></p>
<p>Using this code is very basic and is show below:</p>
<pre class="brush:plain"># ./main.py 
Swipe Card:
%B723153771056623250476791397038?;2216500111623676=1?</pre>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=253</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pathfinder Bestiary Python Style!</title>
		<link>http://newblog.flip-edesign.com/?p=244</link>
		<comments>http://newblog.flip-edesign.com/?p=244#comments</comments>
		<pubDate>Tue, 20 Dec 2011 21:51:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=244</guid>
		<description><![CDATA[So recently I&#8217;ve been getting the family together to play some Pathfinder. My kids love it since using their imaginations come natural, and lets face it boys like hitting things with Great Axes! Having no prior experience to Pathfinder or Tabletop RPGs for that matter i&#8217;ve found online content to be very beneficial, one site in particular being [...]]]></description>
			<content:encoded><![CDATA[<p>So recently I&#8217;ve been getting the family together to play some Pathfinder. My kids love it<br />
since using their imaginations come natural, and lets face it boys like hitting things with Great Axes!</p>
<p>Having no prior experience to Pathfinder or Tabletop RPGs for that matter<br />
i&#8217;ve found online content to be very beneficial, one site in particular being <a href="http://www.d20pfsrd.com">d20pfsrd.com</a>.</p>
<p>Just the other day I was on d20pfsrd and noticed a <a href="http://www.d20pfsrd.com/extras/downloads">Download</a> section, and low and behold<br />
they had a Monster manual in the form of <a href="http://www.d20pfsrd.com/extras/downloads/Monsters_Full.zip?attredirects=0&amp;d=1">Excel spreadsheet</a>. Using the spreadsheet I exported<br />
it as cvs and fired up Python to make a happy little dictionary. I&#8217;ll go ahead and show it below,<br />
as well as provide a downloadable file containing the dictionary.</p>
<pre class="brush:py">&gt;&gt;&gt; import pickle
&gt;&gt;&gt; f = open('monsters.pk1', 'rb')
&gt;&gt;&gt; monsters = pickle.load(f)
&gt;&gt;&gt; f.close()</pre>
<p>Once I have the Python dictionary loaded I can easily use basic python to interact:</p>
<pre class="brush:py">&gt;&gt;&gt; monsters.keys()
['Shoggoth', 'Elder Air Elemental', 'Small Fire Elemental', 'Medium Earth Elemental',
'Hydra', 'Elephant', 'Young Copper Dragon', 'Wererat (Hybrid Form)', 'Pseudodragon',
'Vegepygmy', 'Mite', 'Adult White Dragon', 'Otyugh', 'Giant Squid', 'Storm Giant', 'Wolf',
'Axe Beak', 'Dark Stalker', 'Dire Ape', 'Ancient Copper Dragon', 'Adult Black Dragon',
'Quasit', 'Ankheg', 'Nightmare', 'Bulette', 'Adult Brass Dragon', 'Fire Giant',
'Elder Water Elemental', 'Babau', 'Iron Golem', 'Nessian Warhound', 'Giant Frilled Lizard',
......</pre>
<p>Lets go ahead and look at a single monster and see what we get:</p>
<pre class="brush:py">&gt;&gt;&gt; monsters['Rat'].keys()
['Group', 'HP_Mods', 'HP', 'CMD', 'CMB', 'SpecialAttacks', 'Save_Mods', 'Immune',
'Init', 'Description_Visual', 'SpecialAbilities', 'CR', 'Type', 'HD', 'Melee',
'AbilitiyScores', 'Resist', 'Senses', 'BaseAtk', 'Gear', 'Ranged', 'Ref', 'DR',
'Weaknesses', 'Reach', 'DuringCombat', 'Environment', 'SubType', 'MonsterSource',
'Feats', 'CompanionFlag', 'AC_Mods', 'Class', 'Fort', 'RacialMods', 'AC', 'Treasure',
'Name', 'Bloodline', 'Skills', 'Gender', 'AbilitiyScore_Mods', 'IsTemplate',
'SpellsKnown', 'Note', 'Will', 'BeforeCombat', 'Race', 'Space', 'Aura', 'Organization',
'XP', 'ProhibitedSchools', 'Description', 'Languages', 'OtherGear', 'CharacterFlag',
'Source', 'SR', 'SQ', 'Saves', 'Vulnerability', 'Morale', 'SpellLikeAbilities',
'DefensiveAbilities', 'SpellsPrepared', 'Size', 'Speed', 'Alignment', 'SpellDomains']</pre>
<p>That quite a bit of information at our disposal:</p>
<pre class="brush:py">&gt;&gt;&gt; monsters['Rat']['Name']
'Rat'
&gt;&gt;&gt; monsters['Rat']['HP']
'4'
&gt;&gt;&gt; monsters['Rat']['XP']
'100'
&gt;&gt;&gt; monsters['Rat']['CR']
'1/4'</pre>
<p>The Ability scores are returned as a string as this was how the Excel file returned it,<br />
however I&#8217;m sure you can use split() to resolve that if you need it in a list:</p>
<pre class="brush:py">&gt;&gt;&gt; monsters['Rat']['AbilitiyScores']
'Str 2, Dex 15, Con 11, Int 2, Wis 13, Cha 2'</pre>
<p>I&#8217;m sure seeing the monsters Attack would be beneficial :)<br />
In the case of the Rat&#8217;s below they only have a Melee attack, go figure:</p>
<pre class="brush:py">&gt;&gt;&gt; monsters['Rat']['Melee']       
'bite +4 (1d3-4)'
&gt;&gt;&gt;
&gt;&gt;&gt; monsters['Rat']['Ranged']
''</pre>
<p>You also have access to the Descriptions which could be useful:</p>
<pre class="brush:py">&gt;&gt;&gt; monsters['Rat']['Description']
'Fecund and secretive, rats are omnivorous rodents that particularly thrive in urban areas.'
&gt;&gt;&gt;
&gt;&gt;&gt; monsters['Rat']['Description_Visual']
'Presented here are the base animal statistics for all of the most commonly used
familiars-of course, these statistics can also be used for normal animals as well.
Small animals like these use Dexterity to modify Climb and Swim checks.'</pre>
<p>This Dictionary contains 354 Monster, which I believe is the same amount found in the Bestiary:</p>
<pre class="brush:py">&gt;&gt;&gt; len(monsters)
354</pre>
<p>If you would like to use this for any of your application feel free to download the Python Pickle<br />
file:</p>
<p><strong>Download:</strong> <a href="http://newblog.flip-edesign.com/wp-content/uploads/2011/12/monsters.pk1_.tar.gz">monsters.pk1.tar</a> <em>422K </em></p>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=244</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reading from the Bible using Python</title>
		<link>http://newblog.flip-edesign.com/?p=233</link>
		<comments>http://newblog.flip-edesign.com/?p=233#comments</comments>
		<pubDate>Mon, 19 Dec 2011 19:50:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=233</guid>
		<description><![CDATA[Last week I went over the steps I used to convert a KJV Bible from XML to a Python dictionary. This week I figured I will show you how to have Python read from that Bible. I found a great Python module named pyttsx which is able to perform text to speech on Windows, Linux, [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I went over the steps I used to convert a <a href="http://newblog.flip-edesign.com/?p=218">KJV Bible from XML to a Python<br />
dictionary</a>. This week I figured I will show you how to have Python read from that<br />
Bible.</p>
<p>I found a great Python module named <strong><a href="http://packages.python.org/pyttsx/engine.html">pyttsx</a></strong> which is able to perform text to speech<br />
on Windows, Linux, and Mac OSX, looking at the docs gave me the idea to setup a small<br />
bit of code to read from the Bible, and like that this post was created.</p>
<p>First off I had to install pyttsx on my system, easy enough since I have setuptool:</p>
<pre class="brush:plain">$ sudo easy_install pyttsx</pre>
<p>Next was to verify everything was setup and working on my system,<br />
I went ahead and followed the <a href="http://packages.python.org/pyttsx/engine.html#speaking-text">example</a> outlined in the docs:</p>
<pre class="brush:py">import pyttsx
engine = pyttsx.init()
engine.say('Sally sells seashells by the seashore.')
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()</pre>
<p>All systems were go! I heard the text from my speakers and was very impressed<br />
at just how easy that was.</p>
<p>Next I wanted to be sure I could read a verse from the Bible:</p>
<pre class="brush:py">import pyttsx
import pickle

f = open('bible.pk1', 'rb')
bible = pickle.load(f)

engine = pyttsx.init()
engine.say(bible['John'][3][16])
engine.runAndWait()</pre>
<p>Everything up to this point worked excellent! Next I would create a function<br />
to help read entire chapters, or verse by verse:</p>
<pre class="brush:py">import pyttsx
import pickle

f = open('bible.pk1', 'rb')
bible = pickle.load(f)

engine = pyttsx.init()

def read(book=False, chapter=False, verse=False):
  if book and chapter:
       if verse:
         print '%s %s:%s\n%s' % (book, chapter, verse, bible[book][chapter][verse])
         engine.say(bible[book][chapter][verse])
         engine.runAndWait()
       else:
         for ver in bible[book][chapter]:
           print '%s %s:%s\n%s' % (book, chapter, ver, bible[book][chapter][ver])
           engine.say(bible[book][chapter][ver])
           engine.runAndWait()
  else:
    print 'Please provide a book and chapter'</pre>
<p>Using this function I&#8217;m able to read a single verse:</p>
<pre class="brush:plain">&gt;&gt;&gt; read(book='John', chapter=3, verse=16)
John 3:16
For God so loved the world, that he gave his only begotten Son, that whosoever believeth in
him should not perish, but have everlasting life.</pre>
<p>or I can read an entire chapter:</p>
<pre class="brush:plain">&gt;&gt;&gt; read(book='Psalms', chapter=23)
Psalms 23:1
The LORD is my shepherd; I shall not want.
Psalms 23:2
He maketh me to lie down in green pastures: he leadeth me beside the still waters.
Psalms 23:3
He restoreth my soul: he leadeth me in the paths of righteousness for his name's sake.
Psalms 23:4
Yea, though I walk through the valley of the shadow of death, I will fear no evil: for thou art with me; thy 
rod and thy staff they comfort me.
Psalms 23:5
Thou preparest a table before me in the presence of mine enemies: thou anointest my head with oil; my cup runneth over.
Psalms 23:6
Surely goodness and mercy shall follow me all the days of my life: and I will dwell in the house of the LORD for ever.</pre>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=233</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using a KJV Bible with Pickle and Python</title>
		<link>http://newblog.flip-edesign.com/?p=218</link>
		<comments>http://newblog.flip-edesign.com/?p=218#comments</comments>
		<pubDate>Wed, 14 Dec 2011 17:17:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=218</guid>
		<description><![CDATA[Just the other day I was looking at some of the old projects I posted at flip-edesign.com and seen the old KJV PHP app i wrote, I figured it wouldn&#8217;t hurt to do something similar with Python. First off I wanted to find a easy to use source for the Bible&#8217;s content, I found just [...]]]></description>
			<content:encoded><![CDATA[<p>Just the other day I was looking at some of the old projects I posted at <a href="http://flip-edesign.com/">flip-edesign.com</a><br />
and seen the old <a href="http://bible.flip-edesign.com/index.php?book=Genesis&amp;chapter=1">KJV PHP app</a> i wrote, I figured it wouldn&#8217;t hurt to do something similar<br />
with Python.</p>
<p>First off I wanted to find a easy to use source for the Bible&#8217;s content,<br />
I found just that with an <a href="http://www.believersresource.com/downloads/xml-bible-55.html">XML file</a> shared from believersresource.com.</p>
<p>The next step was to uncompress the archive and see the naming convention of this XML file:</p>
<pre class="brush:plain"># head kjv.xml 
&lt;?xml version="1.0"?&gt;
&lt;bible translation="King James Version"&gt;
    &lt;testament name="Old"&gt;
        &lt;book name="Genesis"&gt;
           &lt;chapter number="1"&gt;
               &lt;verse number="1"&gt;In the beginning God created the heaven and the earth.&lt;/verse&gt;</pre>
<p>Once I seen the format it was just a couple lines of Python to add this to a <a href="http://docs.python.org/library/collections.html#collections.OrderedDict">OrderedDict</a>:</p>
<pre class="brush:py">from xml.dom import minidom
from collections import OrderedDict

dom = minidom.parse(open('kjv.xml', 'r'))

bible = OrderedDict()
for book in dom.getElementsByTagName('book'):
   book_name = book.getAttribute('name')
   bible[book_name] = {}
   for chapter in book.getElementsByTagName('chapter'):
      chapter_number = chapter.getAttribute('number')
      bible[book_name][int(chapter_number)] = {}
      for verse in chapter.getElementsByTagName('verse'):
         verse_number = verse.getAttribute('number')
         verse_text = verse.firstChild.wholeText
         bible[book_name][int(chapter_number)][int(verse_number)] = verse_text</pre>
<p>And just like that we have a OrderedDict with our KJV Bible:</p>
<pre class="brush:py">&gt;&gt;&gt; for book in bible:
...   print book
... 
Genesis
Exodus
Leviticus
Numbers
Deuteronomy
Joshua
Judges
Ruth
1 Samuel
2 Samuel
1 Kings
2 Kings
1 Chronicles
2 Chronicles
Ezra
Nehemiah
Esther
Job
Psalms
Proverbs
Ecclesiastes
Song of Solomon
Isaiah
Jeremiah
Lamentations
Ezekiel
Daniel
Hosea
Joel
Amos
Obadiah
Jonah
Micah
Nahum
Habakkuk
Zephaniah
Haggai
Zechariah
Malachi
Matthew
Mark
Luke
John
Acts
Romans
1 Corinthians
2 Corinthians
Galatians
Ephesians
Philippians
Colossians
1 Thessalonians
2 Thessalonians
1 Timothy
2 Timothy
Titus
Philemon
Hebrews
James
1 Peter
2 Peter
1 John
2 John
3 John
Jude
Revelation</pre>
<p>Reading a individual verse works just like you would expect:</p>
<pre class="brush:py">&gt;&gt;&gt; print bible['John'][3][16]
For God so loved the world, that he gave his only begotten Son, that whosoever believeth in him 
should not perish, but have everlasting life.</pre>
<p>At this point I wanted to be sure I could save the Python Dictionary for later use,<br />
to achieve this I used <a href="http://docs.python.org/library/pickle.html">Pickle</a> to serialize the data.</p>
<pre class="brush:py">import pickle

f = open('bible.pk1', 'wb')
pickle.dump(bible, f)
f.close()</pre>
<p>Now that we have working data we can create all sorts of functions,<br />
for example here is a random_verse function:</p>
<pre class="brush:py">import random

def random_verse(bible, book=False):
  if not book:
     book = random.choice(bible.keys())
  chapter = random.choice(bible[book].keys())
  verse = random.choice(bible[book][chapter].keys())
  return '%s %s:%s \n%s' % (book, chapter, verse, bible[book][chapter][verse])</pre>
<p>The above function used as so:</p>
<pre class="brush:py">&gt;&gt;&gt; print random_verse(bible)
Galatians 5:19 
Now the works of the flesh are manifest, which are these; Adultery, fornication, uncleanness, lasciviousness,
&gt;&gt;&gt;
&gt;&gt;&gt; print random_verse(bible)
Ezra 8:7 
And of the sons of Elam; Jeshaiah the son of Athaliah, and with him seventy males.</pre>
<p>Or if you want random verses from a specific book:</p>
<pre class="brush:py">&gt;&gt;&gt; print random_verse(bible, 'Acts')
Acts 5:6 
And the young men arose, wound him up, and carried him out, and buried him.
&gt;&gt;&gt; 
&gt;&gt;&gt; print random_verse(bible, 'Acts')
Acts 9:30 
Which when the brethren knew, they brought him down to Caesarea, and sent him forth to Tarsus.</pre>
<p>I&#8217;ve went ahead and uploaded my Pickle file incase you wanted to test it out, or use<br />
it for any of your projects.</p>
<p><strong>Download:</strong> <a href="http://newblog.flip-edesign.com/wp-content/uploads/2011/12/bible.pk1_.tar.gz">bible.pk1.tar</a> (1.3M)</p>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=218</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python Device Hacking (Keyboard)</title>
		<link>http://newblog.flip-edesign.com/?p=200</link>
		<comments>http://newblog.flip-edesign.com/?p=200#comments</comments>
		<pubDate>Thu, 08 Dec 2011 18:42:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=200</guid>
		<description><![CDATA[After spending a bit of time hacking at the gamepad I decided to take a deeper look in to how /dev devices worked in Python, the easiest device I could get my hands on of course was a keyboard. First things first I needed to discover which device name represented my keyboard, to do this I [...]]]></description>
			<content:encoded><![CDATA[<p>After spending a bit of time <a href="http://newblog.flip-edesign.com/?p=195">hacking at the gamepad</a> I decided to take a deeper look<br />
in to how /dev devices worked in Python, the easiest device I could get my hands on<br />
of course was a keyboard.</p>
<p>First things first I needed to discover which device name represented my keyboard,<br />
to do this I used the virtual /proc filesystem at <strong>/proc/bus/input/devices</strong>:</p>
<pre class="brush:plain">I: Bus=0011 Vendor=0001 Product=0001 Version=ab41
N: Name="AT Translated Set 2 keyboard"
P: Phys=isa0060/serio0/input0
S: Sysfs=/devices/platform/i8042/serio0/input/input3
U: Uniq=
H: Handlers=sysrq kbd event2
B: PROP=0
B: EV=120013
B: KEY=4 2000000 3803078 f800d001 feffffdf ffefffff ffffffff fffffffe
B: MSC=10
B: LED=7</pre>
<p>From the above output I can see my device is event2 within Handlers,<br />
which I know is the block device <strong>/dev/input/event2</strong>.</p>
<p>Next I want to confirm that by running a simple piece of Python while holding down<br />
the <strong>A</strong> key on the keyboard:</p>
<pre class="brush:py">&gt;&gt;&gt; f = open('/dev/input/event2', 'r')
&gt;&gt;&gt; while True:
...   print f.read(8)</pre>
<p>Running the above snippet while holding the <strong>A</strong> key resulted in the below:</p>
<pre class="brush:py">&gt;&gt;&gt; f = open('/dev/input/event2', 'r')
&gt;&gt;&gt; while True:
...   print f.read(8)
...
¦áN*

¦áN*

¦áN *

¦áN;

¦áN
   ;</pre>
<p>Knowing the block device is correct, and Python can read from it we can move<br />
on to understanding how the keyboard device works.</p>
<p>Like in the last blog post I convert the binary output in to easily readable Python<br />
list containing ASCII character numbers using a simple function:</p>
<pre class="brush:py">&gt;&gt;&gt; def k():
...   byte = []
...   f = open('/dev/input/event2', 'r')
...   while True:
...     for bit in f.read(1):
...       byte.append(ord(bit))
...       if len(byte) == 8:
...         print byte
...         byte = []</pre>
<p>Calling this function I then press the letter <strong>A</strong> again on the keyboard and review the output:</p>
<pre class="brush:plain">&gt;&gt;&gt; k()
[72, 1, 225, 78, 39, 228, 8, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[72, 1, 225, 78, 53, 228, 8, 0]
[1, 0, 30, 0, 1, 0, 0, 0]
[72, 1, 225, 78, 57, 228, 8, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[72, 1, 225, 78, 188, 251, 9, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[72, 1, 225, 78, 199, 251, 9, 0]
[1, 0, 30, 0, 0, 0, 0, 0]
[72, 1, 225, 78, 202, 251, 9, 0]
[0, 0, 0, 0, 0, 0, 0, 0]</pre>
<p>This time I notice something a bit more interesting, something I&#8217;m sure that would of helped<br />
in the gamepad code.  I notice on key press I get the following:</p>
<pre class="brush:plain">[1, 0, 30, 0, 1, 0, 0, 0]</pre>
<p>and on key release I receive:</p>
<pre class="brush:plain">[1, 0, 30, 0, 0, 0, 0, 0]</pre>
<p>This is great as I realize element <strong>3</strong> <em>(30)</em> is the letter, but more importantly the fifth element<br />
states if the key is pressed or release<em> (1 of press and 0 for release)</em>.</p>
<p>Next was to determine what is returned when you hold down the key,<br />
so again I run the k() function and hold the key. This time I found the below:</p>
<pre class="brush:plain">&gt;&gt;&gt; k()
[204, 2, 225, 78, 126, 197, 3, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[204, 2, 225, 78, 141, 197, 3, 0]
[1, 0, 30, 0, 1, 0, 0, 0]
[204, 2, 225, 78, 145, 197, 3, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[204, 2, 225, 78, 202, 116, 7, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[204, 2, 225, 78, 217, 116, 7, 0]
[1, 0, 30, 0, 2, 0, 0, 0]
[204, 2, 225, 78, 221, 116, 7, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[204, 2, 225, 78, 237, 237, 7, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[204, 2, 225, 78, 252, 237, 7, 0]
[1, 0, 30, 0, 2, 0, 0, 0]
[204, 2, 225, 78, 0, 238, 7, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[204, 2, 225, 78, 129, 104, 8, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[204, 2, 225, 78, 144, 104, 8, 0]
[1, 0, 30, 0, 2, 0, 0, 0]
[204, 2, 225, 78, 148, 104, 8, 0]
[0, 0, 0, 0, 0, 0, 0, 0]
[204, 2, 225, 78, 144, 231, 8, 0]
[4, 0, 4, 0, 30, 0, 0, 0]
[204, 2, 225, 78, 159, 231, 8, 0]
[1, 0, 30, 0, 2, 0, 0, 0]
[204, 2, 225, 78, 163, 231, 8, 0]
[0, 0, 0, 0, 0, 0, 0, 0]</pre>
<p>With a ken eye you will notice a line almost identical to the above two, but with one<br />
slight difference (a value to repeat!):</p>
<pre class="brush:plain">[1, 0, 30, 0, 2, 0, 0, 0]</pre>
<p>At this point I&#8217;m pretty impressed and all that is left is to write a bit of Python to interrupt<br />
the keys and repeats. Luckily for me I found a piece of Python that already had a <a href="http://svn.navi.cx/misc/trunk/python/evdev/evdev.py">Keyboard Map</a><br />
written, slight editing it creates me a working keyboardMap dictionary:</p>
<pre class="brush:py">keyboardMap = {
        0: "KEY_RESERVED",
        1: "KEY_ESC",
        2: "KEY_1",
        3: "KEY_2",
        4: "KEY_3",
        5: "KEY_4",
        6: "KEY_5",
        7: "KEY_6",
        8: "KEY_7",
        9: "KEY_8",
        10: "KEY_9",
        11: "KEY_0",
        12: "KEY_MINUS",
        13: "KEY_EQUAL",
        14: "KEY_BACKSPACE",
        15: "KEY_TAB",
        16: "KEY_Q",
        17: "KEY_W",
        18: "KEY_E",
        19: "KEY_R",
        20: "KEY_T",
        21: "KEY_Y",
        22: "KEY_U",
        23: "KEY_I",
        24: "KEY_O",
        25: "KEY_P",
        26: "KEY_LEFTBRACE",
        27: "KEY_RIGHTBRACE",
        28: "KEY_ENTER",
        29: "KEY_LEFTCTRL",
        30: "KEY_A",
        31: "KEY_S",
        32: "KEY_D",
        33: "KEY_F",
        34: "KEY_G",
        35: "KEY_H",
        36: "KEY_J",
        37: "KEY_K",
        38: "KEY_L",
        39: "KEY_SEMICOLON",
        40: "KEY_APOSTROPHE",
        41: "KEY_GRAVE",
        42: "KEY_LEFTSHIFT",
        43: "KEY_BACKSLASH",
        44: "KEY_Z",
        45: "KEY_X",
        46: "KEY_C",
        47: "KEY_V",
        48: "KEY_B",
        49: "KEY_N",
        50: "KEY_M",
        51: "KEY_COMMA",
        52: "KEY_DOT",
        53: "KEY_SLASH",
        54: "KEY_RIGHTSHIFT",
        55: "KEY_KPASTERISK",
        56: "KEY_LEFTALT",
        57: "KEY_SPACE",
        58: "KEY_CAPSLOCK"
}</pre>
<p>You will notice above, just like I said earlier the element with result 30 was the key for the letter <strong>A</strong>,<br />
you will notice the keymap maps 30 to KEY_A.</p>
<p>All that is left is that bit of Python I mentioned:</p>
<pre class="brush:py">def k():
  byte = []
  f = open('/dev/input/event2', 'r')
  while True:
    for bit in f.read(1):
      byte.append(ord(bit))
      if len(byte) == 8:
        if byte[2] in keyboardMap:
          if byte == [1, 0, byte[2], 0, 1, 0, 0, 0]:
            print keyboardMap[byte[2]]
          elif byte == [1, 0, byte[2], 0, 2, 0, 0, 0]:
            print keyboardMap[byte[2]]
        byte = []</pre>
<p>Now I can connect to my Linux device over SSH and run this bit of code,<br />
and when the keyboard on the Linux box is pressed I get the following output:</p>
<pre class="brush:plain">&gt;&gt;&gt; k()
KEY_F
KEY_L
KEY_I
KEY_P
KEY_MINUS
KEY_E
KEY_D
KEY_E
KEY_S
KEY_I
KEY_G
KEY_N
KEY_DOT
KEY_C
KEY_O
KEY_M</pre>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=200</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python Device Hacking with USB Gamepad</title>
		<link>http://newblog.flip-edesign.com/?p=195</link>
		<comments>http://newblog.flip-edesign.com/?p=195#comments</comments>
		<pubDate>Thu, 08 Dec 2011 16:12:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Hacking]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=195</guid>
		<description><![CDATA[So today I was reading an article on Hack A Day about a user who wrote a Python script to interrupt his USB Gamepad, I watched the video and realized I had a very similar gamepad laying around. One thing led to another and I found my self attempting the same sort of project. The [...]]]></description>
			<content:encoded><![CDATA[<p>So today I was reading an article on <a href="http://hackaday.com/2011/03/17/writing-python-drivers-for-input-devices/">Hack A Day</a> about a user who wrote a Python script<br />
to interrupt his USB Gamepad, I watched the video and realized I had a very similar gamepad<br />
laying around. One thing led to another and I found my self attempting the same sort of project.</p>
<p><iframe src="http://www.youtube.com/embed/9zTdxKtufYQ" frameborder="0" width="420" height="315"></iframe></p>
<p>The Gamepad I am using is a <strong><a href="http://www.logitech.com/en-us/441/288">Logitec Dual Action</a></strong>:</p>
<p><img class="alignnone" src="http://images.highspeedbackbone.net/skuimages/large/Logitech-DualActionUSB-L23-.jpg" alt="" width="210" height="210" /></p>
<p>Using some of the code posted on Hackaday I quickly realized my Gamepad returned quite different<br />
result and thus needed different code.</p>
<p>I started with a very small Python script to print out my data in a list of character numbers:</p>
<pre class="brush:py">#!/usr/bin/env python
import sys

pipe = open('/dev/input/by-id/usb-Logitech_Logitech_Dual_Action-event-joystick', 'r')
action = []

while 1:
    for character in pipe.read(1):
        action += ['%02X' % ord(character)]
        if len(action) == 8:
            print action
            action = []</pre>
<p>To understand how the buttons worked I began by pressing and holding the <strong>number 1 button</strong>,<br />
and then pressing the <strong>Enter key</strong> on my keyboard a couple times to create spacing, I then<br />
released the <strong>number 1 button</strong>. This is what I found:</p>
<pre class="brush:plain">['B2', 'DD', 'E0', '4E', 'CF', 'DF', '0B', '00']
['04', '00', '04', '00', '01', '00', '09', '00']
['B2', 'DD', 'E0', '4E', 'D2', 'DF', '0B', '00']
['01', '00', '20', '01', '01', '00', '00', '00']
['B2', 'DD', 'E0', '4E', 'B4', 'E0', '0B', '00']
['00', '00', '00', '00', '00', '00', '00', '00']

['B4', 'DD', 'E0', '4E', '83', 'D2', '08', '00']
['04', '00', '04', '00', '01', '00', '09', '00']
['B4', 'DD', 'E0', '4E', '87', 'D2', '08', '00']
['01', '00', '20', '01', '00', '00', '00', '00']
['B4', 'DD', 'E0', '4E', '6C', 'D3', '08', '00']
['00', '00', '00', '00', '00', '00', '00', '00']</pre>
<p>Looking over the list I noticed the second lines were the same, I thought this must be the<br />
pressing of the button results. To verify I tried the same code but this time I pressed the <strong>number </strong><br />
<strong>2 button</strong>.</p>
<pre class="brush:plain">['C0', 'DE', 'E0', '4E', 'C7', '43', '0B', '00']
['04', '00', '04', '00', '02', '00', '09', '00']
['C0', 'DE', 'E0', '4E', 'C9', '43', '0B', '00']
['01', '00', '21', '01', '01', '00', '00', '00']
['C0', 'DE', 'E0', '4E', 'A9', '44', '0B', '00']
['00', '00', '00', '00', '00', '00', '00', '00']

['C2', 'DE', 'E0', '4E', 'FF', 'FD', '06', '00']
['04', '00', '04', '00', '02', '00', '09', '00']
['C2', 'DE', 'E0', '4E', '02', 'FE', '06', '00']
['01', '00', '21', '01', '00', '00', '00', '00']
['C2', 'DE', 'E0', '4E', 'E2', 'FE', '06', '00']
['00', '00', '00', '00', '00', '00', '00', '00']</pre>
<p>Again I noticed the second lines were the same, but this time the fifth element increased.<br />
How convenient the <strong>number 1 button</strong> is 01 in the fifth element where as the <strong>number 2 button</strong> is 02.</p>
<p>The only thing left was to create a variable to hold the state of the button,<br />
<strong>True</strong> for being pressed/held and <strong>False</strong> for being released (Not to difficult at all).</p>
<p>The ending code I wrote looks like this:</p>
<pre class="brush:py">#!/usr/bin/env python
import sys

pipe = open('/dev/input/by-id/usb-Logitech_Logitech_Dual_Action-event-joystick', 'r')
action = []

# set all buttons to off
buttons = []
for num in range(1,9):
    vars()['b0%s' % num] = False
    buttons.append('0%s' % num)

while 1:
    # read from the device pipe and set the action
    for character in pipe.read(1):
        action += ['%02X' % ord(character)]
        if len(action) == 8:

            # if button pressed is in our buttons list
            # print what was pressed  / released
            if action[4] in buttons:
                button = action[4]
                varbutton = vars()['b%s' % button]
                if action == ['04', '00', '04', '00', button, '00', '09', '00'] and not varbutton:
                    print 'Pressed Button %s' % action[4]
                    vars()['b%s' % button] = True
                elif action == ['04', '00', '04', '00', button, '00', '09', '00'] and varbutton:
                    print 'Released Button %s' % action[4]
                    vars()['b%s' % button] = False

            # empty action list
            action = []</pre>
<p>And the output of running it like this:</p>
<pre class="brush:plain"># ./game.py
Pressed Button 01
Released Button 01
Pressed Button 02
Released Button 02
Pressed Button 01
Pressed Button 02
Released Button 01
Released Button 02
Pressed Button 08
Released Button 08
Pressed Button 07
Released Button 07
Pressed Button 06
Released Button 06
Pressed Button 05
Released Button 05</pre>
<p>Some revised code to include Arrows and removal of True/False button press flag:</p>
<pre class="brush:py">#!/usr/bin/env python
import sys

pipe = open('/dev/input/by-id/usb-Logitech_Logitech_Dual_Action-event-joystick', 'r')

byte = []
while 1:
    # read from the device pipe and set the byte
    for bit in pipe.read(1):
        byte.append('%02X' % ord(bit))

        # 8 bits make a byte
        if len(byte) == 8:

            # Button 1
            if byte[2] == '20':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 2
            if byte[2] == '21':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 3
            if byte[2] == '22':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 4
            if byte[2] == '23':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 5
            if byte[2] == '24':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 6
            if byte[2] == '25':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 7
            if byte[2] == '26':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Button 8
            if byte[2] == '27':
                button = byte[2]
                if byte == ['01', '00', button, '01', '01', '00', '00', '00']:
                    print 'Pressed Button %s' % button
                elif byte == ['01', '00', button, '01', '00', '00', '00', '00']:
                    print 'Released Button %s' % button

            # Arror Up
            if byte[0] == '03':
                if byte == ['03', '00', '01', '00', '01', '00', '00', '00']:
                    print 'Pressed Up Arrow'

            # Arror Down
            if byte[0] == '03':
                if byte == ['03', '00', '01', '00', 'FE', '00', '00', '00']:
                    print 'Pressed Down Arrow'

            # Arror Left
            if byte[0] == '03':
                if byte == ['03', '00', '00', '00', '01', '00', '00', '00']:
                    print 'Pressed Left Arrow'

            # Arror Right
            if byte[0] == '03':
                if byte == ['03', '00', '00', '00', 'FE', '00', '00', '00']:
                    print 'Pressed Right Arrow'

            # Release Arrow
            if byte[0] == '03':
                if byte == ['03', '00', '01', '00', '80', '00', '00', '00']:
                    print 'Release Arrow'

            # empty byte
            byte = []</pre>
<p>And a simple test to show a very common pattern =)</p>
<pre class="brush:plain"># ./game.py
Pressed Down Arrow
Pressed Right Arrow
Release Arrow
Pressed Button 20
Released Button 20</pre>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=195</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wordlist with all possible ASCII elements</title>
		<link>http://newblog.flip-edesign.com/?p=183</link>
		<comments>http://newblog.flip-edesign.com/?p=183#comments</comments>
		<pubDate>Wed, 07 Dec 2011 01:33:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://newblog.flip-edesign.com/?p=183</guid>
		<description><![CDATA[After a bit of thinking I believe I have a better way to create all possible ASCII passphrases, rather than create a recursive function that calls itself as I did in the previous post. This method takes a slightly different approach, but I believe it to return the same results. First off let&#8217;s create a list of all [...]]]></description>
			<content:encoded><![CDATA[<p>After a bit of thinking I believe I have a better way to create all possible ASCII passphrases,<br />
rather than create a recursive function that calls itself as I did in the <a href="http://newblog.flip-edesign.com/?p=178">previous post</a>.</p>
<p>This method takes a slightly different approach, but I believe it to return the same results.</p>
<p>First off let&#8217;s create a list of all lower case ASCII character numbers:</p>
<pre class="brush:py">&gt;&gt;&gt; chars = range(97, 123)
&gt;&gt;&gt; chars
[97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122]
&gt;&gt;&gt; map(chr, chars)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']</pre>
<p>Next we can set our max word width and current word width variables:</p>
<pre class="brush:py">import itertools
maxwidth = 3
currentwidth = 1</pre>
<p>At this point we are ready to run with a while loop:</p>
<pre class="brush:py">while int(currentwidth) &lt;= int(maxwidth):
    for i in itertools.product(chars, repeat=currentwidth):
        print ''.join(['%c' % c for c in list(i)])
    currentwidth += 1</pre>
<p>The loop above will run until <strong>currentwidth</strong> is greater than <strong>maxwidth</strong> (makes sense right),<br />
at that point we use itertools&#8217;s <a href="http://docs.python.org/library/itertools.html#itertools.product">product</a> tool to create all possible orderings for our characters.</p>
<p>Then using list comprehension I print out the <strong>%c</strong> which returns the alphabetical character.</p>
<p>And lastly we increase the <strong>currentwidth</strong> by 1</p>
<p>What itertools.product does is creates all possible combinations (including repeated chars):</p>
<pre class="brush:py">&gt;&gt;&gt; [i for i in itertools.product(chars, repeat=2)]
[(97, 97), (97, 98), (97, 99), (97, 100), (97, 101), (97, 102), (97,
 103), (97, 104), (97, 105), (97, 106), (97, 107), (97, 108), (97, 109),
 (97, 110), (97, 111), (97, 112), (97, 113), (97, 114), (97, 115), (97,
 116), (97, 117), (97, 118), (97, 119), (97, 120), (97, 121), (97, 122),
 (98, 97), (98, 98), (98, 99), (98, 100), (98, 101), (98, 102), (98,
103), (98, 104), (98, 105), (98, 106), (98, 107), (98, 108), (98, 109),
 (98, 110), (98, 111), (98, 112), (98, 113), (98, 114), (98, 115), (98,
 116), (98, 117), (98, 118), (98, 119), (98, 120), (98, 121), (98, 122),
 (99, 97), (99, 98), (99, 99), (99, 100), (99, 101), (99, 102), (99,
......
.....
...</pre>
<p>Of course you probably want to see those tuples of <strong>characters</strong> as letters right?</p>
<pre class="brush:py">&gt;&gt;&gt; for i in itertools.product(chars, repeat=2):
...   ''.join(['%c' % c for c in i])
... 
'aa'
'ab'
'ac'
'ad'
'ae'
'af'
'ag'
'ah'
'ai'
'aj'
'ak'
'al'
'am'
'an'
'ao'
'ap'
'aq'
'ar'
'as'
'at'
'au'
'av'
'aw'
'ax'
..
..
..</pre>
]]></content:encoded>
			<wfw:commentRss>http://newblog.flip-edesign.com/?feed=rss2&#038;p=183</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

