hacking

You are currently browsing the archive for the hacking category.

During the last 12 hours of the hackathon I decided to write a TCP server for an old project I want to finally finish. I decided to write it in Python, mostly because my friend Adam likes Python and Adam would inevitably be the one answering my questions when I got stuck. I should mention that prior to yesterday evening I knew nothing about socket programing. And I only had a vague idea of what threading was.

Since not everyone has friends like Adam, I’m writing up my findings in a tutorial.

Note: A bug in my CSS is causing the code blocks to show up extra wide. I’ll fix it once I’m back home from the hackathon

Understanding Sockets

First, I’m going to assume you understand that this is not a tutorial about writing an HTTP server. Instead this server will take connections from clients and keep them open to pass data back and forth until one side decides to close the connection. By keeping the connection open we eliminate the need to constantly poll the server for updates.

Socket Programming HOWTO provides a broad overview of sockets and is a good starting place.

Python’s Socket Library

Luckily python has an easy to use library. Like other libraries, we import it with thusly:

from socket import *

Many of the socket methods you’ll use are pretty self explanatory:
socket.listen() – listens for incoming connections
socket.accept() – accepts an incoming connection
socket.recv() – returns incoming data as a string
socket.send() – sends data to client socket*
socket.close() – closes the socket

*in this context the ‘client socket’ can be on either the server or client side. When a client connects to a server, the server creates a new client socket on its end. The two clients, one on each end, communicate with each other while the server socket remains open for incoming connections. This becomes more clear as you work with socket connections.

Writing the server
First thing’s first, we need to establish our server socket:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
##server.py
from socket import *      #import the socket library
 
##let's set up some constants
HOST = ''    #we are the host
PORT = 29876    #arbitrary port not currently in use
ADDR = (HOST,PORT)    #we need a tuple for the address
BUFSIZE = 4096    #reasonably sized buffer for data
 
## now we create a new socket object (serv)
## see the python docs for more information on the socket types/flags
serv = socket( AF_INET,SOCK_STREAM)    
 
##bind our socket to the address
serv.bind((ADDR))    #the double parens are to create a tuple with one element
serv.listen(5)    #5 is the maximum number of queued connections we'll allow

So now we have a server that’s listening for a connection. Or at least we did until the script reached the end and terminated, but we’ll get to that in a bit. Let’s leave our server hanging and jump to our client software.

Creating the client
Start a new python script for the client. We’ll need many of the same constants from the server, but our host will be ‘localhost’. For now we’ll be running both the server and the client on the same machine.

1
2
3
4
5
6
7
8
9
10
##client.py
from socket import *
 
HOST = 'localhost'
PORT = 29876    #our port from before
ADDR = (HOST,PORT)
BUFSIZE = 4096
 
cli = socket( AF_INET,SOCK_STREAM)
cli.connect((ADDR))

Notice that we’re creating another socket object on this end but instead of binding and listening, we’re using the connect() method to connect to our server.

So what happens if we run our server and then run our client? Well, not much. While our server starts to listen, it then hits the end of the script. We need it to instead wait until it accepts a connection and then do something with that connection.
socket.accept() does just that, and returns two things: a new client socket and the address bound to the socket on the other end. Once we have that, we can send data!

Continuing on server.py:

12
13
14
15
16
17
18
19
20
21
22
23
serv = socket( AF_INET,SOCK_STREAM)    
 
##bind our socket to the address
serv.bind((ADDR))    #the double parens are to create a tuple with one element
serv.listen(5)    #5 is the maximum number of queued connections we'll allow
print 'listening...'
 
conn,addr = serv.accept() #accept the connection
print '...connected!'
conn.send('TEST')
 
conn.close()

The last step is to jump back over to our client and tell our client to expect to receive data:

9
10
11
12
13
14
15
cli = socket( AF_INET,SOCK_STREAM)
cli.connect((ADDR))
 
data = cli.recv(BUFSIZE)
print data
 
cli.close()

Now when you run your server it will wait until a client connects. Once you run your client it will connect and receive a short message (the word “TEST” in this case) and print it to the screen. If you wanted to you could have the client send a response, using the same send() and recv() methods (but reversed).

Make sure you close() your connections when you’re done using them. If you don’t close things nicely they have a nasty habit of staying bound/connected until you forcibly kill the python process. This can be a real pain when you’re debugging.

By itself this isn’t particularly useful, especially considering we can only handle one connection at a time and exit once it’s closed. By adding a few while loops and some threading we can make this into something much more valuable. As it is, I’m pretty wiped from the hackathon, so the threading tutorial will have to wait until another day.

Exploding Capacitors

When I went to boot up an old computer which had sat dormant since I moved in April, nothing happened. No lights, no whirring, nothing. I assumed it was a bad power supply, and left it for another day. Over the weekend my boyfriend got sick of seeing it out, guts exposed to the world, and threw a new power supply in it. Still no life. Then he pulled out everything but the motherboard, and it booted! Or at least, as much as a computer with just a motherboard can.

