title:Displaying Data from a Tempest Weather Station on a Static Site
posted:2024-02-11
tags:["all", "api", "javascript", "meta", "serverless"]

As I covered briefly in a recent Scribble, I was inspired by the way Kris's omg.lol page displays realtime data from his Weatherflow Tempest weather station. I thought that was really neat and wanted to do the same on my omg.lol page with data from my own Tempest, but I wanted to find a way to do it without needing to include an authenticated API call in the client-side JavaScript.

I realized I could use a GitHub Actions workflow to retrieve the data from the authenticated Tempest API, post it somewhere publicly accessible, and then have the client-side code fetch the data from there without needing any authentication. After a few days of tinkering, I came up with a presentation I'm happy with.

Glowing green text on a dark grey background showing weather data like conditions, temperature, and pressure, with a note that the data is 2 minutes old

This post will cover how I did it.

Retrieve Weather Data from Tempest API

To start, I want to play with the API a bit to see what the responses look like. Before I can talk to the API, though, I need to generate a new token for my account at https://tempestwx.com/settings/tokens. I also make a note of my station ID, and store both of those values in my shell for easier use.

read wx_token
read wx_station

After browsing the Tempest API Explorer a little, it seems to me like the /better_forecast endpoint will probably be the easiest to work with, particularly since it lets the user choose which units will be used in the response. That will keep me from having to do metric-to-imperial conversions for many of the data.

So I start out calling the API like this:

curl -sL "https://swd.weatherflow.com/swd/rest/better_forecast?station_id=$wx_station&token=$wx_token&units_temp=f&units_wind=mph&units_pressure=inhg&units_precip=in&units_distance=mi" \
| jq
{
"current_conditions": {
"air_density": 1.2,
"air_temperature": 59.0,
"brightness": 1,
"conditions": "Rain Possible",
"delta_t": 2.0,
"dew_point": 55.0,
"feels_like": 59.0,
"icon": "possibly-rainy-night",
"is_precip_local_day_rain_check": true,
"is_precip_local_yesterday_rain_check": true,
"lightning_strike_count_last_1hr": 0,
"lightning_strike_count_last_3hr": 0,
"lightning_strike_last_distance": 12,
"lightning_strike_last_distance_msg": "11 - 13 mi",
"lightning_strike_last_epoch": 1706394852,
"precip_accum_local_day": 0,
"precip_accum_local_yesterday": 0.05,
"precip_minutes_local_day": 0,
"precip_minutes_local_yesterday": 28,
"pressure_trend": "falling",
"relative_humidity": 88,
"sea_level_pressure": 29.89,
"solar_radiation": 0,
"station_pressure": 29.25,
"time": 1707618643,
"uv": 0,
"wet_bulb_globe_temperature": 57.0,
"wet_bulb_temperature": 56.0,
"wind_avg": 2.0,
"wind_direction": 244,
"wind_direction_cardinal": "WSW",
"wind_gust": 2.0
},
"forecast": { { ... }
"daily": [
{
[...],
"day_num": 10,
[...],
},
{
[...],
"day_num": 11,
[...],
},
{
[...],
"day_num": 12,
[...],
}
]
}
}

So that validates that the endpoint will give me what I want, but I don't really need the extra 10-day forecast since I'm only interested in showing the current conditions. I can start working some jq magic to filter down to just what I'm interested in. And, while I'm at it, I'll stick the API URL in a variable to make that easier to work with.

endpoint="https://swd.weatherflow.com/swd/rest/better_forecast?station_id=$wx_station&token=$wx_token&units_temp=f&units_wind=mph&units_pressure=inhg&units_precip=in&units_distance=mi"
curl -sL "$endpoint" | jq '.current_conditions'
{
"air_density": 1.2,
"air_temperature": 59.0,
"brightness": 1,
"conditions": "Light Rain",
"delta_t": 2.0,
"dew_point": 55.0,
"feels_like": 59.0,
"icon": "rainy",
"is_precip_local_day_rain_check": true,
"is_precip_local_yesterday_rain_check": true,
"lightning_strike_count_last_1hr": 0,
"lightning_strike_count_last_3hr": 0,
"lightning_strike_last_distance": 12,
"lightning_strike_last_distance_msg": "11 - 13 mi",
"lightning_strike_last_epoch": 1706394852,
"precip_accum_local_day": 0,
"precip_accum_local_yesterday": 0.05,
"precip_description": "Light Rain",
"precip_minutes_local_day": 0,
"precip_minutes_local_yesterday": 28,
"pressure_trend": "falling",
"relative_humidity": 88,
"sea_level_pressure": 29.899,
"solar_radiation": 0,
"station_pressure": 29.258,
"time": 1707618703,
"uv": 0,
"wet_bulb_globe_temperature": 57.0,
"wet_bulb_temperature": 56.0,
"wind_avg": 1.0,
"wind_direction": 230,
"wind_direction_cardinal": "SW",
"wind_gust": 2.0
}

