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

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 

Recently uploaded (20)

HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 

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