12-03-2018 13:11
12-03-2018 13:11
I'm doing quite a lot of efforts in the art of coding and I'm now learning how to make external functions that help to keep the code clean.
However i'm having some problems to create a module for my weather script; I guess I'm having issues about dealing with the concept companion/apps exchange of information.
The entire experimental clockface with weather information is hosted here
And the relevant app and companion scripts are below:
App Index.js
import clock from "clock"; import document from "document"; import { units } from "user-settings"; import * as util from "../common/utils"; import { battery } from "power"; // Import the messaging module import * as messaging from "messaging"; import document from "document"; // Import measure units const measureUnitsPref = units.distance; // Set clock granularity (minutes or seconds) clock.granularity = "minutes"; // Get a handle on the <text> element const timeHandle = document.getElementById("timeLabel"); const temperatureHandle = document.getElementById("temperatureLabel"); const weatherConditionsHandle = document.getElementById("weatherConditionsLabel"); const locationHandle = document.getElementById("locationLabel"); const dateHandle = document.getElementById("dateLabel"); const batteryHandle = document.getElementById("batteryLabel"); // Update the <text> element every tick with the current time clock.ontick = (evt) => { let today = evt.date; timeHandle.text = util.timeFunction(today); dateHandle.text = util.dateFunction(today); batteryHandle.text = 'Battery: '+ battery.chargeLevel + ' %'; // Battery Measurement } // Weather module // Request weather data from the companion function fetchWeather() { if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) { // Send a command to the companion messaging.peerSocket.send({ command: 'weather' }); } } // Display the weather data received from the companion weatherConditionsHandle.text = function processWeatherData(data) { if (measureUnitsPref === "us") { temperatureHandle.text = Math.round((data.temperature * 9 / 5) +32) + " °F"; } else { temperatureHandle.text = Math.round(data.temperature) + " °C"; } weatherConditionsHandle.text = data.weatherConditions; // locationHandle.text = data.location; } // Listen for the onopen event messaging.peerSocket.onopen = function() { // Fetch weather when the connection opens fetchWeather(); } // Listen for messages from the companion messaging.peerSocket.onmessage = function(evt) { if (evt.data) { processWeatherData(evt.data); } } // Listen for the onerror event messaging.peerSocket.onerror = function(err) { // Handle any errors console.log("Connection error: " + err.code + " - " + err.message); } setInterval(fetchWeather, 30 * 1000 * 60);
Companion index.js
// Import the messaging module import * as messaging from "messaging"; import { geolocation } from "geolocation"; var API_KEY = "MY APY KEY"; // Fetch the weather from OpenWeather function queryOpenWeather() { geolocation.getCurrentPosition(locationSuccess, locationError); function locationSuccess(position) { var lat = position.coords.latitude; var long = position.coords.longitude; var linkApi = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&units=metric" + "&APPID=" + API_KEY; fetch(linkApi) .then(function (response) { response.json() .then(function(data) { // We just want some data var weather = { temperature: data.main.temp, weatherConditions: data.weather[0].main, location: data["name"] } // Send the weather data to the device returnWeatherData(weather); }); }) .catch(function (err) { console.log("Error fetching weather: " + err); }); }; function locationError(error) { console.log("Error: " + error.code, "Message: " + error.message); } } // Send the weather data to the device function returnWeatherData(data) { if (messaging.peerSocket.readyState === messaging.peerSocket.OPEN) { // Send a command to the device messaging.peerSocket.send(data); } else { console.log("Error: Connection is not open"); } } // Listen for messages from the device messaging.peerSocket.onmessage = function(evt) { if (evt.data && evt.data.command == "weather") { // The device requested weather data queryOpenWeather(); } } // Listen for the onerror event messaging.peerSocket.onerror = function(err) { // Handle any errors console.log("Connection error: " + err.code + " - " + err.message); }
I would really appreciate your help as I'm a little stuck. Thanks!
12-12-2018 13:30
12-12-2018 13:30
How about something like this? It's incomplete and untested, but should give you an idea.
export default class Weather { conditions; constructor(options) { this.options = options; } fetchWeather(lat, long) { var linkApi = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&units=metric&APPID=${API_KEY}`; fetch(linkApi) .then((response) => { response.json(); }) .then((data) => { this.conditions = { temperature: data.main.temp, weatherConditions: data.weather[0].main, location: data["name"] } if (this.callback && typeof this.callback == "function") { this.callback(); } }) } locationSuccess(position) { this.fetchWeather(position.coords.latitude, position.coords.longitude); } getWeather(callback) { this.callback = callback; geolocation.getCurrentPosition(this.locationSuccess, this.locationError); } }
import Weather from "./weather"; let weather = new Weather({ sample: "setting" }); function callback() { console.log(JSON.stringify(weather.conditions)); } weather.getWeather(callback);
12-12-2018 19:24
12-12-2018 19:24
Thanks a lot @JonFitbit, I will try to give it a go over the weekend, this week RL job is crazy and in the evening I really want to do everything (aka sleeping) but coding