[AIoT] How to use LangChain to Chat with Sensor Data

[AIoT] How to use LangChain to Chat with Sensor Data

January 3, 2024

It all started with the RPi projects I published here about a Pi working together with a DHT22 sensor..

Then, I learnt how to use LangChain to chat with a DB.

The next step is pretty much clear.

To join both worlds.

This is the goal of this post.

To be able to chat with a DB where the DHT22 sensor data (temp and humidity) is being stored.

Chat with DHT22 Sensor

Pre-Requisites

  1. Recommended - Setup Containers for simpler dependency management

  2. Get the DB Ready - We will do it with a MariaDB SQL Container, but you can use a MYSQL container or with MYSQL baremetal as in the initial example post

MariaDB with Docker-Compose 📌

We just need a MariaDB or MySQL container deployed

version: '3'

services:
  mariadb:
    image: mariadb:10.5
    container_name: mariadb-db
    environment:
      - MYSQL_ROOT_PASSWORD=rootpassword
      - MYSQL_DATABASE=chinook
      - MYSQL_USER=myuser
      - MYSQL_PASSWORD=mypassword
    volumes:
      - ./mariadb-data:/var/lib/mysql
    ports:
      - "3306:3306"
docker-compose up -d

Once the DB container is running:

docker exec -it mariadb-db bash
#mysql -u root -p

# CREATE DATABASE chinook;
# USE chinook;
# SOURCE /path/to/chinook.sql; -- Update this path to your SQL file
# SOURCE /path/to/Chinook_MySql.sql; -- Update this path to your SQL file if needed

#SHOW TABLES;

Part 1 - IoT

Hardware Setup

pinout

Software Setup

We need two things:

  1. The Database (MariaDB / MySQL) to store the IoT data
  2. The Python Script to push the DHT sensor information
pip install -r requirements.txt

#pip install Adafruit_DHT==1.4.0
#pip show Adafruit_DHT

Saving IoT Data

Python | DHT Data to DB 📌
import Adafruit_DHT
import time
import os
import mysql.connector

# Replace with your MySQL connection credentials
MYSQL_HOST = "localhost"
MYSQL_USER = "username"
MYSQL_PASSWORD = "password"
MYSQL_DATABASE = "sensor_data"

DHT_SENSOR = Adafruit_DHT.DHT11  # Example with DHT11, we can use DHT22 as well
DHT_PIN = 4

while True:
    humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)

    if humidity is not None and temperature is not None:
        # Connect to the MySQL database
        try:
            connection = mysql.connector.connect(
                host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DATABASE
            )
            cursor = connection.cursor()

            # Prepare the SQL INSERT statement
            sql = "INSERT INTO dht_sensor (timestamp, temperature, humidity) VALUES (%s, %s, %s)"
            data = (time.strftime("%Y-%m-%dT%H:%M:%SZ"), temperature, humidity)

            # Execute the SQL statement
            cursor.execute(sql, data)
            connection.commit()

            print("Data sent to MySQL")

        except mysql.connector.Error as err:
            print("Error connecting to MySQL database:", err)

        finally:
            if connection:
                connection.cursor().close()
                connection.close()

    else:
        print("Sensor failure. Check wiring.")

    time.sleep(3)
docker build -t dht_sensor_mariadb .

Visualize the IoT Data

Lets use Metabase as BI Tool to visualize the IoT data that we are storing already.

Part 2 - AIoT Setup

Is the IoT Part already working?

Lets go with the AI part.

What it is Pydantic? 📌

Conclusions


FAQ

How to install Adafruit from its source? 📌
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
python3 setup.py install --force-pi

#This will bypass any issues you may encounter when doing pip install Adafuit_DHT==1.4.0

Setup Containers

  • Or just get ready for SelfHosting: