Python Socket Examples
A collection of simple Python programs that show off the capabilities of the socket module.
Because of the nature of socket programming I've used some embedded devices including a RaspberryPi, an iRacer, and an eLua board.
This was presented at the 2012 Kiwi Pycon in Dunedin, New Zealand.
Much has been used from the Python socket documentation.
To really get an understanding of websockets I wrote a pure Python websocket server. Developer caveat - it is not a full implementation of RFC6455.
To demonstrate Bluetooth Sockets in Python 3.3 I used the iRacer from sparkfun with:
- on-board Bluetooth radio
- RFCOMM Bluetooth...
- Protocol is dead easy -
0xXYwhere X is the direction and Y is the speed. E.G
0x16: Direction=Forwards, mid-speed.
There was only ONE mention of "bluetooth" on the Python 3.3 socket docs... so I had to use the source.
Boiled down to creating a Bluetooth controlled iRacer car with something like this:
import socket import time class BluetoothCar: def __init__(self, mac_address="00:12:05:XX:XX:XX"): self.socket = socket.socket( socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM) self.socket.connect((mac_address, 1)) def forwards(self, duration=1.0): self.drive(0x16, duration) ... def drive(self, command, duration): self.socket.send(bytes([command])) time.sleep(duration) self.socket.send(bytes([0x00]))
The Controller Area Network is a bus standard designed to allow microcontrollers and devices to communicate with each other. It has priority based bus arbitration, reliable deterministic communication. Used in cars, trucks, wheelchairs... wikipedia has more info
SocketCAN is a set of open source CAN drivers and a networking stack contributed by Volkswagen Research to the Linux kernel. Although out of date, there are some good docs at brown hat on the low level CAN API.
raw_can.py shows sending CAN messages using a raw can socket and
receiving a filtered selection of them.
Required creating a patch for Python. Found in
There are much more thorough treatments of normal network sockets out
there, but for completeness I've included examples
basic_socket_server.py that will work
My presentation notes are in
slideshow.md which can be turned into
some sort of slideshow with pandoc:
$ pandoc -s --self-contained --webtex -i -t slidy slideshow.md -o presentation.html