Piping the response through jq '.current_conditions' works well to select that objects, but I'm still not going to want to display all of that information. After some thought, these are the fields I want to hold on to:

  • air_temperature
  • conditions
  • feels_like (apparent air temperature)
  • icon
  • precip_accum_local_day (rainfall total for the day)
  • pressure_trend (rising, falling, or steady)
  • relative_humidity
  • sea_level_pressure (the pressure recorded by the station, adjusted for altitude)
  • time (epoch timestamp of the report)
  • wind_direction_cardinal (which way the wind is blowing from)
  • wind_gust

I can use more jq wizardry to grab only those fields, and I'll also rename a few of the more cumbersome ones and round some of the values where I don't need full decimal precision:

curl -sL "$endpoint" | jq '.current_conditions | {temperature: (.air_temperature | round), conditions,
feels_like: (.feels_like | round), icon, rain_today: .precip_accum_local_day, pressure_trend,
humidity: .relative_humidity, pressure: ((.sea_level_pressure * 100) | round | . / 100), time,
wind_direction: .wind_direction_cardinal, wind_gust}'
{
"temperature": 58,
"conditions": "Very Light Rain",
"feels_like": 58,
"icon": "rainy",
"rain_today": 0.01,
"pressure_trend": "steady",
"humidity": 91,
"pressure": 29.9,
"time": 1707620142,
"wind_direction": "W",
"wind_gust": 0.0
}

Now I'm just grabbing the specific data points that I plan to use, and I'm renaming messy names like precip_accum_local_day to things like rain_today to make them a bit less unwieldy. I'm also rounding the temperatures to whole numbers1, and reducing the pressure from three decimal points to just two.

Now that I've got the data I want, I'll just stash it in a local file for safe keeping:

curl -sL "$endpoint" | jq '.current_conditions | {temperature: (.air_temperature | round), conditions,
feels_like: (.feels_like | round), icon, rain_today: .precip_accum_local_day, pressure_trend,
humidity: .relative_humidity, pressure: ((.sea_level_pressure * 100) | round | . / 100), time,
wind_direction: .wind_direction_cardinal, wind_gust}' \
> tempest.json

Post to paste.lol

I've been using omg.lol for a couple of months now, and I'm constantly discovering new uses for the bundled services. I thought that the paste.lol service would be a great fit for this project. For one it was easy to tie it to a custom domain2, and it's got an easy API that I can use for automating this.

To use the API, I'll of course need a token. I can find that at the bottom of my omg.lol Account page, and I'll once again store that as an environment variable. I can then test out the API by creating a new paste:

curl -L --request POST --header "Authorization: Bearer $omg_token" \
"https://api.omg.lol/address/jbowdre/pastebin/" \
--data '{"title": "paste-test", "content": "Tastes like paste."}'
{
"request": {
"status_code": 200,
"success": true
},
"response": {
"message": "OK, your paste has been saved. <a href=\"https:\/\/paste.lol\/jbowdre\/paste-test\" target=\"_blank\">View it live<\/a>.",
"title": "paste-test"
}
}

And, sure enough, I can view it at my slick custom domain for my pastes, https://paste.jbowdre.lol/paste-test

Simple webpage with the message, Tastes like paste.

That page is simple enough, but I'll really want to be sure I can store and retrieve the raw JSON that I captured from the Tempest API. There's a handy button the webpage for that, or I can just append /raw to the URL:

Plaintext page with the same message

Yep, looks like that will do the trick. One small hurdle, though: I have to send the --data as a JSON object. I already have the JSON file that I pulled from the Tempest API, but I'll need to wrap that inside another layer of JSON. Fortunately, jq can come to the rescue once more.

request_body='{"title": "tempest.json", "content": '"$(jq -Rsa . tempest.json)"'}'

The jq command here reads the tempest.json file as plaintext (not as a JSON object), and then formats it as a JSON string so that it can be wrapped in the request body JSON:

jq -Rsa '.' tempest.json
"{\n \"temperature\": 58,\n \"conditions\": \"Heavy Rain\",\n \"feels_like\": 58,\n \"icon\": \"rainy\",\n \"rain_today\": 0.05,\n \"pressure_trend\": \"steady\",\n \"humidity\": 93,\n \"pressure\": 29.89,\n \"time\": 1707620863,\n \"wind_direction\": \"S\",\n \"wind_gust\": 1.0\n}\n"

So then I can repeat the earlier curl but this time pass in $request_body to include the file contents:

curl -L --request POST --header "Authorization: Bearer $omg_token" \
"https://api.omg.lol/address/jbowdre/pastebin/" \
--data "$request_body"
{
"request": {
"status_code": 200,
"success": true
},
"response": {
"message": "OK, your paste has been saved. <a href=\"https:\/\/paste.lol\/jbowdre\/tempest.json\" target=\"_blank\">View it live<\/a>.",
"title": "tempest.json"
}
}

And there it is, at https://paste.jbowdre.lol/tempest.json/raw:

Plaintext weather data in JSON format

