How to use suncalc - 10 common examples

To help you get started, we’ve selected a few suncalc examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github glenmurphy / route / modules / weather / weather.js View on Github external
Weather.prototype.calculateSunEvents = function() {
  var times = SunCalc.getTimes(new Date(), this.latitude, this.longitude);
  var position = SunCalc.getPosition(new Date(), this.latitude, this.longitude);
  this.emit("StateEvent", {sunEvents:times});
  this.emit("StateEvent", {sunPosition:position});

  var logstring = "";
  for (var attrname in times) {
    logstring += attrname + ":" + times[attrname].getHours() + ":" +  times[attrname].getMinutes() + " ";
    setDateTimeout(this.processSunEvent.bind(this, attrname), times[attrname]);
  }
  console.log("Sun Events:" + logstring)

  // recalculate tomorrow at midnight;
  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  tomorrow.setHours(0);
  tomorrow.setMinutes(0);
github honestbleeps / Reddit-Enhancement-Suite / lib / modules / nightMode.js View on Github external
async function getNightModeTimes() {
	switch (module.options.automaticNightMode.value) {
		case 'automatic':
			try {
				const { latitude, longitude } = await getGeolocation();
				const { sunrise, sunset } = getSunriseSunset(new Date(), latitude, longitude);
				return { startingTime: sunset, endingTime: sunrise };
			} catch (err) {
				console.warn('Failed to init automatic night mode:', err);

				switch (err.code) {
					case err.PERMISSION_DENIED:
						return Alert.open(i18n('nightModeAutomaticNightModeDenied', 'confirm'), { cancelable: true })
							.then(() => {
								// they clicked confirm, turn it off
								module.options.automaticNightMode.value = 'none';
								Options.save(module.options.automaticNightMode);

								return {
									startingTime: new Date(0),
									endingTime: new Date(0),
								};
github ceejbot / nanoleaves / examples / timeofday.js View on Github external
function pickColors()
{
	const now = new Date();
	const hour = now.getHours();
	const minute = now.getMinutes();

	const times = suncalc.getTimes(now, process.env.LAT, process.env.LONG);
	console.log(times);

	const hourPos = hour % 12 - 1;
	const minutePos = Math.ceil(minute / 5) - 1;
	console.log(`current time: ${hour}:${minute}; positions == ${hourPos}:${minutePos}`);

	// now figure out colors
}
github Whitevinyl / ARP / js / node / _GENTWEET.js View on Github external
function timeInit() {
    // get today's sunlight times for Atacama
    timeNow = new Date();
    atacamaTime = SunCalc.getTimes(timeNow, -23.8, -67.4);

    morningLight = (timeNow > atacamaTime.dawn && timeNow < atacamaTime.goldenHourEnd);
    eveningLight = (timeNow > atacamaTime.goldenHour && timeNow < atacamaTime.nauticalDusk);
    nightTime = (timeNow < atacamaTime.dawn || timeNow > atacamaTime.nauticalDusk);
}
github grover / homebridge-automation-switches / src / SolarClockAccessory.js View on Github external
// algorithm based on https://github.com/kcharwood/homebridge-suncalc
    ///////////////////////////////////////////////////////////////////////////////////////////

    const today = new Date();
    const now = today.getTime();
    const solarTime = Characteristic.SolarPeriod._SolarTimes[this._state.period];

    let sunDates = suncalc.getTimes(today, this.location.latitude, this.location.longitude);
    let timeout = sunDates[solarTime].getTime() + (this._state.offset * 60 * 1000);
    let diff = timeout - now;

    if (timeout <= now) {
      const tomorrow = new Date();

      tomorrow.setDate(tomorrow.getDate() + 1);
      sunDates = suncalc.getTimes(tomorrow, this.location.latitude, this.location.longitude);
      timeout = sunDates[solarTime].getTime() + (this._state.offset * 60 * 1000);
      diff = timeout - now;
    }

    this.log(`Raising next solar timer for ${solarTime} at ${new Date(timeout).toLocaleString()} in ${Math.round(diff / (60 * 1000))}mins`);
    this._timer = setTimeout(this._solar.bind(this), diff);
  }
github grover / homebridge-automation-switches / src / SolarClockAccessory.js View on Github external
_scheduleSolarClock() {
    ///////////////////////////////////////////////////////////////////////////////////////////
    // algorithm based on https://github.com/kcharwood/homebridge-suncalc
    ///////////////////////////////////////////////////////////////////////////////////////////

    const today = new Date();
    const now = today.getTime();
    const solarTime = Characteristic.SolarPeriod._SolarTimes[this._state.period];

    let sunDates = suncalc.getTimes(today, this.location.latitude, this.location.longitude);
    let timeout = sunDates[solarTime].getTime() + (this._state.offset * 60 * 1000);
    let diff = timeout - now;

    if (timeout <= now) {
      const tomorrow = new Date();

      tomorrow.setDate(tomorrow.getDate() + 1);
      sunDates = suncalc.getTimes(tomorrow, this.location.latitude, this.location.longitude);
      timeout = sunDates[solarTime].getTime() + (this._state.offset * 60 * 1000);
      diff = timeout - now;
    }

    this.log(`Raising next solar timer for ${solarTime} at ${new Date(timeout).toLocaleString()} in ${Math.round(diff / (60 * 1000))}mins`);
    this._timer = setTimeout(this._solar.bind(this), diff);
  }
github crownstone / CrownstoneApp / js / views / deviceViews / smartBehaviour / supportCode / AicoreUtil.ts View on Github external
let obj = (timeObj as aicoreTimeDataClock).data;
      return {hours:obj.hours, minutes: obj.minutes}
    }
    else {
      let state = core.store.getState();
      let sphere = state.spheres[sphereId];

      // position of Crownstone HQ.
      let lat = 51.923611570463152;
      let lon = 4.4667693378575288;
      if (sphere) {
        lat = sphere.config.latitude  || lat;
        lon = sphere.config.longitude || lon;
      }
      let baseTime = 0;
      var times = SunCalc.getTimes(new Date(), lat, lon);

      let obj = (timeObj as aicoreTimeDataSun);
      if (obj.type === "SUNSET") {
        baseTime = new Date(times.sunset).valueOf();
      }
      else if (obj.type === "SUNRISE") {
        baseTime = new Date(times.sunriseEnd).valueOf();
      }


      if (obj.offsetMinutes !== 0) {
        baseTime += 60*1000*obj.offsetMinutes;
      }

      return {hours: new Date(baseTime).getHours(), minutes: new Date(baseTime).getMinutes()}
    }
github OpenSprinkler / OpenSprinkler-Weather / routes / weather.ts View on Github external
function getTimeData( coordinates: GeoCoordinates ): TimeData {
	const timezone = moment().tz( geoTZ( coordinates[ 0 ], coordinates[ 1 ] )[ 0 ] ).utcOffset();
	const tzOffset: number = getTimezone( timezone, true );

	// Calculate sunrise and sunset since Weather Underground does not provide it
	const sunData = SunCalc.getTimes( new Date(), coordinates[ 0 ], coordinates[ 1 ] );

	sunData.sunrise.setUTCMinutes( sunData.sunrise.getUTCMinutes() + tzOffset );
	sunData.sunset.setUTCMinutes( sunData.sunset.getUTCMinutes() + tzOffset );

	return {
		timezone:	timezone,
		sunrise:	( sunData.sunrise.getUTCHours() * 60 + sunData.sunrise.getUTCMinutes() ),
		sunset:		( sunData.sunset.getUTCHours() * 60 + sunData.sunset.getUTCMinutes() )
	};
}
github nebrius / aquarium-control / server / src / controller.js View on Github external
var entries = currentSchedule.schedule.map(function(entry) {

    // If we're manual, calculate the time for today and return it
    if (entry.type == 'manual') {
      return {
        date: createDate(entry.time.hour, entry.time.minute, 0),
        state: entry.state,
        name: entry.name
      };
    }

    // If we're dynamic, use suncalc to figure out the time
    var times = sunCalc.getTimes(createDate(12, 0, 0), config.location.latitude, config.location.longitude);
    var date = times[entry.event];
    if (!date) {
      throw new Error('Invalid dynamic event "' + entry.event + '". Must be one of ' +
        Object.keys(times).join(', '));
    }
    return {
      date: date,
      state: entry.state,
      name: entry.name
    };
  });
github nebrius / aquarium-control / server / src / scheduler.ts View on Github external
let entries = currentSchedule.schedule.map((entry) => {

    // If we're manual, calculate the time for today and return it
    if (entry.type === 'manual') {
      const manualDetails: IManualScheduleEntry = entry.details as IManualScheduleEntry;
      return {
        date: createDate(manualDetails.hour, manualDetails.minute, 0),
        state: entry.state,
        name: entry.name
      };
    }

    // If we're dynamic, use suncalc to figure out the time
    const dynamicDetails: IDynamicScheduleEntry = entry.details as IDynamicScheduleEntry;
    const times = getTimes(createDate(12, 0, 0), getServerConfig().latitude, getServerConfig().longitude);
    const date = times[dynamicDetails.event];
    if (!date) {
      const eventNames = Object.keys(times).join(', ');
      throw new Error(`Invalid dynamic event "${dynamicDetails.event}". Must be one of ${eventNames}.`);
    }
    return {
      date,
      state: entry.state,
      name: entry.name
    };
  });

suncalc

A tiny JavaScript library for calculating sun/moon positions and phases.

BSD-2-Clause
Latest version published 3 years ago

Package Health Score

56 / 100
Full package analysis

Popular suncalc functions