SlideShare a Scribd company logo
1 of 24
Download to read offline
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

What's hot

Monitoring with Syslog and EventMachine
Monitoring with Syslog and EventMachineMonitoring with Syslog and EventMachine
Monitoring with Syslog and EventMachineWooga
 
Windows persistence presentation
Windows persistence presentationWindows persistence presentation
Windows persistence presentationOlehLevytskyi1
 
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru OtsukaTake a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru OtsukaCODE BLUE
 
Fedora Atomic Workshop handout for Fudcon Pune 2015
Fedora Atomic Workshop handout for Fudcon Pune  2015Fedora Atomic Workshop handout for Fudcon Pune  2015
Fedora Atomic Workshop handout for Fudcon Pune 2015rranjithrajaram
 
Troubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversTroubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversSatpal Parmar
 
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCanSecWest
 
Asynchronous Io Programming
Asynchronous Io ProgrammingAsynchronous Io Programming
Asynchronous Io Programmingl xf
 
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...CODE BLUE
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationMohammed Farrag
 
Possibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented ProgrammingPossibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented Programmingkozossakai
 

What's hot (20)

Monitoring with Syslog and EventMachine
Monitoring with Syslog and EventMachineMonitoring with Syslog and EventMachine
Monitoring with Syslog and EventMachine
 
Mini CTF workshop dump
Mini CTF workshop dumpMini CTF workshop dump
Mini CTF workshop dump
 
Basic onos-tutorial
Basic onos-tutorialBasic onos-tutorial
Basic onos-tutorial
 
Windows persistence presentation
Windows persistence presentationWindows persistence presentation
Windows persistence presentation
 
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru OtsukaTake a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
Take a Jailbreak -Stunning Guards for iOS Jailbreak- by Kaoru Otsuka
 
Topo gigio
Topo gigioTopo gigio
Topo gigio
 
Fedora Atomic Workshop handout for Fudcon Pune 2015
Fedora Atomic Workshop handout for Fudcon Pune  2015Fedora Atomic Workshop handout for Fudcon Pune  2015
Fedora Atomic Workshop handout for Fudcon Pune 2015
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Os Cook
Os CookOs Cook
Os Cook
 
Fabric Fast & Furious edition
Fabric Fast & Furious editionFabric Fast & Furious edition
Fabric Fast & Furious edition
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Hands-on ethernet driver
Hands-on ethernet driverHands-on ethernet driver
Hands-on ethernet driver
 
Troubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device DriversTroubleshooting Linux Kernel Modules And Device Drivers
Troubleshooting Linux Kernel Modules And Device Drivers
 
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershellCSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
CSW2017 Amanda rousseau cansecwest2017_net_hijacking_powershell
 
Monit
MonitMonit
Monit
 
Linux administration ii-parti
Linux administration ii-partiLinux administration ii-parti
Linux administration ii-parti
 
Asynchronous Io Programming
Asynchronous Io ProgrammingAsynchronous Io Programming
Asynchronous Io Programming
 
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
 
Possibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented ProgrammingPossibility of arbitrary code execution by Step-Oriented Programming
Possibility of arbitrary code execution by Step-Oriented Programming
 

Viewers also liked

啄木鸟Twisted
啄木鸟Twisted啄木鸟Twisted
啄木鸟TwistedXuYj
 
OSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityOSCon - Performance vs Scalability
OSCon - Performance vs ScalabilityGleicon Moraes
 
GEE_OVERVIEW_SALESSHEET
GEE_OVERVIEW_SALESSHEETGEE_OVERVIEW_SALESSHEET
GEE_OVERVIEW_SALESSHEETSayli Warde
 
3rd International Conference IFE & Connectivity, 24 – 26 March 2015, Hamburg ...
3rd International Conference IFE & Connectivity, 24 – 26 March 2015, Hamburg ...3rd International Conference IFE & Connectivity, 24 – 26 March 2015, Hamburg ...
3rd International Conference IFE & Connectivity, 24 – 26 March 2015, Hamburg ...Torben Haagh
 
A revolution in the air: Mary Kirby, Runway Girl Network
 A revolution in the air: Mary Kirby, Runway Girl Network A revolution in the air: Mary Kirby, Runway Girl Network
A revolution in the air: Mary Kirby, Runway Girl NetworkSITA
 
Обзор фреймворка Twisted
Обзор фреймворка TwistedОбзор фреймворка Twisted
Обзор фреймворка TwistedPython Meetup
 
Asynchronous Python with Twisted
Asynchronous Python with TwistedAsynchronous Python with Twisted
Asynchronous Python with TwistedAdam Englander
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Smart Airplanes. Creating Connections.
Smart Airplanes. Creating Connections.Smart Airplanes. Creating Connections.
Smart Airplanes. Creating Connections.Gogo Business Aviation
 
