WXforum.net

Web Weather => Weather Website PHP/AJAX scripting => Topic started by: azchrisf on December 30, 2017, 10:12:07 AM

Title: Purpleair PHP Retrieval script
Post by: azchrisf on December 30, 2017, 10:12:07 AM
This PHP script provides information retrieval from your Purpleair sensor's JSON file to a basic HTML interface.

This will come in great handy for those of you who wish to add a Purpleair "widget" to your websites like I do, which they STILL have yet to offer after 2 years. I wrote this in less than an hour being a novice, certainly they could...

The script is released under the Creative Commons Attribution-ShareAlike license.
Modify and redistribute as you want, but you must leave the credits intact, and if you make modifications, please share with your fellow members. Make sure to identify the version of the script you are sharing, as new ones can be released and of course it becomes confusing.

Enjoy!

NOTE:
If you are not familiar with the setup and install of PHP scripts, find someone who is. Web scripts and programs are not for beginners or the inexperienced.

Cavaets
weatherbee has noted that the JSON file appears to be two minutes behind the Purpleair site. This was in the first version of the script, since then changes have been made and it should display exactly what is being displayed on the PA website.

Current Version
The current version of the script attached to this message is v1.5 FINAL released 2/22/18.
Changes are listed in the script.

Finding your Sensor IDs:
You can find your sensor's IDs by going to www.purpleair.com/json and searching for your sensor's name. Usually 2 are listed, get both IDs - you will need them. The first is A and the second is B. Or email Purpleair for help with getting your sensor IDs.

For the Thingspeak IDs for PM10 values, these are listed in the JSON file as well. You will need the values THINGSPEAK_PRIMARY_ID and THINGSPEAK_PRIMARY_ID_READ_KEY from both sensors (A and B). A will have a set of those, and B will have a set of those. If you are using the All Data option, you will also need the THINGSPEAK_SECONDARY_ID and THINGSPEAK_SECONDARY_ID_READ_KEY again from both sensors.

Caching Mode - OPTIONAL
Purpleair and Thingspeak do not like it (and will block you) if you make too many requests in a short period of time to their website. What the limits are I have no idea, but small weather sites unless they are high traffic shouldn't have an issue and is a non-issue. But if you want to decrease loading time anyways, you can enable the Caching mode of the script (Version 1.5). It will download the data and store it locally on the server for the period of time you set. Once that period is over it will re-request new data - just like any other cache. You can automate the process by enabling this option and CRON'ing the script.

All Data Mode - OPTIONAL
Version 1.5 has an option that will request all data from the sensor - you can use this to write additional HTML for different sensors, etc. However, it can take up to 15-20 seconds for all this data to be requested. It is recommended you use caching mode and CRON'ing the script when using this option. The All Data option returns the particles per deciliter and temp/hum of the sensor.

SQL Logging Mode - OPTIONAL
You can use the script in a CRON-type configuration at a predetermined interval to log the Purpleair data to a MySQL database without displaying anything, or you can do it with displaying the data as usual. In phpMyAdmin, create a database for the data, then attached is a SQL dump file you can import to phpMyAdmin that will create the tables for you. Make sure you import this under the database you just created. THIS IS NOT NECESSARY UNLESS YOU WANT TO USE THE SQL LOGGING MODE.
Title: Re: Purpleair PHP Retrieval script
Post by: weatherbee on December 30, 2017, 03:59:28 PM
Thanks for the script.  I've incorporated it with my AQI block.
You can see at www.shermanctweather.org.
Tom
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on December 31, 2017, 02:46:09 AM
Looks great! Hope you enjoy it!
Title: Re: Purpleair PHP Retrieval script
Post by: WSP on December 31, 2017, 09:57:12 AM
Many Thanks for the good work ;-)
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 02, 2018, 11:21:45 PM
I just got my PurpleAir and setup this script but noticed the AQI on the PurpleAir site and this script do not match.

This there more than one way to calculate AQI?

Is this script calculating the AQI correctly?

http://www.weathercat.net/purpleair.php
https://www.purpleair.com/map?&zoom=15&selected=393264|393266&lat=36.98094&lng=-122.01315899999997&clustersize=30&orderby=L&latr=0.03081979434855242&lngr=0.05776405334472656 (https://www.purpleair.com/map?&zoom=15&selected=393264|393266&lat=36.98094&lng=-122.01315899999997&clustersize=30&orderby=L&latr=0.03081979434855242&lngr=0.05776405334472656)
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on January 03, 2018, 04:44:49 AM
I just got my PurpleAir and setup this script but noticed the AQI on the PurpleAir site and this script do not match.

This there more than one way to calculate AQI?

Is this script calculating the AQI correctly?

http://www.weathercat.net/purpleair.php
https://www.purpleair.com/map?&zoom=15&selected=393264|393266&lat=36.98094&lng=-122.01315899999997&clustersize=30&orderby=L&latr=0.03081979434855242&lngr=0.05776405334472656 (https://www.purpleair.com/map?&zoom=15&selected=393264|393266&lat=36.98094&lng=-122.01315899999997&clustersize=30&orderby=L&latr=0.03081979434855242&lngr=0.05776405334472656)
Yes there are more ways to calculate. But only one "official" for the US.
https://www.airnow.gov/index.cfm?action=airnow.calculator

When I enter the values for PM2.5 Santa Cruz HighSchool https://www.purpleair.com/json?show=4355 there I get the same AQI as at the map:
21 ug/m3 => 70 AQI  Moderate

This purpleair script returns similar results when I test it for Santa Cruz HighSchool
21.58 ug/m3 => AQI 71 Moderate

But your script http://www.weathercat.net/purpleair.php returns lower values but the calculation is correct
14 ug/m3 => AQI 55 Moderate
Those 14 ug/m3 values are different from Santa Cruz HighSchool at the purpleair map which are all in the 20 ug/m3  range.

Check your script and  the number you entered at:
Code: [Select]
$sensorid = '4355';
Wim

Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 03, 2018, 07:44:08 AM
I checked my station ID and it's correct. https://www.purpleair.com/json?show=5650

The vales are much closer today but never seem to be the same.

At this point I guess it could be a rounding issue.

Title: Re: Purpleair PHP Retrieval script
Post by: weatherbee on January 03, 2018, 07:51:19 AM
I changed the script a little to pull the time of the file it is using.  I noticed it's about two minutes behind then the script on the map.  Also script pulls data only from channel A and I assume the AQI on the map is the average between channel A and B.
Tom
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on January 03, 2018, 07:55:25 AM
I changed the script a little to pull the time of the file it is using.  I noticed it's about two minutes behind then the script on the map.  Also script pulls data only from channel A and I assume the AQI on the map is the average between channel A and B.
Tom
Exactly, I was typing that now, When you check the link, https://www.purpleair.com/json?show=5650 you see that the two sensors are reported separate, their PM2.5 are  9.02 and 9.79  which result in an AQI of 38 and 40.

Succes, Wim


Title: Re: Purpleair PHP Retrieval script
Post by: weatherbee on January 03, 2018, 08:13:10 AM
I also changed the script to pull in both channels and average them together.
Tom
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on January 03, 2018, 09:42:46 AM
Thanks for the script, works nicely though I had   to change some of the html code due to formatting and xHTML validation failures.

Does.anyone have html/PHP code for both sensors?

Sent from my ONEPLUS A5010 using Tapatalk

Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 03, 2018, 10:04:20 AM
I would appreciate both of you sending me the updates you made, and I'll update the script for everyone.