As he added each component in one by one, the culprit became clear without even having to power up the machine:

exploded capacitors

Not seeing it? Here, let me get a little closer:

This is, or was, my video card. A reasonably nice (at the time) 7600 GT. The most remarkable thing is that this is not the first time I've seen this happen to this particular card. In fact, it's the third. Two other friends of mine have had theirs blow capacitors as well. And a google search for "exploding capacitors 7600" brings up tons of results.

Goodbye, video card. We have these in a number of the computers in the house, including my main machine. I wonder how long it will be until the next one goes.

Don't forget to register for the hackathon! It's totally free, but we're asking folks to sign up so we can get an idea of how many people to expect!

NYC Resistor's first 48 hour hackathon will run from 6pm Friday, Feburary 12 to 6pm Friday, February 14. At the end of the hackfest there will be time to share your projects as well as exciting prizes for the most awesome hacks.

You can work by yourself or with a team, and if you don't have a team/project we'll assign you to one. Projects we've heard buzz about include:

  • Re-enabling the 1930's teletype
  • Building props to do a trivia quiz. Buzzers, lights, etc
  • Subway wifi radio station aka "Radio Free MTA"

 

The format is open, you're welcome to come and go as you please. We'll keep the Club Mate flowing and follow a loose schedule of demos and workshops to help spark your imagination. PS, interested in giving a demo of some sort at the hackathon? Contact Kelly!

Friday, Feb 12

6pm – 8pm: Intros and whatnot. There's no formal registration, but it would be nice if folks introduced themselves and what they're working on

8pm – 12am: hack hack hack hack hack

Saturday, Feb 13

12am-4pm: hack hack hack hack

Afternoon-ish: Makerbot demo! Watch as Widget produces widgets with his magical printing device!

12pm – 2pm: Soldering lab! Practice your soldering skills. We'll have some of the TV-Be-Gone kits on hand for folks who want to learn to solder (or just irritate employees at Best Buy)

4pm – 6pm: GO EAT SOMETHING. We'll need to make space for the Audio Fun with Coils class from 4-6, so it's a good excuse to get some food, take a shower, reunite with your kids, etc.

4pm – 12am:  hack hack hack hack hack

Sunday, Feb 14

12am – 5pm: hack hack hack hack

7am: Late night breakfast. We'll strike out for food before the valentine's day brunchers are even awake.

5pm: PRESENTATIONS! Everyone will get a few minutes to show off what they did. We promise this won't be long and painful. 

5:45- 6pm: We'll award awesome awards, tidy up, and have you all home in time for Valentine's dinner.

Since I moved to New Jersey and stopped biking to, or even going to, an office, I haven’t used my iPod much. For the last year it has languished in a drawer as newer and fancier generations of iPod are released.

My iPod’s reluctance to awake from its slumber is by no means surprising. And this iPod has not led a particularly cushy life. On an alarmingly regular basis my iPod would fall out of my pocket during my bike ride to work. When it did it would either hang precariously from the headphone jack or, more likely, tumble down the street.

While the industrial strength case I got (shown left) is the sole reason the thing functions at all, my iPod cries of protest want me to know it’s time for a new one. The battery lasts about a third of what it used to and every now and then the whole thing just freezes with a big black bar across the bottom. Not even a sad mac face, just an angry black bar. This is undoubtedly related to the repeated head trauma the little device has faced. The classic iPods have hard drives in them (as opposed to flash) and really don’t appreciate being shaken or dropped.

So now my quandry is whether to stick it out until the thing finally dies, and get the latest and greatest now, or to give into my technophile tendencies and put it out of its misery. While the lack of battery life would be enough for many to give up on a device, I’m frankly not away from a power source for very long stretches of time. Even at the gym there are iPod chargers on every cardio machine.

The sudden freezing can be distressing, although it fixes itself when I re-sync with iTunes. I’ve been listening to a lot of books on tape lately, and having the iPod cut out at a climactic point in the story leaves me furiously stabbing at its little buttons in an attempt to revive the thing and find out what happens.

Looking at a timeline of Apple media devices on wikipedia, the current generation (6) has been around for about as long as mine (5th gen) was allowed to live, which means it’s due for an update. I have an amazing knack for buying Apple devices right before they up the specs. So I suppose the prudent thing would be to wait until the next one comes along and my iPod is really and truly dead, not just begging to be put out to pasture.

While I’m mostly considering another iPod classic, the Nano does have the advantage of being smaller and supports the Nike+ features at my gym. If you have a snazzy enough iPod it will log your workout onto it and then upload it to a tracking website when you do your next iTunes sync. Or so I’ve been told. My iPod is not nearly snazzy enough. But even the 16GB Nano is smaller than my music collection, not to mention video, so it’s less than ideal. And I’m not interested in the iPod Touch, I already have one infuriating touchscreen device rattling around in my purse: the G1.