Android Push Server & MQTT
Android Push Server & MQTTAndroid Push Server & MQTT
Android Push Server & MQTT광운 이
 

Viewers also liked (13)

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

Similar to Building an inflight entertainment system controller in twisted

An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsMarcus Frödin
 
Presentation Lfoppiano Pycon
Presentation Lfoppiano PyconPresentation Lfoppiano Pycon
Presentation Lfoppiano PyconLuca Foppiano
 
Web Applications with Eclipse RT and Docker in the Cloud
Web Applications with Eclipse RT and Docker in the CloudWeb Applications with Eclipse RT and Docker in the Cloud
Web Applications with Eclipse RT and Docker in the CloudMarkus Knauer
 
Linux internet server security and configuration tutorial
Linux internet server security and configuration tutorialLinux internet server security and configuration tutorial
Linux internet server security and configuration tutorialannik147
 
Python twisted
Python twistedPython twisted
Python twistedMahendra M
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)OPNFV
 
Nginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولNginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولefazati
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidenceJohn Congdon
 
JDO 2019: Tips and Tricks from Docker Captain - Łukasz Lach
JDO 2019: Tips and Tricks from Docker Captain - Łukasz LachJDO 2019: Tips and Tricks from Docker Captain - Łukasz Lach
JDO 2019: Tips and Tricks from Docker Captain - Łukasz LachPROIDEA
 
05 module managing your network enviornment
05  module managing your network enviornment05  module managing your network enviornment
05 module managing your network enviornmentAsif
 
Bare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and ChefBare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and ChefMatt Ray
 
Managing Large-scale Networks with Trigger
Managing Large-scale Networks with TriggerManaging Large-scale Networks with Trigger
Managing Large-scale Networks with Triggerjathanism
 
vmaf deployement & upgrade for software projects
vmaf deployement & upgrade for software projectsvmaf deployement & upgrade for software projects
vmaf deployement & upgrade for software projectsThierry Gayet
 
Ato2019 weave-services-istio
Ato2019 weave-services-istioAto2019 weave-services-istio
Ato2019 weave-services-istioLin Sun
 
Weave Your Microservices with Istio
Weave Your Microservices with IstioWeave Your Microservices with Istio
Weave Your Microservices with IstioAll Things Open
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioAll Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioLin Sun
 
Network Automation Tools
Network Automation ToolsNetwork Automation Tools
Network Automation ToolsEdwin Beekman
 

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

An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
Presentation Lfoppiano Pycon
Presentation Lfoppiano PyconPresentation Lfoppiano Pycon
Presentation Lfoppiano Pycon
 
Web Applications with Eclipse RT and Docker in the Cloud
Web Applications with Eclipse RT and Docker in the CloudWeb Applications with Eclipse RT and Docker in the Cloud
Web Applications with Eclipse RT and Docker in the Cloud
 
Linux internet server security and configuration tutorial
Linux internet server security and configuration tutorialLinux internet server security and configuration tutorial
Linux internet server security and configuration tutorial
 
moscmy2016: Extending Docker
moscmy2016: Extending Dockermoscmy2016: Extending Docker
moscmy2016: Extending Docker
 
Python twisted
Python twistedPython twisted
Python twisted
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)How Many Ohs? (An Integration Guide to Apex & Triple-o)
How Many Ohs? (An Integration Guide to Apex & Triple-o)
 
Nginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصولNginx وب سروری برای تمام فصول
Nginx وب سروری برای تمام فصول
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
JDO 2019: Tips and Tricks from Docker Captain - Łukasz Lach
JDO 2019: Tips and Tricks from Docker Captain - Łukasz LachJDO 2019: Tips and Tricks from Docker Captain - Łukasz Lach
JDO 2019: Tips and Tricks from Docker Captain - Łukasz Lach
 
05 module managing your network enviornment
05  module managing your network enviornment05  module managing your network enviornment
05 module managing your network enviornment
 
Bare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and ChefBare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and Chef
 
Managing Large-scale Networks with Trigger
Managing Large-scale Networks with TriggerManaging Large-scale Networks with Trigger
Managing Large-scale Networks with Trigger
 
vmaf deployement & upgrade for software projects
vmaf deployement & upgrade for software projectsvmaf deployement & upgrade for software projects
vmaf deployement & upgrade for software projects
 
Ato2019 weave-services-istio
Ato2019 weave-services-istioAto2019 weave-services-istio
Ato2019 weave-services-istio
 
Weave Your Microservices with Istio
Weave Your Microservices with IstioWeave Your Microservices with Istio
Weave Your Microservices with Istio
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioAll Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istio
 
Network Automation Tools
Network Automation ToolsNetwork Automation Tools
Network Automation Tools
 

Recently uploaded

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 

Recently uploaded (20)

Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 

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