Sent from my Pixel using Tapatalk

Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 04, 2018, 07:46:19 AM
I would appreciate both of you sending me the updates you made, and I'll update the script for everyone.

Sent from my Pixel using Tapatalk
Yes please, I would love having the improvements others have made in this script.
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on January 05, 2018, 05:12:01 PM
I would appreciate both of you sending me the updates you made, and I'll update the script for everyone.

Sent from my Pixel using Tapatalk

Once I have my unit and testing with my Website I'll update the code for my Saratoga Script. the only improvements I have done so far is some xHTML validation

Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 06, 2018, 10:50:07 AM
I have updated the original post with Version 1.1 of the script.
The following changes were made:

// Version 1.1
// * Added Sensor channel B and averaging for ug/m3 - thanks to weatherbee
// * Addded timestamp option
// * Added averaging option for AQI values (try and see if it shows more acurately to Purpleair's site when turned on)

Not listed in the changes (forgot):

* Changed AQI value to center
* Changed appearance to 100% of width, this way it can be integrated within tables, etc. and auto-adjust for different screen areas

I will integrate Toxic's HTML changes for the next version.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 06, 2018, 07:44:19 PM
Thanks for the update. I made a few changes and thought I'd pass them on to see what you think of them.

I fixed the Show Time Stamp option.
I changed the Average API option to show both channels or to average them.
I added the One Week reading.
I added the GetPMComment.

Keep in mind I'm not a programmer so I probably did not do things the most efficient way.

http://www.weathercat.net/wxpurpleair.php

Edit: Made a few small fixes to the file.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 07, 2018, 12:16:12 AM
Looks great! I will add that all in.
One thing I'd like to ask after further reflection is that if you make changes, please send them to me via PM, otherwise posting different versions of updates in the thread could confuse other users as to what's up to date or not. If your making cosmetic changes, feel free to post them but code changes please send to me.

Two thing I need to tackle, and need help with:

1. The PA display shows a kind of color transition as you get near another level (ex. Low to Moderate) using a yellow-green type color - same for others. If someone can come up with code for that I'm sure all of us would appreciate it, I have the Purpleair code for it but they use a lot of different functions it seems.

2. For you Weatherbee espicially - how can we get the Meteotemplate block to auto refresh? Once we get this done I'll submit it to Jachym for inclusion on his site for everyone.

Thank you all for helping out with the script - I'm glad we are making something we can all use :-)
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 10, 2018, 12:34:00 PM
Incase anyone wants to work on those transition colors, here is the complete PA javascript file showing what they do.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 14, 2018, 12:11:13 AM
If your are using the ajax dashboard cell template I have modified the get-aqi-rss-with-link.php file to pull data from the json file.

Just add your IDs and pick if you want to show the real time or short term reading.

http://www.weathercat.net/cell.php

Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 14, 2018, 12:43:02 AM
Excellent work - when I get a little more time me and weatherbee will try and submit an official block for Meteotemplate.

www.copperwoodwx.com
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 14, 2018, 10:21:43 AM
Posted Version 1.2 today -

Changes from the script:

// Version 1.2
// * Changed the Average API option to show both channels or to average them (thanks to Forever)
// * Added the One Week reading (thanks to Forever)
// * Added the GetPMComment (thanks to Forever)
// * Updated GetPMComment to the PurpleAir levels as they specify for the messages rather than US Gov standard
// * Did some Error Handling for connections
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 14, 2018, 12:27:04 PM
Doing a quick update to 1.2a, Forever made some quick fixes:

// Version 1.2a - all changes thanks to Forever
// * Fixed issue with styling missing in Channel B
// * Cleaned up table structure
// * Fixed typos/punctuation
// * Fixed W3 validation errors
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 20, 2018, 09:13:40 AM
Would anyone be interested if I added a MySQL logging function?
I'd add both a mode when the script is loaded, and a CRON-type function that wouldn't display the HTML but just pull the values from PA's site and log them (good for doing your own graphs, logs, etc.).
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on January 20, 2018, 09:43:41 AM
Would anyone be interested if I added a MySQL logging function?
I'd add both a mode when the script is loaded, and a CRON-type function that wouldn't display the HTML but just pull the values from PA's site and log them (good for doing your own graphs, logs, etc.).
Sounds like a good idea. Would be interested in this myself.

Sent from my ONEPLUS A5010 using Tapatalk

Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 29, 2018, 04:07:35 AM
Releasing Version 1.3a today.
Changes:

// --
// Version 1.3
// * Added option of logging of sensor data to MySQL DB
// * Added PM10 data from Thingspeak
// --
// Version 1.3a
// * Added option to show values of ug/m3 in 2 decimal places if value is less than 1 (ex. instead of 0 you will see 0.35 or whatever the value)
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 30, 2018, 11:31:51 AM
Thanks for the update.

I was not able to get the SQL to work.

Any change you could make a SQL Import file? I'm not getting an error but I may have setup something wrong.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 30, 2018, 12:35:17 PM
I screwed up with the SQL statement, I fixed it and also attached a SQL dump file to create the tables for you. See directions I posted in original post.

Sorry 'bout that.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 30, 2018, 06:56:38 PM
Thanks for fixing the SQL.

There are two new issues now.
The Combine HTML broke the color and format on channel b.
There are 3 lines of code I had to remove to get the page to load.
echo getAQIColorGradedRGBA(32.1,1);
echo getAQIColorRGB(48);
echo getAQIColorTonedTR(48);
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 30, 2018, 07:21:27 PM
Does anyone have a list of what values are in all of the ThingSpeak fields?
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on January 30, 2018, 09:29:21 PM
I'm being a total idiot today - I uploaded the testing version of the script I'm trying things in.
I uploaded the CORRECT file that fixes both those problems.

Purpleair sent me this that shows what fields are what -

https://docs.google.com/document/d/15ijz94dXJ-YAZLi9iZ_RaBwrZ4KtYeCy08goGBwnbCU/edit?usp=sharing

I barely could figure out how to work with that REST API, and the best I did was a fluke and I got the PM10 value.
So by all means play with it and if you can get it to work let me know! :D
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 30, 2018, 10:37:37 PM
Thanks again.

It seems to be working well.
http://www.weathercat.net/wxpurpleair.php

Thanks for the link, the file will be very useful. I'll see what I can do with it this weekend.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on January 31, 2018, 11:18:34 PM
It looking like the css code for channel A when both channels are shown was removed.

Now when you show both channels channel A is showing the color for the combination of both channels rather than the channel by it's self.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 01, 2018, 01:47:09 AM
Yes I combined the CSS code, but I made sure a 2nd one was reference, so Hmmm...I see it's referencing the AQI values correct, so I'm not sure why.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 01, 2018, 02:28:36 AM
Currently there are only 2 sets of CSS code. You need 3, one for A, B And A+B.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 01, 2018, 02:53:43 AM
Yeah I see the problem.
I'll update the thing in a few hours.

Thanks for letting me know :-)
Title: Re: Purpleair PHP Retrieval script
Post by: weatherbee on February 01, 2018, 07:30:33 AM
I noticed that for PM10 that the PPMLevel is calculated the same as PM2.5.  For particles over 12 µg/m3 goes to medium level but PM10 doesn't go to medium level till it's over 50 µg/m3.  You can see the PM10 levels change at https://aqicn.org/calculator/.
Tom
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 01, 2018, 09:28:01 AM
Alright I uploaded 1.4 - I fixed the CSS problem, and I verified that it is infact putting out the correct LOW, MEDIUM, etc. for PM10.
Keep in mind I am using the values from Purpleair's site/scripts, not the US EPA standard. If you want them different then by all means you can change them in your script. But I would be careful, the way the Purpleair sensor measures things and does the math could be totally different than the way EPA does things for certain reasons and you could be giving an erronous value. Or the other way around - who knows, not my job :-P

