Understanding the Adafruit DHT Library

I was working on a getting an IoT demo running on the raspberry pi and so I downloaded the Adafruit DHT library. I want to be able to create libraries like this in future so I took a peek inside.

The Adafruit DHT library is written in Python with C extensions. The C code is used to communicate directly to the DHT sensor and I would assume the reason for this is that C code is faster than Python code in general (always? ). The Python code is written with several layers and it works with the Raspberry Pi 1, the Raspberry Pi 2 and the Beaglebone black.

DescriptionOfCodeStructure

It starts with the __init__.py file. This file contains just one line of code

from common import DHT11, DHT22, AM2302, read, read_retry

The point of this is to make it possible to refer to Adafruit_DHT.read(). The common.py file detects the platform on which the program is run ( Pi 1, Pi2, or Beaglebone) and then call the appropriate read function for each one. Platform specific code is under the files named Raspberry_Pi.py, Raspberry_Pi_2.py and the Beaglebone_black.py. These files are now used to make calls to C extensions installed by setup.py. setup.py installs C extensions based on _Raspberry_Pi.cĀ and other files on the same level (check the diagram). _Raspberry_Pi.c contain details of the interface between the C and Python code. pi_dht_read.c takes care of communication with the DHT sensor. The pi_mmio.c is a fast memory-map for memory-mapped io (I am yet to understand why this is required or what it really means).

What I liked was the beauty and the structure of the program, it was very well organized and it reminds me of one of the lessons I learnt from SICP about how programs are built in layers of abstraction. As it is, it wont be hard to extend this library for another platform just because of the way it is written. Bravo!

I need to imbibe and do this in my own programs

You can find the code on github here