Automate with GitHub Actions

At this point, I know the commands needed to retrieve weather data from the Tempest API, and I know what will be needed to post it to the omg.lol pastebin. The process works, but now it's time to automate it. And I'll do that with a simple GitHub Actions workflow.

I create a new GitHub repo to store this (and future?) omg.lol sorcery, and navigate to Settings > Secrets and variables > Actions. I'll create four new repository secrets to hold my variables:

  • OMG_ADDR
  • OMG_TOKEN
  • TEMPEST_STATION
  • TEMPEST_TOKEN

And I'll create a new file at .github/workflows/tempest.yml to define my new workflow. Here's the start:

1name: Tempest Update
2on:
3 schedule:
4 - cron: "*/5 * * * *"
5 workflow_dispatch:
6 push:
7 branches:
8 - main
9 
10defaults:
11 run:
12 shell: bash

The on block defines when the workflow will run:

  1. On a schedule which fires (roughly3) every five minutes
  2. On a workflow_dispatch event (so I can start it manually if I want)
  3. When changes are pushed to the main branch

And the defaults block makes sure that the following scripts will be run in bash:

1name: Tempest Update { ... }
2on:
3 schedule:
4 - cron: "*/5 * * * *"
5 workflow_dispatch:
6 push:
7 branches:
8 - main
9 
10defaults:
11 run:
12 shell: bash
13 
14jobs:
15 fetch-and-post-tempest:
16 runs-on: ubuntu-latest
17 steps:
18 - name: Fetch Tempest API data
19 run: |
20 curl -sL "https://swd.weatherflow.com/swd/rest/better_forecast?station_id=${{ secrets.TEMPEST_STATION }}&token=${{ secrets.TEMPEST_TOKEN }}&units_temp=f&units_wind=mph&units_pressure=inhg&units_precip=in&units_distance=mi" \
21 | jq '.current_conditions | {temperature: (.air_temperature | round), conditions, feels_like: (.feels_like | round), icon, rain_today: .precip_accum_local_day, pressure_trend, humidity: .relative_humidity, pressure: ((.sea_level_pressure * 100) | round | . / 100), time, wind_direction: .wind_direction_cardinal, wind_gust}' \
22 > tempest.json
23 - name: POST to paste.lol
24 run: |
25 request_body='{"title": "tempest.json", "content": '"$(jq -Rsa . tempest.json)"'}'
26 curl --location --request POST --header "Authorization: Bearer ${{ secrets.OMG_TOKEN }}" \
27 "https://api.omg.lol/address/${{ secrets.OMG_ADDR }}/pastebin/" \
28 --data "$request_body"

Each step in the jobs section should look pretty familiar since those are almost exactly the commands that I used earlier. The only real difference is that they now use the format ${{ secrets.SECRET_NAME }} to pull in the repository secrets I just created.

Once I save, commit, and push this new file to the repo, it will automatically execute, and I can go to the Actions tab to confirm that the run was succesful. I can also check https://paste.jbowdre.lol/tempest.json to confirm that the contents have updated.

Show Weather on Homepage

By this point, I've fetched the weather data from Tempest, filtered it for just the fields I want to see, and posted the condensed JSON to a publicly-accessible pastebin. Now I just need to figure out how to make it show up on my omg.lol homepage. Rather than implementing these changes on the public site right away, I'll start with a barebones tempest.html that I can test with locally. Here's the initial structure that I'll be building from:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A==" crossorigin="anonymous">
<title>Weather Test</title>
<script>
// TODO
</script>
</head>
<body>
<h1>Local Weather</h1>
<ul>
<li>Conditions: <i class='fa-solid fa-cloud-sun-rain'></i><span id="conditions"></span></li>
<li>Temperature: <i class='fa-solid fa-temperature-half'></i> <span id="temp"></span></li>
<li>Humidity: <span id="humidity"></span></li>
<li>Wind: <span id="wind"></span></li>
<li>Precipitation: <i class='fa-solid fa-droplet-slash'></i><span id="rainToday"></span></li>
<li>Pressure: <i class='fa-solid fa-arrow-right-long'></i><span id="pressure"></span></li>
<li><i>Last Update: <span id="time"></span></i></li>
</body>
</html>

In the <head>, I'm specifying the character set so that I won't get any weird reactions when using exotic symbols like °, and I'm also pulling in the Font Awesome stylesheet so I can easily use those icons in the weather display. The <body> just holds empty <span>s that will later be populated with data via JavaScript.

I only included a few icons here. I'm going to try to make those icons dynamic so that they'll change depending on how hot/cold it is or what the pressure trend is doing. I don't plan to toy with the humidity, wind, or last update icons (yet) so I'm not going to bother with testing those locally.

With that framework in place, I can use python3 -m http.server 8080 to serve the page at http://localhost:8080/tempest.html.

Simple local web page showing placeholders for weather information