I also added Channel B to the PM10 - so make sure you re-read the thread, it requires the keys from Channel B too.

I don't plan to add it to the script but on my site you can see I added a PM10 AQI number. Feel free to customize the script.
If you want to do this all you have to do is copy the AQI cell at top and change it to aqiFromPM($pm10val).
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on February 01, 2018, 10:21:33 AM
tried to get this working but ended up as a blank screen on my saratoga template.  1.3 worked, but 1.4 will not show. just curious,  looking at your code should you not wrap all php code (that is within the html table code) with

Code: [Select]
<?php
phpcode
....
?>

rather than no php opening and closing tags?

example:
Code: [Select]
<tr>
<td colspan="7" style="height: 48px" class="auto-style13">Short-term PM<sub>2.5</sub> is '. GetPPMLevel($aqst) . ' at ' . $aqst . ' &#181;g/m3 - '. $MessageComment . '</td></tr> ';
if (empty($TSID)) {
} else {
echo '
<tr><td colspan="7" style="height: 48px" class="auto-style13">Short-term PM<sub>10</sub> is '. GetPPMLevel($pm10val) . ' at ' . $pm10val . ' &#181;g/m3 </td> ';
}
echo ' </tr>
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 01, 2018, 10:53:13 AM
You can do it different ways....It's running fine on my PHP (http://copperwoodwx.com/purpleair.php)
Make sure you have entered BOTH keys for the Thingspeak, that could kill it, also try removing this line:

Code: [Select]
if ($TSID == "" || $TSID2 = "")
{
echo "No Thingspeak credentials entered.";
die;
}

Give me a link to your site too and check the PHP error log.
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on February 01, 2018, 11:07:45 AM
I've recreated the file again managed to get the template working now.  think it was an extra ;' somewhere since i had added the AQI categories table below the values.

https://www.conligwx.org/wxairquality.php
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 01, 2018, 11:45:11 AM
I found some bugs too, at least with my PHP version.
Uploaded 1.4b.

Sorry for all the changes and updates, I know it's a PITA to update so frequently.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 01, 2018, 06:22:15 PM
weatherbee I re-read your post, I think I may have misunderstood.
I don't have any values for PM10, nor does Purpleair, and EPA standard is over 24 hours...so I am unsure what to use?
Title: Re: Purpleair PHP Retrieval script
Post by: weatherbee on February 01, 2018, 07:20:42 PM
azchrisf
Quote
so I am unsure what to use?
I am too.  I think I'll have to reseach more on PM10 before I know how to handle it.
Tom
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 01, 2018, 11:25:09 PM
It's hard to test with the site going up and down but I think the PM10 is outputting 0 or a value lower than it should be for channel B. I see to be getting a value about half what I should be getting.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 02, 2018, 02:40:56 AM
Make sure your running 1.4b, I fixed a bug that caused that.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 02, 2018, 07:43:35 AM
I just checked and I have the 1.4b version and this is still an issue. It looks like there is an extra /2 in the code.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 02, 2018, 08:57:48 AM
Can't be...?
This is running the raw 1.4b version, and it works fine:
http://copperwoodwx.com/purpleair.php
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 02, 2018, 10:31:08 AM
All I know is when I go to the IP address of my PurpleAir the PM10 displayed there is 2 X higher then what shows in the script.

If I remove the extra /2 in the code the numbers match. I removed this in the code that shows the value if it's less than zero if I remember correctly.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 03, 2018, 07:58:48 AM
If you are refering to this line:

Code: [Select]
if ($pm10 + $pm102 < "1.0") {
$pm10val = round(($pm10 + $pm102)/2,2);
} else {
$pm10val = round(($pm10 + $pm102)/2,0);
}
} else {
...
$pm10val = round(($pm10 + $pm102)/2,0);

Then no, it is supposed to be there. The first two in the if block are for the decimal ON, deciding whether it's less than 1 or not, and the 3rd one under the else block is for when the decimal option is OFF. All the ,0 and ,2 do is tell it how many decimal places to use.

If the PM10 ug/m3 level is below 0 (ex. 0.35), it's just going to show 0 like it always did. That's why
I added the option to show the decimal place. Some people may want to see it others don't.

I'd like to know what your PM10 value is when this problem is happening from both your sensor and what it shows.

weatherbee - Consider that the sensor is providing a particle ug/m3 reading instantaneous.

From all appearances, it appears Purpleair is using the 24hr formula for an instantaneous read on the PM 2.5 AQI according to published tables for the math, and I also tested it with the EPA calculator for PM10.

If you want to, I personally am, but do not want to add it to the script because I am unsure if it is correct, here is the code I came up with:

Code: [Select]
function aqiFromPM10 ($pm10num) {
if (is_nan($pm10num)) {
return "-";
}
if (isset($pm10num) == false) {
return "Error: No value";
}
if ($pm10num < 0.0) {
return $pm10num;
}
if ($pm10num > 1000.0) {
return "Polluted beyond belief";
}
if ($pm10num > 505) {
return calcAQI($pm10num, 500.0, 401.0, 604.0, 505.0);
} else if ($pm10num > 425) {
    return calcAQI($pm10num, 400.0, 301.0, 504.0, 425.0);
  } else if ($pm10num > 355) {
    return calcAQI($pm10num, 300.0, 201.0, 424.0, 355.0);
  } else if ($pm10num > 255) {
    return calcAQI($pm10num, 200.0, 151.0, 354.0, 255.0);
  } else if ($pm10num > 155) {
    return calcAQI($pm10num, 150.0, 101.0, 254.0, 155.0);
  } else if ($pm10num > 55) {
    return calcAQI($pm10num, 100.0, 51.0, 154.0, 55.0);
  } else if ($pm10num >= 0.0) {
    return calcAQI($pm10num, 50.0, 0.0, 54.0, 0.0);
  } else {
    return "-";
  }
}

and also

Code: [Select]
function GetPPMLevel($pmlevel, $pmtype)
{
if ($pmtype = "PM25") {
if ($pmlevel <= 30) {
return "LOW";
} else if ($pmlevel >=30) {
return "MODERATE";
} else if ($pmlevel >=70) {
return "HIGH";
} else if ($pmlevel >=200) {
return "VERY HIGH";
} else if ($pmlevel > 500) {
return "EXTREME";
} else {
return "UNKNOWN";
}
} elseif ($pmtype = "PM10") {
      if ($type = "PM10") {
if ($pmlevel <= 54) {
return "LOW";
} else if ($pmlevel >=55) {
return "MODERATE";
} else if ($pmlevel >=155) {
return "HIGH";
} else if ($pmlevel >=255) {
return "VERY HIGH";
} else if ($pmlevel >= 355) {
return "EXTREME";
} else {
return "UNKNOWN";
}
}
}
}

When using that and Purpleair's existing code, the values mirror exactly the EPA calc's. So if you think it's correct, I'll add it, otherwise I'll leave it out.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 03, 2018, 12:57:12 PM
Looking at this again the /2 should be there but the script is not pulling a value for channel b.

I made a small script to just pull the PM10 data and I do have data for both channels.

I'm not sure why the script will not output data for channel b.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 04, 2018, 12:33:57 AM
I was not able to fix the bad data in channel b from Thingspeak.

I replaced the code to pull the PM1, PM2.5 and PM10 from the PurpleAir directly.

http://www.weathercat.net/wxaqi.php
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 04, 2018, 12:43:15 AM
I was not able to fix the bad data in channel b from Thingspeak.

I replaced the code to pull the PM1, PM2.5 and PM10 from the PurpleAir directly.

http://www.weathercat.net/wxpurpleair.php
Send me via PM the entire script, with your data filled out in it. Use the 1.4b I posted, please don't include any of your changes.

I will look and see whats going on.

Sent from my Pixel using Tapatalk

Title: Re: Purpleair PHP Retrieval script
Post by: weatherbee on February 04, 2018, 10:40:26 AM
azchrisf,
I think what you've done on the PM10 looks good.
When I pull the info on PM10 channel B I am getting -1.
Tom
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 04, 2018, 11:21:29 AM
azchrisf, I just sent you my file that will not pull PM10 channel b data and a file that simple pulls PM10 data to verify that the data is there.

Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 04, 2018, 11:26:06 AM
OK I found the problem, 1.4c forthcoming.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 04, 2018, 11:52:04 AM
Okey dokey - posted 1.4c.

// Version 1.4c
// * Fixed bug with PM10 values
// * Added experinmental PM10 AQI function
// * Tuning of script
// * Other misc. changes
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on February 05, 2018, 05:58:52 PM
Okey dokey - posted 1.4c.

// Version 1.4c
// * Fixed bug with PM10 values
// * Added experinmental PM10 AQI function
// * Tuning of script
// * Other misc. changes

is the same type of aqi values available locally?  http://ip.of.purple.air/json   ??
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 05, 2018, 06:12:05 PM
The PM data is there but it lacks the Running Averages.

Here is a little script that will pull data from your PurpleAir you can play with. Just change the IP in the script.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 06, 2018, 04:26:18 PM
I noticed that the script for my cell broke when the PM reached 0.09. I did not have change to check this script before it went back over 0.1 but I used the same code on my cell page.

Will this script handle PM vales below 0.1?

Nice air quality in Northern California today. :)
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 07, 2018, 03:10:11 AM
I substitued a made up value and it displayed fine.

 [ You are not allowed to view attachments ]
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on February 08, 2018, 08:00:05 AM
Small change to mine template.

