Raspberry Pi - DHT11 and mySQL

This program reads a DHT22 sensor. Then it gets the hostname and external IP address, and adds the info to an external database.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/python3

# IMPORTS 
import Adafruit_DHT
import time
import socket
import re
from datetime import datetime
from urllib.request import urlopen
import requests

# DECLARATIONS
now = datetime.now()
sensor_type = 22
sensor_pin = 4
timestamp = now.strftime("%Y-%m-%d-%H:%M:%S")

# FUNCTIONS
# This function reads the humidity and temperature. The data is stored in global variables
def read_temp_hum():
    global humidity
    global temperature

    # Read the sensor
    humidity, temperature = Adafruit_DHT.read_retry(sensor_type, sensor_pin)
    time.sleep(2)
    while True:
        if humidity is not None and temperature is not None:
            print ("Data from sensor are OK. Humidity= {0:0.1f}% Temperature= {1:0.1f} *C".format(humidity, temperature))
            break
        else:
            print ("Error getting data from sensor.")
            break

# Function that gets the systems host name.
def get_hostname():
    global local_hostname
    local_hostname = socket.gethostname()
    print ("Hostname: "+local_hostname)

# Function that get the external IP-adress
def get_external_ip_address():
    global external_ip
    url = "http://checkip.dyndns.org"           # This site return one line of text.
    my_request = urlopen(url).read()            # Read the URL
    res = re.findall(b'\d{1,3}', my_request)    # Search and findall integers in my_request
    my_ip_list = list(map(int, res))            # Clean up the list
    my_ip = str(my_ip_list)[1:-1]               # Remove the square brackets
    temp_ip = my_ip.replace(",", ".")           # Replace comma with periods
    external_ip = temp_ip.replace(" ", "")      # Replace <space> with none-space
    print ("External IP: " +external_ip)        # Print the External IP address as xxx.xxx.xxx.xxx

# Function to gather all the global variables and sending them to the server
def send_data():
    output = "http://apk.nerdegutta.org:90/temperature/add_temp.php?temp="+str(temperature) \
    +"&humi="+str(humidity)+"&time="+str(timestamp)+"&sensor="+str(local_hostname) \
    +"&ip="+str(external_ip)
    print (output)
    html = urlopen(output).read()

# Main function of the program
def main():
    read_temp_hum()
    get_hostname()
    get_external_ip_address()
    send_data()

if __name__ == "__main__":
    main()

blogroll

social