It's rather sparse, but it works. I won't be tinkering with any of that HTML from this point on, I'll just focus on the (currently-empty) <script> block. I don't think I'm super great with JavaScript, so I leaned heavily upon the code on Kris's page to get started and then put my own spin on it as I went along.

Before I can do much of anything, though, I'll need to start by retrieving the JSON data from my paste.lol endpoint and parsing the data:

8const wx_endpoint = 'https://paste.jbowdre.lol/tempest.json/raw';
9// fetch data from pastebin
10fetch(wx_endpoint)
11 .then(res => res.json())
12 .then(function(res){
13 // parse data
14 let updateTime = res.time;
15 let conditions = res.conditions;
16 let temp = res.temperature;
17 let humidity = res.humidity;
18 let wind = res.wind_gust;
19 let rainToday = res.rain_today;
20 let pressure = res.pressure;
21 
22 // display data
23 document.getElementById('time').innerHTML = updateTime;
24 document.getElementById('conditions').innerHTML = conditions;
25 document.getElementById('temp').innerHTML = temp;
26 document.getElementById('humidity').innerHTML = humidity;
27 document.getElementById('wind').innerHTML = wind;
28 document.getElementById('rainToday').innerHTML = rainToday;
29 document.getElementById('pressure').innerHTML = pressure;
30 });

So this is fetching the data from the pastebin, mapping variables to the JSON fields, and using document.getElementById() to select the placeholder <span>s by their id and replace the corresponding innerHTML with the appropriate values.

The result isn't very pretty, but it's a start:

Simple local web page showing basic weather information without any units, and the timestamp is in Unix format showing the number of seconds since January 1, 1970

That Unix epoch timestamp stands out as being particularly unwieldy. Instead of the exact timestamp, I'd prefer to show that as the relative time since the last update. I'll do that with the Intl.RelativeTimeFormat object.

8const wx_endpoint = 'https://paste.jbowdre.lol/tempest.json/raw';
+// get ready to calculate relative time
+const units = {
+ year : 24 * 60 * 60 * 1000 * 365,
+ month : 24 * 60 * 60 * 1000 * 365/12,
+ day : 24 * 60 * 60 * 1000,
+ hour : 60 * 60 * 1000,
+ minute: 60 * 1000,
+ second: 1000
+}
+let rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
+let getRelativeTime = (d1, d2 = new Date()) => {
+ let elapsed = d1 - d2
+ for (var u in units)
+ if (Math.abs(elapsed) > units[u] || u === 'second')
+ return rtf.format(Math.round(elapsed/units[u]), u)
+}
25// fetch data from pastebin
26fetch(wx_endpoint)
27 .then(res => res.json())
28 .then(function(res){
29 // calculate age of last update
30 let updateTime = res.time;
31 updateTime = parseInt(updateTime);
32 updateTime = updateTime*1000;
33 updateTime = new Date(updateTime);
34 let updateAge = getRelativeTime(updateTime);
35 
36 // parse data
- let updateTime = res.time;
37 let conditions = res.conditions;
38 let temp = res.temperature;
39 let humidity = res.humidity;
40 let wind = res.wind_gust;
41 let rainToday = res.rain_today;
42 let pressure = res.pressure;
43 
44 // display data
+ document.getElementById('time').innerHTML = updateAge;
- document.getElementById('time').innerHTML = updateTime;
46 document.getElementById('conditions').innerHTML = conditions;
47 document.getElementById('temp').innerHTML = temp;
48 document.getElementById('humidity').innerHTML = humidity;
49 document.getElementById('wind').innerHTML = wind;
50 document.getElementById('rainToday').innerHTML = rainToday;
51 document.getElementById('pressure').innerHTML = pressure;
52 });

That's a bit more friendly:

The same simple weather display but the last update is now "2 minutes ago"

Alright, let's massage some of the other fields a little. I'll add units and labels, translate temperature and speed values to metric for my international friends, and combine a few additional fields for more context. I'm also going to make sure everything is lowercase to match the, uh, aesthetic of my omg page.