changing code "m3" to m&#179; to show the m3 as m³
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 12, 2018, 08:07:50 AM
Just to let everyone know I'm working on some changes for the next iteration. It's becoming "all it can be", so development will be slowing to, well, nothing, unless someone finds a bug or wants a feature.

// Version 1.5
// * Fixed bug where if decimal point was turned off decimal point numbers would still show - now display 0 as originally intended
// * Added option to cache results for x seconds - this is useful if you have a high traffic site. PA doesn't like you doing many calls to it.
// * Removed the site up checking, it slows the script and is redundant since the script will return an error anyways if it fails.
// * Changed m/3 to proper HTML entity (thanks Toxic)
// * Added all the variables from other sensor items (PM 1.0, ug/m3 for 0.3mm, 5mm, etc. - these can be used as you like but won't appear in the script HTML)
// * Added "Very Low" value to GetPMMessage for values < 1.0
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 14, 2018, 12:11:04 PM
Has version 1.5 been released or are the changes listed being worked on still?
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 14, 2018, 01:13:09 PM
Still working on it.

Sent from my Pixel using Tapatalk

Title: Re: Purpleair PHP Retrieval script
Post by: JupiterJoe on February 15, 2018, 12:33:33 PM
Thank you for your script, it's nice being able to get the data visualized on my website. http://www.joe4speed.com/purple.php

I was wondering if you would perhaps know any way to use this data to control the AQI on the front page of the Alt. Dashboard? Currently, I am only able to display the AirNow.gov data from West Palm Beach, and their AQI is totally different than our local AQI. www.jupiterwx.com

Thank you for any advice. It may not be possible, but I thought there would be no harm in asking. :)
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on February 15, 2018, 06:00:06 PM
Sure you can include the AQI from your PurpleAir if you know what code to change.

I'm not familiar with the dashboard you're using so I'll show you what I did for the one on my cell page and you should be able to see what is being done.

http://www.weathercat.net/cell.php

I have attached the file I changed to pull data directly from my PurpleAir. This will probably not work for you but it should get you pointed in the correct direction.
Title: Re: Purpleair PHP Retrieval script
Post by: JupiterJoe on February 15, 2018, 06:46:49 PM

Hi Forever,
Thank you for that code. I use the Alt Ajax dashboard built off of the Saratoga template. It looks very similar to yours and uses the aqirss.php script similar to yours.
I will definitely check it out though. Thank you for your reply.

Sure you can include the AQI from your PurpleAir if you know what code to change.

I'm not familiar with the dashboard you're using so I'll show you what I did for the one on my cell page and you should be able to see what is being done.

http://www.weathercat.net/cell.php

I have attached the file I changed to pull data directly from my PurpleAir. This will probably not work for you but it should get you pointed in the correct direction.
Title: Re: Purpleair PHP Retrieval script
Post by: sjforster on February 17, 2018, 07:27:45 PM
Hi azchrisf, Toxic and Forever,

Thanks for the script and developing this, it's been most usefull.  I've just got my purple air sensor up and running today and with the help of the script getting the data onto my website so thankyou very much.   =D&gt;

To contribute a small bit heres a tweak I've made to allow just the Air Quality index to be displayed on the main dashboard, by appending ?aqionly=true to the purpleair.php e.g. purpleair.php?aqionly=true.  Obviously you need to create a place within the dasboard to display the data i.e it won't do it automatically.

Hope it's of use and feel free to do with it what ever you want and thanks once again.

Regards,

Simon.


Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on February 22, 2018, 11:10:14 AM
Okey dokey, releasing the final version - 1.5.
Updated in the original post.

I'd like to thank Toxic, Weatherbee and Forever for all of their contributions to the script. Without them it wouldn't have progressed so good.

Enjoy!
Final Changelog:

// Version 1.5 FINAL RELEASE
// * Fixed bug where if decimal point was turned off decimal point numbers would still show - now display 0 as originally intended
// * Added option to cache results - this is useful if you have a high traffic site. PA doesn't like you doing many calls to it.
// * Removed the site up checking, it slows the script and is redundant since the script will return an error anyways if it fails.
// * Changed m/3 to proper HTML entity (thanks Toxic)
// * Added "Very Low" value to GetPMMessage for values < 1.0
// * Added additional levels to GetPMComment
// * Added GetAQIExMessage - returns extended EPA recommendations for the AQI passed to it
// * Added options to turn on/off the Title and Timestamps
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on March 07, 2018, 05:01:30 PM
Okey dokey, releasing the final version - 1.5.

Hi I have been cleaning up scripts since moving to PHP 7.2.x

looking at my Apache error  logs I see the following:

Quote
[Wed Mar 07 21:51:04.631870 2018] [php7:notice] [pid 5162:tid 140706869860096] [client xx.xx.188.229:58420] PHP Notice:  Undefined index: version in /htdocs/weather/purpleair.php on line 143
[Wed Mar 07 21:51:06.498380 2018] [php7:notice] [pid 5162:tid 140706869860096] [client xx.xx.188.229:58420] PHP Notice:  Undefined variable: showtitle in /htdocs/weather/purpleair.php on line 969
[Wed Mar 07 21:51:06.498440 2018] [php7:notice] [pid 5162:tid 140706869860096] [client xx.xx.188.229:58420] PHP Notice:  Undefined variable: sensorstamp in /htdocs/weather/purpleair.php on line 979