I keep reminding myself that today’s shiny new iPod will be next year’s whiny old curmudgeon, and as such I think I’ll wait it out a bit longer.

I've been slowly (very slowly) setting up a small store at Resistor to carry electronics parts and prototyping tools, since there aren't any retail stores in town where you can pick up an Arduino RIGHT NOW. While ordering parts and figuring out where it will all go, I had a vision:

Vending machine full of components!

I've been surfing Craigslist and eBay, and while I'm not allowed to bring any new equipment into the space until we're all settled in post-move, it looks like a used vending machine can be found for $300 – $700 depending on what you're looking for.

One of the old school snack machines sounds just about perfect, but the one we found can only handle prices up to $3.95. Most vending machine hacks I was able to find were about getting free stuff out of them, not modding them to sell out of. Another fun hack which probably wouldn't be terribly difficult would be hooking it up to the net and letting people pay with PayPal or credit card.

I'll continue to hunt for the perfect machine, but in the mean time I'd love to hear about any vending machine hacks folks have seen or done. Because clearly what we need a robot who sells robot parts!

I have to admit, I’m more than a little confused by Mark Frauenfelder’s contribution to Mac|Life’s “Apple Products of the Future” article. Specifically, I’m astounded that nowhere in the article does it give attribution to Makerbot, despite drawing liberally from Makerbot’s design.

Makerbot

The imaginary iMake

I’m not sure if Frauenfelder himself directed the “finished product” rendering, as it’s pretty different from his sketch shown in the article. But any attribution to Makerbot is conspicuously missing from the article. And they clearly were inspired by it somewhere along the line. It’s extra confusing because Frauenfelder is with Make:, who is currently documenting the unboxing of a Makerbot for all to see.

It’s disheartening. I think this sort of failure to attribute ideas hurts open source. Let’s give credit to the people who are actively realizing their ideas, not just doodling them. The Makerbot guys are taking it in stride, because they’re classy like that, but personally I’m disappointed to see their work being passed off as an Apple Product of the Future. The printer, while still in an early stage and without a high gloss shell, exists. In fact, that “App Store” to download printable models exists too, it’s called Thingiverse. So why are people who clearly already know this acting like they don’t?

Sweet Classes at NYCR

Right now there is a super sweet list of classes coming up at NYCR, so many I wish I had the time to take them all.

I’m teaching my standby Intro to PHP class again, and also trying out a new one: Designing with QCAD. QCAD is used for 2D drawing, and is a great tool for designing things to be laser cut.

Aside from what I’m teaching there’s a DIY Vacuum Form class coming up this weekend, and a Hacking Classic Nintendo Games class I’ll sadly be missing due to Thanksgiving. Soldering 101 has been merged with Arudino 101, bringing you a class which teaches you to solder AND make things!

Overall I’m really excited and hope the classes are well attended. We’ll see how badly the holidays screw up everyone’s schedule. Stupid holidays.

Introduction to Algorithms

What’re you doing Sunday evening? Nothing? Come down to NYC Resistor where starting this weekend we’ll be working through the Introduction to Algorithms course available through MIT’s OpenCourseWare project. What’s OpenCourseWare?

MIT OpenCourseWare (OCW) is a web-based publication of virtually all MIT course content. OCW is open and available to the world and is a permanent MIT activity.

We’ll start at 5pm and the lectures run about an hour and a half. The time may shift a bit each week due to other classes happening at the space, but we’ll post it on the calendar well in advance. The class uses the text “Introduction to Algorithms” which you may want to pick up or borrow from a friend. We’ll try to scrounge up a couple copies to have on hand.

This event series is totally free to attend, but if you enjoy it please consider donating to the MIT OpenCourseWare project!

This week we’ll be watching Session 1: Introduction – Analysis of Algorithms, Insertion Sort, Mergesort

This short and somewhat boring clip is the result of playing around with CHDK (Canon Hack Development Kit). I’m working on a stop-motion animation for Tinysaur, but sadly neither of my cameras (a Canon Digital Rebel XT and a Canon SD1100IS Point and Shoot) had a built in timer that would shoot over and over indefinitely. Using the CHDK Ultra Intervalometer script I set my camera to take a shot every .5 seconds. Although it didn’t quite go that fast… I’ll get to that in a bit.

CHDK is a firmware add-on for Canon point and shoot cameras that lets you control absolutely every aspect of the shot. It loads from your SD card at boot, so it’s non-permanent (although you can set it to auto load). It gives you access to a plethora of fine tuning options and display monitors, and also lets you run scripts to take pictures based on time, motion detection, etc. But the most exciting thing I found is that there’s a script which will let you trigger the camera with a hacked USB cord with a switch.

