Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.0 kB
1
Indexable
Never
import * as messaging from "messaging";
import { geolocation } from "geolocation";
import { settingsStorage } from "settings";

var lat;
var lon;

geolocation.getCurrentPosition(locationSuccess, locationError, {timeout: 60 * 1000});

function locationSuccess(position) {
  lat = position.coords.latitude
  lon = position.coords.longitude
  console.log("Lat: " + lat, "Lon: " + lon)
}

function locationError(error) {
  console.log("Error: " + error.code, "Message: " + error.message);
}

var API_KEY = "removedforsecurity";
var ENDPOINT = "https://api.openweathermap.org/data/2.5/weather";

function queryOpenWeather() {
  geolocation.getCurrentPosition(locationSuccess, locationError);
  fetch(ENDPOINT + "?lat=" + lat + "&lon=" + lon + "&APPID=" + API_KEY)
  .then(function (response) {
      response.json()
      .then(function(data) {
        console.log(data)
        // Get current, high, low temps and condition
        var weather = {
          condition: data["weather"][0]["icon"],
          temperature: data["main"]["temp"],
          temp_min: data["main"]["temp_min"],
          temp_max: data["main"]["temp_max"]
        }
        // Send the weather data to the device
        //console.log("weather not sent")
        returnWeatherData(weather);
        //console.log("Weather Sent")
      });
  })
  .catch(function (err) {
    console.error(`Error fetching weather: ${err}`);
  });
}

function returnWeatherData(data) {
  if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) {
    console.log("weather not sent")      
    messaging.peerSocket.send(data);
    console.log("Weather Sent")
  } else {
    console.error("Error: Connection is not open");
  }
}

messaging.peerSocket.addEventListener("message", (evt) => {
  if (evt.data && evt.data.command === "weather") {
    queryOpenWeather();
  }
});

messaging.peerSocket.addEventListener("error", (err) => {
  console.error(`Connection error: ${err.code} - ${err.message}`);
});