Can you tell me whats needed to fix this? As the Variables are not defined, why are they there?
Title: Re: Purpleair PHP Retrieval script
Post by: jeffm5690 on March 11, 2018, 01:10:52 PM
Thanks for the script.  I've incorporated it with my AQI block.
You can see at www.shermanctweather.org.
Tom

Would you be willing to share how you did this?  I would love to actually have a separate tab on the menu to have a page with this.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on March 11, 2018, 03:37:52 PM
Is the PurpleAir server having issues today? I'm not pulling data today for some reason.

http://www.weathercat.net/wxaqi.php
Title: Re: Purpleair PHP Retrieval script
Post by: giordolo on March 11, 2018, 03:40:11 PM
I'm bored by that
"No data from Purpleair servers for the script to process (Sensor A). Possibly PA site is down or incorrect sensor IDs."
Im a purpleair owner, why don't build a script that retrieve data directly from the sensor?
PA seems up. what is the role of thingspeak? who is really down?
giordolo
Title: Re: Purpleair PHP Retrieval script
Post by: ConligWX on March 11, 2018, 03:49:09 PM
It's working here fine. so perhaps route from your server to purpleair.com is broken.

Sent from my ONEPLUS 5T using Tapatalk
Title: Re: Purpleair PHP Retrieval script
Post by: giordolo on March 11, 2018, 03:50:21 PM
mmmm
looking to purpleair (json or map) is all fine
ty
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on March 11, 2018, 04:01:59 PM
Yah, the odd think is I can still pull the json file with my web browser but the script fails.
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on March 11, 2018, 04:29:57 PM
Seems to be a problem with the SSL certificate.

The most resent cacert.pem removed some entries causing the issue.
I reverted back to an older version.
Title: Re: Purpleair PHP Retrieval script
Post by: giordolo on March 11, 2018, 05:02:00 PM
Im live without changes
this is happening too often
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on March 12, 2018, 07:33:05 AM
Toxic -
This happens in PHP7 because it is more strict about variable declaration and usage. If error reporting has E_ALL, then your going to be seeing that from other scripts as well. It's still something I need to fix but it doesn't really mean anythings broken (as far as I know). I get them from Meteotemplate in my error log as well, if you don't want to see those messages (there mostly for debugging of scripts), change E_ALL to something like E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors) in your PHP config file.

As for the script not working today, first off, there is nothing I can do. The script doesn't have a mind of its own and decides it's having a bad day - if it was working and then stops working, something broke on your server or outside of the script. Purpleair's servers the last couple months have been a bit flaky here and there. You all need to remember the server and your machine are in separate locations on separate networks with (usually) separate routes - one route could be having issues (the server) while your PC isn't. There has been many famous cases of things like Google getting knocked offline for everyone who had an ISP that used Level3 for the route. What actually happened I have no idea.

Second, giordolo, based on your comments, you seem to be blaming my script for your troubles. If you don't like the script, don't use it and make something better. Instead of only complaining about the lack of something to retrieve the data, I did something about it and wrote one to do it, but that seems to not satisfy you. It took a lot of research and figuring things out too. Now if I am misinterpreting your comments my apologies but the way I read into them I don't see that.

If there is a bona fide problem with the script, I will be happy to fix it and typically tackle it pretty quick.


Title: Re: Purpleair PHP Retrieval script
Post by: giordolo on March 12, 2018, 08:11:36 AM
Oh No!
First of all I ask sorry if I have created the misunderstanding: I'm absolutely not blaming your script!
I'm sorry but my english is very poor: trust me, I really appreciate open source projects, I know that behind there is a loto of work and time spent on.
I use your script, I will use your script and I try to let you could improve it managing errors that are happenings.
Unfortunately I could only notify to you the errors; I'm not a developer but only a weather fan that tries to arrange a site in order to have some data :-)
Regarding the point, I dont understand how a script could stop and start to work without an external change; this is the why I was asking if purpleair api or thingspeak api were up during my failures. When I have said "this is happening too often" I was simply referring to the fact that it is happening too often; not blaming the script
I ask sorry again
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on March 12, 2018, 09:26:00 AM
Ok no worries then I misunderstood you

Sent from my Pixel using Tapatalk

Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on March 12, 2018, 10:36:42 AM
People are emailing me wanting local sensor data for upload to the web.
The script runs on PHP, which technically requires a webserver to work correctly. I would have to rewrite the entire script to use the local data. So in other words, this just isn't going to happen.

Now, I could write a small program that runs locally that will then upload via FTP the data, but I am not going to do that for free, I would need to charge for the program since it would take more of my already limited free time plus my professional responsibilities. If anyone else can do it I'd love for you to do that for the benefit of all.

I will be making a video explaining how to configure the script, but something I need to point out - PHP and web servers are not for beginners. You need to learn at least a little on how they work and how to work with them or you will be forever lost. ;-)
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on March 12, 2018, 11:35:26 AM
I currently pull the real-time, PM1, PM2.5 and PM10 data directly from my PurpleAir.

The problem is the short-term, 30 minute, 1 hour, 6 hours and other reading are not on the PurpleAir device. The values are calculated on the PurpleAir servers and then made available. The only way to get this kind of data would be to store it in sql and calculate the vales.

Like azchrisf said this is not an easy task.

I can provide a small script to pull just the current value from the local PurpleAir so that people can play around with it.

Code: [Select]
<?php

//Get the sensor data via JSON
$pajsona = @file_get_contents('http://192.168.1.103/json');
$json_resulta=json_decode($pajsonatrue);

//Create our variables for different Sensor results
$pm25a $json_resulta['pm2_5_cf_1'];
$pm25b $json_resulta['pm2_5_cf_1_b'];

$aqia aqiFromPM($pm25a);
$aqib aqiFromPM($pm25b);
$AQI round(($aqia $aqib)/2);

//Function to get AQI number from PPM reading
function aqiFromPM ($pm) {
if (is_nan($pm)) {
return "-";
}
if (isset($pm) == false) {
return "Error: No value";
}
if ($pm 0.0) {
return $pm;
}
if ($pm 1000.0) {
return "-";
}
if ($pm 350.5) {
return calcAQI($pm500.0401.0500.0350.5);
} else if ($pm 250.5) {
    return 
calcAQI($pm400.0301.0350.4250.5);
  } else if (
$pm 150.5) {
    return 
calcAQI($pm300.0201.0250.4150.5);
  } else if (
$pm 55.5) {
    return 
calcAQI($pm200.0151.0150.455.5);
  } else if (
$pm 35.5) {
    return 
calcAQI($pm150.0101.055.435.5);
  } else if (
$pm 12.1) {
    return 
calcAQI($pm100.051.035.412.1);
  } else if (
$pm >= 0.0) {
    return 
calcAQI($pm50.00.012.00.0);
  } else {
    return 
"-";
  }
}

//Function that actually calculates the AQI number
function calcAQI($Cp$Ih$Il$BPh$BPl) {
  
$a = ($Ih $Il);
  
$b = ($BPh $BPl);
  
$c = ($Cp $BPl);
  return 
round(($a/$b) * $c $Il);     
}