8const wx_endpoint = 'https://paste.jbowdre.lol/tempest.json/raw'; { ... }
9// get ready to calculate relative time
10const units = {
11 year : 24 * 60 * 60 * 1000 * 365,
12 month : 24 * 60 * 60 * 1000 * 365/12,
13 day : 24 * 60 * 60 * 1000,
14 hour : 60 * 60 * 1000,
15 minute: 60 * 1000,
16 second: 1000
17}
18let rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
19let getRelativeTime = (d1, d2 = new Date()) => {
20 let elapsed = d1 - d2
21 for (var u in units)
22 if (Math.abs(elapsed) > units[u] || u === 'second')
23 return rtf.format(Math.round(elapsed/units[u]), u)
24}
25// fetch data from pastebin
26fetch(wx_endpoint)
27 .then(res => res.json())
28 .then(function(res){
29 // calculate age of last update
30 let updateTime = res.time;
31 updateTime = parseInt(updateTime);
32 updateTime = updateTime*1000;
33 updateTime = new Date(updateTime);
34 let updateAge = getRelativeTime(updateTime);
35 
36 // parse data
37 let updateTime = res.time;
+ let conditions = (res.conditions).toLowerCase();
- let conditions = res.conditions;
+ let temp = `${res.temperature}°f (${(((res.temperature - 32) * 5) / 9).toFixed(1)}°c)`;
- let temp = res.temperature;
+ let humidity = `${res.humidity}% humidity`;
- let humidity = res.humidity;
+ let wind = `${res.wind_gust}mph (${(res.wind_gust*1.609344).toFixed(1)}kph) from ${(res.wind_direction).toLowerCase()}`;
- let wind = res.wind_gust;
+ let rainToday = `${res.rain_today}" rain today`;
- let rainToday = res.rain_today;
+ let pressureTrend = res.pressure_trend;
+ let pressure = `${res.pressure}inhg and ${pressureTrend}`;
- let pressure = res.pressure;
45 
46 // display data { ... }
47 document.getElementById('time').innerHTML = updateAge;
48 document.getElementById('time').innerHTML = updateTime;
49 document.getElementById('conditions').innerHTML = conditions;
50 document.getElementById('temp').innerHTML = temp;
51 document.getElementById('humidity').innerHTML = humidity;
52 document.getElementById('wind').innerHTML = wind;
53 document.getElementById('rainToday').innerHTML = rainToday;
54 document.getElementById('pressure').innerHTML = pressure;
55 });

That's a bit better:

The sample webpage showing formatted strings for each weather item

Now let's add some conditionals into the mix. I'd like to display the feels_like temperature but only if it's five or more degrees away from the actual air temperature. And if there hasn't been any rain, the page should show no rain today instead of 0.00" rain today.

8const wx_endpoint = 'https://paste.jbowdre.lol/tempest.json/raw'; { ... }
9// get ready to calculate relative time
10const units = {
11 year : 24 * 60 * 60 * 1000 * 365,
12 month : 24 * 60 * 60 * 1000 * 365/12,
13 day : 24 * 60 * 60 * 1000,
14 hour : 60 * 60 * 1000,
15 minute: 60 * 1000,
16 second: 1000
17}
18let rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
19let getRelativeTime = (d1, d2 = new Date()) => {
20 let elapsed = d1 - d2
21 for (var u in units)
22 if (Math.abs(elapsed) > units[u] || u === 'second')
23 return rtf.format(Math.round(elapsed/units[u]), u)
24} //
25// fetch data from pastebin
26fetch(wx_endpoint)
27 .then(res => res.json())
28 .then(function(res){
29 // calculate age of last update
30 let updateTime = res.time;
31 updateTime = parseInt(updateTime);
32 updateTime = updateTime*1000;
33 updateTime = new Date(updateTime);
34 let updateAge = getRelativeTime(updateTime);
35 
36 // parse data
37 let updateTime = res.time;
38 let conditions = (res.conditions).toLowerCase();
+ let tempDiff = Math.abs(res.temperature - res.feels_like);
40 let temp = `${res.temperature}°f (${(((res.temperature - 32) * 5) / 9).toFixed(1)}°c)`;
+ if (tempDiff >= 5) {
+ temp += `, feels ${res.feels_like}°f (${(((res.feels_like - 32) *5) / 9).toFixed(1)}°c)`;
+ }
44 let humidity = `${res.humidity}% humidity`;
45 let wind = `${res.wind_gust}mph (${(res.wind_gust*1.609344).toFixed(1)}kph) from ${(res.wind_direction).toLowerCase()}`;
+ let rainToday;
+ if (res.rain_today === 0) {
+ rainToday = 'no rain today';
+ } else {
+ rainToday = `${res.rain_today}" rain today`;
+ }
- let rainToday = `${res.rain_today}" rain today`;
52 let pressureTrend = res.pressure_trend;
53 let pressure = `${res.pressure}inhg and ${pressureTrend}`;
54 
55 // display data { ... }
56 document.getElementById('time').innerHTML = updateAge;
57 document.getElementById('time').innerHTML = updateTime;
58 document.getElementById('conditions').innerHTML = conditions;
59 document.getElementById('temp').innerHTML = temp;
60 document.getElementById('humidity').innerHTML = humidity;
61 document.getElementById('wind').innerHTML = wind;
62 document.getElementById('rainToday').innerHTML = rainToday;
63 document.getElementById('pressure').innerHTML = pressure;
64 });

For testing this, I can manually alter4 the contents of the pastebin to ensure the values are what I need:

1{
2 "temperature": 57,
3 "conditions": "Rain Likely",
4 "feels_like": 67,
5 "icon": "rainy",
6 "rain_today": 0,
7 "pressure_trend": "steady",
8 "humidity": 92,
9 "pressure": 29.91,
10 "time": 1707676590,
11 "wind_direction": "WSW",
12 "wind_gust": 2
13}

Local test page reflecting "57°f (13.9°c), feels 67°f (19.4°c)" and "no rain today"

