dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: DHT11 readings onto a web page!

Mon Mar 21, 2016 7:03 pm

Hi @danjperron,
I updated my system to Jessie and I have this error when y try to load the pigpio script:

Code: Select all

root@jeedom:~# sudo update-rc.d pigpiod defaults 9
insserv: warning: script 'resizesd' missing LSB tags and overrides
What can I do? :(

Thanks

Best regards

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Mon Mar 21, 2016 7:28 pm

Jessie is different because it is with systemd.

I will need to check what I did but it could take some times. I changed my system using nrf24L01 transmitter and arduino mini . I will have to load one of my unused Pi and check what would be the modification.


I thing that Joan also update the pigpio so this is another check I will have to do.

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Tue Mar 22, 2016 1:39 am

Ok I did check the /etc/init.d/pigpiod and still works fine with Jessie.

So I don't have to change my setup.

I didn't check the latest version from march18.


looks like you could just remove insserv

http://help.directadmin.com/item.php?id=379

dj_janker
Posts: 59
Joined: Thu Jan 08, 2015 6:15 pm

Re: DHT11 readings onto a web page!

Thu Mar 24, 2016 6:49 pm

Ok, I solved the inserv problem, but now my DHT11 is reading wrong values... :shock:

Code: Select all

temp:512.0 Celsius  humidity:1100.8%

Code: Select all

1 1100.8 512.0 0.20 0 0 0 0
2 1100.8 512.0 0.20 0 0 0 0
3 1075.2 512.0 0.19 0 0 0 0
4 1100.8 512.0 0.20 0 0 0 0
5 1075.2 512.0 0.19 0 0 0 0
6 1075.2 512.0 0.20 0 0 0 0
7 1075.2 512.0 0.19 0 0 0 0
8 1075.2 512.0 0.19 0 0 0 0
9 1100.8 512.0 0.19 0 0 0 0
10 1075.2 512.0 0.19 0 0 0 0
11 1075.2 512.0 0.19 0 0 0 0
In other Rpi with Jessie and an DHT22 the values are normals.

Any idea?

Che.guevara
Posts: 28
Joined: Sat Feb 20, 2016 4:27 pm

Re: DHT11 readings onto a web page!

Mon Apr 25, 2016 6:46 pm

hey,

I use a DHT22 Sensor and plugged it like this:

Image

I installed everything like you said in your post here:

viewtopic.php?p=672406#p672406

but all i get, when i run

Code: Select all

sudo python DHT22.py
is:

Code: Select all

root@raspberrypi:~# sudo python DHT22.py
1 1 0 0.17 0 0 0 0
2 1 0 0.17 0 0 0 0
3 1 0 0.18 0 0 0 0
4 1 0 0.16 0 0 0 0
5 1 0 0.18 0 0 0 0

what did i do wrong?

I use an Raspberry Pi B+ and a DHT22 Sensor.

Thank you

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Mon Apr 25, 2016 7:12 pm

On which pin is the DHT22 connected.

A picture of your setup will help. Did you add the 4k7 resistor? What about the power pin , are you using the power reset mode?

Che.guevara
Posts: 28
Joined: Sat Feb 20, 2016 4:27 pm

Re: DHT11 readings onto a web page!

Mon Apr 25, 2016 7:14 pm

danjperron wrote:On which pin is the DHT22 connected.

A picture of your setup will help. Did you add the 4k7 resistor? What about the power pin , are you using the power reset mode?
can't you see the picture i posted in my previous post?

here again the link:

http://fs5.directupload.net/images/160425/8ljnskxh.jpg

DirkS
Posts: 7631
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: DHT11 readings onto a web page!

Mon Apr 25, 2016 7:26 pm

Che.guevara wrote:I use an Raspberry Pi B+ and a DHT22 Sensor.
That output looks like the what I got when the script was set to read a DHT11.

Line 265 in DHT22.py sets the parameter DHT11 to True. That should be False for the DHT22

Code: Select all

   s = DHT22.sensor(pi, 22, LED=None, power=None,DHT11=False)

Che.guevara
Posts: 28
Joined: Sat Feb 20, 2016 4:27 pm

Re: DHT11 readings onto a web page!

Mon Apr 25, 2016 7:28 pm

DirkS wrote:
Che.guevara wrote:I use an Raspberry Pi B+ and a DHT22 Sensor.
That output looks like the what I got when the script was set to read a DHT11.

Line 265 in DHT22.py sets the parameter DHT11 to True. That should be False for the DHT22

Code: Select all

   s = DHT22.sensor(pi, 22, LED=None, power=None,DHT11=False)

line 265 looks like this for me:

Code: Select all

s = DHT22.sensor(pi, 22, LED=None, power=None,DHT11=False)
so already set on false :?

Che.guevara
Posts: 28
Joined: Sat Feb 20, 2016 4:27 pm

Re: DHT11 readings onto a web page!

Thu Apr 28, 2016 8:51 pm

I can't tell what my mistake was, but i formatted my Raspberry, installed NOOBS again and installed everything again.
It is working now!

Code: Select all

root@raspberrypi:/# sudo python DHT22.py
1 39.2 18.6 0.19 0 0 0 0
2 38.6 18.7 0.18 0 0 0 0
but when I try to make part two of the tutorial, I get an error when I want to browse localhost (http://192.168.2.127/charts)
Not Found
The requested URL /charts was not found on this server.

Apache/2.4.10 (Raspbian) Server at 192.168.2.127 Port 80
Does it make a difference if I type

Code: Select all

cd ~
or
cd ..

?

Also the line

Code: Select all

tmpfs      /webdata   tmpfs   defaults,nosuid,uid=www-data,gid=www-data  0      0
can i copy&paste it like this? With the right amount of space characters?

another thing, when i typ

Code: Select all

df
, I get this, the webdata is showing 0%.. Is this maybe an indicator, that something already went wrong?

Code: Select all

Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/root       14044224 3776456   9531308  29% /
devtmpfs          218416       0    218416   0% /dev
tmpfs             222688       0    222688   0% /dev/shm
tmpfs             222688    4936    217752   3% /run
tmpfs               5120       4      5116   1% /run/lock
tmpfs             222688       0    222688   0% /sys/fs/cgroup
tmpfs             222688       0    222688   0% /webdata
/dev/mmcblk0p6     64366   19974     44392  32% /boot
tmpfs              44540       0     44540   0% /run/user/1000
/dev/mmcblk0p5     30701     444     27964   2% /media/pi/SETTINGS
tmpfs              44540       0     44540   0% /run/user/0

sultan
Posts: 57
Joined: Wed Jan 14, 2015 4:50 pm
Location: India

Re: DHT11 readings onto a web page!

Sat Apr 30, 2016 12:28 pm

Che.guevara wrote:I can't tell what my mistake was, but i formatted my Raspberry, installed NOOBS again and installed everything again.
It is working now!

Code: Select all

root@raspberrypi:/# sudo python DHT22.py
1 39.2 18.6 0.19 0 0 0 0
2 38.6 18.7 0.18 0 0 0 0
but when I try to make part two of the tutorial, I get an error when I want to browse localhost (http://192.168.2.127/charts)
Not Found
The requested URL /charts was not found on this server.

Apache/2.4.10 (Raspbian) Server at 192.168.2.127 Port 80
Does it make a difference if I type

Code: Select all

cd ~
or
cd ..

?

Also the line

Code: Select all

tmpfs      /webdata   tmpfs   defaults,nosuid,uid=www-data,gid=www-data  0      0
can i copy&paste it like this? With the right amount of space characters?

another thing, when i typ

Code: Select all

df
, I get this, the webdata is showing 0%.. Is this maybe an indicator, that something already went wrong?

Code: Select all

Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/root       14044224 3776456   9531308  29% /
devtmpfs          218416       0    218416   0% /dev
tmpfs             222688       0    222688   0% /dev/shm
tmpfs             222688    4936    217752   3% /run
tmpfs               5120       4      5116   1% /run/lock
tmpfs             222688       0    222688   0% /sys/fs/cgroup
tmpfs             222688       0    222688   0% /webdata
/dev/mmcblk0p6     64366   19974     44392  32% /boot
tmpfs              44540       0     44540   0% /run/user/1000
/dev/mmcblk0p5     30701     444     27964   2% /media/pi/SETTINGS
tmpfs              44540       0     44540   0% /run/user/0

I am having the same problem. Please someone help us. I cannot view the temp.html as it says 404 error.

I am hoping someone will help us. Been trying to fix this problem for a while. I dont even know what is wrong.
Forgive me for my grammar :(.

jzxpacky
Posts: 12
Joined: Tue Dec 15, 2015 1:47 pm

Re: DHT11 readings onto a web page!

Sat Jun 03, 2017 11:50 am

Hi Dan, I have an interesting one for you. I've got this running on 3 RPi's around the house so I can monitor various rooms, and I'm wanting to pull the data from 2 of the DHT22 sensors on remote RPi's on the network and chart on the same graph on my primary RPi.

I know we can add extra sensors into the script if they are connected to the same RPi but not sure about importing values from remote RPi's running the scripts.

Any ideas?

EDIT: Ok so I've just seen Remote GPIO and I'm going to look into getting this working so I can pull the readings remotely. If you have any tips on this it would be appreciated.

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Sat Jun 03, 2017 1:41 pm

There is multipe way to do it.


The simplest is MQTT. You could add sensors with arduino, esp8266 an other Pi.


This is what I do with my nRF24L01 sensor. Everything is remote except one Pi which is my MQTT and web server.

viewtopic.php?p=720838#p720838

With the MQTT protocol it is easy to read any sensor from my amazon echo dot.

jzxpacky
Posts: 12
Joined: Tue Dec 15, 2015 1:47 pm

Re: DHT11 readings onto a web page!

Tue Jun 06, 2017 8:52 am

Ok so I have managed to use Gpiozero to read temperature and humidity from another RPi on the network with a DHT22 sensor, now I just need to work out how to add this into the database.

To get the local reading, we simply execute the DHT22.py script from bash with

Code: Select all

python DHT22.py
and it cycles through with current temp and humidity etc. To read from a remote pi, I execute the script from a bash prompt with the below code

Code: Select all

GPIOZERO_PIN_FACTORY=PiGPIOPin PIGPIO_ADDR=192.168.1.6 python DHT22.py
Now what I need to do is have this command run for each additional sensor I want to add into readTemp.py, or by adding in another script and appending the RRD file. Also, adding an additional data source to the RRD file is something I am having issues with.

Any help would be appreciated.

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Tue Jun 06, 2017 11:33 am

Did you check my MQTT method ? This is easy to implement and later you could add a multitude of sensors.


Did you read the post completely. There is code I had put there for multiple sensors.
Inside this post, near the beginning you have code for multiple sensors like the DS18B20. Just change the code for another DHT11/22.

Also I will revise my post and update Dropbox link since they removed the public folder.

jzxpacky
Posts: 12
Joined: Tue Dec 15, 2015 1:47 pm

Re: DHT11 readings onto a web page!

Tue Jun 06, 2017 12:52 pm

I did have a brief look at it but hadn't pursued that line as I am unsure how to go about it. I hadn't even heard of MQTT until your post hehe.

Does this incorporate a whole new set of scripts etc? I would like to do what is the most reliable and easy to maintain as I plan on adding in additional sensors along the way on further RPi's.

Basically, do you have a how to on the MQTT method like you did with the method in this thread? Please forgive my ignorance if you have linked it and I have missed it.

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Wed Jun 07, 2017 1:05 am

MQTT is a old protocol made by IBM to communicate with the satellite.

it's like a bbs forum. you subscribe to a topic and any thing publish will be send to you.

Your sensor will publish and your python program will subscribe to the same topic.


Your sensor code will read the temperature and will publish to a specific topic. Ex: "DHT22Sensor1"
Your remote code will subscribe to all the topic it needs and response when it receives the commands fro the sensor.

B.T.W. Everything could be text. This way it is easy to debug.

In Recap you need to know about.

- Create Chart using HighChart.
- Know a little bit of javascript.
- Create a small database using rrdtool. It's not really a database but a Fifo average accumulator.

For the MQTT server I used mosquitto version 1.4 and to publish on MQTT with python I use paho

This is a small example on how to create real time temperature gauge using javascript and MQTT,
tempgauge.jpg
temperature gauge
tempgauge.jpg (28.78 KiB) Viewed 1119 times

and the html source code

Code: Select all

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="MQTT Websocket Temperature">
    <meta name="author" content="Fabian Affolter/JP Mens">

    <link rel="bookmark" href="pool.png">
    <link rel="shortcut icon" href="pool.png">
    <link rel="apple-touch-icon" href="pool.png">
    <link rel="apple-touch-icon" href="pool.png">


    <title>Température Extérieure</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.css" rel="stylesheet">
    <!-- jQuery -->
    <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
    <!-- Sparkline -->
    <script type="text/javascript" src="js/jquery.sparkline.min.js"></script>
    <!-- MQTT over Websockets -->
    <script type="text/javascript" src="js/mqttws31.js"></script>

    <!-- SteelSeries gauges -->
    <script type="text/javascript" src="js/steelseries-min.js"></script>
    <script type="text/javascript" src="js/tween-min.js"></script>


    <script type="text/javascript">

    var websocketserver = 'your IP address';
    var websocketport   = 9001;
    var pool_topic = 'RF_DATA/DS18B20/C6';
    var ext_temp_topic = 'RF_DATA/DHT22/Temp/C8';
    var ext_hum_topic= 'RF_DATA/DHT22/Hum/C8';
    var int_topic = 'RF_DATA/DS18B20/C3';
    var chip_temp_topic = 'CHIP/DHT22/Temp/UNIT1';
    var chip_hum_topic = 'CHIP/DHT22/Hum/UNIT1';


	var tempGauge;

	var arduinoTemp = new Array();

        var client = new Messaging.Client(websocketserver, websocketport,
                                "web_" + parseInt(Math.random() * 100, 10));

        client.onConnectionLost = function (responseObject) {
                $('#message').val("connection lost: " + responseObject.errorMessage);
		tempGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection
        };

        client.onMessageArrived = function (msg) {
                $('#message').val(msg.payloadString);

		console.log(JSON.stringify(msg.destinationName));
		console.log(JSON.stringify(msg.payloadString));

		
		topic_parts = msg.destinationName.split('/');

		sensor_addr = topic_parts[2];
		if (topic_parts[topic_parts.length - 1] == 'C6') {
			poolGauge.setValue(parseFloat(msg.payloadString));
                       }
		else if (topic_parts[topic_parts.length - 1] == 'C3') {
			intGauge.setValue(parseFloat(msg.payloadString));
                       }
		else if (topic_parts[topic_parts.length - 1] == 'C8') {

                    if (topic_parts[topic_parts.length - 2] == 'Temp')
                       {
			tempGauge.setValue(parseFloat(msg.payloadString));
                       }
                   else  if (topic_parts[topic_parts.length - 2] == 'Hum')
                       {
			humGauge.setValue(parseFloat(msg.payloadString));
                       }
                    }
/*		else if (topic_parts[topic_parts.length - 1] == 'UNIT1') {

                    if (topic_parts[topic_parts.length - 2] == 'Temp')
                       {
			chiptempGauge.setValue(parseFloat(msg.payloadString));
                       }
                   else  if (topic_parts[topic_parts.length - 2] == 'Hum')
                       {
			chiphumGauge.setValue(parseFloat(msg.payloadString));
                       }
		}
*/
        };

        var options = {
                timeout: 3,
                onSuccess: function () {
                        $('#message').html('Connected to ' + websocketserver + ':' + websocketport);
                        // Connection succeeded; subscribe to our topic
                        client.subscribe(ext_temp_topic, {qos: 0});
                        client.subscribe(ext_hum_topic, {qos: 0});
                        client.subscribe(pool_topic, {qos: 0});
                        client.subscribe(int_topic, {qos: 0});
                        client.subscribe(chip_temp_topic, {qos: 0});
                        client.subscribe(chip_hum_topic, {qos: 0});

			tempGauge.setLedColor(steelseries.LedColor.GREEN_LED); //change status LED to GREEN on broker connection
			intGauge.setLedColor(steelseries.LedColor.GREEN_LED); //change status LED to GREEN on broker connection
			humGauge.setLedColor(steelseries.LedColor.GREEN_LED); //change status LED to GREEN on broker connection
			poolGauge.setLedColor(steelseries.LedColor.GREEN_LED); //change status LED to GREEN on broker connection
//			chiptempGauge.setLedColor(steelseries.LedColor.GREEN_LED); //change status LED to GREEN on broker connection
//			chiphumGauge.setLedColor(steelseries.LedColor.GREEN_LED); //change status LED to GREEN on broker connection


                },
                onFailure: function (message) {
                        $('#message').html("Connection failed: " + message.errorMessage);
			tempGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection
			intGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection
			humGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection
			poolGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection
//			chiptempGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection
//			chiphumGauge.setLedColor(steelseries.LedColor.RED_LED); //change status LED to RED on broker disconnection

                }
        };

        function init() {
                /* Connect to MQTT broker */
                client.connect(options);

                intGauge = new steelseries.Radial('gaugeCanvas4', {
                        gaugeType: steelseries.GaugeType.TYPE4,
                        minValue:0,
                        maxValue:40,
                        size: 170,
                        frameDesign: steelseries.FrameDesign.STEEL,
                        knobStyle: steelseries.KnobStyle.STEEL,
                        pointerType: steelseries.PointerType.TYPE6,
                        section: null,
                        area: null,
                        titleString: 'Température',
                        unitString: '°C',
                        threshold: 1000,
                        thresholdVisible:false, 
                        lcdVisible: true,
                        lcdDecimals: 1
                   });
                intGauge.setValue(''); //gives a blank display 'NaN' until broker has connected
                intGauge.setLedColor(steelseries.LedColor.RED_LED); //set the LED RED until connected

                poolGauge = new steelseries.Radial('gaugeCanvas3', {
                        gaugeType: steelseries.GaugeType.TYPE4,
                        minValue:0,
                        maxValue:40,
                        size: 170,
                        frameDesign: steelseries.FrameDesign.STEEL,
                        knobStyle: steelseries.KnobStyle.STEEL,
                        pointerType: steelseries.PointerType.TYPE6,
                        section: null,
                        area: null,
                        titleString: 'Température',
                        unitString: '°C',
                        threshold: 1000,
                        thresholdVisible:false, 
                        lcdVisible: true,
                        lcdDecimals: 1
                   });
                poolGauge.setValue(''); //gives a blank display 'NaN' until broker has connected
                poolGauge.setLedColor(steelseries.LedColor.RED_LED); //set the LED RED until connected

                tempGauge = new steelseries.Radial('gaugeCanvas', {
                        gaugeType: steelseries.GaugeType.TYPE4,
                        minValue:-40,
                        maxValue:40,
                        size: 170,
                        frameDesign: steelseries.FrameDesign.STEEL,
                        knobStyle: steelseries.KnobStyle.STEEL,
                        pointerType: steelseries.PointerType.TYPE6,
                        section: null,
                        area: null,
                        titleString: 'Température',
                        unitString: '°C',
                        threshold: 1000,
                        thresholdVisible:false, 
                        lcdVisible: true,
                        lcdDecimals: 1
                   });
                tempGauge.setValue(''); //gives a blank display 'NaN' until broker has connected
                tempGauge.setLedColor(steelseries.LedColor.RED_LED); //set the LED RED until connected

                humGauge = new steelseries.Radial('gaugeCanvas2', {
                        gaugeType: steelseries.GaugeType.TYPE4,
                        minValue:0,
                        maxValue:100,
                        size: 170,
                        frameDesign: steelseries.FrameDesign.STEEL,
                        knobStyle: steelseries.KnobStyle.STEEL,
                        pointerType: steelseries.PointerType.TYPE6,
                        section: null,
                        area: null,
                        titleString: 'Humidité',
                        unitString: '%',
                        threshold: 1000,
                        thresholdVisible:false, 
                        lcdVisible: true,
                        lcdDecimals: 1
                   });
                humGauge.setValue(''); //gives a blank display 'NaN' until broker has connected
                humGauge.setLedColor(steelseries.LedColor.RED_LED); //set the LED RED until connected
/*
                chiptempGauge = new steelseries.Radial('gaugeCanvas5', {
                        gaugeType: steelseries.GaugeType.TYPE4,
                        minValue:0,
                        maxValue:40,
                        size: 170,
                        frameDesign: steelseries.FrameDesign.STEEL,
                        knobStyle: steelseries.KnobStyle.STEEL,
                        pointerType: steelseries.PointerType.TYPE6,
                        section: null,
                        area: null,
                        titleString: 'Température',
                        unitString: '°C',
                        threshold: 1000,
                        thresholdVisible:false, 
                        lcdVisible: true,
                        lcdDecimals: 1
                   });
                chiptempGauge.setValue(''); //gives a blank display 'NaN' until broker has connected
                chiptempGauge.setLedColor(steelseries.LedColor.RED_LED); //set the LED RED until connected

                chiphumGauge = new steelseries.Radial('gaugeCanvas6', {
                        gaugeType: steelseries.GaugeType.TYPE4,
                        minValue:0,
                        maxValue:100,
                        size: 170,
                        frameDesign: steelseries.FrameDesign.STEEL,
                        knobStyle: steelseries.KnobStyle.STEEL,
                        pointerType: steelseries.PointerType.TYPE6,
                        section: null,
                        area: null,
                        titleString: 'Humidité',
                        unitString: '%',
                        threshold: 1000,
                        thresholdVisible:false, 
                        lcdVisible: true,
                        lcdDecimals: 1
                   });
*/                chiphumGauge.setValue(''); //gives a blank display 'NaN' until broker has connected
                chiphumGauge.setLedColor(steelseries.LedColor.RED_LED); //set the LED RED until connected

        }

        $(document).ready(function() {
                init();


        });

    </script>

  </head>

  <body>
  <center><h3>&Agrave; l'Ext&eacute;rieur</h3></center><br>
  <center>
  <table border=0>
  <tr><td>
  <center><canvas id="gaugeCanvas" width="250" height="250">No canvas in your browser...sorry...</canvas><center>
  </td><td width="5"></td>
  <td><center><canvas id="gaugeCanvas2" width="250" height="250">No canvas in your browser...sorry...</canvas><center>
  </td></tr>
  <center>
  <table border=0>
  <tr>
<!---  enlever pour l'instant
  <td colspan="3"><h3><center><h3>&Agrave; l'Int&eacute;rieur! C.H.I.P. DHT22</h3></center></td>
  </tr><tr>

  <tr><td>
  <center><canvas id="gaugeCanvas5" width="250" height="250">No canvas in your browser...sorry...</canvas><center>
  </td><td width="5"></td>
  <td><center><canvas id="gaugeCanvas6" width="250" height="250">No canvas in your browser...sorry...</canvas><center>
  </td></tr>
-->
  <tr>
  <td colspan="3"><h3><center>Room 1</center></h3></td>
  </tr><tr>
  <td colspan="3">
  <center><canvas id="gaugeCanvas3" width="250" height="250">No canvas in your browser...sorry...</canvas><center>
  </td></tr>  
  <tr>
  <td colspan="3"><h3><center>Room 2</center></h3></td>
  </tr><tr>
  <td colspan="3">
  <center><canvas id="gaugeCanvas4" width="250" height="250">No canvas in your browser...sorry...</canvas><center>
  </td>  
  </tr>

  </table>
  </center>
</body>
</html>

jzxpacky
Posts: 12
Joined: Tue Dec 15, 2015 1:47 pm

Re: DHT11 readings onto a web page!

Sun Jun 11, 2017 10:19 am

Ok so I ended up doing it in a roundabout way, only because I started this way and wanted to see if I could do it (I will be looking into using MQTT though as this sounds pretty cool, I just need to learn it)

The way I have configured this is to have individual readTemp.py scripts per additional RPi (I have 3 RPi's so the scripts are readTemp1.py, readTemp2.py etc) that purely reads the sensor and writes the data string to the file CurrentData1(2,3).txt. These python scripts are called from shell scripts as I have to start the python script with shell variables (I'm not sure If I can execute them with the variables inside the file).

Code: Select all

#!/usr/bin/python
import pigpio
import DHT22
import time
import os
import sys
import datetime
import subprocess
import shlex

# Intervals of about 2 seconds or less will eventually hang the DHT22.
INTERVAL=3
RETRY = 3
SENSOR_GPIO = 22
ISDHT11 =False
Valid=False

pi=pigpio.pi()
probe = DHT22.sensor(pi,SENSOR_GPIO,DHT11=ISDHT11)



#Function to read cpu temperature
def readCpuTemperature():
   fichier = open("/sys/class/thermal/thermal_zone0/temp","r")
   texte =  fichier.readline()
   fichier.close()
   return  (float(texte)/1000.0)




#read the DHT22/11 Sensor at corresponding pin
#return None if it can't
#return [humidity temperature]

def readDHT_sensor():
  global pi
  global probe
  #retry at least RETRY times if something wrong
  for loop in range(RETRY):

    #put a minimum of interval stabilization
    if loop!=0:
      time.sleep(INTERVAL)

    #start transfer
    #Be aware that the reading will be from the last conversion
    #It is wise to read it twice and keep the last one

    probe.trigger()

    #wait for completion
    time.sleep(0.2)

    temperature = probe.temperature()
    humidity    = probe.humidity()

    if temperature == (-999):
      continue

    if humidity == (-999):
      continue

    return [temperature,humidity]

  #if we are here it is because with retry and it didn't work
  #just return None
  return [None , None]




##### MAIN #######


#read sensor once to capture the current temp
readDHT_sensor()

#read sensor again but now keep the data
time.sleep(INTERVAL)
sensorData = readDHT_sensor()
cpuTemp = readCpuTemperature()

now = datetime.datetime.now()

webdata = "/webdatanew/"

########rddtool

def Validate(value):
  if value == None:
    return ":U"
  else:
    return ":{}".format(value)

#create text string to insert data

rdata = "N" + Validate(cpuTemp) + Validate(sensorData[0]) + Validate(sensorData[1])

#put current value into a file
def TempS(value):
  if value == None :
    return "---"
  return value

try:
  file = open(webdata+"CurrentData1.txt","w")
  file.write(rdata)
  file.close()
except:
  pass
The only variation between readTemp1.py and the subsequent scripts is the rdata variable. The additional scripts have rdata like below.

Code: Select all

rdata = Validate(sensorData[0]) + Validate(sensorData[1])
The remote RPi's can be read using remotegpio but as I said, I have to specify environment variables to run the python script under.

Code: Select all

GPIOZERO_PIN_FACTORY=pigpio PIGPIO_ADDR=192.168.1.6 python3 readTemp2.py
Therefore, I am putting this into a shell script called readTemp1(2,3).sh and calling them from cron (readTemp1.sh simply contains "python3 readTemp1.py" just for uniformity. My crontab looks like below.

Code: Select all

4-59/5 * * * * /root/readTemp1.sh >/dev/null 2>&1
4-59/5 * * * * /root/readTemp2.sh >/dev/null 2>&1
4-59/5 * * * * /root/readTemp3.sh >/dev/null 2>&1
*/5 * * * * /root/updateRRD.py >/dev/null 2>&1
The final cron job is to update the RRD file from the 3 text files containing the readings, and then extract the data to the appropriate XML files.

Code: Select all

#!/usr/bin/python
import time
import os
import sys
import datetime
import subprocess
import shlex

#now let insert it into the rddtool data

fileRrdtool = "/home/pi/temperaturesnew.rrd"

webdata = "/webdatanew/"

with open (webdata+"CurrentData1.txt", "r") as myfile:
        rdata = myfile.read().replace('\n', '')

with open (webdata+"CurrentData2.txt", "r") as myfile:
        rdata += myfile.read().replace('\n', '')

with open (webdata+"CurrentData3.txt", "r") as myfile:
        rdata += myfile.read().replace('\n', '')

subprocess.Popen(["/usr/bin/rrdtool","update",fileRrdtool,rdata])

#and now let's extract data to create data file for the web page

def rrdExport(start , step , sortieXML):
  texte = "rrdtool xport -s {0} -e now --step {1} ".format(start, step)
  texte += "DEF:a={0}:th_cpu_1:AVERAGE ".format(fileRrdtool)
  texte += "DEF:b={0}:th_dht22_1:AVERAGE ".format(fileRrdtool)
  texte += "DEF:c={0}:hm_dht22_1:AVERAGE ".format(fileRrdtool)
  texte += "DEF:d={0}:th_dht22_2:AVERAGE ".format(fileRrdtool)
  texte += "DEF:e={0}:hm_dht22_2:AVERAGE ".format(fileRrdtool)
  texte += "DEF:f={0}:th_dht22_3:AVERAGE ".format(fileRrdtool)
  texte += "DEF:g={0}:hm_dht22_3:AVERAGE ".format(fileRrdtool)
  texte += "XPORT:a:""th_cpu_1"" "
  texte += "XPORT:b:""th_dht22_1"" "
  texte += "XPORT:c:""hm_dht22_1"" "
  texte += "XPORT:d:""th_dht22_2"" "
  texte += "XPORT:e:""hm_dht22_2"" "
  texte += "XPORT:f:""th_dht22_3"" "
  texte += "XPORT:g:""hm_dht22_3"" "


  fileout = open(webdata+sortieXML,"w")
  args = shlex.split(texte)
  subprocess.Popen(args, stdout=fileout)
  fileout.close()


# ok extact 1 hour data
rrdExport("now-1h",300, "temperature1h.xml")

# ok extact 3 hours data
rrdExport("now-3h",300, "temperature3h.xml")

# ok extact 6 hours data
rrdExport("now-6h",300, "temperature6h.xml")

# ok extact 12 hours data
rrdExport("now-12h",300, "temperature12h.xml")

#ok 24 hours
rrdExport("now-24h",900, "temperature24h.xml")

#ok 48 hours
rrdExport("now-48h",1800, "temperature48h.xml")

#ok 1 week
rrdExport("now-8d",3600, "temperature1w.xml")

#ok 1 month
rrdExport("now-1month",14400, "temperature1m.xml")

#ok 3 month
rrdExport("now-3month",28800, "temperature3m.xml")

#ok 1 year
rrdExport("now-1y",43200, "temperature1y.xml")
I've also updated the html file to reflect the additional sensors and to change the name of them to reflect their location.

I know this might not look very tidy, but for now it works and I know how to do it. I'm going to look into tidying this up and also in using the MQTT protocol instead.

Cheers.

JNie257
Posts: 4
Joined: Tue Oct 03, 2017 9:46 pm

Re: DHT11 readings onto a web page!

Tue Oct 03, 2017 10:01 pm

I know its been a while but i was following this guide and i couldnt see charts or webdata on apache... come to find out its because the document directory in apache was setup as /var/www/html. removed html and it works...

Then when running "wget https://dl.dropboxusercontent.com/u/488 ... ol_data.sh" it comes back with 404 not found. was wondering if you still had the create_rrdtool_data.sh and readTemp.py to save me a headache since im new to this still

jzxpacky
Posts: 12
Joined: Tue Dec 15, 2015 1:47 pm

Re: DHT11 readings onto a web page!

Wed Oct 04, 2017 3:17 am

Paste this into a new file called create_rrdtool_data.sh and make sure you make it executable (chmod +x)

Code: Select all

#! /bin/bash
rrdtool create temperatures.rrd \
--start "01/01/2015" \
--step 300 \
 DS:th_cpu:GAUGE:1200:-40:100 \
 DS:th_dht22:GAUGE:1200:-40:100 \
 DS:hm_dht22:GAUGE:1200:-40:100 \
 RRA:AVERAGE:0.5:1:288 \
 RRA:AVERAGE:0.5:6:336 \
 RRA:AVERAGE:0.5:24:372 \
 RRA:AVERAGE:0.5:144:732 \
 RRA:MIN:0.5:1:288 \
 RRA:MIN:0.5:6:336 \
 RRA:MIN:0.5:24:372 \
 RRA:MIN:0.5:144:732 \
 RRA:MAX:0.5:1:288 \
 RRA:MAX:0.5:6:336 \
 RRA:MAX:0.5:24:372 \
 RRA:MAX:0.5:144:732 \

Same for this one, readTemp.py

Code: Select all

#!/usr/bin/python
import pigpio
import DHT22
import time
import os
import sys
import datetime
import subprocess
import shlex

# Intervals of about 2 seconds or less will eventually hang the DHT22.
INTERVAL=3
RETRY = 3
SENSOR_GPIO = 22
ISDHT11 =False
Valid=False

pi=pigpio.pi()
probe = DHT22.sensor(pi,SENSOR_GPIO,DHT11=ISDHT11)



#Function to read cpu temperature
def readCpuTemperature():
   fichier = open("/sys/class/thermal/thermal_zone0/temp","r")
   texte =  fichier.readline()
   fichier.close()
   return  (float(texte)/1000.0)




#read the DHT22/11 Sensor at corresponding pin
#return None if it can't
#return [humidity temperature]

def readDHT_sensor():
  global pi
  global probe
  #retry at least RETRY times if something wrong
  for loop in range(RETRY):

    #put a minimum of interval stabilization
    if loop!=0:
      time.sleep(INTERVAL)

    #start transfer
    #Be aware that the reading will be from the last conversion
    #It is wise to read it twice and keep the last one

    probe.trigger()

    #wait for completion
    time.sleep(0.2)

    temperature = probe.temperature()
    humidity    = probe.humidity()

    if temperature == (-999):
      continue

    if humidity == (-999):
      continue

    return [temperature,humidity]

  #if we are here it is because with retry and it didn't work
  #just return None
  return [None , None]




##### MAIN #######


#read sensor once to capture the current temp
readDHT_sensor()

#read sensor again but now keep the data
time.sleep(INTERVAL)
sensorData = readDHT_sensor()
cpuTemp = readCpuTemperature()

now = datetime.datetime.now()

webdata = "/webdata/"


#put current value into a file
def TempS(value):
  if value == None :
    return "---"
  return value

try:
  file = open(webdata+"CurrentData.txt","w")
  file.write("{}\t{}\t{}\t{}\n".format(now,TempS(cpuTemp),TempS(sensorData[0]),TempS(sensorData[1])))
  file.close()
except:
  pass


########rddtool

def Validate(value):
  if value == None:
    return ":U"
  else:
    return ":{}".format(value)

#create text string to insert data

rdata = "N" + Validate(cpuTemp) + Validate(sensorData[0]) + Validate(sensorData[1])

#now let insert it into the rddtool data

fileRrdtool = "/home/pi/temperatures.rrd"

subprocess.Popen(["/usr/bin/rrdtool","update",fileRrdtool,rdata])

#and now let's extract data to create data file for the web page

def rrdExport(start , step , sortieXML):
  texte = "rrdtool xport -s {0} -e now --step {1} ".format(start, step)
  texte += "DEF:a={0}:th_cpu:AVERAGE ".format(fileRrdtool)
  texte += "DEF:b={0}:th_dht22:AVERAGE ".format(fileRrdtool)
  texte += "DEF:c={0}:hm_dht22:AVERAGE ".format(fileRrdtool)
  texte += "XPORT:a:""th_cpu"" "
  texte += "XPORT:b:""th_dht22"" "
  texte += "XPORT:c:""hm_dht22"" "

  fileout = open(webdata+sortieXML,"w")
  args = shlex.split(texte)
  subprocess.Popen(args, stdout=fileout)
  fileout.close()


# ok extact 1 hour data
rrdExport("now-1h",300, "temperature1h.xml")

# ok extact 3 hours data
rrdExport("now-3h",300, "temperature3h.xml")

#ok 24 hours
rrdExport("now-24h",900, "temperature24h.xml")

#ok 48 hours
rrdExport("now-48h",1800, "temperature48h.xml")

#ok 1 week
rrdExport("now-8d",3600, "temperature1w.xml")

#ok 1 month
rrdExport("now-1month",14400, "temperature1m.xml")

#ok 3 month
rrdExport("now-3month",28800, "temperature3m.xml")

#ok 1 year
rrdExport("now-1y",43200, "temperature1y.xml")



if sensorData[0]!=None:
  print("Temp:{} Celsius  Humidity:{}%".format(sensorData[0],sensorData[1],))
else:
  print("Unable to read sensor")


#probe.cancel()
pi.stop()

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Wed Oct 04, 2017 6:36 pm

Then when running "wget https://dl.dropboxusercontent.com/u/488 ... ol_data.sh" it comes back with 404 not found.
Yep! Dropbox removes the public access

https://www.dropbox.com/s/y410y5rn94bvy ... ta.sh?dl=0

JNie257
Posts: 4
Joined: Tue Oct 03, 2017 9:46 pm

Re: DHT11 readings onto a web page!

Wed Oct 04, 2017 7:13 pm

Thank you guys! I have my most recent temperature and humidity at "myIPaddress"/webdata/CurrentData.txt... To finish this, i just need temperature.html... its the same issue as before with dropbox.


JNie257
Posts: 4
Joined: Tue Oct 03, 2017 9:46 pm

Re: DHT11 readings onto a web page!

Thu Oct 05, 2017 1:32 am

Thanks again! Ive finished it and can now view my chart but it doesnt update. CurrentData.txt is holding the most up to date reading but no points are plotted in any charts. Anyone have any ideas?

danjperron
Posts: 2667
Joined: Thu Dec 27, 2012 4:05 am
Location: Québec, Canada

Re: DHT11 readings onto a web page!

Thu Oct 05, 2017 11:26 am

if you are using my setup you need to add the temperature reader script into a crontab


Something like that. I will confirm later I'm on the way to work.


* * * * * /usr/bin/python /home/pi/readtemperature.py

Return to “Python”

Who is online

Users browsing this forum: No registered users and 10 guests