Skip to content
Advertisement

I don’t know how to send sensor data from a Raspberry Pie to MySQL Server with Python

I am working on a project at work and I’m having a little trouble, I have a LAMP server with Ubuntu 18.04 Server installed, on the server side I have a PHP script that implements data received from a client in a table in the MySQL database via a URl. The client I am talking about is a Raspberry Pie 3 connected to a DHT22 sensor via serial.

The problem I’m having now is that I don’t have much experience with Python at all. I have made a script that prints the data from the sensor in the console. But I have no clue how to send that data from the client to the DB.

If I am going to use the PHP script, the client is going to need to print the data in the URl path of the PHP script (like so: http://192.168.0.101?temp=20.1&hum=30.2), but i was hoping if you guy’s could tell me how to do that or if there’s any way I can skip the whole PHP script and implement a way to connect in to the DB and print the data straight in to the table with the Python script.

PHP script i am using:

<?php
  class DBtable {
  public $link='';
  function __construct($temperature, $humidity) {
    $this->connect();
    $this->storeInDB($temperature, $humidity);
  }
  function connect() {
    $this->link = mysqli_connect('localhost','Generic_user','Generic_passwd') or die('Cannot connect to DB');
    mysqli_select_db($this->link,'DBtable') or die('Cannot choose DB.');
  }
  function storeInDB($temperature, $humidity) {
    $query = "insert into DBtable set Hum='".$humidity."', Temp='".$temperature."'";
    $result =mysqli_query($this->link,$query) or die('Errant query: '.$query);
    ("Data was implemented correct! Temp = '".$temperature."'°C og Hum = '".$humidity."'%'");
  }
}
if($_GET['Temp'] != '' and $_GET['Hum'] != '') {
  $DBtable=new DBtable($_GET['Temp'],$_GET['Hum']);
}
?>

(I changed some info for security reasons but I can assure you that I have tested it and it works.)

The script is made originally for an Arduino but I could not get it to work so I switched over to the Raspberry platform.

The Python script on the client:

import Adafruit_DHT as dht
from time import sleep
DHT = 3
while True:
    h,t = dht.read_retry(dht.DHT22, DHT)
    print('temp={0:0.1f}*C hum={1:0.1f}%'.format(temperature, humidity))
    sleep(1)

The output to the console:

temp=20.1*C hum=30.2%

The question is then, what do I have to do to either send the data to the PHP script or, failing that, skip the PHP part and use a Python script directly?

If you guys need any more information just ask and I’ll provide as best i can. Thanks!

—–UPDATE—–

So! I have found something that might work, I am trying to POST the data with Requests. I am making a PHP script on the server that is going to inject the data received into to the MySQL DB. Then comes testing, I am going to update you guys on how it went.

If you have any advice just shoot, and I’ll still be here if you need any more info or have any questions!

Advertisement

Answer

So! I found out how i could send the temperature and humidity data over to the database from the Raspberry Pi 3. I used the external module requests suggested by @furas, here’s the Python script i wrote.

import Adafruit_DHT
import requests
sensor = Adafruit_DHT.DHT22
pin = 2
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
    print('Temperature ={0:0.1f}*C  Humidity = {1:0.1f}%'.format(temperature, humidity))
    payload = {'temp': temperature, 'hum': humidity}
    r = requests.post('http://192.168.1.7/test/MySQL_POST_Test.php, data=payload')
    print(r.text)
else:
    print('Failed to read the sensor, try "sudo python3 sensor-post.py" again.')

and the PHP script:

$servername = "localhost";
$username = "Test"
$password = "passwd";
$dbname = "TestDB";
$temperature = $_POST["temp"];
$humidity = $_POST["hum"];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO SensorTest (Temperature, Humidity) VALUES ($temperature, $humidity)";
if ($conn->query($sql) === TRUE) {
  echo "New record created successfully!";
}
else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

The result after running the Python script:

Temperature =22.1*C  Humidity =34.2%
New record created successfully!

I tried to add schedule to the Python script but i have not made it work yet, But these script works just fine without schedule.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement