remove metric

This commit is contained in:
Matt Walsh 2022-12-06 16:25:28 -06:00
parent 6933e7b7f1
commit 8e6fd04b3a
10 changed files with 39 additions and 143 deletions

View file

@ -1,4 +1,3 @@
import { setUnits } from './modules/utils/units.mjs';
import { json } from './modules/utils/fetch.mjs'; import { json } from './modules/utils/fetch.mjs';
import noSleep from './modules/utils/nosleep.mjs'; import noSleep from './modules/utils/nosleep.mjs';
import { import {
@ -114,7 +113,6 @@ const init = () => {
localStorage.removeItem('TwcAutoRefresh'); localStorage.removeItem('TwcAutoRefresh');
document.getElementById('radEnglish').checked = true; document.getElementById('radEnglish').checked = true;
localStorage.removeItem('TwcUnits');
localStorage.removeItem('TwcPlay'); localStorage.removeItem('TwcPlay');
postMessage('navButton', 'play'); postMessage('navButton', 'play');
@ -122,29 +120,11 @@ const init = () => {
localStorage.removeItem('TwcQuery'); localStorage.removeItem('TwcQuery');
}); });
const TwcUnits = localStorage.getItem('TwcUnits');
if (!TwcUnits || TwcUnits === 'ENGLISH') {
document.getElementById('radEnglish').checked = true;
setUnits('english');
} else if (TwcUnits === 'METRIC') {
document.getElementById('radMetric').checked = true;
setUnits('metric');
}
document.getElementById('radEnglish').addEventListener('change', changeUnits);
document.getElementById('radMetric').addEventListener('change', changeUnits);
// swipe functionality // swipe functionality
document.getElementById('container').addEventListener('swiped-left', () => swipeCallBack('left')); document.getElementById('container').addEventListener('swiped-left', () => swipeCallBack('left'));
document.getElementById('container').addEventListener('swiped-right', () => swipeCallBack('right')); document.getElementById('container').addEventListener('swiped-right', () => swipeCallBack('right'));
}; };
const changeUnits = (e) => {
const Units = e.target.value;
localStorage.setItem('TwcUnits', Units);
postMessage('units', Units);
};
const autocompleteOnSelect = async (suggestion, elem) => { const autocompleteOnSelect = async (suggestion, elem) => {
// Do not auto get the same city twice. // Do not auto get the same city twice.
if (elem.previousSuggestionValue === suggestion.value) return; if (elem.previousSuggestionValue === suggestion.value) return;

View file

@ -7,7 +7,9 @@ import { locationCleanup } from './utils/string.mjs';
import { getWeatherIconFromIconLink } from './icons.mjs'; import { getWeatherIconFromIconLink } from './icons.mjs';
import WeatherDisplay from './weatherdisplay.mjs'; import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs'; import { registerDisplay } from './navigation.mjs';
import { getUnits, UNITS, convert } from './utils/units.mjs'; import {
celsiusToFahrenheit, kphToMph, pascalToInHg, metersToFeet, kilometersToMiles,
} from './utils/units.mjs';
class CurrentWeather extends WeatherDisplay { class CurrentWeather extends WeatherDisplay {
constructor(navId, elemId) { constructor(navId, elemId) {
@ -98,21 +100,19 @@ class CurrentWeather extends WeatherDisplay {
if (pressureDiff > 150) data.PressureDirection = 'R'; if (pressureDiff > 150) data.PressureDirection = 'R';
if (pressureDiff < -150) data.PressureDirection = 'F'; if (pressureDiff < -150) data.PressureDirection = 'F';
if (getUnits() === UNITS.english) { data.Temperature = celsiusToFahrenheit(data.Temperature);
data.Temperature = convert.celsiusToFahrenheit(data.Temperature); data.TemperatureUnit = 'F';
data.TemperatureUnit = 'F'; data.DewPoint = celsiusToFahrenheit(data.DewPoint);
data.DewPoint = convert.celsiusToFahrenheit(data.DewPoint); data.Ceiling = Math.round(metersToFeet(data.Ceiling) / 100) * 100;
data.Ceiling = Math.round(convert.metersToFeet(data.Ceiling) / 100) * 100; data.CeilingUnit = 'ft.';
data.CeilingUnit = 'ft.'; data.Visibility = kilometersToMiles(observations.visibility.value / 1000);
data.Visibility = convert.kilometersToMiles(observations.visibility.value / 1000); data.VisibilityUnit = ' mi.';
data.VisibilityUnit = ' mi.'; data.WindSpeed = kphToMph(data.WindSpeed);
data.WindSpeed = convert.kphToMph(data.WindSpeed); data.WindUnit = 'MPH';
data.WindUnit = 'MPH'; data.Pressure = pascalToInHg(data.Pressure).toFixed(2);
data.Pressure = convert.pascalToInHg(data.Pressure).toFixed(2); data.HeatIndex = celsiusToFahrenheit(data.HeatIndex);
data.HeatIndex = convert.celsiusToFahrenheit(data.HeatIndex); data.WindChill = celsiusToFahrenheit(data.WindChill);
data.WindChill = convert.celsiusToFahrenheit(data.WindChill); data.WindGust = kphToMph(data.WindGust);
data.WindGust = convert.kphToMph(data.WindGust);
}
return data; return data;
} }

View file

@ -4,7 +4,6 @@
import STATUS from './status.mjs'; import STATUS from './status.mjs';
import { json } from './utils/fetch.mjs'; import { json } from './utils/fetch.mjs';
import { DateTime } from '../vendor/auto/luxon.mjs'; import { DateTime } from '../vendor/auto/luxon.mjs';
import { UNITS, getUnits, convert } from './utils/units.mjs';
import { getWeatherIconFromIconLink } from './icons.mjs'; import { getWeatherIconFromIconLink } from './icons.mjs';
import { preloadImg } from './utils/image.mjs'; import { preloadImg } from './utils/image.mjs';
import WeatherDisplay from './weatherdisplay.mjs'; import WeatherDisplay from './weatherdisplay.mjs';
@ -23,13 +22,11 @@ class ExtendedForecast extends WeatherDisplay {
const weatherParameters = _weatherParameters ?? this.weatherParameters; const weatherParameters = _weatherParameters ?? this.weatherParameters;
// request us or si units // request us or si units
let units = 'us';
if (getUnits() === UNITS.metric) units = 'si';
let forecast; let forecast;
try { try {
forecast = await json(weatherParameters.forecast, { forecast = await json(weatherParameters.forecast, {
data: { data: {
units, units: 'us',
}, },
}); });
} catch (e) { } catch (e) {
@ -140,13 +137,11 @@ class ExtendedForecast extends WeatherDisplay {
const fill = {}; const fill = {};
fill.date = Day.dayName; fill.date = Day.dayName;
let { low } = Day; const { low } = Day;
if (low !== undefined) { if (low !== undefined) {
if (getUnits() === UNITS.metric) low = convert.fahrenheitToCelsius(low);
fill['value-lo'] = Math.round(low); fill['value-lo'] = Math.round(low);
} }
let { high } = Day; const { high } = Day;
if (getUnits() === UNITS.metric) high = convert.fahrenheitToCelsius(high);
fill['value-hi'] = Math.round(high); fill['value-hi'] = Math.round(high);
fill.condition = Day.text; fill.condition = Day.text;

View file

@ -3,7 +3,7 @@
import STATUS from './status.mjs'; import STATUS from './status.mjs';
import { DateTime, Interval, Duration } from '../vendor/auto/luxon.mjs'; import { DateTime, Interval, Duration } from '../vendor/auto/luxon.mjs';
import { json } from './utils/fetch.mjs'; import { json } from './utils/fetch.mjs';
import { convert, UNITS, getUnits } from './utils/units.mjs'; import { celsiusToFahrenheit, kilometersToMiles } from './utils/units.mjs';
import { getHourlyIcon } from './icons.mjs'; import { getHourlyIcon } from './icons.mjs';
import { directionToNSEW } from './utils/calc.mjs'; import { directionToNSEW } from './utils/calc.mjs';
import WeatherDisplay from './weatherdisplay.mjs'; import WeatherDisplay from './weatherdisplay.mjs';
@ -61,25 +61,13 @@ class Hourly extends WeatherDisplay {
const icons = await Hourly.determineIcon(skyCover, weather, iceAccumulation, probabilityOfPrecipitation, snowfallAmount, windSpeed); const icons = await Hourly.determineIcon(skyCover, weather, iceAccumulation, probabilityOfPrecipitation, snowfallAmount, windSpeed);
return temperature.map((val, idx) => { return temperature.map((val, idx) => ({
if (getUnits() === UNITS.metric) { temperature: celsiusToFahrenheit(temperature[idx]),
return { apparentTemperature: celsiusToFahrenheit(apparentTemperature[idx]),
temperature: temperature[idx], windSpeed: kilometersToMiles(windSpeed[idx]),
apparentTemperature: apparentTemperature[idx], windDirection: directionToNSEW(windDirection[idx]),
windSpeed: windSpeed[idx], icon: icons[idx],
windDirection: directionToNSEW(windDirection[idx]), }));
icon: icons[idx],
};
}
return {
temperature: convert.celsiusToFahrenheit(temperature[idx]),
apparentTemperature: convert.celsiusToFahrenheit(apparentTemperature[idx]),
windSpeed: convert.kilometersToMiles(windSpeed[idx]),
windDirection: directionToNSEW(windDirection[idx]),
icon: icons[idx],
};
});
} }
// given forecast paramaters determine a suitable icon // given forecast paramaters determine a suitable icon

View file

@ -3,7 +3,7 @@ import { distance as calcDistance, directionToNSEW } from './utils/calc.mjs';
import { json } from './utils/fetch.mjs'; import { json } from './utils/fetch.mjs';
import STATUS from './status.mjs'; import STATUS from './status.mjs';
import { locationCleanup } from './utils/string.mjs'; import { locationCleanup } from './utils/string.mjs';
import { convert, UNITS, getUnits } from './utils/units.mjs'; import { celsiusToFahrenheit, kphToMph } from './utils/units.mjs';
import WeatherDisplay from './weatherdisplay.mjs'; import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs'; import { registerDisplay } from './navigation.mjs';
@ -70,25 +70,14 @@ class LatestObservations extends WeatherDisplay {
// sort array by station name // sort array by station name
const sortedConditions = conditions.sort((a, b) => ((a.Name < b.Name) ? -1 : 1)); const sortedConditions = conditions.sort((a, b) => ((a.Name < b.Name) ? -1 : 1));
if (getUnits() === UNITS.english) { this.elem.querySelector('.column-headers .temp.english').classList.add('show');
this.elem.querySelector('.column-headers .temp.english').classList.add('show'); this.elem.querySelector('.column-headers .temp.metric').classList.remove('show');
this.elem.querySelector('.column-headers .temp.metric').classList.remove('show');
} else {
this.elem.querySelector('.column-headers .temp.english').classList.remove('show');
this.elem.querySelector('.column-headers .temp.metric').classList.add('show');
}
const lines = sortedConditions.map((condition) => { const lines = sortedConditions.map((condition) => {
let Temperature = condition.temperature.value;
let WindSpeed = condition.windSpeed.value;
const windDirection = directionToNSEW(condition.windDirection.value); const windDirection = directionToNSEW(condition.windDirection.value);
if (getUnits() === UNITS.english) { const Temperature = Math.round(celsiusToFahrenheit(condition.temperature.value));
Temperature = convert.celsiusToFahrenheit(Temperature); const WindSpeed = Math.round(kphToMph(condition.windSpeed.value));
WindSpeed = convert.kphToMph(WindSpeed);
}
WindSpeed = Math.round(WindSpeed);
Temperature = Math.round(Temperature);
const fill = {}; const fill = {};
fill.location = locationCleanup(condition.city).substr(0, 14); fill.location = locationCleanup(condition.city).substr(0, 14);

View file

@ -1,7 +1,6 @@
// display text based local forecast // display text based local forecast
import STATUS from './status.mjs'; import STATUS from './status.mjs';
import { UNITS, getUnits } from './utils/units.mjs';
import { json } from './utils/fetch.mjs'; import { json } from './utils/fetch.mjs';
import WeatherDisplay from './weatherdisplay.mjs'; import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs'; import { registerDisplay } from './navigation.mjs';
@ -32,10 +31,7 @@ class LocalForecast extends WeatherDisplay {
this.screenTexts = conditions.map((condition) => { this.screenTexts = conditions.map((condition) => {
// process the text // process the text
let text = `${condition.DayName.toUpperCase()}...`; let text = `${condition.DayName.toUpperCase()}...`;
let conditionText = condition.Text; const conditionText = condition.Text;
if (getUnits() === UNITS.metric) {
conditionText = condition.TextC;
}
text += conditionText.toUpperCase().replace('...', ' '); text += conditionText.toUpperCase().replace('...', ' ');
return text; return text;
@ -62,12 +58,10 @@ class LocalForecast extends WeatherDisplay {
// get the unformatted data (also used by extended forecast) // get the unformatted data (also used by extended forecast)
async getRawData(weatherParameters) { async getRawData(weatherParameters) {
// request us or si units // request us or si units
let units = 'us';
if (getUnits() === UNITS.metric) units = 'si';
try { try {
return await json(weatherParameters.forecast, { return await json(weatherParameters.forecast, {
data: { data: {
units, units: 'us',
}, },
}); });
} catch (e) { } catch (e) {

View file

@ -4,7 +4,7 @@
import STATUS from './status.mjs'; import STATUS from './status.mjs';
import { distance as calcDistance } from './utils/calc.mjs'; import { distance as calcDistance } from './utils/calc.mjs';
import { json } from './utils/fetch.mjs'; import { json } from './utils/fetch.mjs';
import { convert, UNITS, getUnits } from './utils/units.mjs'; import { celsiusToFahrenheit } from './utils/units.mjs';
import { getWeatherRegionalIconFromIconLink } from './icons.mjs'; import { getWeatherRegionalIconFromIconLink } from './icons.mjs';
import { preloadImg } from './utils/image.mjs'; import { preloadImg } from './utils/image.mjs';
import { DateTime } from '../vendor/auto/luxon.mjs'; import { DateTime } from '../vendor/auto/luxon.mjs';
@ -87,7 +87,7 @@ class RegionalForecast extends WeatherDisplay {
// format the observation the same as the forecast // format the observation the same as the forecast
const regionalObservation = { const regionalObservation = {
daytime: !!observation.icon.match(/\/day\//), daytime: !!observation.icon.match(/\/day\//),
temperature: convert.celsiusToFahrenheit(observation.temperature.value), temperature: celsiusToFahrenheit(observation.temperature.value),
name: RegionalForecast.formatCity(city.city), name: RegionalForecast.formatCity(city.city),
icon: observation.icon, icon: observation.icon,
x: cityXY.x, x: cityXY.x,
@ -370,8 +370,7 @@ class RegionalForecast extends WeatherDisplay {
fill.icon = { type: 'img', src: getWeatherRegionalIconFromIconLink(period.icon, !period.daytime) }; fill.icon = { type: 'img', src: getWeatherRegionalIconFromIconLink(period.icon, !period.daytime) };
fill.city = period.name; fill.city = period.name;
let { temperature } = period; const { temperature } = period;
if (getUnits() === UNITS.metric) temperature = Math.round(convert.fahrenheitToCelsius(temperature));
fill.temp = temperature; fill.temp = temperature;
const elem = this.fillTemplate('location', fill); const elem = this.fillTemplate('location', fill);

View file

@ -2,7 +2,6 @@
import STATUS from './status.mjs'; import STATUS from './status.mjs';
import { json } from './utils/fetch.mjs'; import { json } from './utils/fetch.mjs';
import { getWeatherRegionalIconFromIconLink } from './icons.mjs'; import { getWeatherRegionalIconFromIconLink } from './icons.mjs';
import { convert, UNITS, getUnits } from './utils/units.mjs';
import { DateTime } from '../vendor/auto/luxon.mjs'; import { DateTime } from '../vendor/auto/luxon.mjs';
import WeatherDisplay from './weatherdisplay.mjs'; import WeatherDisplay from './weatherdisplay.mjs';
import { registerDisplay } from './navigation.mjs'; import { registerDisplay } from './navigation.mjs';
@ -87,12 +86,7 @@ class TravelForecast extends WeatherDisplay {
if (city.icon) { if (city.icon) {
fillValues.city = city.name; fillValues.city = city.name;
// get temperatures and convert if necessary // get temperatures and convert if necessary
let { low, high } = city; const { low, high } = city;
if (getUnits() === UNITS.metric) {
low = convert.fahrenheitToCelsius(low);
high = convert.fahrenheitToCelsius(high);
}
// convert to strings with no decimal // convert to strings with no decimal
const lowString = Math.round(low).toString(); const lowString = Math.round(low).toString();

View file

@ -1,54 +1,17 @@
const UNITS = {
english: Symbol('english'),
metric: Symbol('metric'),
};
let currentUnits = UNITS.english;
const getUnits = () => currentUnits;
const setUnits = (_unit) => {
const unit = _unit.toLowerCase();
if (unit === 'english') {
currentUnits = UNITS.english;
} else {
currentUnits = UNITS.metric;
}
// TODO: refresh current screen
};
// *********************************** unit conversions *********************** // *********************************** unit conversions ***********************
const round2 = (value, decimals) => Number(`${Math.round(`${value}e${decimals}`)}e-${decimals}`); const round2 = (value, decimals) => Number(`${Math.round(`${value}e${decimals}`)}e-${decimals}`);
const mphToKph = (Mph) => Math.round(Mph * 1.60934);
const kphToMph = (Kph) => Math.round(Kph / 1.60934); const kphToMph = (Kph) => Math.round(Kph / 1.60934);
const celsiusToFahrenheit = (Celsius) => Math.round((Celsius * 9) / 5 + 32); const celsiusToFahrenheit = (Celsius) => Math.round((Celsius * 9) / 5 + 32);
const fahrenheitToCelsius = (Fahrenheit) => round2((((Fahrenheit) - 32) * 5) / 9, 1);
const milesToKilometers = (Miles) => Math.round(Miles * 1.60934);
const kilometersToMiles = (Kilometers) => Math.round(Kilometers / 1.60934); const kilometersToMiles = (Kilometers) => Math.round(Kilometers / 1.60934);
const feetToMeters = (Feet) => Math.round(Feet * 0.3048);
const metersToFeet = (Meters) => Math.round(Meters / 0.3048); const metersToFeet = (Meters) => Math.round(Meters / 0.3048);
const inchesToCentimeters = (Inches) => round2(Inches * 2.54, 2);
const pascalToInHg = (Pascal) => round2(Pascal * 0.0002953, 2); const pascalToInHg = (Pascal) => round2(Pascal * 0.0002953, 2);
const convert = { export {
mphToKph,
kphToMph, kphToMph,
celsiusToFahrenheit, celsiusToFahrenheit,
fahrenheitToCelsius,
milesToKilometers,
kilometersToMiles, kilometersToMiles,
feetToMeters,
metersToFeet, metersToFeet,
inchesToCentimeters,
pascalToInHg, pascalToInHg,
}; };
export {
getUnits,
setUnits,
UNITS,
convert,
};
export default getUnits;

View file

@ -159,12 +159,6 @@
<input id="chkAutoRefresh" name="chkAutoRefresh" type="checkbox" /><label id="lblRefreshCountDown" for="chkAutoRefresh">Auto Refresh: <span id="spanRefreshCountDown">--:--</span></label> <input id="chkAutoRefresh" name="chkAutoRefresh" type="checkbox" /><label id="lblRefreshCountDown" for="chkAutoRefresh">Auto Refresh: <span id="spanRefreshCountDown">--:--</span></label>
</div> </div>
<div id="divUnits">
Units:
<input id="radEnglish" name="radUnits" type="radio" value="ENGLISH" /><label for="radEnglish">English</label>
<input id="radMetric" name="radUnits" type="radio" value="METRIC" /><label for="radMetric">Metric</label>
</div>
</body> </body>
</html> </html>