Python Socket ExamplesA 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.
WebsocketsTo really get an understanding of websockets I wrote a pure Python websocket server. Developer caveat - it is not a full implementation of RFC6455.
Bluetooth SocketsTo 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.
:::python 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]))
CAN SocketsThe 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.pyshows sending CAN messages using a raw can socket and receiving a filtered selection of them.
BCMRequired creating a patch for Python. Found in
IPv6 SocketsThere are much more thorough treatments of normal network sockets out there, but for completeness I've included examples
basic_socket_server.pythat will work together.
MiscMy presentation notes are in
slideshow.mdwhich can be turned into some sort of slideshow with pandoc:
$ pandoc -s --self-contained --webtex -i -t slidy slideshow.md -o presentation.html