Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'suncalc' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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);
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),
};
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
}
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);
}
// 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);
}
_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);
}
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()}
}
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() )
};
}
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
};
});
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
};
});