SlideShare a Scribd company logo
Speak Python with Devices
Petertc Chu @ EuroPython 2020
We will see:
● How Python can be used in IoT/infrastructure automation tasks
You might:
● wish to know how Python can be used beyond data analysis and web dev
● a Pythonista who interested in craft some touchable things 🚂🚂🚂
● want to acquire something new into your Python skillset 💪💪💪
Why this session?
Outline
● Devices in Linux/UNIX-like system
● How to manipulate a device
● Manipulate a device in Python, a mini example
● A more attractive example
Computer oganization, briefly
User space
Hardware LED panel, camera and sensors on bluetooth/USB/serial/parallel ports...
Kernel space Driver of LED panel, camera, sensors and other devices...
device files in the /dev/ directory
Your Python interpreter, packages and code here
Everything is a file, so is a
device
Manipulate a device
with common file operations:
● open()
● write()
● read()
● close()
and a more interesting one...
Example: blink an LED on Raspberry Pi
IOCTL()
Input Output ConTroL
Read/write is not enough for a device which is more complex than an LED
Example: a modem
● READ - reveive data
● WRITE - send data
● IOCTL - talk to the modem itself, e.g., set bitrate, get config
IOCTL - What? Why?
IOCTL - Decoration
#include <sys/ioctl.h>
int ioctl(int fd, unsigned long request, ...);
file descriptor arguments
request (direction, type,
number, argument size)
● file descriptor
● request
○ a.k.a. (device-dependent) request code or command
○ composed of:
■ type (8 bits, a~z)
■ number (8 bits, 1~255)
■ argument size (14 bits, max 16KB)
■ direction (2 bits, R/W/RW/NONE)
● argument (string, a C struct or anything)
IOCTL - Parameters
An analogy
PUT /myBucket/my-object.jpg HTTP/1.1
Host: s3.amazonaws.com
Date: Fri, 24 Jul 2020 06:00:00 GMT
Authorization: authorization string
Content-Type: text/plain
Content-Length: 11434
x-amz-meta-author: Janet
Expect: 100-continue
[11434 bytes of object data]
file descriptor
direction type number
argument size
arguments
request (direction, type,
number, argument size)
just like RESTful APIs
we use every day!
“DON’T PANIC!”
IOCTL 💛 Python
Let’s start from a mini example:
Get the name of input devices
Do IOCTL() from Python
Things to do:
● Create an IOCTL request (header)
● C<->Py type convertion (body)
● Do IOCTL system call
(At least) two approaches:
● C extension module
● Pure Python solution
Approach 1: C extension module
Step 1: IOCTL call
Create IOCTL request (header) by macros
Approach 1: C extension module
Step 2: C<->Py type convertion (req/resp body)
Approach 1: C extension module
Step 3: packaging
Approach 1: C extension module
Install and use it as usual
Approach 2: Pure Python solution
Step 1: Create an IOCTL request (header)
● porting IOC* macros from asm-generic/ioctl.h => Someone has already done it!
○ olavmrk/python-ioctl
○ vpelletier/python-ioctl-opt
● porting driver specific macros
Courtesy of
vpelletier/python-ioctl-opt/blob/master/README.rst
Approach 2: Pure Python solution
Step 2: ioctl call and C<-> data type convertion
Use build-in module
byte array <-> str
macro we implemented in
the first step
Approach 2: Pure Python solution
Same result we saw before
Question: any use case? 🤔
OK now I know how these things work but...
Raspberry Pi + ?
Hmm… good for demonstration, boring
to be a use case.
https://zh.wikipedia.org/wiki/%E6%A0%91%E8%8E%93%E6%B4
%BE#/media/File:Raspberry_Pi_4_Model_B_-_Side.jpg
The CERN Advanced STORage system (CASTOR)
http://storageconference.us/2010/Presentations/MSST/15.Bah
yl.pdf
http://castor.web.cern.ch/castor/
https://youtu.be/IDgXa0ioVTs
Explore the universe 🚀
with what we learn today!
Quick start
● Device: mhVTL simulated
● Driver: Linux SCSI tape (st) device driver
Quick start
Typical tape write procedure:
1. Find the cartridge by barcode scanner
2. Load the cartridge by a robot arm
3. Check the cartridge status is ready
4. Rewind the cartridge by a tape drive
5. Write data on the cartridge
6. Unload the cartridge
👈 👈 👈 What we're gonna do today
👇 👇 👇
Snippet 1:
Get tape status
by C extension
// open device file
int fd;
if ((fd = open(device, O_RDONLY)) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
// execute ioctl command
struct mtget status;
if (ioctl(fd, MTIOCGET, (char *)&status) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (status.mt_type != MT_ISSCSI2) {
PyErr_SetString(PyExc_NotImplementedError, "Unsupported tape
type");
return NULL;
}
close(fd);
// return status info in dict
return Py_BuildValue("{s:i,s:i,s:i}",
"file number", status.mt_fileno,
"block number", status.mt_blkno,
"partition", (status.mt_resid & 0xff)
);
}
Snippet 2:
use struct
Convert function arguments back and
forth. struct.pack() and
struct.unpack() are your friends
here.
def rewind(device):
MTREW = 6
mt_com = struct.pack('hi', MTREW, 1)
MTIOCTOP = IOW(ord('m'), 1, len(mt_com))
with open(device, 'r') as fd:
fcntl.ioctl(fd, MTIOCTOP, mt_com)
def status(device):
long_size = 8
int_size = 4
status = bytearray(long_size * 5 + int_size * 2)
MTIOCGET = IOR(ord('m'), 2, len(status))
with open(device, 'r') as fd:
fcntl.ioctl(fd, MTIOCGET, status)
status = struct.unpack('lllllii', status)
return {
"file number": status[-2],
"block number": status[-1],
"partition": status[1] & 0xff
}
Bonus:
rewind cartridge
by ctypes
Define input/output/buffer data
structure by extending
ctypes.Structure
class mtop(ctypes.Structure):
_fields_ = [
("mt_op", ctypes.c_short),
("mt_count", ctypes.c_int)
]
def rewind(device):
MTIOCTOP = ioctl.linux.IOW('m', 1, ctypes.sizeof(mtop))
MTREW = 6
mt_com = mtop(MTREW, 1)
with open(device, 'r') as fd:
ioctl.ioctl(fd.fileno(), MTIOCTOP,
ctypes.byref(mt_com))
Example code is available on https://github.com/hrchu/playioctl
Takeaway
● You can manipulate a device like a file
● IOCTL is just like RESTful APIs we use every day
● Yes, we can speak Python while working on IoT and
infra automation tasks
Thank you! 🙏🙏🙏
@petertc_chu

More Related Content

PDF
PyConline AU 2021 - Things might go wrong in a data-intensive application
PDF
PyCon HK 2018 - Heterogeneous job processing with Apache Kafka
PDF
Large Scale Processing of Unstructured Text
PDF
Deep Postgres Extensions in Rust | PGCon 2019 | Jeff Davis
PDF
The Materials Project - Combining Science and Informatics to Accelerate Mater...
PDF
Collaborative Real-Time Editing: Shane Carr
PDF
NANO266 - Lecture 9 - Tools of the Modeling Trade
PyConline AU 2021 - Things might go wrong in a data-intensive application
PyCon HK 2018 - Heterogeneous job processing with Apache Kafka
Large Scale Processing of Unstructured Text
Deep Postgres Extensions in Rust | PGCon 2019 | Jeff Davis
The Materials Project - Combining Science and Informatics to Accelerate Mater...
Collaborative Real-Time Editing: Shane Carr
NANO266 - Lecture 9 - Tools of the Modeling Trade

What's hot (20)

PDF
EKAW - Publishing with Triple Pattern Fragments
PDF
Tutorial: Implementing your first Postgres extension | PGConf EU 2019 | Burak...
PDF
Distributed Tracing with OpenTracing, ZipKin and Kubernetes
PDF
IoT Data Connector Fluent Bit
PDF
FireWorks workflow software
PDF
Multidimensional Interfaces for Selecting Data with Order
PDF
Creating Art with a Raspberry Pi - Stephanie Nemeth - Codemotion Amsterdam 2017
PPTX
Hadoop summit 2016
PDF
Strata Beijing 2017: Jumpy, a python interface for nd4j
PDF
Scikit-learn: the state of the union 2016
PPTX
JOnConf - A CDC use-case: designing an Evergreen Cache
PDF
MAVRL Workshop 2014 - Python Materials Genomics (pymatgen)
PDF
Anomaly Detection and Automatic Labeling with Deep Learning
PDF
Luigi presentation NYC Data Science
PDF
MAVRL Workshop 2014 - pymatgen-db & custodian
PDF
FireWorks overview
PPTX
Jonathan Coveney: Why Pig?
PDF
Pyparis2017 / Scikit-learn - an incomplete yearly review, by Gael Varoquaux
PDF
Fluent-bit
PDF
Atomate: a high-level interface to generate, execute, and analyze computation...
EKAW - Publishing with Triple Pattern Fragments
Tutorial: Implementing your first Postgres extension | PGConf EU 2019 | Burak...
Distributed Tracing with OpenTracing, ZipKin and Kubernetes
IoT Data Connector Fluent Bit
FireWorks workflow software
Multidimensional Interfaces for Selecting Data with Order
Creating Art with a Raspberry Pi - Stephanie Nemeth - Codemotion Amsterdam 2017
Hadoop summit 2016
Strata Beijing 2017: Jumpy, a python interface for nd4j
Scikit-learn: the state of the union 2016
JOnConf - A CDC use-case: designing an Evergreen Cache
MAVRL Workshop 2014 - Python Materials Genomics (pymatgen)
Anomaly Detection and Automatic Labeling with Deep Learning
Luigi presentation NYC Data Science
MAVRL Workshop 2014 - pymatgen-db & custodian
FireWorks overview
Jonathan Coveney: Why Pig?
Pyparis2017 / Scikit-learn - an incomplete yearly review, by Gael Varoquaux
Fluent-bit
Atomate: a high-level interface to generate, execute, and analyze computation...
Ad

Similar to EuroPython 2020 - Speak python with devices (20)

PDF
Taipei.py 2018 - Control device via ioctl from Python
PPTX
Python-in-Embedded-systems.pptx
PDF
Iot Bootcamp - abridged - part 1
PDF
Getting Started with Embedded Python: MicroPython and CircuitPython
ODP
MicroPython&electronics prezentācija
PDF
Hardware hacking
PDF
Intro to the raspberry pi board
PDF
Tangible Tools For Teaching With Python
PPTX
5-Tut3_Networking_with_Python.pptx good intro
PDF
Getting Started with MicroPython and LoPy
PDF
IoT: Internet of Things with Python
PPTX
Serial Data from Arduino to Raspberry Pi to MySQL using CoAP Protocol
PDF
PyCon_India_2017_MicroPython_Ayan
PDF
Security System with PIR sensor and Raspberry Pi
PDF
Micropython for the iot
PDF
DEF CON 27 - PHILIPPE LAULHERET - introduction to hardware hacking extended v...
PDF
Using ARM Dev.Board in physical experimental instruments
PPTX
IoT for data science Module 5 - Raspberry Pi.pptx
PPTX
embedded system with raspberry piVarun[1].pptx
PPTX
teststststststLecture_3_2022_Arduino.pptx
Taipei.py 2018 - Control device via ioctl from Python
Python-in-Embedded-systems.pptx
Iot Bootcamp - abridged - part 1
Getting Started with Embedded Python: MicroPython and CircuitPython
MicroPython&electronics prezentācija
Hardware hacking
Intro to the raspberry pi board
Tangible Tools For Teaching With Python
5-Tut3_Networking_with_Python.pptx good intro
Getting Started with MicroPython and LoPy
IoT: Internet of Things with Python
Serial Data from Arduino to Raspberry Pi to MySQL using CoAP Protocol
PyCon_India_2017_MicroPython_Ayan
Security System with PIR sensor and Raspberry Pi
Micropython for the iot
DEF CON 27 - PHILIPPE LAULHERET - introduction to hardware hacking extended v...
Using ARM Dev.Board in physical experimental instruments
IoT for data science Module 5 - Raspberry Pi.pptx
embedded system with raspberry piVarun[1].pptx
teststststststLecture_3_2022_Arduino.pptx
Ad

More from Hua Chu (6)

PDF
CYBERSEC2025 - 生成式 AI 合規技術與挑戰 / Gen AI: Risks and Compliance Strategies
PDF
COSCUP2024 - SCaLE:打開北美開源世界的大門 / Insights from SCaLE and Beyond
PDF
TANET 2018 - Insights into the reliability of open-source distributed file sy...
PPTX
Apache spot 系統架構
PPTX
Apache spot 初步瞭解
PDF
TWJUG 2016 - Mogilefs, 簡約可靠的儲存方案
CYBERSEC2025 - 生成式 AI 合規技術與挑戰 / Gen AI: Risks and Compliance Strategies
COSCUP2024 - SCaLE:打開北美開源世界的大門 / Insights from SCaLE and Beyond
TANET 2018 - Insights into the reliability of open-source distributed file sy...
Apache spot 系統架構
Apache spot 初步瞭解
TWJUG 2016 - Mogilefs, 簡約可靠的儲存方案

Recently uploaded (20)

PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
medical staffing services at VALiNTRY
PPTX
L1 - Introduction to python Backend.pptx
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
System and Network Administration Chapter 2
PDF
top salesforce developer skills in 2025.pdf
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Digital Strategies for Manufacturing Companies
PPTX
history of c programming in notes for students .pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Reimagine Home Health with the Power of Agentic AI​
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Softaken Excel to vCard Converter Software.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PTS Company Brochure 2025 (1).pdf.......
wealthsignaloriginal-com-DS-text-... (1).pdf
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
medical staffing services at VALiNTRY
L1 - Introduction to python Backend.pptx
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
System and Network Administration Chapter 2
top salesforce developer skills in 2025.pdf
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Digital Strategies for Manufacturing Companies
history of c programming in notes for students .pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Which alternative to Crystal Reports is best for small or large businesses.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
How to Choose the Right IT Partner for Your Business in Malaysia
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf

EuroPython 2020 - Speak python with devices

  • 1. Speak Python with Devices Petertc Chu @ EuroPython 2020
  • 2. We will see: ● How Python can be used in IoT/infrastructure automation tasks You might: ● wish to know how Python can be used beyond data analysis and web dev ● a Pythonista who interested in craft some touchable things 🚂🚂🚂 ● want to acquire something new into your Python skillset 💪💪💪 Why this session?
  • 3. Outline ● Devices in Linux/UNIX-like system ● How to manipulate a device ● Manipulate a device in Python, a mini example ● A more attractive example
  • 4. Computer oganization, briefly User space Hardware LED panel, camera and sensors on bluetooth/USB/serial/parallel ports... Kernel space Driver of LED panel, camera, sensors and other devices... device files in the /dev/ directory Your Python interpreter, packages and code here
  • 5. Everything is a file, so is a device
  • 6. Manipulate a device with common file operations: ● open() ● write() ● read() ● close() and a more interesting one... Example: blink an LED on Raspberry Pi
  • 8. Input Output ConTroL Read/write is not enough for a device which is more complex than an LED Example: a modem ● READ - reveive data ● WRITE - send data ● IOCTL - talk to the modem itself, e.g., set bitrate, get config IOCTL - What? Why?
  • 9. IOCTL - Decoration #include <sys/ioctl.h> int ioctl(int fd, unsigned long request, ...); file descriptor arguments request (direction, type, number, argument size)
  • 10. ● file descriptor ● request ○ a.k.a. (device-dependent) request code or command ○ composed of: ■ type (8 bits, a~z) ■ number (8 bits, 1~255) ■ argument size (14 bits, max 16KB) ■ direction (2 bits, R/W/RW/NONE) ● argument (string, a C struct or anything) IOCTL - Parameters
  • 11. An analogy PUT /myBucket/my-object.jpg HTTP/1.1 Host: s3.amazonaws.com Date: Fri, 24 Jul 2020 06:00:00 GMT Authorization: authorization string Content-Type: text/plain Content-Length: 11434 x-amz-meta-author: Janet Expect: 100-continue [11434 bytes of object data] file descriptor direction type number argument size arguments request (direction, type, number, argument size)
  • 12. just like RESTful APIs we use every day! “DON’T PANIC!”
  • 14. Let’s start from a mini example: Get the name of input devices
  • 15. Do IOCTL() from Python Things to do: ● Create an IOCTL request (header) ● C<->Py type convertion (body) ● Do IOCTL system call (At least) two approaches: ● C extension module ● Pure Python solution
  • 16. Approach 1: C extension module Step 1: IOCTL call Create IOCTL request (header) by macros
  • 17. Approach 1: C extension module Step 2: C<->Py type convertion (req/resp body)
  • 18. Approach 1: C extension module Step 3: packaging
  • 19. Approach 1: C extension module Install and use it as usual
  • 20. Approach 2: Pure Python solution Step 1: Create an IOCTL request (header) ● porting IOC* macros from asm-generic/ioctl.h => Someone has already done it! ○ olavmrk/python-ioctl ○ vpelletier/python-ioctl-opt ● porting driver specific macros Courtesy of vpelletier/python-ioctl-opt/blob/master/README.rst
  • 21. Approach 2: Pure Python solution Step 2: ioctl call and C<-> data type convertion Use build-in module byte array <-> str macro we implemented in the first step
  • 22. Approach 2: Pure Python solution Same result we saw before
  • 23. Question: any use case? 🤔 OK now I know how these things work but...
  • 24. Raspberry Pi + ? Hmm… good for demonstration, boring to be a use case. https://zh.wikipedia.org/wiki/%E6%A0%91%E8%8E%93%E6%B4 %BE#/media/File:Raspberry_Pi_4_Model_B_-_Side.jpg
  • 25. The CERN Advanced STORage system (CASTOR) http://storageconference.us/2010/Presentations/MSST/15.Bah yl.pdf http://castor.web.cern.ch/castor/ https://youtu.be/IDgXa0ioVTs
  • 26. Explore the universe 🚀 with what we learn today!
  • 27. Quick start ● Device: mhVTL simulated ● Driver: Linux SCSI tape (st) device driver
  • 28. Quick start Typical tape write procedure: 1. Find the cartridge by barcode scanner 2. Load the cartridge by a robot arm 3. Check the cartridge status is ready 4. Rewind the cartridge by a tape drive 5. Write data on the cartridge 6. Unload the cartridge 👈 👈 👈 What we're gonna do today 👇 👇 👇
  • 29. Snippet 1: Get tape status by C extension // open device file int fd; if ((fd = open(device, O_RDONLY)) < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } // execute ioctl command struct mtget status; if (ioctl(fd, MTIOCGET, (char *)&status) < 0) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } if (status.mt_type != MT_ISSCSI2) { PyErr_SetString(PyExc_NotImplementedError, "Unsupported tape type"); return NULL; } close(fd); // return status info in dict return Py_BuildValue("{s:i,s:i,s:i}", "file number", status.mt_fileno, "block number", status.mt_blkno, "partition", (status.mt_resid & 0xff) ); }
  • 30. Snippet 2: use struct Convert function arguments back and forth. struct.pack() and struct.unpack() are your friends here. def rewind(device): MTREW = 6 mt_com = struct.pack('hi', MTREW, 1) MTIOCTOP = IOW(ord('m'), 1, len(mt_com)) with open(device, 'r') as fd: fcntl.ioctl(fd, MTIOCTOP, mt_com) def status(device): long_size = 8 int_size = 4 status = bytearray(long_size * 5 + int_size * 2) MTIOCGET = IOR(ord('m'), 2, len(status)) with open(device, 'r') as fd: fcntl.ioctl(fd, MTIOCGET, status) status = struct.unpack('lllllii', status) return { "file number": status[-2], "block number": status[-1], "partition": status[1] & 0xff }
  • 31. Bonus: rewind cartridge by ctypes Define input/output/buffer data structure by extending ctypes.Structure class mtop(ctypes.Structure): _fields_ = [ ("mt_op", ctypes.c_short), ("mt_count", ctypes.c_int) ] def rewind(device): MTIOCTOP = ioctl.linux.IOW('m', 1, ctypes.sizeof(mtop)) MTREW = 6 mt_com = mtop(MTREW, 1) with open(device, 'r') as fd: ioctl.ioctl(fd.fileno(), MTIOCTOP, ctypes.byref(mt_com))
  • 32. Example code is available on https://github.com/hrchu/playioctl Takeaway ● You can manipulate a device like a file ● IOCTL is just like RESTful APIs we use every day ● Yes, we can speak Python while working on IoT and infra automation tasks