Sun Position

Simple sun position subflow to get the various times. Uses the suncalc library

subpos

Set the latitude and longitude and the output property. Inject a proper timestamp and connect a debug node to receive output.

input Example output:

{
  "times": {
    "solarNoon": "2020-04-14T11:44:29.015Z",
    "nadir": "2020-04-13T23:44:29.015Z",
    "sunrise": "2020-04-14T04:48:54.961Z",
    "sunset": "2020-04-14T18:40:03.069Z",
    "sunriseEnd": "2020-04-14T04:52:32.065Z",
    "sunsetStart": "2020-04-14T18:36:25.965Z",
    "dawn": "2020-04-14T04:13:00.161Z",
    "dusk": "2020-04-14T19:15:57.869Z",
    "nauticalDawn": "2020-04-14T03:28:27.101Z",
    "nauticalDusk": "2020-04-14T20:00:30.929Z",
    "nightEnd": "2020-04-14T02:38:12.290Z",
    "night": "2020-04-14T20:50:45.740Z",
    "goldenHourEnd": "2020-04-14T05:34:30.138Z",
    "goldenHour": "2020-04-14T17:54:27.892Z"
  },
  "sunrisePos": {
    "azimuth": -1.9203444325321162,
    "altitude": -0.06223696175494428
  },
  "sunriseAzimuth": -110.02763119553532
}
[{"id":"523273d5.3e8894","type":"subflow","name":"SunPosition","info":"### Sun Position\n\nSet latitude and longitude in the node\n\n### Input\n\nSet the input `msg` (default `msg.payload`)\n\nInject a valid timestamp\n\n","category":"","in":[{"x":92,"y":96,"wires":[{"id":"c3595d5c.bed268"}]}],"out":[{"x":308,"y":96,"wires":[{"id":"c3595d5c.bed268","port":0}]}],"env":[{"name":"latitude","type":"num","value":"","ui":{"label":{"en-US":"Latitude"},"type":"input","opts":{"types":["num"]}}},{"name":"longitude","type":"num","value":"","ui":{"label":{"en-US":"Longitude"},"type":"input","opts":{"types":["num"]}}},{"name":"msg","type":"str","value":"payload","ui":{"label":{"en-US":"msg."},"type":"input","opts":{"types":["str"]}}}],"color":"#FFCC66","icon":"font-awesome/fa-sun-o"},{"id":"c3595d5c.bed268","type":"function","z":"523273d5.3e8894","name":"","func":"/*\n (c) 2011-2015, Vladimir Agafonkin\n SunCalc is a JavaScript library for calculating sun/moon position and light phases.\n https://github.com/mourner/suncalc\n*/\n\nvar PI   = Math.PI,\n    sin  = Math.sin,\n    cos  = Math.cos,\n    tan  = Math.tan,\n    asin = Math.asin,\n    atan = Math.atan2,\n    acos = Math.acos,\n    rad  = PI / 180;\n\n// sun calculations are based on http://aa.quae.nl/en/reken/zonpositie.html formulas\n\n\n// date/time constants and conversions\n\nvar dayMs = 1000 * 60 * 60 * 24,\n    J1970 = 2440588,\n    J2000 = 2451545;\n\nfunction toJulian(date) { return date.valueOf() / dayMs - 0.5 + J1970; }\nfunction fromJulian(j)  { return new Date((j + 0.5 - J1970) * dayMs); }\nfunction toDays(date)   { return toJulian(date) - J2000; }\n\n\n// general calculations for position\n\nvar e = rad * 23.4397; // obliquity of the Earth\n\nfunction rightAscension(l, b) { return atan(sin(l) * cos(e) - tan(b) * sin(e), cos(l)); }\nfunction declination(l, b)    { return asin(sin(b) * cos(e) + cos(b) * sin(e) * sin(l)); }\n\nfunction azimuth(H, phi, dec)  { return atan(sin(H), cos(H) * sin(phi) - tan(dec) * cos(phi)); }\nfunction altitude(H, phi, dec) { return asin(sin(phi) * sin(dec) + cos(phi) * cos(dec) * cos(H)); }\n\nfunction siderealTime(d, lw) { return rad * (280.16 + 360.9856235 * d) - lw; }\n\nfunction astroRefraction(h) {\n    if (h < 0) // the following formula works for positive altitudes only.\n        h = 0; // if h = -0.08901179 a div/0 would occur.\n\n    // formula 16.4 of \"Astronomical Algorithms\" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.\n    // 1.02 / tan(h + 10.26 / (h + 5.10)) h in degrees, result in arc minutes -> converted to rad:\n    return 0.0002967 / Math.tan(h + 0.00312536 / (h + 0.08901179));\n}\n\n// general sun calculations\n\nfunction solarMeanAnomaly(d) { return rad * (357.5291 + 0.98560028 * d); }\n\nfunction eclipticLongitude(M) {\n\n    var C = rad * (1.9148 * sin(M) + 0.02 * sin(2 * M) + 0.0003 * sin(3 * M)), // equation of center\n        P = rad * 102.9372; // perihelion of the Earth\n\n    return M + C + P + PI;\n}\n\nfunction sunCoords(d) {\n\n    var M = solarMeanAnomaly(d),\n        L = eclipticLongitude(M);\n\n    return {\n        dec: declination(L, 0),\n        ra: rightAscension(L, 0)\n    };\n}\n\n\nvar SunCalc = {};\n\n\n// calculates sun position for a given date and latitude/longitude\n\nSunCalc.getPosition = function (date, lat, lng) {\n\n    var lw  = rad * -lng,\n        phi = rad * lat,\n        d   = toDays(date),\n\n        c  = sunCoords(d),\n        H  = siderealTime(d, lw) - c.ra;\n\n    return {\n        azimuth: azimuth(H, phi, c.dec),\n        altitude: altitude(H, phi, c.dec)\n    };\n};\n\n\n// sun times configuration (angle, morning name, evening name)\n\nvar times = SunCalc.times = [\n    [-0.833, 'sunrise',       'sunset'      ],\n    [  -0.3, 'sunriseEnd',    'sunsetStart' ],\n    [    -6, 'dawn',          'dusk'        ],\n    [   -12, 'nauticalDawn',  'nauticalDusk'],\n    [   -18, 'nightEnd',      'night'       ],\n    [     6, 'goldenHourEnd', 'goldenHour'  ]\n];\n\n// adds a custom time to the times config\n\nSunCalc.addTime = function (angle, riseName, setName) {\n    times.push([angle, riseName, setName]);\n};\n\n\n// calculations for sun times\n\nvar J0 = 0.0009;\n\nfunction julianCycle(d, lw) { return Math.round(d - J0 - lw / (2 * PI)); }\n\nfunction approxTransit(Ht, lw, n) { return J0 + (Ht + lw) / (2 * PI) + n; }\nfunction solarTransitJ(ds, M, L)  { return J2000 + ds + 0.0053 * sin(M) - 0.0069 * sin(2 * L); }\n\nfunction hourAngle(h, phi, d) { return acos((sin(h) - sin(phi) * sin(d)) / (cos(phi) * cos(d))); }\nfunction observerAngle(height) { return -2.076 * Math.sqrt(height) / 60; }\n\n// returns set time for the given sun altitude\nfunction getSetJ(h, lw, phi, dec, n, M, L) {\n\n    var w = hourAngle(h, phi, dec),\n        a = approxTransit(w, lw, n);\n    return solarTransitJ(a, M, L);\n}\n\n\n// calculates sun times for a given date, latitude/longitude, and, optionally,\n// the observer height (in meters) relative to the horizon\n\nSunCalc.getTimes = function (date, lat, lng, height) {\n\n    height = height || 0;\n\n    var lw = rad * -lng,\n        phi = rad * lat,\n\n        dh = observerAngle(height),\n\n        d = toDays(date),\n        n = julianCycle(d, lw),\n        ds = approxTransit(0, lw, n),\n\n        M = solarMeanAnomaly(ds),\n        L = eclipticLongitude(M),\n        dec = declination(L, 0),\n\n        Jnoon = solarTransitJ(ds, M, L),\n\n        i, len, time, h0, Jset, Jrise;\n\n\n    var result = {\n        solarNoon: fromJulian(Jnoon),\n        nadir: fromJulian(Jnoon - 0.5)\n    };\n\n    for (i = 0, len = times.length; i < len; i += 1) {\n        time = times[i];\n        h0 = (time[0] + dh) * rad;\n\n        Jset = getSetJ(h0, lw, phi, dec, n, M, L);\n        Jrise = Jnoon - (Jset - Jnoon);\n\n        result[time[1]] = fromJulian(Jrise);\n        result[time[2]] = fromJulian(Jset);\n    }\n\n    return result;\n};\n\n\n// moon calculations, based on http://aa.quae.nl/en/reken/hemelpositie.html formulas\n\nfunction moonCoords(d) { // geocentric ecliptic coordinates of the moon\n\n    var L = rad * (218.316 + 13.176396 * d), // ecliptic longitude\n        M = rad * (134.963 + 13.064993 * d), // mean anomaly\n        F = rad * (93.272 + 13.229350 * d),  // mean distance\n\n        l  = L + rad * 6.289 * sin(M), // longitude\n        b  = rad * 5.128 * sin(F),     // latitude\n        dt = 385001 - 20905 * cos(M);  // distance to the moon in km\n\n    return {\n        ra: rightAscension(l, b),\n        dec: declination(l, b),\n        dist: dt\n    };\n}\n\nSunCalc.getMoonPosition = function (date, lat, lng) {\n\n    var lw  = rad * -lng,\n        phi = rad * lat,\n        d   = toDays(date),\n\n        c = moonCoords(d),\n        H = siderealTime(d, lw) - c.ra,\n        h = altitude(H, phi, c.dec),\n        // formula 14.1 of \"Astronomical Algorithms\" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.\n        pa = atan(sin(H), tan(phi) * cos(c.dec) - sin(c.dec) * cos(H));\n\n    h = h + astroRefraction(h); // altitude correction for refraction\n\n    return {\n        azimuth: azimuth(H, phi, c.dec),\n        altitude: h,\n        distance: c.dist,\n        parallacticAngle: pa\n    };\n};\n\n\n// calculations for illumination parameters of the moon,\n// based on http://idlastro.gsfc.nasa.gov/ftp/pro/astro/mphase.pro formulas and\n// Chapter 48 of \"Astronomical Algorithms\" 2nd edition by Jean Meeus (Willmann-Bell, Richmond) 1998.\n\nSunCalc.getMoonIllumination = function (date) {\n\n    var d = toDays(date || new Date()),\n        s = sunCoords(d),\n        m = moonCoords(d),\n\n        sdist = 149598000, // distance from Earth to Sun in km\n\n        phi = acos(sin(s.dec) * sin(m.dec) + cos(s.dec) * cos(m.dec) * cos(s.ra - m.ra)),\n        inc = atan(sdist * sin(phi), m.dist - sdist * cos(phi)),\n        angle = atan(cos(s.dec) * sin(s.ra - m.ra), sin(s.dec) * cos(m.dec) -\n                cos(s.dec) * sin(m.dec) * cos(s.ra - m.ra));\n\n    return {\n        fraction: (1 + cos(inc)) / 2,\n        phase: 0.5 + 0.5 * inc * (angle < 0 ? -1 : 1) / Math.PI,\n        angle: angle\n    };\n};\n\n\nfunction hoursLater(date, h) {\n    return new Date(date.valueOf() + h * dayMs / 24);\n}\n\n// calculations for moon rise/set times are based on http://www.stargazing.net/kepler/moonrise.html article\n\nSunCalc.getMoonTimes = function (date, lat, lng, inUTC) {\n    var t = new Date(date);\n    if (inUTC) t.setUTCHours(0, 0, 0, 0);\n    else t.setHours(0, 0, 0, 0);\n\n    var hc = 0.133 * rad,\n        h0 = SunCalc.getMoonPosition(t, lat, lng).altitude - hc,\n        h1, h2, rise, set, a, b, xe, ye, d, roots, x1, x2, dx;\n\n    // go in 2-hour chunks, each time seeing if a 3-point quadratic curve crosses zero (which means rise or set)\n    for (var i = 1; i <= 24; i += 2) {\n        h1 = SunCalc.getMoonPosition(hoursLater(t, i), lat, lng).altitude - hc;\n        h2 = SunCalc.getMoonPosition(hoursLater(t, i + 1), lat, lng).altitude - hc;\n\n        a = (h0 + h2) / 2 - h1;\n        b = (h2 - h0) / 2;\n        xe = -b / (2 * a);\n        ye = (a * xe + b) * xe + h1;\n        d = b * b - 4 * a * h1;\n        roots = 0;\n\n        if (d >= 0) {\n            dx = Math.sqrt(d) / (Math.abs(a) * 2);\n            x1 = xe - dx;\n            x2 = xe + dx;\n            if (Math.abs(x1) <= 1) roots++;\n            if (Math.abs(x2) <= 1) roots++;\n            if (x1 < -1) x1 = x2;\n        }\n\n        if (roots === 1) {\n            if (h0 < 0) rise = i + x1;\n            else set = i + x1;\n\n        } else if (roots === 2) {\n            rise = i + (ye < 0 ? x2 : x1);\n            set = i + (ye < 0 ? x1 : x2);\n        }\n\n        if (rise && set) break;\n\n        h0 = h2;\n    }\n\n    var result = {};\n\n    if (rise) result.rise = hoursLater(t, rise);\n    if (set) result.set = hoursLater(t, set);\n\n    if (!rise && !set) result[ye > 0 ? 'alwaysUp' : 'alwaysDown'] = true;\n\n    return result;\n};\n\n\n\ninput = env.get(\"msg\")\n\n// get today's sunlight times for London\nvar times = SunCalc.getTimes(msg[input],env.get(\"latitude\"), env.get(\"longitude\"));\n\n// format sunrise time from the Date object\nvar sunriseStr = times.sunrise.getHours() + ':' + times.sunrise.getMinutes();\n\n// get position of the sun (azimuth and altitude) at today's sunrise\nvar sunrisePos = SunCalc.getPosition(times.sunrise, 51.5, -0.1);\n\n// get sunrise azimuth in degrees\nvar sunriseAzimuth = sunrisePos.azimuth * 180 / Math.PI;\n\n\nreturn {payload:{times:times,sunrisePos:sunrisePos,sunriseAzimuth:sunriseAzimuth}}\n","outputs":1,"noerr":0,"x":194,"y":96,"wires":[[]]},{"id":"33497473.f0c90c","type":"subflow:523273d5.3e8894","z":"57ffd93.5a29d28","name":"SunPosition","env":[{"name":"latitude","value":"52.1","type":"num"},{"name":"longitude","value":"4.2","type":"num"}],"x":310,"y":168,"wires":[[]]}]

Flow Info

Created 5 years, 5 months ago
Rating: not yet rated

Owner

Actions

Rate:

Node Types

Core
  • function (x1)
Other
  • subflow (x1)
  • subflow:523273d5.3e8894 (x1)

Tags

  • sun
  • position
  • subflow
  • sunrise
  • sunset
Copy this flow JSON to your clipboard and then import into Node-RED using the Import From > Clipboard (Ctrl-I) menu option