SlideShare a Scribd company logo
TWISTED AS AN IOT 
CONTROLLER. 
BUILDING A 300+ SEAT IFE CONTROLLER IN TWISTED. 
David P. Novakovic / @dpn / dpn.name
QUICK OVERVIEW 
WTF is Twisted? 
IFE System Devices 
IFE System requirements 
Code examples
TWISTED THE SLAYER OF NOOBS 
SUPER POWERFUL 
ALSO CONTROVERSIAL 
Seems to have a bad rep with people who don't use it.
TWISTED 
event driven framework in python 
particular focus on networking related things 
from web down to serial ports, tun/tap and udev 
async io - single process can handle thousands of concurrent 
open connections on a low end machine 
Clean APIs for both callbacks and deferreds 
thread pool with deferred interface 
locking "primitives" - DeferredSemaphore, DeferredLock, 
DeferredQueue
MORE TWISTED 
Application framework 
Async unit testing 
Integration with most major event loops 
(wx/gtk/qt/gevent/etc) 
third party libs 
klein - sinatra/flask style web framework 
cyclone - tornado port to twisted 
treq - "requests" style lib 
ampoule - nice enough (if slightly neglected) process pool 
implementation
IFE STUFF.. YAY
TRADITIONAL 
"dumb" screens heavy use of streaming content 
very heavy requirements on servers 
very expensive to upgrade 
GLIDE 
Heavier clients 
system can be upgraded by replacing players 
plane doesnt need rewiring etc 
server can remain fairly unchanged 
more importantly don't need to be upgraded in lockstep
GLIDE SOLUTION 
players - embedded debian 
seat disconnect - custom embedded device 
triple redundant power supplies - switch + power 
cm controller - dual core atom running ubuntu LTS + lots of 
embedded things attached
SYSTEM
SOME RELEVANT REQUIREMENTS 
multicast commands out to embedded devices 
300+ seat updates over HTTP every second 
listen to audio stream over multicast (PA, pilot etc) 
low latency control of players ie. if pilot talks/decomp 
telneting into a streaming VLC process. 
some legacy - sync code needed to run in threads 
respond to and control hardware in the plane (overhead 
screens etc) 
cabin crew inserting HDD with content (lock down usb) 
downloading content from the web (at gate) 
kiosk (lock down control keys/usb ports) 
manhole for debugging a running process 
ssh reverse tunnel for remote access - conch 
tftp - firmware updates to players
MULTICAST 
from twisted.internet import reactor, task, protocol 
class MulticastSeatControl(protocol.DatagramProtocol): 
def startProtocol(self): 
self.transport.joinGroup("228.0.0.5") 
def sendSeatControl(self, bytes): 
self.transport.write(bytes, ("228.0.0.5", 8005)) 
def datagramReceived(self, datagram, address): 
print "Datagram %s from %s" % (repr(datagram), repr(address))
HTTP INTERFACE 
import json 
from klein import Klein 
class DeviceAPI(object): 
app = Klein() 
def __init__(self, cmc): 
self._cmc = {} 
@app.route('/stat/<string:name>') 
def stat(self, request): 
body = json.loads(request.content.read()) 
self._cmc.logstat(body['something']) 
request.setHeader('Content-Type', 'application/json') 
return json.dumps({"status": "success"})</string:name>
SERIAL PORT 
from twisted.internet.serialport import SerialPort 
from twisted.internet import reactor 
from twisted.protocols.basic import LineReceiver 
class SensorProtocol(LineReceiver): 
def connectionMade(self): 
print "Connected to serial port." 
def lineReceived(self, line): 
print "Received line:", line 
def send_our_command(self, command): 
self.sendLine("command:%s" % command) 
def connect_serial_port(): 
return SerialPort(SensorProtocol(), "/dev/ttyACM0", reactor, 
115200, rtscts=False, xonxoff=False, timeout=1)
DJANGO 
WAIT.. WHAT? 
Yep, ORM is used a fair bit, as is admin.
DJANGO 
from django.core.handlers.wsgi import WSGIHandler 
from twisted.python import threadpool 
from twisted.internet import reactor 
from somewhere import Root 
def gimme_some_django(): 
pool = threadpool.ThreadPool() 
wsgi_resource = wsgi.WSGIResource(reactor, pool, WSGIHandler()) 
r = Root(wsgi_resource) 
s = server.Site(r) 
pool.start() 
return internet.TCPServer(8082, s) 
eg. django admin available at http://localhost:8082/admin/ 
https://github.com/clemesha/twisted-wsgi-django
YET MORE 
class VLCRemoteControlProtocol(LineReceiver): 
... 
class UDevMonitor(abstract.FileDescriptor): 
...
AND TELNET INTO YOUR OWN PROCESS.. 
import twisted.manhole.telnet 
from twisted.internet.endpoints import TCP4ServerEndpoint 
def start_manhole(service): 
f = twisted.manhole.telnet.ShellFactory() 
f.username = "b" 
f.password = "b" 
f.namespace["var1"] = service 
endpoint = TCP4ServerEndpoint(reactor, 7777) 
endpoint.listen(f)
TIE IT ALL TOGETHER 
Application framework 
Unit Testing
APPLICATION FRAMEWORK 
TWISTD 
Daemonises optionally 
pidfile 
log files 
Error catchall 
http://twistedmatrix.com/documents/13.2.0/core/howto/basics.html
CREATE SERVICES 
class IOTCServer(Service): 
def startService(self): 
self.serialport = connect_serial_port() 
p = MulticastSeatControl() 
reactor.listenMulticast(8005, p) 
start_manhole(self) 
self.mc_looper = task.LoopingCall(p.sendSeatControl, "s1:on,s2:on") 
self.mc_looper.start(1) 
def stopService(self): 
self.serialport.transport.loseConnection() 
self.mc_looper.stop() 
def get_http_service(iots_instance): 
device_api = DeviceAPI(iots_instance) 
server.Site(device.api.app.resource()) 
return internet.TCPServer(8082)
TWISTD PLUGIN 
class Options(usage.Options): 
optParameters = [["serialport", "s", "/dev/ttyACM0", "Serial port."] 
class ServiceMaker(object): 
tapname = "iotc" 
description = "The IOTC Server" 
options = Options 
def makeService(self, options): 
service_parent = service.MultiService() 
iots = IOTCServer() 
iots.setServiceParent(service_parent) 
http_service = get_http_service() 
http_service.setServiceParent(service_parent) 
django_service = gimme_some_django() 
django_service.setServiceParent(service_parent) 
return service_parent 
serviceMaker = ServiceMaker() 
yourproject/twisted/plugins/iotc_plugin.py 
$ twistd -r epoll -n iotc --serialport=/dev/ttyACM0
UNIT TESTING 
Twisted Trial 
Wrapper around pyunit "unittest" 
Allows tests to return deferred responses 
subclass twisted.trial.unittest.TestCase 
run tests: trial yourpackage 
Some helpers to let you mock wire-level connections 
http://twistedmatrix.com/documents/11.1.0/core/howto/trial.html
BUILD AWESOME THINGS! 
DIGECOR IS HIRING 
If you enjoy working on this kind of stuff, let me know and I'll 
forward your details onto digEcor. 
@dpn
THE END 
DAVID NOVAKOVIC - DPN.NAME

More Related Content

PDF
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
PDF
I/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
PDF
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
PDF
Make container without_docker_6-overlay-network_1
PPT
Stackless Python In Eve
PDF
Make container without_docker_7
PDF
Unix executable buffer overflow
PDF
Cloud RPI4 tomcat ARM64
도커 없이 컨테이너 만들기 4편 네트워크네임스페이스 (2)
I/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
도커 없이 컨테이너 만들기 5편 마운트 네임스페이스와 오버레이 파일시스템
Make container without_docker_6-overlay-network_1
Stackless Python In Eve
Make container without_docker_7
Unix executable buffer overflow
Cloud RPI4 tomcat ARM64

What's hot (20)

PDF
Monitoring with Syslog and EventMachine
PDF
Basic onos-tutorial
PDF
Windows persistence presentation
PDF
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
TXT
PDF
Fedora Atomic Workshop handout for Fudcon Pune 2015
PDF
The future of async i/o in Python
ODP
Os Cook
ODP
Fabric Fast & Furious edition
PDF
Python, do you even async?
PDF
Hands-on ethernet driver
PPT
Troubleshooting Linux Kernel Modules And Device Drivers
PDF
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
PDF
PDF
Linux administration ii-parti
PDF
Asynchronous Io Programming
PDF
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
PPTX
Lecture 3 Perl & FreeBSD administration
PDF
Possibility of arbitrary code execution by Step-Oriented Programming
Monitoring with Syslog and EventMachine
Basic onos-tutorial
Windows persistence presentation
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
Fedora Atomic Workshop handout for Fudcon Pune 2015
The future of async i/o in Python
Os Cook
Fabric Fast & Furious edition
Python, do you even async?
Hands-on ethernet driver
Troubleshooting Linux Kernel Modules And Device Drivers
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
Linux administration ii-parti
Asynchronous Io Programming
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
Lecture 3 Perl & FreeBSD administration
Possibility of arbitrary code execution by Step-Oriented Programming
Ad

Viewers also liked (13)

PDF
啄木鸟Twisted
PPT
OSCon - Performance vs Scalability
PDF
GEE_OVERVIEW_SALESSHEET
PDF
3rd International Conference IFE & Connectivity, 24 – 26 March 2015, Hamburg ...
PDF
A revolution in the air: Mary Kirby, Runway Girl Network
PDF
Обзор фреймворка Twisted
PDF
HCL Interviews Thales
PPTX
Asynchronous Python with Twisted
PDF
WTF is Twisted?
PPTX
Smart Airplanes. Creating Connections.
PDF
Air Travel Product Levels
PDF
Android Push Server & MQTT
啄木鸟Twisted
OSCon - Performance vs Scalability
GEE_OVERVIEW_SALESSHEET
3rd International Conference IFE & Connectivity, 24 – 26 March 2015, Hamburg ...
A revolution in the air: Mary Kirby, Runway Girl Network
Обзор фреймворка Twisted
HCL Interviews Thales
Asynchronous Python with Twisted
WTF is Twisted?
Smart Airplanes. Creating Connections.
Air Travel Product Levels
Android Push Server & MQTT
Ad

Similar to Building an inflight entertainment system controller in twisted (20)

ZIP
How we use Twisted in Launchpad
PDF
Twisted
PDF
Twisted logic
KEY
Twisted: a quick introduction
PDF
Python twisted
PDF
Scaling Django with gevent
PPTX
Building the Internet of Things with Thingsquare and Contiki - day 1, part 3
PDF
Blending django, Sockjs, Twisted, Celery, FTP and some magic sauce into a bla...
PPTX
Realtime web2012
PPTX
Using Coroutines to Create Efficient, High-Concurrency Web Applications
PDF
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
PDF
Django at Scale
PDF
Python for IoT, A return of experience
PDF
Using Python for IoT: a return of experience, Alexandre Abadie
PDF
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
PDF
Elegant concurrency
PPTX
Connecting Stuff to Azure (IoT)
PDF
Twisted中文
PPTX
5-Tut3_Networking_with_Python.pptx good intro
PDF
IoT Prototyping using BBB and Debian
How we use Twisted in Launchpad
Twisted
Twisted logic
Twisted: a quick introduction
Python twisted
Scaling Django with gevent
Building the Internet of Things with Thingsquare and Contiki - day 1, part 3
Blending django, Sockjs, Twisted, Celery, FTP and some magic sauce into a bla...
Realtime web2012
Using Coroutines to Create Efficient, High-Concurrency Web Applications
Asynchronous Architectures for Implementing Scalable Cloud Services - Evan Co...
Django at Scale
Python for IoT, A return of experience
Using Python for IoT: a return of experience, Alexandre Abadie
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
Elegant concurrency
Connecting Stuff to Azure (IoT)
Twisted中文
5-Tut3_Networking_with_Python.pptx good intro
IoT Prototyping using BBB and Debian

Recently uploaded (20)

PPTX
L1 - Introduction to python Backend.pptx
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
top salesforce developer skills in 2025.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
Online Work Permit System for Fast Permit Processing
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
AI in Product Development-omnex systems
L1 - Introduction to python Backend.pptx
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
ManageIQ - Sprint 268 Review - Slide Deck
VVF-Customer-Presentation2025-Ver1.9.pptx
Odoo POS Development Services by CandidRoot Solutions
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Upgrade and Innovation Strategies for SAP ERP Customers
CHAPTER 2 - PM Management and IT Context
top salesforce developer skills in 2025.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Design an Analysis of Algorithms II-SECS-1021-03
How Creative Agencies Leverage Project Management Software.pdf
Online Work Permit System for Fast Permit Processing
2025 Textile ERP Trends: SAP, Odoo & Oracle
AI in Product Development-omnex systems

Building an inflight entertainment system controller in twisted

  • 1. TWISTED AS AN IOT CONTROLLER. BUILDING A 300+ SEAT IFE CONTROLLER IN TWISTED. David P. Novakovic / @dpn / dpn.name
  • 2. QUICK OVERVIEW WTF is Twisted? IFE System Devices IFE System requirements Code examples
  • 3. TWISTED THE SLAYER OF NOOBS SUPER POWERFUL ALSO CONTROVERSIAL Seems to have a bad rep with people who don't use it.
  • 4. TWISTED event driven framework in python particular focus on networking related things from web down to serial ports, tun/tap and udev async io - single process can handle thousands of concurrent open connections on a low end machine Clean APIs for both callbacks and deferreds thread pool with deferred interface locking "primitives" - DeferredSemaphore, DeferredLock, DeferredQueue
  • 5. MORE TWISTED Application framework Async unit testing Integration with most major event loops (wx/gtk/qt/gevent/etc) third party libs klein - sinatra/flask style web framework cyclone - tornado port to twisted treq - "requests" style lib ampoule - nice enough (if slightly neglected) process pool implementation
  • 7. TRADITIONAL "dumb" screens heavy use of streaming content very heavy requirements on servers very expensive to upgrade GLIDE Heavier clients system can be upgraded by replacing players plane doesnt need rewiring etc server can remain fairly unchanged more importantly don't need to be upgraded in lockstep
  • 8. GLIDE SOLUTION players - embedded debian seat disconnect - custom embedded device triple redundant power supplies - switch + power cm controller - dual core atom running ubuntu LTS + lots of embedded things attached
  • 10. SOME RELEVANT REQUIREMENTS multicast commands out to embedded devices 300+ seat updates over HTTP every second listen to audio stream over multicast (PA, pilot etc) low latency control of players ie. if pilot talks/decomp telneting into a streaming VLC process. some legacy - sync code needed to run in threads respond to and control hardware in the plane (overhead screens etc) cabin crew inserting HDD with content (lock down usb) downloading content from the web (at gate) kiosk (lock down control keys/usb ports) manhole for debugging a running process ssh reverse tunnel for remote access - conch tftp - firmware updates to players
  • 11. MULTICAST from twisted.internet import reactor, task, protocol class MulticastSeatControl(protocol.DatagramProtocol): def startProtocol(self): self.transport.joinGroup("228.0.0.5") def sendSeatControl(self, bytes): self.transport.write(bytes, ("228.0.0.5", 8005)) def datagramReceived(self, datagram, address): print "Datagram %s from %s" % (repr(datagram), repr(address))
  • 12. HTTP INTERFACE import json from klein import Klein class DeviceAPI(object): app = Klein() def __init__(self, cmc): self._cmc = {} @app.route('/stat/<string:name>') def stat(self, request): body = json.loads(request.content.read()) self._cmc.logstat(body['something']) request.setHeader('Content-Type', 'application/json') return json.dumps({"status": "success"})</string:name>
  • 13. SERIAL PORT from twisted.internet.serialport import SerialPort from twisted.internet import reactor from twisted.protocols.basic import LineReceiver class SensorProtocol(LineReceiver): def connectionMade(self): print "Connected to serial port." def lineReceived(self, line): print "Received line:", line def send_our_command(self, command): self.sendLine("command:%s" % command) def connect_serial_port(): return SerialPort(SensorProtocol(), "/dev/ttyACM0", reactor, 115200, rtscts=False, xonxoff=False, timeout=1)
  • 14. DJANGO WAIT.. WHAT? Yep, ORM is used a fair bit, as is admin.
  • 15. DJANGO from django.core.handlers.wsgi import WSGIHandler from twisted.python import threadpool from twisted.internet import reactor from somewhere import Root def gimme_some_django(): pool = threadpool.ThreadPool() wsgi_resource = wsgi.WSGIResource(reactor, pool, WSGIHandler()) r = Root(wsgi_resource) s = server.Site(r) pool.start() return internet.TCPServer(8082, s) eg. django admin available at http://localhost:8082/admin/ https://github.com/clemesha/twisted-wsgi-django
  • 16. YET MORE class VLCRemoteControlProtocol(LineReceiver): ... class UDevMonitor(abstract.FileDescriptor): ...
  • 17. AND TELNET INTO YOUR OWN PROCESS.. import twisted.manhole.telnet from twisted.internet.endpoints import TCP4ServerEndpoint def start_manhole(service): f = twisted.manhole.telnet.ShellFactory() f.username = "b" f.password = "b" f.namespace["var1"] = service endpoint = TCP4ServerEndpoint(reactor, 7777) endpoint.listen(f)
  • 18. TIE IT ALL TOGETHER Application framework Unit Testing
  • 19. APPLICATION FRAMEWORK TWISTD Daemonises optionally pidfile log files Error catchall http://twistedmatrix.com/documents/13.2.0/core/howto/basics.html
  • 20. CREATE SERVICES class IOTCServer(Service): def startService(self): self.serialport = connect_serial_port() p = MulticastSeatControl() reactor.listenMulticast(8005, p) start_manhole(self) self.mc_looper = task.LoopingCall(p.sendSeatControl, "s1:on,s2:on") self.mc_looper.start(1) def stopService(self): self.serialport.transport.loseConnection() self.mc_looper.stop() def get_http_service(iots_instance): device_api = DeviceAPI(iots_instance) server.Site(device.api.app.resource()) return internet.TCPServer(8082)
  • 21. TWISTD PLUGIN class Options(usage.Options): optParameters = [["serialport", "s", "/dev/ttyACM0", "Serial port."] class ServiceMaker(object): tapname = "iotc" description = "The IOTC Server" options = Options def makeService(self, options): service_parent = service.MultiService() iots = IOTCServer() iots.setServiceParent(service_parent) http_service = get_http_service() http_service.setServiceParent(service_parent) django_service = gimme_some_django() django_service.setServiceParent(service_parent) return service_parent serviceMaker = ServiceMaker() yourproject/twisted/plugins/iotc_plugin.py $ twistd -r epoll -n iotc --serialport=/dev/ttyACM0
  • 22. UNIT TESTING Twisted Trial Wrapper around pyunit "unittest" Allows tests to return deferred responses subclass twisted.trial.unittest.TestCase run tests: trial yourpackage Some helpers to let you mock wire-level connections http://twistedmatrix.com/documents/11.1.0/core/howto/trial.html
  • 23. BUILD AWESOME THINGS! DIGECOR IS HIRING If you enjoy working on this kind of stuff, let me know and I'll forward your details onto digEcor. @dpn
  • 24. THE END DAVID NOVAKOVIC - DPN.NAME