img_0149Mine is shown on the left, it’s not very pretty. I spliced a reset switch into the +5v (red) wire. It uses a USB port for power, which makes it a little silly, although ok for my uses. Ideally you’d rig up a power supply along with the switch. I would have but I only had AA battery holders and it needs between 3.5V and 5V of juice. There are some neat hacks listed on the CHDK wiki for making remote cables out of old joysticks and flashlights and whatnot.

There’s a ton of documentation, but it’s a bit scattered around the CHDK wiki. Here’s what I did to get the Ultra Intervalometer script up and running. The instructions are almost identical for the USB remote script:

Getting CHDK going:

  • Grab a spare SD card and format it. If it’s >2 gig and you think you’ll want to auto boot CHDK, format it as FAT16 (‘format X: /fs:fat’ from the comand line). Leave it in your machine’s SD reader (which, by the way, you need for this).
  • Make sure you have a CHDK compatible camera. My SD1100 works well with it (and without it, for that matter), apparently the latest version of that camera (SD1200) doesn’t yet have a version of CHDK for it. CHDK isn’t available for SLR cameras.
  • Check your camera’s firmware version. Create a blank file called ver.req on the SD card. Put the card in your camera. Make sure the camera is set to playback mode and turn it on. Press “Func Set” and “Disp” at the same time. A screen with the firmware version should pop up.
  • Download the appropriate version of CHDK. Unzip it onto your SD card.
  • While not necessary to get CHDK running, now is a good time to stick the Ultra Intervalometer script on the card, so you don’t have to take it out to do it later. Copy the script code and save it as something like ‘ult_interval.bas’ in the SCRIPTS subdirectory on the SD card.
  • Pop the SD card in your camera.
  • Make sure your camera is set to playback and turn it on. Hit ‘Menu’ and scroll down, you should see an option to update the firmware. Do it!
  • When you update the firmware, the ‘print’ button will blink for a bit, strange things will happen, and you should see the CHDK splash screen. Hooray!

Now you can use the ‘print’ button to switch between the normal boring Canon menus / normal shooting and “<ALT>” mode, which brings up a totally different list of options when you press the Menu button, and triggers a script when you press the shutter release rather than taking a picture.

Using Ultra Intervalometer

  • Make sure you’re in <ALT> mode
  • Press Menu and scroll down to Script Parameters
  • Select “Load script from file” and select ultra_interval.bas or whatever you called the script.
  • Set the script parameters (those under the heading Ultra Intervalometer) to your whim. Use left/right to increase or decrease parameter values.
    • Delay 1st Shot (mins) – this is the time between when you start the script and the first shot, in minutes
    • Delay 1st Shot (secs) – As above, but seconds
    • Number of Shots – how many to take
    • Interval (minutes) – number of minutes between shots
    • Interval (seconds) – number of seconds between shots
    • Inerval (10th seconds) – as above, with 10ths of seconds
  • Exit out of the menu (by hitting menu)
  • Press the shutter to start the script. The camera will fire at the interval you chose, hooray! Press the shutter again if you want to stop the script before it finishes.

When I set the interval to 1 second I noticed that the camera wasn’t actually shooting that often. The ‘review’ period, where it shows you waht you just took, seemed to be getting in the way. I exited out of <ALT> mode and was able to set the review time to 0 seconds in the camera’s normal menu. I also turned off AF-Zoom. It still takes a little bit of time to auto focus between each shot,  I haven’t dug through enough of the CHDK documentation to find out how to only focus at the start of the sequence.

Here’s a short (ok, still boring) clip of my walk from NYC Resistor down the street, in search of some tacos:

Folded paper boxes

I’ve been working on learning Processing, a language which is a bastardization of Java used for drawing pretty pictures (among other things). Most of its functions are based around drawing/graphics.

Processing project #1 was to generate templates to be cut on the laser cutter. Specifically paper boxes, because I needed something to package my Tinysaurs in. They end up looking like this:

Laser-cut boxes

You enter the depth, width, and height of the box, and Processing draws the pattern

Processing has a PDF library which I use to generate the template in PDF format, which Corel Draw is able to read. I’m looking into using Python instead of Processing, because it apparently has a nice DXF library. Although the fact that Adam scoffs at Processing makes me want to keep using it just to annoy him.

The Processing program is available in the NYC Resistor SVN repository. Which is public, hooray! The code is only vaguely commented, but it should be pretty clear what it’s doing. Maybe.

Of course you dont’ need a laser to cut these out, and xacto knife would work just fine. But… I have a laser so I use it.

If you don’t want to mess with Processing and just want to print box patterns, you can do that too. I’ve generated a bunch of sizes:

You may need to right-click and save the pdf to your hard drive to get it to load.

« Older entries