The final touch will be to change the icons depending on the values of certain fields:

  • The conditions icon will vary from to , roughly corresponding to the icon value from the Tempest API.
  • The temperature icon will range from to depending on the temperature.
  • The precipitation icon will be for no precipitation, and progress through and for a bit more rain, and cap out at for lots of rain5.
  • The pressure icon should change based on the trend: , , and .

I'll set up a couple of constants to define the ranges, and a few more for mapping the values to icons. Then I'll use the Array.prototype.find method to select the appropriate upper value from each range. And then I leverage document.getElementsByClassName to match the placeholder icon classes and dynamically replace them.

8const wx_endpoint = 'https://paste.jbowdre.lol/tempest.json/raw'; { ... }
9// get ready to calculate relative time
10const units = {
11 year : 24 * 60 * 60 * 1000 * 365,
12 month : 24 * 60 * 60 * 1000 * 365/12,
13 day : 24 * 60 * 60 * 1000,
14 hour : 60 * 60 * 1000,
15 minute: 60 * 1000,
16 second: 1000
17}
18let rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
19let getRelativeTime = (d1, d2 = new Date()) => {
20 let elapsed = d1 - d2
21 for (var u in units)
22 if (Math.abs(elapsed) > units[u] || u === 'second')
23 return rtf.format(Math.round(elapsed/units[u]), u)
24}
25 
+// set up temperature and rain ranges
+const tempRanges = [
+ { upper: 32, label: 'cold' },
+ { upper: 60, label: 'cool' },
+ { upper: 80, label: 'warm' },
+ { upper: Infinity, label: 'hot' }
+];
+const rainRanges = [
+ { upper: 0.02, label: 'none' },
+ { upper: 0.2, label: 'light' },
+ { upper: 1.4, label: 'moderate' },
+ { upper: Infinity, label: 'heavy' }
+]
+ 
+// maps for selecting icons
+const CLASS_MAP_PRESS = {
+ 'steady': 'fa-solid fa-arrow-right-long',
+ 'rising': 'fa-solid fa-arrow-trend-up',
+ 'falling': 'fa-solid fa-arrow-trend-down'
+}
+const CLASS_MAP_RAIN = {
+ 'none': 'fa-solid fa-droplet-slash',
+ 'light': 'fa-solid fa-glass-water-droplet',
+ 'moderate': 'fa-solid fa-glass-water',
+ 'heavy': 'fa-solid fa-bucket'
+}
+const CLASS_MAP_TEMP = {
+ 'hot': 'fa-solid fa-thermometer-full',
+ 'warm': 'fa-solid fa-thermometer-half',
+ 'cool': 'fa-solid fa-thermometer-quarter',
+ 'cold': 'fa-solid fa-thermometer-empty'
+}
+const CLASS_MAP_WX = {
+ 'clear-day': 'fa-solid fa-sun',
+ 'clear-night': 'fa-solid fa-moon',
+ 'cloudy': 'fa-solid fa-cloud',
+ 'foggy': 'fa-solid fa-cloud-showers-smog',
+ 'partly-cloudy-day': 'fa-solid fa-clouds-sun',
+ 'partly-cloudy-night': 'fa-solid fa-clouds-moon',
+ 'possibly-rainy-day': 'fa-solid fa-cloud-sun-rain',
+ 'possibly-rainy-night': 'fa-solid fa-cloud-moon-rain',
+ 'possibly-sleet-day': 'fa-solid fa-cloud-meatball',
+ 'possibly-sleet-night': 'fa-solid fa-cloud-moon-rain',
+ 'possibly-snow-day': 'fa-solid fa-snowflake',
+ 'possibly-snow-night': 'fa-solid fa-snowflake',
+ 'possibly-thunderstorm-day': 'fa-solid fa-cloud-bolt',
+ 'possibly-thunderstorm-night': 'fa-solid fa-cloud-bolt',
+ 'rainy': 'fa-solid fa-cloud-showers-heavy',
+ 'sleet': 'fa-solid fa-cloud-rain',
+ 'snow': 'fa-solid fa-snowflake',
+ 'thunderstorm': 'fa-solid fa-cloud-bolt',
+ 'windy': 'fa-solid fa-wind',
+}
79 
80// fetch data from pastebin { ... }
81fetch(wx_endpoint)
82 .then(res => res.json())
83 .then(function(res){
84 // calculate age of last update
85 let updateTime = res.time;
86 updateTime = parseInt(updateTime);
87 updateTime = updateTime*1000;
88 updateTime = new Date(updateTime);
89 let updateAge = getRelativeTime(updateTime);
90 
91 // parse data
92 let updateTime = res.time;
93 let conditions = (res.conditions).toLowerCase();
94 let tempDiff = Math.abs(res.temperature - res.feels_like);
95 let temp = `${res.temperature}°f (${(((res.temperature - 32) * 5) / 9).toFixed(1)}°c)`;
96 if (tempDiff >= 5) {
97 temp += `, feels ${res.feels_like}°f (${(((res.feels_like - 32) *5) / 9).toFixed(1)}°c)`;
98 }
+ let tempLabel = (tempRanges.find(range => res.feels_like < range.upper)).label;
100 let humidity = `${res.humidity}% humidity`;
101 let wind = `${res.wind_gust}mph (${(res.wind_gust*1.609344).toFixed(1)}kph) from ${(res.wind_direction).toLowerCase()}`;
+ let rainLabel = (rainRanges.find(range => res.rain_today < range.upper)).label;
103 let rainToday;
104 if (res.rain_today === 0) {
105 rainToday = 'no rain today';
106 } else {
107 rainToday = `${res.rain_today}" rain today`;
108 }
109 let rainToday = `${res.rain_today}" rain today`;
110 let pressureTrend = res.pressure_trend;
111 let pressure = `${res.pressure}inhg and ${pressureTrend}`;
+ let icon = res.icon;
113 
114 // display data { ... }
115 document.getElementById('time').innerHTML = updateAge;
116 document.getElementById('time').innerHTML = updateTime;
117 document.getElementById('conditions').innerHTML = conditions;
118 document.getElementById('temp').innerHTML = temp;
119 document.getElementById('humidity').innerHTML = humidity;
120 document.getElementById('wind').innerHTML = wind;
121 document.getElementById('rainToday').innerHTML = rainToday;
122 document.getElementById('pressure').innerHTML = pressure;
+ // update icons
+ document.getElementsByClassName('fa-cloud-sun-rain')[0].classList = CLASS_MAP_WX[icon];
+ document.getElementsByClassName('fa-temperature-half')[0].classList = CLASS_MAP_TEMP[tempLabel];
+ document.getElementsByClassName('fa-droplet-slash')[0].classList = CLASS_MAP_RAIN[rainLabel];
+ document.getElementsByClassName('fa-arrow-right-long')[0].classList = CLASS_MAP_PRESS[pressureTrend];
128 });

