# Chapter 20: Python and IoT

Python is a popular language in the Internet of Things (IoT) ecosystem due to its simplicity and extensive library support. It enables the development of applications that interact with sensors, actuators, and other devices to build IoT solutions.

***

#### Using Python on IoT Devices

Python is commonly used on devices like Raspberry Pi and Arduino to control and manage IoT hardware.

**Setting Up Python on Raspberry Pi**

1. Install Raspbian OS on the Raspberry Pi.
2. Python comes pre-installed on Raspbian.
3. Update Python:

   ```bash
   sudo apt update
   sudo apt install python3
   ```

**Example: Blinking an LED with Raspberry Pi**

```python
import RPi.GPIO as GPIO
import time

# Set up GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

# Blink LED
for _ in range(5):
    GPIO.output(18, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(18, GPIO.LOW)
    time.sleep(1)

GPIO.cleanup()
```

***

#### Working with Sensors and Actuators

Python libraries like `Adafruit_DHT` and `smbus` allow interaction with various sensors and actuators.

**Example: Reading Temperature and Humidity**

Install the `Adafruit_DHT` library:

```bash
pip install Adafruit_DHT
```

```python
import Adafruit_DHT

# Sensor type and GPIO pin
sensor = Adafruit_DHT.DHT22
pin = 4

# Read data
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
    print(f"Temp: {temperature:.1f} C  Humidity: {humidity:.1f}%")
else:
    print("Failed to retrieve data from the sensor")
```

**Example: Controlling a Servo Motor**

```python
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

# Set up PWM
pwm = GPIO.PWM(18, 50)  # 50 Hz
pwm.start(0)

# Rotate servo
pwm.ChangeDutyCycle(7)  # Middle position
time.sleep(1)

pwm.ChangeDutyCycle(12)  # Right position
time.sleep(1)

pwm.ChangeDutyCycle(2)  # Left position
time.sleep(1)

pwm.stop()
GPIO.cleanup()
```

***

#### IoT Protocols

IoT devices communicate using protocols like MQTT and HTTP.

**MQTT with Python**

Install the `paho-mqtt` library:

```bash
pip install paho-mqtt
```

**Example: Publish and Subscribe**

```python
import paho.mqtt.client as mqtt

# Callback for when a message is received
def on_message(client, userdata, message):
    print(f"Received message: {message.payload.decode()}")

# Connect to broker
client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883, 60)

# Subscribe to topic
client.subscribe("test/topic")

# Publish a message
client.publish("test/topic", "Hello, MQTT")

# Loop forever
client.loop_forever()
```

***

#### Building an IoT Project

**Example: Home Automation System**

1. **Sensors**: Read temperature and humidity.
2. **Actuators**: Control a fan and light.
3. **Server**: Send data to a cloud server using HTTP.

**Example Code:**

```python
import requests
import Adafruit_DHT
import RPi.GPIO as GPIO

# Set up GPIO and sensor
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)  # Fan
sensor = Adafruit_DHT.DHT22
pin = 4

# Read data
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if temperature > 30:
    GPIO.output(18, GPIO.HIGH)  # Turn on fan
else:
    GPIO.output(18, GPIO.LOW)  # Turn off fan

# Send data to server
payload = {"temperature": temperature, "humidity": humidity}
response = requests.post("http://example.com/api/data", json=payload)
print(response.status_code)

GPIO.cleanup()
```

***

#### Exercises

**Exercise 1: Monitor Temperature**

Write a script to monitor temperature and print an alert if it exceeds 35°C.

**Solution:**

```python
import Adafruit_DHT

sensor = Adafruit_DHT.DHT22
pin = 4

while True:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    if temperature > 35:
        print("Alert! High temperature detected.")
```

***

**Exercise 2: Automate LED Control**

Write a script to turn an LED on or off based on user input.

**Solution:**

```python
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

while True:
    command = input("Enter 'on' to turn on LED, 'off' to turn off, 'quit' to exit: ").strip().lower()
    if command == "on":
        GPIO.output(18, GPIO.HIGH)
    elif command == "off":
        GPIO.output(18, GPIO.LOW)
    elif command == "quit":
        break

GPIO.cleanup()
```

***

#### Best Practices

1. Use proper GPIO cleanup to avoid pin conflicts.
2. Secure IoT devices with firewalls and encrypted communication.
3. Test sensor and actuator configurations thoroughly.
4. Follow energy-efficient practices for battery-powered devices.
5. Document hardware setups and code for reproducibility.

In the next chapter, we will explore Python appendices, including cheat sheets, glossaries, and recommended resources to deepen your Python knowledge.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://py.d19.in/chapter-20-python-and-iot.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