//Function that gets the AQI's description
function getAQIDescription($aqinum) {
  if (
$aqinum >= 401) {
  
return 'Hazardous';
  } else if (
$aqinum >= 301) {
  
return 'Hazardous';
  } else if (
$aqinum >= 201) {
  
return 'Very Unhealthy';
  } else if (
$aqinum >= 151) {
  
return 'Unhealthy';
  } else if (
$aqinum >= 101) {
  
return 'Unhealthy for Sensitive Groups';
  } else if (
$aqinum >= 51) {
  
return 'Moderate';
  } else if (
$aqinum >= 0) {
  
return 'Good';
  } else {
  
return 'Unknown';
  }
}

?>

Thinking about this a little more this may not work for others, my server is on my local network so it has access to my PurpleAir.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on March 21, 2018, 07:57:35 PM
Anyone notice that certainty graph they got up there now? How do you think it applies to this script (should I add it)?
Title: Re: Purpleair PHP Retrieval script
Post by: i_fiorentino on April 15, 2018, 05:47:43 AM
Hi guys,
thanks for sharing this script!

I've just installed my purple air sensor and installed script here: http://www.meteopistoia.it/custom/purpleair.php

Just a question.
Is there a meteotemplate block to sharing Pm10 / PM2.5?

Thansk in advance.
Regards,


Alessandro
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on April 15, 2018, 08:02:26 AM
Meteotemplate has a block available but it does not show AQI, only ug/m3 counts.
Title: Re: Purpleair PHP Retrieval script
Post by: azchrisf on April 15, 2018, 08:09:24 AM
Just wanted to point this out -

From further research, Purpleair is using the math for 24 hour weighted average for instant PM 2.5, which from my understanding, is wrong. You can see they are using 24 hours values in the script (I C/P verbatim except for conversion to PHP from their JS) from https://en.wikipedia.org/wiki/Air_quality_index#Computing_the_AQI. There really is no way I can see you can get an "instant" AQI - all the formulas need 24 hours of data, and NowCast looks like it needs at least 2 or more (2 works when I use their calculator).

Furthermore, the PM10 formula is also a 24 hour weighted average, and that is incorrect as well.

Someone needs to sit down and figure out the proper values for an AQI using an instantaneous read - IF it's even possible, like I said it doesn't seem to be. It's beyond my understanding as many times as I try to figure out the math, etc. for it, but I can see having an analytical personality that the math they are using (and likewise I am using in the script) for what they are doing vs. what it is meant for is wrong.

In order to actually to display the AQI bona-fide as the EPA does it, I would have to re-write the script to log values over a 24 hour period, then every hour do math to give a new AQI.

I'd love to hear comments from you guys.
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on April 15, 2018, 09:04:57 AM
Just wanted to point this out -

From further research, Purpleair is using the math for 24 hour weighted average for instant PM 2.5, which from my understanding, is wrong. You can see they are using 24 hours values in the script (I C/P verbatim except for conversion to PHP from their JS) from https://en.wikipedia.org/wiki/Air_quality_index#Computing_the_AQI. There really is no way I can see you can get an "instant" AQI - all the formulas need 24 hours of data, and NowCast looks like it needs at least 2 or more (2 works when I use their calculator).

Furthermore, the PM10 formula is also a 24 hour weighted average, and that is incorrect as well.

Someone needs to sit down and figure out the proper values for an AQI using an instantaneous read - IF it's even possible, like I said it doesn't seem to be. It's beyond my understanding as many times as I try to figure out the math, etc. for it, but I can see having an analytical personality that the math they are using (and likewise I am using in the script) for what they are doing vs. what it is meant for is wrong.

In order to actually to display the AQI bona-fide as the EPA does it, I would have to re-write the script to log values over a 24 hour period, then every hour do math to give a new AQI.

I'd love to hear comments from you guys.

The health effects of AQ are based on a continuous exposure to the measured value.
If the measured value  xyz remains the same for 24 hours the health effects would be abc

When calculating an AQ-index I display the current ("instant" AQI) with a warning that the health effects for that index are for a 24 hour period.

The Luftdaten and the PurpleAir sensor allow uploading the raw data to ones own website where calculation of "instant" and "24 hour" AQI can easily be done.

But  far more important than using "instant" or "24 hour" values, is the quality of the sensor itself.

After almost 2 months testing the PurpleAir sensor,  it turns out that the measured values (p/um3  or ug/m3)  are always higher then the official stations.