And I can see that the icons do indeed match the conditions:

Local test page with matching icons

OMG, LOL, Let's Do It

Now that all that prep work is out of the way, transposing the code into the live omg.lol homepage doesn't really take much effort.

I'll just use the online editor to drop this at the bottom of my web page:

47# /proc/wx
48- <span id="conditions"></span> {cloud-sun-rain}
49- <span id="temp"></span> {temperature-half}
50- <span id="humidity"></span> {droplet}
51- <span id="wind"></span> {wind}
52- <span id="rainToday"></span> {droplet-slash}
53- <span id="pressure"></span> {arrow-right-long}
54- <i>as of <span id="time"></span></i> {clock}

A bit further down the editor page, there's a box for inserting additional content into the page's <head> block. That's a great place to past in the entirety of my script:

3<script>
4 const wx_endpoint = 'https://paste.jbowdre.lol/tempest.json/raw';
5 // get ready to calculate relative time
6 const units = {
7 year : 24 * 60 * 60 * 1000 * 365,
8 month : 24 * 60 * 60 * 1000 * 365/12,
9 day : 24 * 60 * 60 * 1000,
10 hour : 60 * 60 * 1000,
11 minute: 60 * 1000,
12 second: 1000
13 }
14 let rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })
15 let getRelativeTime = (d1, d2 = new Date()) => {
16 let elapsed = d1 - d2
17 for (var u in units)
18 if (Math.abs(elapsed) > units[u] || u === 'second')
19 return rtf.format(Math.round(elapsed/units[u]), u)
20 }
21 
22 // set up temperature and rain ranges
23 const tempRanges = [
24 { upper: 32, label: 'cold' },
25 { upper: 60, label: 'cool' },
26 { upper: 80, label: 'warm' },
27 { upper: Infinity, label: 'hot' }
28 ];
29 const rainRanges = [
30 { upper: 0.02, label: 'none' },
31 { upper: 0.2, label: 'light' },
32 { upper: 1.4, label: 'moderate' },
33 { upper: Infinity, label: 'heavy' }
34 ]
35 
36 // maps for selecting icons
37 const CLASS_MAP_PRESS = {
38 'steady': 'fa-solid fa-arrow-right-long',
39 'rising': 'fa-solid fa-arrow-trend-up',
40 'falling': 'fa-solid fa-arrow-trend-down'
41 }
42 const CLASS_MAP_RAIN = {
43 'none': 'fa-solid fa-droplet-slash',
44 'light': 'fa-solid fa-glass-water-droplet',
45 'moderate': 'fa-solid fa-glass-water',
46 'heavy': 'fa-solid fa-bucket'
47 }
48 const CLASS_MAP_TEMP = {
49 'hot': 'fa-solid fa-thermometer-full',
50 'warm': 'fa-solid fa-thermometer-half',
51 'cool': 'fa-solid fa-thermometer-quarter',
52 'cold': 'fa-solid fa-thermometer-empty'
53 }
54 const CLASS_MAP_WX = {
55 'clear-day': 'fa-solid fa-sun',
56 'clear-night': 'fa-solid fa-moon',
57 'cloudy': 'fa-solid fa-cloud',
58 'foggy': 'fa-solid fa-cloud-showers-smog',
59 'partly-cloudy-day': 'fa-solid fa-clouds-sun',
60 'partly-cloudy-night': 'fa-solid fa-clouds-moon',
61 'possibly-rainy-day': 'fa-solid fa-cloud-sun-rain',
62 'possibly-rainy-night': 'fa-solid fa-cloud-moon-rain',
63 'possibly-sleet-day': 'fa-solid fa-cloud-meatball',
64 'possibly-sleet-night': 'fa-solid fa-cloud-moon-rain',
65 'possibly-snow-day': 'fa-solid fa-snowflake',
66 'possibly-snow-night': 'fa-solid fa-snowflake',
67 'possibly-thunderstorm-day': 'fa-solid fa-cloud-bolt',
68 'possibly-thunderstorm-night': 'fa-solid fa-cloud-bolt',
69 'rainy': 'fa-solid fa-cloud-showers-heavy',
70 'sleet': 'fa-solid fa-cloud-rain',
71 'snow': 'fa-solid fa-snowflake',
72 'thunderstorm': 'fa-solid fa-cloud-bolt',
73 'windy': 'fa-solid fa-wind',
74 }
75 
76 // fetch data from pastebin
77 fetch(wx_endpoint)
78 .then(res => res.json())
79 .then(function(res){
80 
81 // calculate age of last update
82 let updateTime = res.time;
83 updateTime = parseInt(updateTime);
84 updateTime = updateTime*1000;
85 updateTime = new Date(updateTime);
86 let updateAge = getRelativeTime(updateTime);
87 
88 // parse data
89 let conditions = (res.conditions).toLowerCase();
90 let tempDiff = Math.abs(res.temperature - res.feels_like);
91 let temp = `${res.temperature}°f (${(((res.temperature - 32) * 5) / 9).toFixed(1)}°c)`;
92 if (tempDiff >= 5) {
93 temp += `, feels ${res.feels_like}°f (${(((res.feels_like - 32) *5) / 9).toFixed(1)}°c)`;
94 }
95 let tempLabel = (tempRanges.find(range => res.feels_like < range.upper)).label;
96 let humidity = `${res.humidity}% humidity`;
97 let wind = `${res.wind_gust}mph (${(res.wind_gust*1.609344).toFixed(1)}kph) from ${(res.wind_direction).toLowerCase()}`;
98 let rainLabel = (rainRanges.find(range => res.rain_today < range.upper)).label;
99 let rainToday;
100 if (res.rain_today === 0) {
101 rainToday = 'no rain today';
102 } else {
103 rainToday = `${res.rain_today}" rain today`;
104 }
105 let pressureTrend = res.pressure_trend;
106 let pressure = `${res.pressure}inhg and ${pressureTrend}`;
107 let icon = res.icon;
108 
109 // display data
110 document.getElementById('time').innerHTML = updateAge;
111 document.getElementById('conditions').innerHTML = conditions;
112 document.getElementById('temp').innerHTML = temp;
113 document.getElementById('humidity').innerHTML = humidity;
114 document.getElementById('wind').innerHTML = wind;
115 document.getElementById('rainToday').innerHTML = rainToday;
116 document.getElementById('pressure').innerHTML = pressure;
117 // update icons
118 document.getElementsByClassName('fa-cloud-sun-rain')[0].classList = CLASS_MAP_WX[icon];
119 document.getElementsByClassName('fa-temperature-half')[0].classList = CLASS_MAP_TEMP[tempLabel];
120 document.getElementsByClassName('fa-droplet-slash')[0].classList = CLASS_MAP_RAIN[rainLabel];
121 document.getElementsByClassName('fa-arrow-right-long')[0].classList = CLASS_MAP_PRESS[pressureTrend];
122 });
123</script>

With that, I hit the happy little Save & Publish button in the editor, and then revel in seeing my new weather display at the bottom of my omg.lol page:

Mobile screenshot of an omg.lol homepage with a (near) realtime weather display at the bottom

I'm quite pleased with how this turned out, and I had fun learning a few JavaScript tricks in the process. I stashed the code for this little project in my lolz repo in case you'd like to take a look. I have some ideas for other APIs I might want to integrate in a similar way in the future so stay tuned.


  1. These are degrees Fahrenheit, after all. If I needed precision I'd be using better units. ↩︎

  2. I'm such a sucker for basically anything that I can tie one of my domains to. ↩︎

  3. Per the docs, runs can run at most once every five minutes, and they may be delayed (or even canceled) if a runner isn't available due to heavy load. ↩︎

  4. My dishonest values will just get corrected the next time the workflow is triggered. ↩︎

  5. Okay, admittedly this progression isn't perfect, but it's the best I could come up with within the free FA icon set. ↩︎


Celebrate this post: 

runtimeterror  


 jbowdre