I attached a screenshot, the legenda with the health effects and the index are for Belgium/Europe not the US ones.
Top part is a Luftdaten sensor, always in the same range as the official measuring station. As are most of the 50+ Luftdaten sensors in our city. Check  current Luftdaten page at my website (https://weer.sluispark.be/index.php?p=mnu_aqhi_luft2&lang=en)

The Purpleair sensor at the bottom, is at the same location and always measures slightly more in the low AQ  to a lot higher in the high AQ.  Check  current PurpleAir page at my website (https://weer.sluispark.be/index.php?p=mnu_aqhi_purple&lang=en)

There is also a website where we compare our 50+ Luftdaten stations with the nearby official validated measurements. It uses the Dutch language as that is the official language here. https://leuvenair.be/in-detail/grafieken/
I attached a graph comparing my station with the official validated measurements.

Wim
Title: Re: Purpleair PHP Retrieval script
Post by: i_fiorentino on April 16, 2018, 06:57:18 PM
Hi guys,
before all, thanks for sharing this script!!  =D&gt; =D&gt;
i would show also pm2.5.

Which is the name of variable to show pm2.5? $aqst?
And what about Pm2.5 30min, 60min, 1hr, and 1week?


Thanks in advance.
Regards,


Alessandro
Title: Re: Purpleair PHP Retrieval script
Post by: ALITTLEweird1 on August 08, 2018, 08:25:56 PM
Why does the reading using the script show 18, but on the purple air map it shows 55?
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on August 09, 2018, 07:35:59 AM
Why does the reading using the script show 18, but on the purple air map it shows 55?
The Purpleair map shows realtime values for PM2.5 for your location here (https://www.purpleair.com/map?&zoom=15&detailsshowing=14033&selected=553337|553339&lat=47.49702591960684&lng=-121.78222797403566&clustersize=21&orderby=L&latr=0.028356942489018877&lngr=0.05119800567626953)  When I write this: AQHI is 70 for PM2.5 count of 21µg/m3

But one can not calculate the official AQHI based on a realtime value, it should be the 24 hour average value. At his moment your 24 hours value  from the  same Purpleair data  (https://www.purpleair.com/json?show=14033) is 4.45 µg/m3 with  an correct 24 hours AQHI of 19. I assume that your script also calculates using the 24 hour value.

I put your sensorID 14033 in the demo version of my script at  https://leuven-template.eu/purpleair/_test1.php (https://leuven-template.eu/purpleair/_test1.php)

You can check all PM2.5 values and the corresponding theoretical / correct AQHI for your sensor and compare those with your script.

Wim
Title: Re: Purpleair PHP Retrieval script
Post by: ALITTLEweird1 on August 09, 2018, 09:14:56 AM
I was just thinking the number on the purple air map would match the script.
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on August 09, 2018, 09:58:00 AM
I was just thinking the number on the purple air map would match the script.
If there are settings for selecting what to display and they are set correct, it should.
It all depends what you want to display.
The map uses "AQHI" but that can not be based on realtime-values.
Check he script you are using if one can select the realtime value and then they should be the same.

Wim
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on August 09, 2018, 10:17:29 AM
I downloaded this script Chris Formeister. www.copperwoodwx.com/www.cfcsaz.com
I set the sensor settings to yours: 14033 and 14034
No toher changes as by default the script displays the ShortTerm, almost equal to the value on the PurpleAir map

If you are also using that script, check your settings again or post a zip.

Wim
 
Title: Re: Purpleair PHP Retrieval script
Post by: ALITTLEweird1 on August 09, 2018, 10:43:10 AM
Thanks for checking that Wim. That looks much better.  Do you know where i can get a copy of that script so i can try it?

Thanks
Title: Re: Purpleair PHP Retrieval script
Post by: wvdkuil on August 09, 2018, 11:39:06 AM
Thanks for checking that Wim. That looks much better.  Do you know where i can get a copy of that script so i can try it?

Thanks
The link is in the first message of this topic.   https://www.wxforum.net/index.php?topic=33482.0

Wim
Title: Re: Purpleair PHP Retrieval script
Post by: giordolo on October 14, 2018, 05:29:23 AM
Hello, I'm using the script in this way (see attach, renamed in txt because the Forum dont allow php attachments). I'm a beginner and I'm not able to obtain the paga background same as the cell background that contains the current AUI value. Could someone help me please?
many thanks
giordolo
Title: Re: Purpleair PHP Retrieval script
Post by: JohnMaino on November 17, 2021, 05:25:40 PM
I'm posting here instead of starting a new thread since this is a PurpleAir-specific question.

I'm happy grabbing live, real-time data from my PurpleAir PA-II-SD, firmware v6.01 sensor on my local LAN for use with my home-automation setup via http://192.168.1.100/json?live=true. It's working great. No latency or reliability issues compared to using PurpleAir's public cloud API.

I'm concerned that at some point in future, PurpleAir Inc. may (for selfish corporate reasons) simply decide to remove direct access to the live, local-LAN json data. That they'll nix it "just because" with no reason given. The feature is both undocumented and unsupported by PurpleAir so presumably they could turn it off (via a firmware update) at their discretion and without warning. If they did so it would break my home automation setup.

Does anyone have details on how the PurpleAir PA-II unit implements checking for firmware updates? Does it do so in the course of normal push data requests to sensor-logging cloud servers, or does it contact a separate server to check on firmware updates?

If possibly I'd like to use a firewall rule to block firmware-update checks while still allowing the normal 2-minute push sensor-data uploads to the PurpleAir cloud.

Appreciate it if anyone has insight into firmware-update mechanics on the PA-II-SD, v.6.01
Title: Re: Purpleair PHP Retrieval script
Post by: 92merc on May 17, 2022, 12:54:25 PM
Bringing up an old thread.  I implemented the script.  But I noticed a little formatting issue.

Main PHP is formatting fine.
https://www.bismarckweather.net/purpleair.php

But I used a simple include PHP into Saratoga's wxnewpage.php template.  The top number with "Good" gets run into the number, unlike the main page.  Is there an easy fix?

https://www.bismarckweather.net/wxpa.php
Title: Re: Purpleair PHP Retrieval script
Post by: 92merc on May 19, 2022, 08:51:45 AM
Looks like this script will need a re-write.  ThingSpeak is going away.  Here is the post from Facebook:

A heads up to anyone using PurpleAir's ThingSpeak data.
We are switching to Google BigQuery for our database and there will be a new API on https://api.purpleair.com to get historic data soon. You will need to migrate your code to this new API as some time around August, ThingSpeak will no longer be available. We will let everyone know here and on the community site as soon as we have more information on the new history end point for sensors.
Title: Re: Purpleair PHP Retrieval script
Post by: 92merc on May 19, 2022, 08:53:58 AM
OK, more info:
https://community.purpleair.com/t/purpleair-data-migration-to-bigquery-and-a-new-api/295/3?fbclid=IwAR2YXj-WjhvW6s6lnovqjGKYvXtms1lZW1lnEvGhF6dMlK3Pdq_4WfD66Ng

"The current API used to access real-time data will not be affected. Instead, we will be adding a new endpoint for historical data. We want to keep backward compatibility as much as possible, and if significant changes need to be made, a new version will be released rather than updating the existing systems."
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on May 27, 2022, 12:55:48 PM
It looks like the script no longer works and will need to be redone to work with the API keys. I just requested my API keys.
Title: Re: Purpleair PHP Retrieval script
Post by: 92merc on May 27, 2022, 01:33:58 PM
Wow, they didn't take long to kill the old script.  Sounded like they were going to leave it running longer than that.
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on May 27, 2022, 02:28:21 PM
Yep, requested my keys also...
Title: Re: Purpleair PHP Retrieval script
Post by: mexbound on May 28, 2022, 08:25:24 AM
I had to comment out my include:

// include_once('get-aqi-rss.php');        // get AQI index value for dashboard display

in ajaxdashboard6.php.

It was causing a huge time delay on my main page that made my site look like it was down. It wasn't. It was just waiting on Purpleair.

How (and or where) did you request API keys?
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on May 28, 2022, 10:14:44 AM
That script doesn't use Purpleair -- it uses feeds.enviroflash.info for data -- it's not related to the Purpleair API change.

Your webserver is likely having a connectivity issue with feeds.enviroflash.info, and that's the cause of the delays.
Title: Re: Purpleair PHP Retrieval script
Post by: mexbound on May 28, 2022, 10:26:12 AM
Here is my get-aqi-rss.php script. No references to feeds.enviroflash.info
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on May 28, 2022, 10:49:35 AM
That's not the get-aqi-rss.php distributed with the alternative dashboard .. I'd not seen your script before.

It would have to be changed like I showed in the purpleair-inc.txt file above (and an API key acquired) to work again .. the old feed is no longer valid.
Title: Re: Purpleair PHP Retrieval script
Post by: mexbound on May 28, 2022, 10:55:30 AM
Ya, not sure where I got that script from. I got a purpleair device about a year ago and added the info to my site. I just asked purpleair for my API keys. When I get them I will update my script from the one you posted. Probably rename it from get-aqi-rss.php to get back in sync ...
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on May 28, 2022, 11:50:28 AM
When you get your API key, plug this into the updated script below (also renamed to get-purpleair-aqi to not interfere with the one in the alternative dashboard).
Title: Re: Purpleair PHP Retrieval script
Post by: mexbound on May 28, 2022, 12:03:44 PM
Thanks Ken. Will do.
Title: Re: Purpleair PHP Retrieval script
Post by: zeppline on May 31, 2022, 02:54:35 PM
Ken I have the two programs purpleair-inc.php and wxpurpleair1.php I had to add a 1 because I have wxpurpleair already. When I run it I get error (No sensor ID entered in Script source!) but I added it where the nnnn is two places. ID is 19455. I am missing something do I need the get-purpleair-aqi.php.  Thanks Joe
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on May 31, 2022, 03:53:11 PM
Hi Joe,
You just need to put in the script the replacements for
Code: [Select]
$sensorid = "nnnn";
// Insert your api.purpleair.com READ api key below
$PurpleAirAPI = '-read-api-key-here-';
and that should work.  I'm assuming you have a api.purpleair.com READ API key from them to use.

if you get "No sensor ID entered in Script source!" then it's not seeing your $sensorid value.  Make sure you're using the updated script I posted above and that you've configured and uploaded it to your website.
Title: Re: Purpleair PHP Retrieval script
Post by: meteohila on June 02, 2022, 09:40:50 AM
Hello,
I am writing to you from Spain, sorry for my bad English. I am contacting you about the purpleair script, I would like to add it to my website and these days I am watching this forum.
I have downloaded the file wxpurpleair.php and the new one to replace it get-purpleair-aqi.php from Saratoga weather, but I can't get it to work for me, I guess it must be easy, I don't know if I have a problem with hosting or permissions..
could you help me?
my website is: http://meteohila.esy.es/pronostico/wxpurpleair.php (http://meteohila.esy.es/pronostico/wxpurpleair.php)
but the script doesn't work for me...
I attach the files in case you see something wrong, the truth is that I have started to tweak to see if it could work but I have not been successful.
Thanks in advance and greetings
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on June 02, 2022, 10:21:56 AM
The wxpurpleair.php needs purpleair-inc.php for display.  The get-purpleair-aqi.php script wasn't the correct script.

For the page display, use the attached (after customization of purpleair-inc.php)
Title: Re: Purpleair PHP Retrieval script
Post by: mexbound on June 02, 2022, 10:34:01 AM
Thanks for the scripts Ken.  They work for me.  I wonder when we will hear from the WD developer about fixing the "flatlined" WD graph. I currently have taken it off my AQI web page until it gets fixed.  Thanks for all your support.
Title: Re: Purpleair PHP Retrieval script
Post by: meteohila on June 02, 2022, 11:09:40 AM
Ok, thank you for the answer Ken !!!
After having reloaded the new files and put the id of my purpleair and my api key it still doesn't work.
Now in the wxpurpleair.php file I get a black page
http://meteohila.esy.es/pronostico/wxpurpleair.php (http://meteohila.esy.es/pronostico/wxpurpleair.php)
  :???:
Title: Re: Purpleair PHP Retrieval script
Post by: mexbound on June 02, 2022, 11:19:21 AM
Hi Ken, Using the scripts you just posted here is what I get back. (see attached image).

I have two questions:
1. What does "Page Load" mean under the real time sensor icons?
2. What variable would I change in purple-inc.php to increase the description font size?



Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on June 02, 2022, 11:22:52 AM
The problem may be caused by two things:
1) your PHP is  5.3.29 which is WAY out-of-date.  The templates need at least PHP 5.6+ (preferably PHP 7.4 or 8.1) to work correctly.
2) you have a lot of scripts to update with your installation ( http://meteohila.esy.es/pronostico/check-fetch-times.php?show=versions )

The wxpurpleair.php page seems to be stopping after the top.php is included, so there is likely a PHP fatal error (syntax error?) somewhere below the include_once("top.php"); statement.  I tried a view-source:http://meteohila.esy.es/pronostico/purpleair-inc.php and that seems to be the stopping point.. it's returning no data or HTML comments.  There may be a PHP syntax error in your specification of the sourceid or API key (missing closing quote or semicolon) causing a fatal PHP error.  Or.. the PHP 5.3 json_decode() function is blowing up .. PHP 5.6 fixed most of those json_decode() errors.

When you do update your PHP version past 5.6, you'll need to change header.php
Code: [Select]
$tuom = split('°',$temperature);  // extract units to
Code: [Select]
$tuom = explode('°',$temperature);  // extract units as the split() function is removed from PHP in PHP 7.4+
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on June 02, 2022, 11:31:04 AM
Hi Ken, Using the scripts you just posted here is what I get back. (see attached image).

I have two questions:
1. What does "Page Load" mean under the real time sensor icons?
2. What variable would I change in purple-inc.php to increase the description font size?

"Page Load" is the current date/time from the server that the page was loaded.. as 'realtime' as can be.

The font sizes can be adjusted in the script by changing the built-in CSS  .. the description is displayed with
Code: [Select]
<td class="auto-style9" style="width: 85%"><strong>' . $Description . '</strong><br/> , but the auto-style9 is used in multiple places, so I'd change that line to have an inline style like
Code: [Select]
<td class="auto-style9" style="width: 85%;font-size:100%;"><strong>' . $Description . '</strong><br/>
Title: Re: Purpleair PHP Retrieval script
Post by: ALITTLEweird1 on June 10, 2022, 06:46:22 PM
I can't find where you request an API key. Anyone have that link by chance? Thanks
Title: Re: Purpleair PHP Retrieval script
Post by: Forever on June 10, 2022, 07:18:53 PM
Just ask them for one at contact@purpleair.com.
Title: Re: Purpleair PHP Retrieval script
Post by: txweather.org on July 01, 2022, 11:29:12 PM
As always, a million thanks @Ken. @Forever purpleair was quick to send me the key.
Title: Re: Purpleair PHP Retrieval script
Post by: staccermaccer on July 12, 2022, 01:45:15 PM
Hi, all

Maybe a stupid question but is this script adaptable for "luftdaten" data, i know it is configurable in WD where it works and give readings but i can't display it on my dashboard or i must have missed something?

Would be great if someone could help me out here!

Thanks in advance for any help provided...

Staccermaccer AKA Marc,

Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on July 12, 2022, 06:48:16 PM
Hi Marc,
The script *may* be adaptable to Luftdaten if they also have a JSON query for values present in their firmware.  I don't have a Luftdaten sensor, so don't know.   If you have one, take a snapshot of the JSON query (in text) and post it -- I'll take a look.
Title: Re: Purpleair PHP Retrieval script
Post by: staccermaccer on July 13, 2022, 01:09:08 AM
Hi Ken,

Yes it works also with a JSON-file, i will include a screenshot!

Marc,

PS: THX for giving it a stab!
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on July 13, 2022, 10:46:32 AM
I'm not sure that JSON has enough details to use.. I see SDS_P1 and SDS_P2 values (along with temperature, humidity), but I don't know if either SDS_P1 or SDS_P2 is a PM2.5 value that the script needs.

Looking more into it .. the SDS_P1 is the PM10 reading and SDS_P2 is the PM2.5 reading.  The firmware JSON return only returns the instantaneous value at the time of the local query -- no trending/historical data such as returned by the PurpleAir JSON query, so I think the PurpleAir script is not directly adaptable to the Luftdaten due to lack of extra data needed by the script.  Sorry...
Title: Re: Purpleair PHP Retrieval script
Post by: Scobey on August 26, 2023, 10:47:29 AM
I guess I'm a bonehead. Can't find this script here.
Title: Re: Purpleair PHP Retrieval script
Post by: 92merc on August 26, 2023, 11:59:29 AM
I think this is what you're looking for.  Just a page back...

https://www.wxforum.net/index.php?topic=33482.msg447542#msg447542
Title: Re: Purpleair PHP Retrieval script
Post by: Vasco on August 27, 2023, 01:15:22 PM
I've just started to use these scripts, but I'm puzzled by the fact that purpleair-inc.php seems to have two identical file_get_contents() calls to the API on lines 41 and 62:

Code: [Select]
$pajson = file_get_contents("https://api.purpleair.com/v1/sensors/$sensorid?api_key=$PurpleAirAPI",0,$STRcontext);
and a $fname location (line 61) when there is no caching that I can see.

Now that newcomers have to pay for PurpleAir API calls a cache might be useful: see here (https://www.wxforum.net/index.php?topic=45730.msg463332#msg463332) (you don't have to run the cron every 5 minutes)  :-)

But I would probably cache at

Code: [Select]
$fname = './cache/purpleair-'.$sensorid.'.json';
for a standard Saratoga setup.
Title: Re: Purpleair PHP Retrieval script
Post by: saratogaWX on August 27, 2023, 04:06:23 PM
Yes, silly me.. delete the one at line 62.  Only one pull on the API was needed.