diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 09b7afa..d29ea15 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -18,6 +18,42 @@ Rules for a section, all of them learned from what reads badly on that card: --- +## 2.21.04 + +- Fixed: opening the Weather Radar soon after the Orb started could restart it, until the four-day forecast had arrived + +--- + +## 2.21.03 + +- Weather map text sizes: the range, the last-updated line and the RainViewer credit are 20% larger; the temperature line is a little smaller than in 2.21.02 + +--- + +## 2.21.02 + +- Choose where the clock gets its time: the internet over WiFi, or GPS. Settings > Location > Time from +- The weather map's temperature and conditions are bigger and as bright as the wind line +- The weather map says NO RAIN when the radar arrived and the sky is clear, so a clear map no longer looks like a broken one + +--- + +## 2.20.02 + +- Satellites: a new screen showing the ISS, Tiangong, Hubble and three ham satellites on a sky dial, with when each next rises, how high it climbs and which way it goes. Push the knob (or tap) for the next one. With Radar sounds on, the Orb pings when one rises for a good pass +- The Weather Radar is back on the menu +- The screen answers to touch: tap a plane to select it, tap anywhere else to push, drag up or down to scroll, swipe for the next app, hold for the menu + +--- + +## 2.19.01 + +- An Orb with the GPS module finds its own location again. Settings > Location > GPS turns it on or off and shows how many satellites it can see. Picking a city by hand switches GPS off, so your choice still wins +- Capsule Radar can be your flight tracker. Settings > Flight radar sets the style, or opens it straight away. Press the knob to come back to the Orb, turn it to zoom +- Needs the Mac installer (or a USB flash) once, because the Orb now keeps two firmwares side by side. Your WiFi and settings stay; the theme artwork is prepared again on the first start + +--- + ## 2.18.01 - Rocking the knob to open the menu works the way you expect now. It used to want the knob to come to a stop first, and to see no more than two clicks in either direction, so most people rocked it over and over before anything happened. Any amount of turn counts now, as long as you change direction inside a quarter second. Fixed by Lerxtwood diff --git a/lib/Sgp4/LICENSE b/lib/Sgp4/LICENSE new file mode 100644 index 0000000..853b46d --- /dev/null +++ b/lib/Sgp4/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/lib/Sgp4/Sgp4.h b/lib/Sgp4/Sgp4.h new file mode 100644 index 0000000..d440dad --- /dev/null +++ b/lib/Sgp4/Sgp4.h @@ -0,0 +1,6 @@ +#ifndef SGP4_H +#define SGP4_H + +#include "sgp4pred.h" + +#endif \ No newline at end of file diff --git a/lib/Sgp4/brent.cpp b/lib/Sgp4/brent.cpp new file mode 100644 index 0000000..af45789 --- /dev/null +++ b/lib/Sgp4/brent.cpp @@ -0,0 +1,150 @@ + +#include +#include "brent.h" +#include "sgp4pred.h" + +#define ITMAX 100 //Here ITMAX is the maximum allowed number of iterations; +#define R 0.61803399 +#define C 0.3819660 //CGOLD is the golden ratio; +#define ZEPS 2.22e-15 // ZEPS is a small number that protects against trying to achieve fractional accuracy for a minimum that happens to be exactly zero. + +#define SHFT2(a,b,c) (a)=(b);(b)=(c); +#define SHFT3(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); + +double brentmin(double ax, double bx, double cx, double (Sgp4::*f)(double), double tol, double *xmin, Sgp4* obj) +//Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is +//between ax and cx, and f(bx) is less than both f(ax) and f(cx)), this routine isolates +//the minimum to a fractional precision of about tol using Brent’s method. The abscissa of +//the minimum is returned as xmin, and the minimum function value is returned as brent, the +//returned function value. +{ + + int iter; + double a,b,d,etemp,fu,fv,fw,fx,p,q,r,tol1,tol2,u,v,w,x,xm; + double e=0.0; //This will be the distance moved on the step before last. + + a=(ax < cx ? ax : cx); //a and b must be in ascending order, + b=(ax > cx ? ax : cx); //but input abscissas need not be. + x=w=v=bx; //Initializations... + fw=fv=fx=(obj->*f)(x); + for (iter = 1; iter <= ITMAX; iter++) { //Main program loop. + xm = 0.5*(a+b); + tol2 = 2.0*(tol1=tol+ZEPS); //2.0*(tol1=tol*fabs(x)+ZEPS); + if (fabs(x-xm) <= (tol2-0.5*(b-a))) {// Test for done here. + *xmin=x; + return fx; + } + if (fabs(e) > tol1) { //Construct a trial parabolic fit. + r=(x-w)*(fx-fv); + q=(x-v)*(fx-fw); + p=(x-v)*q-(x-w)*r; + q=2.0*(q-r); + if (q > 0.0) p = -p; + q=fabs(q); + etemp=e; + e=d; + if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) + d=C*(e=(x >= xm ? a-x : b-x)); + //The above conditions determine the acceptability of the parabolic fit. Here we + //take the golden section step into the larger of the two segments. + else { + d=p/q; //Take the parabolic step. + u=x+d; + if (u-a < tol2 || b-u < tol2) + d=copysign(tol1,xm-x); + } + } else { + d=C*(e=(x >= xm ? a-x : b-x)); + } + u=(fabs(d) >= tol1 ? x+d : x+copysign(tol1,d)); + fu=(obj->*f)(u); + //This is the one function evaluation per iteration. + if (fu <= fx) { //Now decide what to do with our func + if (u >= x) a=x; else b=x; //tion evaluation. + SHFT3(v,w,x,u) //Housekeeping follows: + SHFT3(fv,fw,fx,fu) + } else { + if (u < x) a=u; else b=u; + if (fu <= fw || w == x) { + v=w; + w=u; + fv=fw; + fw=fu; + } else if (fu <= fv || v == x || v == w) { + v=u; + fv=fu; + } + } //Done with housekeeping. Back for + } //another iteration. + //nrerror("Too many iterations in brent"); + *xmin=-1.0; //Never get here. + return fx; + +} + + +double zbrent(double (Sgp4::*func)(double), double x1, double x2, double tol, Sgp4* obj) +//Using Brent’s method, find the root of a function func known to lie between x1 and x2. The +//root, returned as zbrent, will be refined until its accuracy is tol. +{ +int iter; +double a=x1,b=x2,c=x2,d,e,min1,min2; +double fa=(obj->*func)(a),fb=(obj->*func)(b),fc,p,q,r,s,tol1,xm; + +if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) +return -1.0; +fc=fb; +for (iter=1;iter<=ITMAX;iter++) { + if ((fb > 0.0 && fc > 0.0) || (fb < 0.0 && fc < 0.0)) { + c=a; //Rename a, b, c and adjust bounding interval + fc=fa; //d. + e=d=b-a; + } + if (fabs(fc) < fabs(fb)) { + a=b; + b=c; + c=a; + fa=fb; + fb=fc; + fc=fa; + } + tol1=2.0*ZEPS+0.5*tol; //Convergence check. + xm=0.5*(c-b); + if (fabs(xm) <= tol1 || fb == 0.0) return b; + if (fabs(e) >= tol1 && fabs(fa) > fabs(fb)) { + s=fb/fa; //Attempt inverse quadratic interpolation. + if (a == c) { + p=2.0*xm*s; + q=1.0-s; + } else { + q=fa/fc; + r=fb/fc; + p=s*(2.0*xm*q*(q-r)-(b-a)*(r-1.0)); + q=(q-1.0)*(r-1.0)*(s-1.0); + } + if (p > 0.0) q = -q; //Check whether in bounds. + p=fabs(p); + min1=3.0*xm*q-fabs(tol1*q); + min2=fabs(e*q); + if (2.0*p < (min1 < min2 ? min1 : min2)) { + e=d; //Accept interpolation. + d=p/q; + } else { + d=xm; //Interpolation failed, use bisection. + e=d; + } + } else { //Bounds decreasing too slowly, use bisection. + d=xm; + e=d; + } + a=b; //Move last best guess to a. + fa=fb; + if (fabs(d) > tol1) //Evaluate new trial root. + b += d; + else + b += copysign(tol1,xm); + fb=(obj->*func)(b); + } +//nrerror("Maximum number of iterations exceeded in zbrent"); +return -1.0; //Never get here. +} diff --git a/lib/Sgp4/brent.h b/lib/Sgp4/brent.h new file mode 100644 index 0000000..cb0553d --- /dev/null +++ b/lib/Sgp4/brent.h @@ -0,0 +1,17 @@ +#ifndef _brent_ +#define _brent_ + +#include "sgp4pred.h" + +//Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is +//between ax and cx, and f(bx) is less than both f(ax) and f(cx)), this routine isolates +//the minimum to a fractional precision of about tol using Brent’s method. The abscissa of +//the minimum is returned as xmin, and the minimum function value is returned as brent, the +//returned function value. +double brentmin(double ax, double bx, double cx, double (Sgp4::*f)(double), double tol, double *xmin, Sgp4* obj); + +//Using Brent’s method, find the root of a function func known to lie between x1 and x2. The +//root, returned as zbrent, will be refined until its accuracy is tol. +double zbrent(double (Sgp4::*func)(double), double x1, double x2, double tol, Sgp4* obj); + +#endif diff --git a/lib/Sgp4/library.json b/lib/Sgp4/library.json new file mode 100644 index 0000000..39ab2f0 --- /dev/null +++ b/lib/Sgp4/library.json @@ -0,0 +1,11 @@ +{ + "name": "Sgp4", + "version": "1.0.3", + "description": "SGP4 satellite propagation + pass prediction (Hopperpop/Sgp4-Library 1.0.3, MIT). Vendored for the native simulator. Changes: sgp4pred.cpp's #include is guarded by ARDUINO; the visibletype value `daylight` is renamed `sgp4_daylight` (it collides with POSIX time.h's global `daylight`); a parameter named `unix` is renamed (Linux GCC predefines `unix`).", + "license": "MIT", + "frameworks": "*", + "platforms": "*", + "build": { + "srcDir": "." + } +} \ No newline at end of file diff --git a/lib/Sgp4/sgp4coord.cpp b/lib/Sgp4/sgp4coord.cpp new file mode 100644 index 0000000..c47186f --- /dev/null +++ b/lib/Sgp4/sgp4coord.cpp @@ -0,0 +1,400 @@ +/* +sgp4coord.cpp + +This file contains miscellaneous functions required for coordinate transformation. +Functions were originally written for Matlab as companion code for "Fundamentals of Astrodynamics +and Applications" by David Vallado (2007). (w) 719-573-2600, email dvallado@agi.com + +Ported to C++ by Grady Hillhouse with some modifications, July 2015. +*/ +#include "sgp4coord.h" +#include "sgp4ext.h" + +/* +teme2ecef + +This function transforms a vector from a true equator mean equinox (TEME) +frame to an earth-centered, earth-fixed (ECEF) frame. + +Author: David Vallado, 2007 +Ported to C++ by Grady Hillhouse with some modifications, July 2015. + +INPUTS DESCRIPTION RANGE/UNITS +rteme Position vector (TEME) km +vteme Velocity vector (TEME) km/s +jdut1 Julian date days + +OUTPUTS DESCRIPTION RANGE/UNITS +recef Position vector (ECEF) km +vecef Velocity vector (ECEF) km/s +*/ + +//void teme2ecef(double rteme[3], double vteme[3], double jdut1, double recef[3], double vecef[3]) +void teme2ecef(double rteme[3], double jdut1, double recef[3]) +{ + double gmst; + double st[3][3]; + double rpef[3]; + //double vpef[3]; + double pm[3][3]; + //double omegaearth[3]; + + //Get Greenwich mean sidereal time + gmst = gstime(jdut1); + + //st is the pef - tod matrix + st[0][0] = cos(gmst); + st[0][1] = -sin(gmst); + st[0][2] = 0.0; + st[1][0] = sin(gmst); + st[1][1] = cos(gmst); + st[1][2] = 0.0; + st[2][0] = 0.0; + st[2][1] = 0.0; + st[2][2] = 1.0; + + //Get pseudo earth fixed position vector by multiplying the inverse pef-tod matrix by rteme + rpef[0] = st[0][0] * rteme[0] + st[1][0] * rteme[1] + st[2][0] * rteme[2]; + rpef[1] = st[0][1] * rteme[0] + st[1][1] * rteme[1] + st[2][1] * rteme[2]; + rpef[2] = st[0][2] * rteme[0] + st[1][2] * rteme[1] + st[2][2] * rteme[2]; + + //Get polar motion vector + polarm(jdut1, pm); + + //ECEF postion vector is the inverse of the polar motion vector multiplied by rpef + recef[0] = pm[0][0] * rpef[0] + pm[1][0] * rpef[1] + pm[2][0] * rpef[2]; + recef[1] = pm[0][1] * rpef[0] + pm[1][1] * rpef[1] + pm[2][1] * rpef[2]; + recef[2] = pm[0][2] * rpef[0] + pm[1][2] * rpef[1] + pm[2][2] * rpef[2]; + + //Earth's angular rotation vector (omega) + //Note: I don't have a good source for LOD. Historically it has been on the order of 2 ms so I'm just using that as a constant. The effect is very small. + //omegaearth[0] = 0.0; + //omegaearth[1] = 0.0; + //omegaearth[2] = 7.29211514670698e-05 * (1.0 - 0.0015563/86400.0); + + //Pseudo Earth Fixed velocity vector is st'*vteme - omegaearth X rpef + //vpef[0] = st[0][0] * vteme[0] + st[1][0] * vteme[1] + st[2][0] * vteme[2] - (omegaearth[1]*rpef[2] - omegaearth[2]*rpef[1]); + //vpef[1] = st[0][1] * vteme[0] + st[1][1] * vteme[1] + st[2][1] * vteme[2] - (omegaearth[2]*rpef[0] - omegaearth[0]*rpef[2]); + //vpef[2] = st[0][2] * vteme[0] + st[1][2] * vteme[1] + st[2][2] * vteme[2] - (omegaearth[0]*rpef[1] - omegaearth[1]*rpef[0]); + + //ECEF velocty vector is the inverse of the polar motion vector multiplied by vpef + //vecef[0] = pm[0][0] * vpef[0] + pm[1][0] * vpef[1] + pm[2][0] * vpef[2]; + //vecef[1] = pm[0][1] * vpef[0] + pm[1][1] * vpef[1] + pm[2][1] * vpef[2]; + //vecef[2] = pm[0][2] * vpef[0] + pm[1][2] * vpef[1] + pm[2][2] * vpef[2]; +} + +/* +polarm + +This function calulates the transformation matrix that accounts for polar +motion. Polar motion coordinates are estimated using IERS Bulletin +rather than directly input for simplicity. + +Author: David Vallado, 2007 +Ported to C++ by Grady Hillhouse with some modifications, July 2015. + +INPUTS DESCRIPTION RANGE/UNITS +jdut1 Julian date days + +OUTPUTS DESCRIPTION +pm Transformation matrix for ECEF - PEF +*/ + +void polarm(double jdut1, double pm[3][3]) +{ + double MJD; //Julian Date - 2,400,000.5 days + double A; + double C; + double xp; //Polar motion coefficient in radians + double yp; //Polar motion coefficient in radians + + //Predict polar motion coefficients using IERS Bulletin - A (Vol. XXVIII No. 030) + MJD = jdut1 - 2400000.5; + A = 2 * pi * (MJD - 57226) / 365.25; + C = 2 * pi * (MJD - 57226) / 435; + + xp = (0.1033 + 0.0494*cos(A) + 0.0482*sin(A) + 0.0297*cos(C) + 0.0307*sin(C)) * 4.84813681e-6; + yp = (0.3498 + 0.0441*cos(A) - 0.0393*sin(A) + 0.0307*cos(C) - 0.0297*sin(C)) * 4.84813681e-6; + + pm[0][0] = cos(xp); + pm[0][1] = 0.0; + pm[0][2] = -sin(xp); + pm[1][0] = sin(xp) * sin(yp); + pm[1][1] = cos(yp); + pm[1][2] = cos(xp) * sin(yp); + pm[2][0] = sin(xp) * cos(yp); + pm[2][1] = -sin(yp); + pm[2][2] = cos(xp) * cos(yp); +} + +/* +ijk2ll + +This function calulates the latitude, longitude and altitude +given the ECEF position matrix. + +Author: David Vallado, 2007 +Ported to C++ by Grady Hillhouse with some modifications, July 2015. + +INPUTS DESCRIPTION RANGE/UNITS +r Position matrix (ECEF) km + +OUTPUTS DESCRIPTION +latlongh Latitude, longitude, and altitude (rad, rad, and km) +*/ + +void ijk2ll(double r[3], double latlongh[3]) +{ + double twopi = 2.0*pi; + double small = 0.00000001; //small value for tolerances + double re = 6378.137; //radius of earth in km + double eesqrd = 0.006694385000; //eccentricity of earth sqrd + double magr, temp, rtasc; + + magr = mag(r); + temp = sqrt(r[0]*r[0] + r[1]*r[1]); + + if(fabs(temp) < small) + { + rtasc = sgn(r[2]) * pi * 0.5; + } + else + { + rtasc = atan2(r[1], r[0]); + } + + latlongh[1] = rtasc; + + if (fabs(latlongh[1]) >= pi) + { + if (latlongh[1] < 0.0) + { + latlongh[1] += twopi; + } + else + { + latlongh[1] -= twopi; + } + } + + latlongh[0] = asin(r[2] / magr); + + //Iterate to find geodetic latitude + int i = 1; + double olddelta = latlongh[0] + 10.0; + double sintemp, c = 0; + + while ( (fabs(olddelta - latlongh[0]) >= small) && (i < 10) ) + { + olddelta = latlongh[0]; + sintemp = sin(latlongh[0]); + c = re / sqrt(1.0 - eesqrd*sintemp*sintemp); + latlongh[0] = atan( (r[2] + c*eesqrd*sintemp) / temp ); + i++; + } + + if (0.5*pi - fabs(latlongh[0]) > pi/180.0) + { + latlongh[2] = (temp/cos(latlongh[0])) - c; + } + else + { + latlongh[2] = r[2]/sin(latlongh[0]) - c*(1.0 - eesqrd); + } +} + +/* +site + +This function finds the position and velocity vectors for a site. The +outputs are in the ECEF coordinate system. Note that the velocity vector +is zero because the coordinate system rotates with the earth. + +Author: David Vallado, 2007 +Ported to C++ by Grady Hillhouse with some modifications, July 2015. + +INPUTS DESCRIPTION RANGE/UNITS +latgd Site geodetic latitude -pi/2 to pi/2 in radians +lon Longitude -2pi to 2pi in radians +alt Site altitude km + +OUTPUTS DESCRIPTION +rs Site position vector km +vs Site velocity vector km/s +*/ + +//void site(double latgd, double lon, double alt, double rs[3], double vs[3]) +void site(double latgd, double lon, double alt, double rs[3]) +{ + double sinlat, re, eesqrd, cearth, rdel, rk; + re = 6378.137; //radius of earth in km + eesqrd = 0.006694385000; //eccentricity of earth sqrd + + //Find rdel and rk components of site vector + sinlat = sin(latgd); + cearth = re / sqrt( 1.0 - (eesqrd*sinlat*sinlat) ); + rdel = (cearth + alt) * cos(latgd); + rk = ((1.0 - eesqrd) * cearth + alt ) * sinlat; + + //Find site position vector (ECEF) + rs[0] = rdel * cos( lon ); + rs[1] = rdel * sin( lon ); + rs[2] = rk; + + //Velocity of site is zero because the coordinate system is rotating with the earth + //vs[0] = 0.0; + //vs[1] = 0.0; + //vs[2] = 0.0; +} + + +/* +rv2azel + +This function calculates the range, elevation, and azimuth (and their rates) +from the TEME vectors output by the SGP4 function. + +Author: David Vallado, 2007 +Ported to C++ by Grady Hillhouse with some modifications, July 2015. + +INPUTS DESCRIPTION RANGE/UNITS +ro Sat. position vector (TEME) km +vo Sat. velocity vector (TEME) km/s +latgd Site geodetic latitude -pi/2 to pi/2 in radians +lon Site longitude -2pi to 2pi in radians +alt Site altitude km +jdut1 Julian date days + +OUTPUTS DESCRIPTION +razel Range, azimuth, and elevation matrix +razelrates Range rate, azimuth rate, and elevation rate matrix +*/ + +//void rv2azel(double ro[3], double vo[3], double latgd, double lon, double alt, double jdut1, double razel[3], double razelrates[3]) +void rv2azel(double ro[3], double latgd, double lon, double alt, double jdut1, double razel[3]) +{ + //Locals + double halfpi = pi * 0.5; + double small = 0.00000001; + double temp; + double rs[3]; + //double vs[3]; + double recef[3]; + //double vecef[3]; + double rhoecef[3]; + //double drhoecef[3]; + double tempvec[3]; + double rhosez[3]; + //double drhosez[3]; + double magrhosez; + double rho, az, el; + //double drho, daz, del; + + //Get site vector in ECEF coordinate system + //site(latgd, lon, alt, rs, vs); + site(latgd, lon, alt, rs); + + //Convert TEME vectors to ECEF coordinate system + //teme2ecef(ro, vo, jdut1, recef, vecef); + teme2ecef(ro, jdut1, recef); + + //Find ECEF range vectors + for (int i = 0; i < 3; i++) + { + rhoecef[i] = recef[i] - rs[i]; + //drhoecef[i] = vecef[i]; + } + rho = mag(rhoecef); //Range in km + + //Convert to SEZ (topocentric horizon coordinate system) + rot3(rhoecef, lon, tempvec); + rot2(tempvec, (halfpi-latgd), rhosez); + + //rot3(drhoecef, lon, tempvec); + //rot2(tempvec, (halfpi-latgd), drhosez); + + //Calculate azimuth, and elevation + temp = sqrt(rhosez[0]*rhosez[0] + rhosez[1]*rhosez[1]); + if (temp < small) + { + el = sgn(rhosez[2]) * halfpi; + //az = atan2(drhosez[1], -drhosez[0]); + az = NAN; + } + else + { + magrhosez = mag(rhosez); + el = asin(rhosez[2]/magrhosez); + az = atan2(rhosez[1], -rhosez[0]); + } + + //Calculate rates for range, azimuth, and elevation + /** + drho = dot(rhosez,drhosez) / rho; + + if(fabs(temp*temp) > small) + { + daz = (drhosez[0]*rhosez[1] - drhosez[1]*rhosez[0]) / (temp * temp); + } + else + { + daz = 0.0; + } + + if(fabs(temp) > small) + { + del = (drhosez[2] - drho*sin(el)) / temp; + } + else + { + del = 0.0; + } + ***/ + //Move values to output vectors + razel[0] = rho; //Range (km) + razel[1] = az; //Azimuth (radians) + razel[2] = el; //Elevation (radians) + + //razelrates[0] = drho; //Range rate (km/s) + //razelrates[1] = daz; //Azimuth rate (rad/s) + //razelrates[2] = del; //Elevation rate (rad/s) +} + +void rot3(double invec[3], double xval, double outvec[3]) +{ + double temp = invec[1]; + double c = cos(xval); + double s = sin(xval); + + outvec[1] = c*invec[1] - s*invec[0]; + outvec[0] = c*invec[0] + s*temp; + outvec[2] = invec[2]; +} + +void rot2(double invec[3], double xval, double outvec[3]) +{ + double temp = invec[2]; + double c = cos(xval); + double s = sin(xval); + + outvec[2] = c*invec[2] + s*invec[0]; + outvec[0] = c*invec[0] - s*temp; + outvec[1] = invec[1]; +} + +/* +getJulianFromUnix + +returns the Julian Date from Unix Time +*/ + +double getJulianFromUnix(double unixSecs) +{ + return ( unixSecs / 86400.0 ) + 2440587.5; +} + + +unsigned long getUnixFromJulian(double julian) +{ + return (unsigned long)((julian - 2440587.5)*86400.0 + 0.5); +} diff --git a/lib/Sgp4/sgp4coord.h b/lib/Sgp4/sgp4coord.h new file mode 100644 index 0000000..6496d30 --- /dev/null +++ b/lib/Sgp4/sgp4coord.h @@ -0,0 +1,38 @@ +#ifndef _sgp4coord_ +#define _sgp4coord_ + +/* +sgp4coord.h + +This file contains miscellaneous functions required for coordinate transformation. +Functions were originally written for Matlab as companion code for "Fundamentals of Astrodynamics +and Applications" by David Vallado (2007). (w) 719-573-2600, email dvallado@agi.com + +Ported to C++ by Grady Hillhouse with some modifications, July 2015. +*/ + +#include +#include + +//void teme2ecef(double rteme[3], double vteme[3], double jdut1, double recef[3], double vecef[3]); +void teme2ecef(double rteme[3], double jdut1, double recef[3]); + +void polarm(double jdut1, double pm[3][3]); + +void ijk2ll(double r[3], double latlongh[3]); + +//void site(double latgd, double lon, double alt, double rs[3], double vs[3]); +void site(double latgd, double lon, double alt, double rs[3]); + +//void rv2azel(double ro[3], double vo[3], double latgd, double lon, double alt, double jdut1, double razel[3], double razelrates[3]); +void rv2azel(double ro[3], double latgd, double lon, double alt, double jdut1, double razel[3]); + +void rot3(double invec[3], double xval, double outvec[3]); + +void rot2(double invec[3], double xval, double outvec[3]); + +double getJulianFromUnix(double unixSecs); + +unsigned long getUnixFromJulian(double julian); + +#endif diff --git a/lib/Sgp4/sgp4ext.cpp b/lib/Sgp4/sgp4ext.cpp new file mode 100644 index 0000000..547a4b9 --- /dev/null +++ b/lib/Sgp4/sgp4ext.cpp @@ -0,0 +1,750 @@ +/* ---------------------------------------------------------------- +* +* sgp4ext.cpp +* +* this file contains extra routines needed for the main test program for sgp4. +* these routines are derived from the astro libraries. +* +* companion code for +* fundamentals of astrodynamics and applications +* 2007 +* by david vallado +* +* (w) 719-573-2600, email dvallado@agi.com +* +* current : +* 7 may 08 david vallado +* fix sgn +* changes : +* 2 apr 07 david vallado +* fix jday floor and str lengths +* updates for constants +* 14 aug 06 david vallado +* original baseline +* ---------------------------------------------------------------- */ + +#include "sgp4ext.h" + + +double sgn + ( + double x + ) + { + if (x < 0.0) + { + return -1.0; + } + else + { + return 1.0; + } + + } // end sgn + +/* ----------------------------------------------------------------------------- +* +* function mag +* +* this procedure finds the magnitude of a vector. the tolerance is set to +* 0.000001, thus the 1.0e-12 for the squared test of underflows. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* vec - vector +* +* outputs : +* vec - answer stored in fourth component +* +* locals : +* none. +* +* coupling : +* none. +* --------------------------------------------------------------------------- */ + +double mag + ( + double x[3] + ) + { + return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]); + } // end mag + +/* ----------------------------------------------------------------------------- +* +* procedure cross +* +* this procedure crosses two vectors. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* vec1 - vector number 1 +* vec2 - vector number 2 +* +* outputs : +* outvec - vector result of a x b +* +* locals : +* none. +* +* coupling : +* mag magnitude of a vector + ---------------------------------------------------------------------------- */ + +void cross + ( + double vec1[3], double vec2[3], double outvec[3] + ) + { + outvec[0]= vec1[1]*vec2[2] - vec1[2]*vec2[1]; + outvec[1]= vec1[2]*vec2[0] - vec1[0]*vec2[2]; + outvec[2]= vec1[0]*vec2[1] - vec1[1]*vec2[0]; + } // end cross + + +/* ----------------------------------------------------------------------------- +* +* function dot +* +* this function finds the dot product of two vectors. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* vec1 - vector number 1 +* vec2 - vector number 2 +* +* outputs : +* dot - result +* +* locals : +* none. +* +* coupling : +* none. +* +* --------------------------------------------------------------------------- */ + +double dot + ( + double x[3], double y[3] + ) + { + return (x[0]*y[0] + x[1]*y[1] + x[2]*y[2]); + } // end dot + +/* ----------------------------------------------------------------------------- +* +* procedure angle +* +* this procedure calculates the angle between two vectors. the output is +* set to 999999.1 to indicate an undefined value. be sure to check for +* this at the output phase. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* vec1 - vector number 1 +* vec2 - vector number 2 +* +* outputs : +* theta - angle between the two vectors -pi to pi +* +* locals : +* temp - temporary real variable +* +* coupling : +* dot dot product of two vectors +* --------------------------------------------------------------------------- */ + +double angle + ( + double vec1[3], + double vec2[3] + ) + { + double small, undefined, magv1, magv2, temp; + small = 0.00000001; + undefined = 999999.1; + + magv1 = mag(vec1); + magv2 = mag(vec2); + + if (magv1*magv2 > small*small) + { + temp= dot(vec1,vec2) / (magv1*magv2); + if (fabs( temp ) > 1.0) + temp= sgn(temp) * 1.0; + return acos( temp ); + } + else + return undefined; + } // end angle + + +/* ----------------------------------------------------------------------------- +* +* function asinh +* +* this function evaluates the inverse hyperbolic sine function. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* xval - angle value any real +* +* outputs : +* arcsinh - result any real +* +* locals : +* none. +* +* coupling : +* none. +* +* --------------------------------------------------------------------------- */ + +double asinh + ( + double xval + ) + { + return log( xval + sqrt( xval*xval + 1.0 ) ); + } // end asinh + + +/* ----------------------------------------------------------------------------- +* +* function newtonnu +* +* this function solves keplers equation when the true anomaly is known. +* the mean and eccentric, parabolic, or hyperbolic anomaly is also found. +* the parabolic limit at 168� is arbitrary. the hyperbolic anomaly is also +* limited. the hyperbolic sine is used because it's not double valued. +* +* author : david vallado 719-573-2600 27 may 2002 +* +* revisions +* vallado - fix small 24 sep 2002 +* +* inputs description range / units +* ecc - eccentricity 0.0 to +* nu - true anomaly -2pi to 2pi rad +* +* outputs : +* e0 - eccentric anomaly 0.0 to 2pi rad 153.02 � +* m - mean anomaly 0.0 to 2pi rad 151.7425 � +* +* locals : +* e1 - eccentric anomaly, next value rad +* sine - sine of e +* cose - cosine of e +* ktr - index +* +* coupling : +* asinh - arc hyperbolic sine +* +* references : +* vallado 2007, 85, alg 5 +* --------------------------------------------------------------------------- */ + +void newtonnu + ( + double ecc, double nu, + double& e0, double& m + ) + { + double small, sine, cose; + + // --------------------- implementation --------------------- + e0= 999999.9; + m = 999999.9; + small = 0.00000001; + + // --------------------------- circular ------------------------ + if ( fabs( ecc ) < small ) + { + m = nu; + e0= nu; + } + else + // ---------------------- elliptical ----------------------- + if ( ecc < 1.0-small ) + { + sine= ( sqrt( 1.0 -ecc*ecc ) * sin(nu) ) / ( 1.0 +ecc*cos(nu) ); + cose= ( ecc + cos(nu) ) / ( 1.0 + ecc*cos(nu) ); + e0 = atan2( sine,cose ); + m = e0 - ecc*sin(e0); + } + else + // -------------------- hyperbolic -------------------- + if ( ecc > 1.0 + small ) + { + if ((ecc > 1.0 ) && (fabs(nu)+0.00001 < pi-acos(1.0 /ecc))) + { + sine= ( sqrt( ecc*ecc-1.0 ) * sin(nu) ) / ( 1.0 + ecc*cos(nu) ); + e0 = asinh( sine ); + m = ecc*sinh(e0) - e0; + } + } + else + // ----------------- parabolic --------------------- + if ( fabs(nu) < 168.0*pi/180.0 ) + { + e0= tan( nu*0.5 ); + m = e0 + (e0*e0*e0)/3.0; + } + + if ( ecc < 1.0 ) + { + m = floatmod( m,2.0 *pi ); + if ( m < 0.0 ) + m = m + 2.0 *pi; + e0 = floatmod( e0,2.0 *pi ); + } + } // end newtonnu + + +/* ----------------------------------------------------------------------------- +* +* function rv2coe +* +* this function finds the classical orbital elements given the geocentric +* equatorial position and velocity vectors. +* +* author : david vallado 719-573-2600 21 jun 2002 +* +* revisions +* vallado - fix special cases 5 sep 2002 +* vallado - delete extra check in inclination code 16 oct 2002 +* vallado - add constant file use 29 jun 2003 +* vallado - add mu 2 apr 2007 +* +* inputs description range / units +* r - ijk position vector km +* v - ijk velocity vector km / s +* mu - gravitational parameter km3 / s2 +* +* outputs : +* p - semilatus rectum km +* a - semimajor axis km +* ecc - eccentricity +* incl - inclination 0.0 to pi rad +* omega - longitude of ascending node 0.0 to 2pi rad +* argp - argument of perigee 0.0 to 2pi rad +* nu - true anomaly 0.0 to 2pi rad +* m - mean anomaly 0.0 to 2pi rad +* arglat - argument of latitude (ci) 0.0 to 2pi rad +* truelon - true longitude (ce) 0.0 to 2pi rad +* lonper - longitude of periapsis (ee) 0.0 to 2pi rad +* +* locals : +* hbar - angular momentum h vector km2 / s +* ebar - eccentricity e vector +* nbar - line of nodes n vector +* c1 - v**2 - u/r +* rdotv - r dot v +* hk - hk unit vector +* sme - specfic mechanical energy km2 / s2 +* i - index +* e - eccentric, parabolic, +* hyperbolic anomaly rad +* temp - temporary variable +* typeorbit - type of orbit ee, ei, ce, ci +* +* coupling : +* mag - magnitude of a vector +* cross - cross product of two vectors +* angle - find the angle between two vectors +* newtonnu - find the mean anomaly +* +* references : +* vallado 2007, 126, alg 9, ex 2-5 +* --------------------------------------------------------------------------- */ + +void rv2coe + ( + double r[3], double v[3], double mu, + double& p, double& a, double& ecc, double& incl, double& omega, double& argp, + double& nu, double& m, double& arglat, double& truelon, double& lonper + ) + { + double undefined, small, hbar[3], nbar[3], magr, magv, magn, ebar[3], sme, + rdotv, infinite, temp, c1, hk, twopi, magh, halfpi, e; + + int i; + char typeorbit[3]; + + twopi = 2.0 * pi; + halfpi = 0.5 * pi; + small = 0.00000001; + undefined = 999999.1; + infinite = 999999.9; + + // ------------------------- implementation ----------------- + magr = mag( r ); + magv = mag( v ); + + // ------------------ find h n and e vectors ---------------- + cross( r,v, hbar ); + magh = mag( hbar ); + if ( magh > small ) + { + nbar[0]= -hbar[1]; + nbar[1]= hbar[0]; + nbar[2]= 0.0; + magn = mag( nbar ); + c1 = magv*magv - mu /magr; + rdotv = dot( r,v ); + for (i= 0; i <= 2; i++) + ebar[i]= (c1*r[i] - rdotv*v[i])/mu; + ecc = mag( ebar ); + + // ------------ find a e and semi-latus rectum ---------- + sme= ( magv*magv*0.5 ) - ( mu /magr ); + if ( fabs( sme ) > small ) + a= -mu / (2.0 *sme); + else + a= infinite; + p = magh*magh/mu; + + // ----------------- find inclination ------------------- + hk= hbar[2]/magh; + incl= acos( hk ); + + // -------- determine type of orbit for later use -------- + // ------ elliptical, parabolic, hyperbolic inclined ------- + strcpy(typeorbit,"ei"); + if ( ecc < small ) + { + // ---------------- circular equatorial --------------- + if ((incl small ) + { + temp= nbar[0] / magn; + if ( fabs(temp) > 1.0 ) + temp= sgn(temp); + omega= acos( temp ); + if ( nbar[1] < 0.0 ) + omega= twopi - omega; + } + else + omega= undefined; + + // ---------------- find argument of perigee --------------- + if ( strcmp(typeorbit,"ei") == 0 ) + { + argp = angle( nbar,ebar); + if ( ebar[2] < 0.0 ) + argp= twopi - argp; + } + else + argp= undefined; + + // ------------ find true anomaly at epoch ------------- + if ( typeorbit[0] == 'e' ) + { + nu = angle( ebar,r); + if ( rdotv < 0.0 ) + nu= twopi - nu; + } + else + nu= undefined; + + // ---- find argument of latitude - circular inclined ----- + if ( strcmp(typeorbit,"ci") == 0 ) + { + arglat = angle( nbar,r ); + if ( r[2] < 0.0 ) + arglat= twopi - arglat; + m = arglat; + } + else + arglat= undefined; + + // -- find longitude of perigee - elliptical equatorial ---- + if (( ecc>small ) && (strcmp(typeorbit,"ee") == 0)) + { + temp= ebar[0]/ecc; + if ( fabs(temp) > 1.0 ) + temp= sgn(temp); + lonper= acos( temp ); + if ( ebar[1] < 0.0 ) + lonper= twopi - lonper; + if ( incl > halfpi ) + lonper= twopi - lonper; + } + else + lonper= undefined; + + // -------- find true longitude - circular equatorial ------ + if (( magr>small ) && ( strcmp(typeorbit,"ce") == 0 )) + { + temp= r[0]/magr; + if ( fabs(temp) > 1.0 ) + temp= sgn(temp); + truelon= acos( temp ); + if ( r[1] < 0.0 ) + truelon= twopi - truelon; + if ( incl > halfpi ) + truelon= twopi - truelon; + m = truelon; + } + else + truelon= undefined; + + // ------------ find mean anomaly for all orbits ----------- + if ( typeorbit[0] == 'e' ) + newtonnu(ecc,nu, e, m); + } + else + { + p = undefined; + a = undefined; + ecc = undefined; + incl = undefined; + omega= undefined; + argp = undefined; + nu = undefined; + m = undefined; + arglat = undefined; + truelon= undefined; + lonper = undefined; + } + } // end rv2coe + +/* ----------------------------------------------------------------------------- +* +* procedure jday +* +* this procedure finds the julian date given the year, month, day, and time. +* the julian date is defined by each elapsed day since noon, jan 1, 4713 bc. +* +* algorithm : calculate the answer in one step for efficiency +* +* author : david vallado 719-573-2600 1 mar 2001 +* changed by : bram gurdebeke +* +* inputs description range / units +* year - year 1900 .. 2100 +* mon - month 1 .. 12 +* day - day 1 .. 28,29,30,31 +* hr - time hour 0 .. 23 +* min - time min 0 .. 59 +* sec - time sec 0.0 .. 59.999 +* timezone - hours from utc -11 .. 14 +* daylighsaving true/false +* +* outputs : +* jd - julian date days from 4713 bc +* +* locals : +* none. +* +* coupling : +* none. +* +* references : +* vallado 2007, 189, alg 14, ex 3-14 +* +* --------------------------------------------------------------------------- */ + +void jday + ( + int year, int mon, int day, int hr, int minute, double sec, + int timezone, bool daylightsaving, double& jd + ) + { + jd = 367.0 * year - + floor((7 * (year + floor((mon + 9) / 12.0))) * 0.25) + + floor( 275 * mon / 9.0 ) + + day + 1721013.5 + + ((sec / 60.0 + minute) / 60.0 + hr - timezone - (daylightsaving && summertime(year,mon,day,hr,timezone))) / 24.0; // ut in days + // - 0.5*sgn(100.0*year + mon - 190002.5) + 0.5; + } // end jday + + +/* ----------------------------------------------------------------------------- +* +* procedure days2mdhms +* +* this procedure converts the day of the year, days, to the equivalent month +* day, hour, minute and second. +* +* algorithm : set up array for the number of days per month +* find leap year - use 1900 because 2000 is a leap year +* loop through a temp value while the value is < the days +* perform int conversions to the correct day and month +* convert remainder into h m s using type conversions +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* year - year 1900 .. 2100 +* days - julian day of the year 0.0 .. 366.0 +* +* outputs : +* mon - month 1 .. 12 +* day - day 1 .. 28,29,30,31 +* hr - hour 0 .. 23 +* min - minute 0 .. 59 +* sec - second 0.0 .. 59.999 +* +* locals : +* dayofyr - day of year +* temp - temporary extended values +* inttemp - temporary int value +* i - index +* lmonth[12] - int array containing the number of days per month +* +* coupling : +* none. +* --------------------------------------------------------------------------- */ + +void days2mdhms + ( + int year, double days, + int& mon, int& day, int& hr, int& minute, double& sec + ) + { + int i, inttemp, dayofyr; + double temp; + int lmonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + dayofyr = (int)floor(days); + /* ----------------- find month and day of month ---------------- */ + if ( (year % 4) == 0 ) + lmonth[1] = 29; + + i = 1; + inttemp = 0; + while ((dayofyr > inttemp + lmonth[i-1]) && (i < 12)) + { + inttemp = inttemp + lmonth[i-1]; + i++; + } + mon = i; + day = dayofyr - inttemp; + + /* ----------------- find hours minutes and seconds ------------- */ + temp = (days - dayofyr) * 24.0; + hr = (int)floor(temp); + temp = (temp - hr) * 60.0; + minute = (int)floor(temp); + sec = (temp - minute) * 60.0; + } // end days2mdhms + +/* ----------------------------------------------------------------------------- +* +* procedure invjday +* +* this procedure finds the year, month, day, hour, minute and second +* given the julian date. tu can be ut1, tdt, tdb, etc. +* +* algorithm : set up starting values +* find leap year - use 1900 because 2000 is a leap year +* find the elapsed days through the year in a loop +* call routine to find each individual value +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* jd - julian date days from 4713 bc +* +* outputs : +* year - year 1900 .. 2100 +* mon - month 1 .. 12 +* day - day 1 .. 28,29,30,31 +* hr - hour 0 .. 23 +* min - minute 0 .. 59 +* sec - second 0.0 .. 59.999 +* +* locals : +* days - day of year plus fractional +* portion of a day days +* tu - julian centuries from 0 h +* jan 0, 1900 +* temp - temporary double values +* leapyrs - number of leap years from 1900 +* +* coupling : +* days2mdhms - finds month, day, hour, minute and second given days and year +* +* references : +* vallado 2007, 208, alg 22, ex 3-13 +* --------------------------------------------------------------------------- */ + +void invjday + ( + double jd, int timezone, bool daylightsaving, + int& year, int& mon, int& day, + int& hr, int& minute, double& sec + ) + { + int leapyrs; + double days, tu, temp; + + jd += (double)timezone / 24.0; + + /* --------------- find year and days of the year --------------- */ + temp = jd - 2415019.5; + tu = temp / 365.25; + year = 1900 + (int)floor(tu); + leapyrs = (int)floor((year - 1901) * 0.25); + + // optional nudge by 8.64x10-7 sec to get even outputs + days = temp - ((year - 1900) * 365.0 + leapyrs) + 0.00000000001; + + /* ------------ check for case of beginning of a year ----------- */ + if (days < 1.0) + { + year = year - 1; + leapyrs = (int)floor((year - 1901) * 0.25); + days = temp - ((year - 1900) * 365.0 + leapyrs); + } + + /* ----------------- find remaing data ------------------------- */ + days2mdhms(year, days, mon, day, hr, minute, sec); + if (daylightsaving && summertime(year, mon, day, hr, timezone)) { + days2mdhms(year, days + 1.0/24.0, mon, day, hr, minute, sec); + } + sec = sec - 0.00000086400; + } // end invjday + +float floatmod(float a, float b) +{ + return (a - b * floor(a / b)); +} + +double floatmod(double a, double b) +{ + return (a - b * floor(a / b)); +} + +bool summertime(int year, int month, int day, int hour, int tzHours) +// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) +{ + if (month<3 || month>10) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez + if (month>3 && month<10) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep + if (((month == 3) && ((hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)))) + || ((month == 10) && ((hour + 24 * day) < (1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))))) + return true; + else + return false; +} diff --git a/lib/Sgp4/sgp4ext.h b/lib/Sgp4/sgp4ext.h new file mode 100644 index 0000000..dd45c2a --- /dev/null +++ b/lib/Sgp4/sgp4ext.h @@ -0,0 +1,103 @@ +#ifndef _sgp4ext_ +#define _sgp4ext_ +/* ---------------------------------------------------------------- +* +* sgp4ext.h +* +* this file contains extra routines needed for the main test program for sgp4. +* these routines are derived from the astro libraries. +* +* companion code for +* fundamentals of astrodynamics and applications +* 2007 +* by david vallado +* +* (w) 719-573-2600, email dvallado@agi.com +* +* current : +* 20 apr 07 david vallado +* misc documentation updates +* changes : +* 14 aug 06 david vallado +* original baseline +* ---------------------------------------------------------------- */ + +#include +#include + +#include "sgp4unit.h" + + +// ------------------------- function declarations ------------------------- + +double sgn + ( + double x + ); + +double mag + ( + double x[3] + ); + +void cross + ( + double vec1[3], double vec2[3], double outvec[3] + ); + +double dot + ( + double x[3], double y[3] + ); + +double angle + ( + double vec1[3], + double vec2[3] + ); + +void newtonnu + ( + double ecc, double nu, + double& e0, double& m + ); + +double asinh + ( + double xval + ); + +void rv2coe + ( + double r[3], double v[3], double mu, + double& p, double& a, double& ecc, double& incl, double& omega, double& argp, + double& nu, double& m, double& arglat, double& truelon, double& lonper + ); + +void jday + ( + int year, int mon, int day, int hr, int minute, double sec, + int timezone, bool daylightsaving, double& jd + ); + +void days2mdhms + ( + int year, double days, + int& mon, int& day, int& hr, int& minute, double& sec + ); + +void invjday + ( + double jd, int timezone, bool daylightsaving, + int& year, int& mon, int& day, + int& hr, int& minute, double& sec + ); + +float floatmod(float a, float b); + +double floatmod(double a, double b); + +bool summertime(int year, int month, int day, int hour, int tzHours); + +#endif + diff --git a/lib/Sgp4/sgp4io.cpp b/lib/Sgp4/sgp4io.cpp new file mode 100644 index 0000000..b1f66da --- /dev/null +++ b/lib/Sgp4/sgp4io.cpp @@ -0,0 +1,310 @@ +/* ---------------------------------------------------------------- +* +* sgp4io.cpp +* +* this file contains a function to read two line element sets. while +* not formerly part of the sgp4 mathematical theory, it is +* required for practical implemenation. +* +* companion code for +* fundamentals of astrodynamics and applications +* 2007 +* by david vallado +* +* (w) 719-573-2600, email dvallado@agi.com +* +* current : +* 27 Aug 10 david vallado +* fix input format and delete unused variables in twoline2rv +* changes : +* 3 sep 08 david vallado +* add operationmode for afspc (a) or improved (i) +* 9 may 07 david vallado +* fix year correction to 57 +* 27 mar 07 david vallado +* misc fixes to manual inputs +* 14 aug 06 david vallado +* original baseline +* ---------------------------------------------------------------- */ + +#include "sgp4io.h" +#include "stdlib.h" + +/* ----------------------------------------------------------------------------- +* +* function twoline2rv +* +* this function converts the two line element set character string data to +* variables and initializes the sgp4 variables. several intermediate varaibles +* and quantities are determined. note that the result is a structure so multiple +* satellites can be processed simultaneously without having to reinitialize. the +* verification mode is an important option that permits quick checks of any +* changes to the underlying technical theory. this option works using a +* modified tle file in which the start, stop, and delta time values are +* included at the end of the second line of data. this only works with the +* verification mode. the catalog mode simply propagates from -1440 to 1440 min +* from epoch and is useful when performing entire catalog runs. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs : +* longstr1 - first line of the tle +* longstr2 - second line of the tle +* typerun - type of run verification 'v', catalog 'c', +* manual 'm' +* typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd' +* opsmode - mode of operation afspc or improved 'a', 'i' +* whichconst - which set of constants to use 72, 84 +* +* outputs : +* satrec - structure containing all the sgp4 satellite information +* +* coupling : +* getgravconst- +* days2mdhms - conversion of days to month, day, hour, minute, second +* jday - convert day month year hour minute second into julian date +* sgp4init - initialize the sgp4 variables +* +* references : +* norad spacetrack report #3 +* vallado, crawford, hujsak, kelso 2006 + --------------------------------------------------------------------------- */ + +void twoline2rv + ( + char longstr1[130], char longstr2[130], + char opsmode, gravconsttype whichconst, + elsetrec& satrec + ) + { + char tempstr[13]; + const double deg2rad = pi / 180.0; // 0.0174532925199433 + const double xpdotp = 1440.0 / (2.0 *pi); // 229.1831180523293 + + double sec, mu, radiusearthkm, tumin, xke, j2, j3, j4, j3oj2; + double startsec, stopsec, startdayofyr, stopdayofyr, jdstart, jdstop; + int startyear, stopyear, startmon, stopmon, startday, stopday, + starthr, stophr, startmin, stopmin; + int cardnumb, numb, j; + long revnum = 0, elnum = 0; + char classification, intldesg[11]; + int year = 0; + int mon, day, hr, minute, nexp, ibexp; + + getgravconst( whichconst, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 ); + + satrec.error = 0; + + // set the implied decimal points since doing a formated read + // fixes for bad input data values (missing, ...) + for (j = 10; j <= 15; j++) + if (longstr1[j] == ' ') + longstr1[j] = '_'; + + if (longstr1[44] != ' ') + longstr1[43] = longstr1[44]; + longstr1[44] = '.'; + if (longstr1[7] == ' ') + longstr1[7] = 'U'; + if (longstr1[9] == ' ') + longstr1[9] = '.'; + for (j = 45; j <= 49; j++) + if (longstr1[j] == ' ') + longstr1[j] = '0'; + if (longstr1[51] == ' ') + longstr1[51] = '0'; + if (longstr1[53] != ' ') + longstr1[52] = longstr1[53]; + longstr1[53] = '.'; + longstr2[25] = '.'; + for (j = 26; j <= 32; j++) + if (longstr2[j] == ' ') + longstr2[j] = '0'; + if (longstr1[62] == ' ') + longstr1[62] = '0'; + if (longstr1[68] == ' ') + longstr1[68] = '0'; + + /** + sscanf(longstr1,"%2d %5ld %1c %10s %2d %12lf %11lf %7lf %2d %7lf %2d %2d %6ld ", + &cardnumb,&satrec.satnum,&classification, intldesg, &satrec.epochyr, + &satrec.epochdays,&satrec.ndot, &satrec.nddot, &nexp, &satrec.bstar, + &ibexp, &numb, &elnum ); + **/ + + //memcpy( tempstr, &longstr1[0] , 2); tempstr[1] = '\0'; satrec.cardnumb = atoi(tempstr); + memcpy( tempstr, &longstr1[2] , 5); tempstr[5] = '\0'; satrec.satnum = atol(tempstr); + //classification = longstr1[7]; + //memcpy( intldesg, &longstr1[8] , 10); intldesg[10] = '\0'; + memcpy( tempstr, &longstr1[18] , 2); tempstr[2] = '\0'; satrec.epochyr = atoi(tempstr); + memcpy( tempstr, &longstr1[20] , 12); tempstr[12] = '\0'; satrec.epochdays = atof(tempstr); + memcpy( tempstr, &longstr1[32] , 11); tempstr[11] = '\0'; satrec.ndot = atof(tempstr); + memcpy( tempstr, &longstr1[43] , 7); tempstr[7] = '\0'; satrec.nddot = atof(tempstr); + memcpy( tempstr, &longstr1[50] , 2); tempstr[2] = '\0'; nexp = atoi(tempstr); + memcpy( tempstr, &longstr1[52] , 7); tempstr[7] = '\0'; satrec.bstar = atof(tempstr); + memcpy( tempstr, &longstr1[59] , 2); tempstr[2] = '\0'; ibexp = atoi(tempstr); + //memcpy( tempstr, &longstr1[61] , 2); tempstr[2] = '\0'; numb = atoi(tempstr); + //memcpy( tempstr, &longstr1[63] , 6); tempstr[6] = '\0'; elnum = atol(tempstr); + + memcpy( tempstr, &longstr2[2] , 5); tempstr[5] = '\0'; satrec.satnum = atol(tempstr); + memcpy( tempstr, &longstr2[7] , 9); tempstr[9] = '\0'; satrec.inclo = atof(tempstr); + memcpy( tempstr, &longstr2[16] , 9); tempstr[9] = '\0'; satrec.nodeo = atof(tempstr); + memcpy( tempstr, &longstr2[25] , 8); tempstr[8] = '\0'; satrec.ecco = atof(tempstr); + memcpy( tempstr, &longstr2[33] , 9); tempstr[9] = '\0'; satrec.argpo = atof(tempstr); + memcpy( tempstr, &longstr2[42] , 9); tempstr[9] = '\0'; satrec.mo = atof(tempstr); + memcpy( tempstr, &longstr2[51] , 11); tempstr[10] = '\0'; satrec.no = atof(tempstr); + //memcpy( tempstr, &longstr2[63] , 6); tempstr[6] = '\0'; revnum = atol(tempstr); + + + + // ---- find no, ndot, nddot ---- + satrec.no = satrec.no / xpdotp; //* rad/min + satrec.nddot= satrec.nddot * pow(10.0, nexp); + satrec.bstar= satrec.bstar * pow(10.0, ibexp); + + // ---- convert to sgp4 units ---- + satrec.a = pow( satrec.no*tumin , (-2.0/3.0) ); + satrec.ndot = satrec.ndot / (xpdotp*1440.0); //* ? * minperday + satrec.nddot= satrec.nddot / (xpdotp*1440.0*1440); + + // ---- find standard orbital elements ---- + satrec.inclo = satrec.inclo * deg2rad; + satrec.nodeo = satrec.nodeo * deg2rad; + satrec.argpo = satrec.argpo * deg2rad; + satrec.mo = satrec.mo * deg2rad; + + satrec.alta = satrec.a*(1.0 + satrec.ecco) - 1.0; + satrec.altp = satrec.a*(1.0 - satrec.ecco) - 1.0; + + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + + // ---------------- temp fix for years from 1957-2056 ------------------- + // --------- correct fix will occur when year is 4-digit in tle --------- + if (satrec.epochyr < 57) + year= satrec.epochyr + 2000; + else + year= satrec.epochyr + 1900; + + days2mdhms ( year,satrec.epochdays, mon,day,hr,minute,sec ); + jday( year,mon,day,hr,minute,sec, 0,false,satrec.jdsatepoch ); + + /*** + // ---- input start stop times manually + if ((typerun != 'v') && (typerun != 'c')) + { + // ------------- enter start/stop ymd hms values -------------------- + if (typeinput == 'e') + { + printf("input start prop year mon day hr min sec \n"); + // make sure there is no space at the end of the format specifiers in scanf! + scanf( "%i %i %i %i %i %lf",&startyear, &startmon, &startday, &starthr, &startmin, &startsec); + fflush(stdin); + jday( startyear,startmon,startday,starthr,startmin,startsec, jdstart ); + + printf("input stop prop year mon day hr min sec \n"); + scanf( "%i %i %i %i %i %lf",&stopyear, &stopmon, &stopday, &stophr, &stopmin, &stopsec); + fflush(stdin); + jday( stopyear,stopmon,stopday,stophr,stopmin,stopsec, jdstop ); + + startmfe = (jdstart - satrec.jdsatepoch) * 1440.0; + stopmfe = (jdstop - satrec.jdsatepoch) * 1440.0; + + printf("input time step in minutes \n"); + scanf( "%lf",&deltamin ); + } + // -------- enter start/stop year and days of year values ----------- + if (typeinput == 'd') + { + printf("input start year dayofyr \n"); + scanf( "%i %lf",&startyear, &startdayofyr ); + printf("input stop year dayofyr \n"); + scanf( "%i %lf",&stopyear, &stopdayofyr ); + + days2mdhms ( startyear,startdayofyr, mon,day,hr,minute,sec ); + jday( startyear,mon,day,hr,minute,sec, jdstart ); + days2mdhms ( stopyear,stopdayofyr, mon,day,hr,minute,sec ); + jday( stopyear,mon,day,hr,minute,sec, jdstop ); + + startmfe = (jdstart - satrec.jdsatepoch) * 1440.0; + stopmfe = (jdstop - satrec.jdsatepoch) * 1440.0; + + printf("input time step in minutes \n"); + scanf( "%lf",&deltamin ); + } + // ------------------ enter start/stop mfe values ------------------- + if (typeinput == 'm') + { + printf("input start min from epoch \n"); + scanf( "%lf",&startmfe ); + printf("input stop min from epoch \n"); + scanf( "%lf",&stopmfe ); + printf("input time step in minutes \n"); + scanf( "%lf",&deltamin ); + } + } + ***/ + // ---------------- initialize the orbit at sgp4epoch ------------------- + sgp4init( whichconst, opsmode, satrec.satnum, satrec.jdsatepoch-2433281.5, satrec.bstar, + satrec.ecco, satrec.argpo, satrec.inclo, satrec.mo, satrec.no, + satrec.nodeo, satrec); + } // end twoline2rv + +/* ----------------------------------------------------------------------------- +* +* function twolineChecksum +* +* this function checks if the checksum on the end of the line is correct. +* +* author : Hopperpop 6 mar 2016 +* +* inputs : +* longstr - line of the tle +* +* outputs : +* bool - true if test was succesfull +* +* references : +* https://en.wikipedia.org/wiki/Two-line_element_set + --------------------------------------------------------------------------- */ +bool twolineChecksum + ( + const char longstr[80] + ) +{ + + unsigned int cks = 0; + const char* checksumpointer = longstr + 68; + + for (const char* p = longstr; p < checksumpointer; p++){ + + switch(*p){ + case 0: + return false; + break; + case '-': + cks++; + break; + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + cks += *p - '0'; + break; + } + + } + cks %= 10; //modulo 10 + if (cks + '0' == *checksumpointer) + return true; + + return false; +} diff --git a/lib/Sgp4/sgp4io.h b/lib/Sgp4/sgp4io.h new file mode 100644 index 0000000..3099303 --- /dev/null +++ b/lib/Sgp4/sgp4io.h @@ -0,0 +1,47 @@ +#ifndef _sgp4io_ +#define _sgp4io_ +/* ---------------------------------------------------------------- +* +* sgp4io.h; +* +* this file contains a function to read two line element sets. while +* not formerly part of the sgp4 mathematical theory, it is +* required for practical implemenation. +* +* companion code for +* fundamentals of astrodynamics and applications +* 2007 +* by david vallado +* +* (w) 719-573-2600, email dvallado@agi.com +* +* current : +* 3 sep 07 david vallado +* add operationmode for afspc (a) or improved (i) +* changes : +* 20 apr 07 david vallado +* misc updates for manual operation +* 14 aug 06 david vallado +* original baseline +* ---------------------------------------------------------------- */ + +#include +#include + +#include "sgp4ext.h" // for several misc routines +#include "sgp4unit.h" // for sgp4init and getgravconst + +// ------------------------- function declarations ------------------------- + +void twoline2rv + ( + char longstr1[130], char longstr2[130], + char opsmode, gravconsttype whichconst, + elsetrec& satrec + ); + + bool twolineChecksum + ( + const char longstr[] + ); +#endif diff --git a/lib/Sgp4/sgp4pred.cpp b/lib/Sgp4/sgp4pred.cpp new file mode 100644 index 0000000..53a0c73 --- /dev/null +++ b/lib/Sgp4/sgp4pred.cpp @@ -0,0 +1,282 @@ +/* +This file contains miscellaneous functions required for predicting satellite overpasses and the main class for easy acces to all the functions. +Most functions are based on the columns written by Dr. T.S. Kelso on the celestrak website (https://celestrak.com/columns/) + +Written by Hopperpop +*/ + +#ifdef ARDUINO +#include +#endif +#include "sgp4ext.h" +#include "sgp4unit.h" +#include "sgp4io.h" +#include "sgp4coord.h" +#include "brent.h" +#include "sgp4pred.h" +#include "visible.h" +#include + +#define MAX_itter 30 +#define tol 0.000005 //tol = +-0,432 sec + + +///////////Classs/////////// + +Sgp4::Sgp4(){ + opsmode = 'i'; //improved mode + whichconst = wgs84; //newest constants + sunoffset = -0.10471975511966; //sun aboven -6° => not dark enough + offset = 0.0; +} + +///Init functions///// +bool Sgp4::init(const char naam[24], char longstr1[130], char longstr2[130]){ + + if (strcmp(longstr1, line1) == 0) { + return false; + } + + strlcpy(satName, naam, sizeof(satName)); + strlcpy(line1, longstr1, sizeof(line1)); + strlcpy(line2, longstr2, sizeof(line2)); + + twoline2rv(longstr1, longstr2, opsmode, whichconst, satrec ); + + revpday = 1440.0 / (2.0 * pi) * satrec.no; + return true; +} + + +//set site coordinates +void Sgp4::site(double lat, double lon, double alt){ + siteLat = lat; + siteLon = lon; + siteAlt = alt / 1000; //meters to kilometers + siteLatRad = siteLat * pi / 180.0; + siteLonRad = siteLon * pi / 180.0; +} + +///set sunoffset +void Sgp4::setsunrise(double degrees){ + sunoffset = degrees * pi / 180.0; +} + +////Location functions///// +void Sgp4::findsat(double jdI){ + + double latlongh[3]; + double recef[3]; + double vecef[3]; + double razelrates[3]; + + jdC = jdI; + + double tsince = (jdC - satrec.jdsatepoch) * 24.0 * 60.0; + sgp4(whichconst, satrec, tsince, ro, vo); + rv2azel(ro, siteLatRad, siteLonRad, siteAlt, jdC, razel); + teme2ecef(ro, jdC, recef); + ijk2ll(recef, latlongh); + + satLat = latlongh[0]*180/pi; //Latidude sattelite (degrees) + satLon = latlongh[1]*180/pi; //longitude sattelite (degrees) + satAlt = latlongh[2]; //Altitude sattelite (degrees) + satAz = floatmod( razel[1]*180/pi+360.0, 360.0); //Azemith sattelite (degrees) + satEl = razel[2]*180/pi; //elevation sattelite (degrees) + satDist = razel[0]; //Distance to sattelite (km) + satJd = jdI; //time (julian day) + + satVis = visible(); + if (satEl < 0.0) { + satVis = -2; //under horizon + } + +} + +void Sgp4::findsat(unsigned long unixtime){ + findsat(getJulianFromUnix(unixtime)); +} + + +//////Predict functions///////// + +//returns the elevation for a given julian date +double Sgp4::sgp4wrap( double jdCe){ + + double tsince = (jdCe - satrec.jdsatepoch) * 24.0 * 60.0; + + sgp4(whichconst, satrec, tsince, ro, vo); + rv2azel(ro, siteLatRad, siteLonRad, siteAlt, jdCe, razel); + return -razel[2]+offset; + +} + + +// returns next overpass maximum, starting from a maximum called startpoint +bool Sgp4::nextpass(passinfo* passdata, int itterations) { + return (Sgp4::nextpass( passdata, itterations, false, 0.0)); +} + +// returns next overpass. Set direc to false for forward search, true for backwards search +bool Sgp4::nextpass(passinfo* passdata, int itterations, bool direc) { + return (Sgp4::nextpass( passdata, itterations, direc, 0.0)); +} + +// returns next overpass maximum, starting from a maximum called startpoint +// direc = false for forward search, true for backwards search +// minimumElevation is the minimum elevation above the horizon in degrees. Passes which are lower than this are rejected +// returns false if all itterations are below the minimumElevation +bool Sgp4::nextpass( passinfo* passdata, int itterations, bool direc, double minimumElevation){ + + double range,jump; + int i; + double max_elevation = -1.0; + int16_t vissum,vis; + bool isdaylight; + double startphi, stopphi,phi; + + range = 0.25/revpday; + + if (direc) { ///set search direction + jump = -1.0 / revpday; + } + else { + jump = 1.0 / revpday; + } + + for (i = 0; i < itterations && max_elevation <= (minimumElevation * pi / 180); i++){ //search for elevation above minimumElevation + jdCp+= jump; + max_elevation = - brentmin(jdCp - range , jdCp, jdCp + range, &Sgp4::sgp4wrap , tol, &jdCp, this); + #ifdef ESP8266 + yield(); + #endif + } + jdC = jdCp; + if (i>=itterations) return 0; + + ///max elevation + + (*passdata).maxelevation = (max_elevation+offset)*180/pi; + (*passdata).jdmax = jdC; + (*passdata).azmax = floatmod(razel[1] * 180 / pi + 360.0, 360.0); + vis = visible(isdaylight,phi); + + if (isdaylight) {(*passdata).vismax = sgp4_daylight;} + else if (vis < 1000){(*passdata).vismax = eclipsed;} + else {(*passdata).vismax = lighted;} + + //start point + + range = 0.5/revpday; + jdC = zbrent(&Sgp4::sgp4wrap, jdCp, jdCp - range, tol, this); + if (jdC < 0.0) return 0; + (*passdata).jdstart = jdC; + (*passdata).azstart = floatmod(razel[1] * 180 / pi + 360.0, 360.0); + vis = visible(isdaylight,startphi); + + if (isdaylight) {(*passdata).visstart = sgp4_daylight;} + else if (vis < 1000){(*passdata).visstart = eclipsed;} + else {(*passdata).visstart = lighted;} + vissum = vis; + + //stop point + + jdC = zbrent(&Sgp4::sgp4wrap, jdCp, jdCp + range, tol, this); + if (jdC < 0.0) return 0; + (*passdata).jdstop = jdC; + (*passdata).azstop = floatmod(razel[1] * 180 / pi + 360.0, 360.0); + vis = visible(isdaylight,stopphi); + + if (isdaylight) {(*passdata).visstop = sgp4_daylight;} + else if (vis < 1000){(*passdata).visstop = eclipsed;} + else {(*passdata).visstop = lighted;} + vissum += vis; + + //global visibility + + if ((*passdata).visstop == sgp4_daylight && (*passdata).visstart == sgp4_daylight) {(*passdata).sight = sgp4_daylight;} + else if (vissum < 1000){(*passdata).sight = eclipsed;} + else {(*passdata).sight = lighted;} + + //transit + + if (sgn(startphi) == sgn(stopphi)) { + (*passdata).transit = none; + (*passdata).jdtransit = NAN; + (*passdata).aztransit = NAN; + (*passdata).transitelevation = NAN; + (*passdata).vistransit = sgp4_daylight; + } + else { + if (sgn(startphi)>sgn(stopphi)) { + (*passdata).transit = enter; + } + else { + (*passdata).transit = leave; + } + + jdC = zbrent(&Sgp4::visiblewrap, (*passdata).jdstart, (*passdata).jdstop, tol, this); + if (jdC < 0.0) return 0; + (*passdata).jdtransit = jdC; + (*passdata).aztransit = floatmod(razel[1] * 180 / pi + 360.0, 360.0); + (*passdata).transitelevation = razel[2] * 180 / pi; + vis = visible(isdaylight,phi); + + if (isdaylight) {(*passdata).vistransit = sgp4_daylight;} + else {(*passdata).vistransit = eclipsed;} + //else {(*passdata).visstop = lighted;} + } + + + (*passdata).minelevation = offset*180/pi; + + return 1; +} + + +// finds a startpoint for the prediction algorithm +bool Sgp4::initpredpoint( double startpoint, double startelevation){ + + + double a,b,c; + double fa,fb,fc; + double jdI; + int i; + + offset = startelevation *pi/180.0; + + c = startpoint; + fc = sgp4wrap( c ); + b = startpoint - 0.166/revpday; + fb = sgp4wrap( b ); + a = startpoint - 0.322/revpday; + fa = sgp4wrap( a ); + + for(i = 0; i < MAX_itter && ( fb > fa || fb > fc ); i++){ + fc=fb; + fb=fa; + c=b; + b=a; + a = startpoint - 0.166*(i+3)/revpday; + fa = sgp4wrap( a ); + } + if ( i >= MAX_itter-1){ + return 0; + } + + brentmin(a , b, c, &Sgp4::sgp4wrap , tol, &jdI, this); + jdCp = jdI; + return 1; +} + +bool Sgp4::initpredpoint( unsigned long unixtime, double startelevation){ + return initpredpoint( getJulianFromUnix(unixtime), startelevation); +} + +double Sgp4::getpredpoint() { + return jdCp; +} + +void Sgp4::setpredpoint(double bob) { + jdCp = bob; +} diff --git a/lib/Sgp4/sgp4pred.h b/lib/Sgp4/sgp4pred.h new file mode 100644 index 0000000..07ce969 --- /dev/null +++ b/lib/Sgp4/sgp4pred.h @@ -0,0 +1,108 @@ +/* +This file contains miscellaneous functions required for predicting satellite overpasses and the main class for easy acces to all the functions. +Most functions are based on the columns written by Dr. T.S. Kelso on the celestrak website (https://celestrak.com/columns/) + +Written by Hopperpop +*/ + +#ifndef _sgp4pred_ +#define _sgp4pred_ + +#include "sgp4ext.h" +#include "sgp4unit.h" +#include "sgp4io.h" +#include "sgp4coord.h" +#include + +enum visibletype +{ + sgp4_daylight, + eclipsed, + lighted +}; + +enum shadowtransit +{ + none, + enter, + leave +}; + +struct passinfo +{ + double jdstart; + double jdstop; + double jdmax; + double jdtransit; + + double maxelevation; + double minelevation; //elevation at start and end + double transitelevation; + + double azstart; + double azmax; + double azstop; + double aztransit; + + visibletype visstart; + visibletype visstop; + visibletype vismax; + visibletype vistransit; + + visibletype sight; + shadowtransit transit; + +}; + + + +class Sgp4 { + char opsmode; + gravconsttype whichconst; + double ro[3]; + double vo[3]; + double razel[3]; + double offset; //Min elevation for overpass prediction in radials + double sunoffset; //Min elevation sun for sgp4_daylight in radials + double jdC; //Current used julian date + double jdCp; //Current used julian date for prediction + + double sgp4wrap( double jdCe); //returns the elevation for a given julian date + double visiblewrap(double jdCe); //returns angle between sun surface and earth surface + + public: + char satName[25]; ///satellite name + char line1[80]; //tle line 1 + char line2[80]; //tle line 2 + + double revpday; ///revolutions per day + elsetrec satrec; + double siteLat, siteLon, siteAlt, siteLatRad, siteLonRad; + double satLat, satLon, satAlt, satAz, satEl, satDist,satJd; + double sunAz, sunEl; + int16_t satVis; + + Sgp4(); + bool init(const char naam[], char longstr1[130], char longstr2[130]); //initialize parameters from 2 line elements + void site(double lat, double lon, double alt); //initialize site latitude[degrees],longitude[degrees],altitude[meters] + void setsunrise(double degrees); //change the elevation that the sun needs to make it sgp4_daylight + + void findsat(double jdI); //find satellite position from julian date + void findsat(unsigned long unixtime); //find satellite position from unix time + + bool nextpass( passinfo* passdata, int itterations); // calculate next overpass data, returns true if succesfull + bool nextpass(passinfo* passdata, int itterations, bool direc); //direc = false for forward search, true for backwards search + bool nextpass(passinfo* passdata, int itterations, bool direc, double minimumElevation); //minimumElevation = minimum elevation above the horizon (in degrees) + bool initpredpoint( double juliandate , double startelevation); //initialize prediction algorithm, starting from a juliandate and predict passes aboven startelevation + bool initpredpoint( unsigned long unixtime, double startelevation); // from unix time + + int16_t visible(); //check if satellite is visible + int16_t visible(bool& notdark, double& deltaphi); + + double getpredpoint(); + void setpredpoint(double jdCe); +} ; + + + +#endif diff --git a/lib/Sgp4/sgp4unit.cpp b/lib/Sgp4/sgp4unit.cpp new file mode 100644 index 0000000..4e7f632 --- /dev/null +++ b/lib/Sgp4/sgp4unit.cpp @@ -0,0 +1,2127 @@ +/* ---------------------------------------------------------------- +* +* sgp4unit.cpp +* +* this file contains the sgp4 procedures for analytical propagation +* of a satellite. the code was originally released in the 1980 and 1986 +* spacetrack papers. a detailed discussion of the theory and history +* may be found in the 2006 aiaa paper by vallado, crawford, hujsak, +* and kelso. +* +* companion code for +* fundamentals of astrodynamics and applications +* 2007 +* by david vallado +* +* (w) 719-573-2600, email dvallado@agi.com +* +* current : +* 30 Aug 10 david vallado +* delete unused variables in initl +* replace pow inetger 2, 3 with multiplies for speed +* changes : +* 3 Nov 08 david vallado +* put returns in for error codes +* 29 sep 08 david vallado +* fix atime for faster operation in dspace +* add operationmode for afspc (a) or improved (i) +* performance mode +* 16 jun 08 david vallado +* update small eccentricity check +* 16 nov 07 david vallado +* misc fixes for better compliance +* 20 apr 07 david vallado +* misc fixes for constants +* 11 aug 06 david vallado +* chg lyddane choice back to strn3, constants, misc doc +* 15 dec 05 david vallado +* misc fixes +* 26 jul 05 david vallado +* fixes for paper +* note that each fix is preceded by a +* comment with "sgp4fix" and an explanation of +* what was changed +* 10 aug 04 david vallado +* 2nd printing baseline working +* 14 may 01 david vallado +* 2nd edition baseline +* 80 norad +* original baseline +* ---------------------------------------------------------------- */ + +#include "sgp4unit.h" +#include "sgp4ext.h" + +const char help = 'n'; +FILE *dbgfile; + + +/* ----------- local functions - only ever used internally by sgp4 ---------- */ +static void dpper + ( + double e3, double ee2, double peo, double pgho, double pho, + double pinco, double plo, double se2, double se3, double sgh2, + double sgh3, double sgh4, double sh2, double sh3, double si2, + double si3, double sl2, double sl3, double sl4, double t, + double xgh2, double xgh3, double xgh4, double xh2, double xh3, + double xi2, double xi3, double xl2, double xl3, double xl4, + double zmol, double zmos, double inclo, + char init, + double& ep, double& inclp, double& nodep, double& argpp, double& mp, + char opsmode + ); + +static void dscom + ( + double epoch, double ep, double argpp, double tc, double inclp, + double nodep, double np, + double& snodm, double& cnodm, double& sinim, double& cosim, double& sinomm, + double& cosomm,double& day, double& e3, double& ee2, double& em, + double& emsq, double& gam, double& peo, double& pgho, double& pho, + double& pinco, double& plo, double& rtemsq, double& se2, double& se3, + double& sgh2, double& sgh3, double& sgh4, double& sh2, double& sh3, + double& si2, double& si3, double& sl2, double& sl3, double& sl4, + double& s1, double& s2, double& s3, double& s4, double& s5, + double& s6, double& s7, double& ss1, double& ss2, double& ss3, + double& ss4, double& ss5, double& ss6, double& ss7, double& sz1, + double& sz2, double& sz3, double& sz11, double& sz12, double& sz13, + double& sz21, double& sz22, double& sz23, double& sz31, double& sz32, + double& sz33, double& xgh2, double& xgh3, double& xgh4, double& xh2, + double& xh3, double& xi2, double& xi3, double& xl2, double& xl3, + double& xl4, double& nm, double& z1, double& z2, double& z3, + double& z11, double& z12, double& z13, double& z21, double& z22, + double& z23, double& z31, double& z32, double& z33, double& zmol, + double& zmos + ); + +static void dsinit + ( + gravconsttype whichconst, + double cosim, double emsq, double argpo, double s1, double s2, + double s3, double s4, double s5, double sinim, double ss1, + double ss2, double ss3, double ss4, double ss5, double sz1, + double sz3, double sz11, double sz13, double sz21, double sz23, + double sz31, double sz33, double t, double tc, double gsto, + double mo, double mdot, double no, double nodeo, double nodedot, + double xpidot, double z1, double z3, double z11, double z13, + double z21, double z23, double z31, double z33, double ecco, + double eccsq, double& em, double& argpm, double& inclm, double& mm, + double& nm, double& nodem, + int& irez, + double& atime, double& d2201, double& d2211, double& d3210, double& d3222, + double& d4410, double& d4422, double& d5220, double& d5232, double& d5421, + double& d5433, double& dedt, double& didt, double& dmdt, double& dndt, + double& dnodt, double& domdt, double& del1, double& del2, double& del3, + double& xfact, double& xlamo, double& xli, double& xni + ); + +static void dspace + ( + int irez, + double d2201, double d2211, double d3210, double d3222, double d4410, + double d4422, double d5220, double d5232, double d5421, double d5433, + double dedt, double del1, double del2, double del3, double didt, + double dmdt, double dnodt, double domdt, double argpo, double argpdot, + double t, double tc, double gsto, double xfact, double xlamo, + double no, + double& atime, double& em, double& argpm, double& inclm, double& xli, + double& mm, double& xni, double& nodem, double& dndt, double& nm + ); + +static void initl + ( + int satn, gravconsttype whichconst, + double ecco, double epoch, double inclo, double& no, + char& method, + double& ainv, double& ao, double& con41, double& con42, double& cosio, + double& cosio2,double& eccsq, double& omeosq, double& posq, + double& rp, double& rteosq,double& sinio , double& gsto, char opsmode + ); + +/* ----------------------------------------------------------------------------- +* +* procedure dpper +* +* this procedure provides deep space long period periodic contributions +* to the mean elements. by design, these periodics are zero at epoch. +* this used to be dscom which included initialization, but it's really a +* recurring function. +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* e3 - +* ee2 - +* peo - +* pgho - +* pho - +* pinco - +* plo - +* se2 , se3 , sgh2, sgh3, sgh4, sh2, sh3, si2, si3, sl2, sl3, sl4 - +* t - +* xh2, xh3, xi2, xi3, xl2, xl3, xl4 - +* zmol - +* zmos - +* ep - eccentricity 0.0 - 1.0 +* inclo - inclination - needed for lyddane modification +* nodep - right ascension of ascending node +* argpp - argument of perigee +* mp - mean anomaly +* +* outputs : +* ep - eccentricity 0.0 - 1.0 +* inclp - inclination +* nodep - right ascension of ascending node +* argpp - argument of perigee +* mp - mean anomaly +* +* locals : +* alfdp - +* betdp - +* cosip , sinip , cosop , sinop , +* dalf - +* dbet - +* dls - +* f2, f3 - +* pe - +* pgh - +* ph - +* pinc - +* pl - +* sel , ses , sghl , sghs , shl , shs , sil , sinzf , sis , +* sll , sls +* xls - +* xnoh - +* zf - +* zm - +* +* coupling : +* none. +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +static void dpper + ( + double e3, double ee2, double peo, double pgho, double pho, + double pinco, double plo, double se2, double se3, double sgh2, + double sgh3, double sgh4, double sh2, double sh3, double si2, + double si3, double sl2, double sl3, double sl4, double t, + double xgh2, double xgh3, double xgh4, double xh2, double xh3, + double xi2, double xi3, double xl2, double xl3, double xl4, + double zmol, double zmos, double inclo, + char init, + double& ep, double& inclp, double& nodep, double& argpp, double& mp, + char opsmode + ) +{ + /* --------------------- local variables ------------------------ */ + const double twopi = 2.0 * pi; + double alfdp, betdp, cosip, cosop, dalf, dbet, dls, + f2, f3, pe, pgh, ph, pinc, pl , + sel, ses, sghl, sghs, shll, shs, sil, + sinip, sinop, sinzf, sis, sll, sls, xls, + xnoh, zf, zm, zel, zes, znl, zns; + + /* ---------------------- constants ----------------------------- */ + zns = 1.19459e-5; + zes = 0.01675; + znl = 1.5835218e-4; + zel = 0.05490; + + /* --------------- calculate time varying periodics ----------- */ + zm = zmos + zns * t; + // be sure that the initial call has time set to zero + if (init == 'y') + zm = zmos; + zf = zm + 2.0 * zes * sin(zm); + sinzf = sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * cos(zf); + ses = se2* f2 + se3 * f3; + sis = si2 * f2 + si3 * f3; + sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf; + sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf; + shs = sh2 * f2 + sh3 * f3; + zm = zmol + znl * t; + if (init == 'y') + zm = zmol; + zf = zm + 2.0 * zel * sin(zm); + sinzf = sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * cos(zf); + sel = ee2 * f2 + e3 * f3; + sil = xi2 * f2 + xi3 * f3; + sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf; + sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf; + shll = xh2 * f2 + xh3 * f3; + pe = ses + sel; + pinc = sis + sil; + pl = sls + sll; + pgh = sghs + sghl; + ph = shs + shll; + + if (init == 'n') + { + pe = pe - peo; + pinc = pinc - pinco; + pl = pl - plo; + pgh = pgh - pgho; + ph = ph - pho; + inclp = inclp + pinc; + ep = ep + pe; + sinip = sin(inclp); + cosip = cos(inclp); + + /* ----------------- apply periodics directly ------------ */ + // sgp4fix for lyddane choice + // strn3 used original inclination - this is technically feasible + // gsfc used perturbed inclination - also technically feasible + // probably best to readjust the 0.2 limit value and limit discontinuity + // 0.2 rad = 11.45916 deg + // use next line for original strn3 approach and original inclination + // if (inclo >= 0.2) + // use next line for gsfc version and perturbed inclination + if (inclp >= 0.2) + { + ph = ph / sinip; + pgh = pgh - cosip * ph; + argpp = argpp + pgh; + nodep = nodep + ph; + mp = mp + pl; + } + else + { + /* ---- apply periodics with lyddane modification ---- */ + sinop = sin(nodep); + cosop = cos(nodep); + alfdp = sinip * sinop; + betdp = sinip * cosop; + dalf = ph * cosop + pinc * cosip * sinop; + dbet = -ph * sinop + pinc * cosip * cosop; + alfdp = alfdp + dalf; + betdp = betdp + dbet; + nodep = floatmod(nodep, twopi); + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if ((nodep < 0.0) && (opsmode == 'a')) + nodep = nodep + twopi; + xls = mp + argpp + cosip * nodep; + dls = pl + pgh - pinc * nodep * sinip; + xls = xls + dls; + xnoh = nodep; + nodep = atan2(alfdp, betdp); + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if ((nodep < 0.0) && (opsmode == 'a')) + nodep = nodep + twopi; + if ((fabs(xnoh - nodep)) > pi) + { + if (nodep < xnoh) + nodep = nodep + twopi; + else + nodep = nodep - twopi; + } + mp = mp + pl; + argpp = xls - mp - cosip * nodep; + } + } // if init == 'n' + +//#include "debug1.cpp" +} // end dpper + +/*----------------------------------------------------------------------------- +* +* procedure dscom +* +* this procedure provides deep space common items used by both the secular +* and periodics subroutines. input is provided as shown. this routine +* used to be called dpper, but the functions inside weren't well organized. +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* epoch - +* ep - eccentricity +* argpp - argument of perigee +* tc - +* inclp - inclination +* nodep - right ascension of ascending node +* np - mean motion +* +* outputs : +* sinim , cosim , sinomm , cosomm , snodm , cnodm +* day - +* e3 - +* ee2 - +* em - eccentricity +* emsq - eccentricity squared +* gam - +* peo - +* pgho - +* pho - +* pinco - +* plo - +* rtemsq - +* se2, se3 - +* sgh2, sgh3, sgh4 - +* sh2, sh3, si2, si3, sl2, sl3, sl4 - +* s1, s2, s3, s4, s5, s6, s7 - +* ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3 - +* sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - +* xgh2, xgh3, xgh4, xh2, xh3, xi2, xi3, xl2, xl3, xl4 - +* nm - mean motion +* z1, z2, z3, z11, z12, z13, z21, z22, z23, z31, z32, z33 - +* zmol - +* zmos - +* +* locals : +* a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 - +* betasq - +* cc - +* ctem, stem - +* x1, x2, x3, x4, x5, x6, x7, x8 - +* xnodce - +* xnoi - +* zcosg , zsing , zcosgl , zsingl , zcosh , zsinh , zcoshl , zsinhl , +* zcosi , zsini , zcosil , zsinil , +* zx - +* zy - +* +* coupling : +* none. +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +static void dscom + ( + double epoch, double ep, double argpp, double tc, double inclp, + double nodep, double np, + double& snodm, double& cnodm, double& sinim, double& cosim, double& sinomm, + double& cosomm,double& day, double& e3, double& ee2, double& em, + double& emsq, double& gam, double& peo, double& pgho, double& pho, + double& pinco, double& plo, double& rtemsq, double& se2, double& se3, + double& sgh2, double& sgh3, double& sgh4, double& sh2, double& sh3, + double& si2, double& si3, double& sl2, double& sl3, double& sl4, + double& s1, double& s2, double& s3, double& s4, double& s5, + double& s6, double& s7, double& ss1, double& ss2, double& ss3, + double& ss4, double& ss5, double& ss6, double& ss7, double& sz1, + double& sz2, double& sz3, double& sz11, double& sz12, double& sz13, + double& sz21, double& sz22, double& sz23, double& sz31, double& sz32, + double& sz33, double& xgh2, double& xgh3, double& xgh4, double& xh2, + double& xh3, double& xi2, double& xi3, double& xl2, double& xl3, + double& xl4, double& nm, double& z1, double& z2, double& z3, + double& z11, double& z12, double& z13, double& z21, double& z22, + double& z23, double& z31, double& z32, double& z33, double& zmol, + double& zmos + ) +{ + /* -------------------------- constants ------------------------- */ + const double zes = 0.01675; + const double zel = 0.05490; + const double c1ss = 2.9864797e-6; + const double c1l = 4.7968065e-7; + const double zsinis = 0.39785416; + const double zcosis = 0.91744867; + const double zcosgs = 0.1945905; + const double zsings = -0.98088458; + const double twopi = 2.0 * pi; + + /* --------------------- local variables ------------------------ */ + int lsflg; + double a1 , a2 , a3 , a4 , a5 , a6 , a7 , + a8 , a9 , a10 , betasq, cc , ctem , stem , + x1 , x2 , x3 , x4 , x5 , x6 , x7 , + x8 , xnodce, xnoi , zcosg , zcosgl, zcosh , zcoshl, + zcosi , zcosil, zsing , zsingl, zsinh , zsinhl, zsini , + zsinil, zx , zy; + + nm = np; + em = ep; + snodm = sin(nodep); + cnodm = cos(nodep); + sinomm = sin(argpp); + cosomm = cos(argpp); + sinim = sin(inclp); + cosim = cos(inclp); + emsq = em * em; + betasq = 1.0 - emsq; + rtemsq = sqrt(betasq); + + /* ----------------- initialize lunar solar terms --------------- */ + peo = 0.0; + pinco = 0.0; + plo = 0.0; + pgho = 0.0; + pho = 0.0; + day = epoch + 18261.5 + tc / 1440.0; + xnodce = floatmod(4.5236020 - 9.2422029e-4 * day, twopi); + stem = sin(xnodce); + ctem = cos(xnodce); + zcosil = 0.91375164 - 0.03568096 * ctem; + zsinil = sqrt(1.0 - zcosil * zcosil); + zsinhl = 0.089683511 * stem / zsinil; + zcoshl = sqrt(1.0 - zsinhl * zsinhl); + gam = 5.8351514 + 0.0019443680 * day; + zx = 0.39785416 * stem / zsinil; + zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; + zx = atan2(zx, zy); + zx = gam + zx - xnodce; + zcosgl = cos(zx); + zsingl = sin(zx); + + /* ------------------------- do solar terms --------------------- */ + zcosg = zcosgs; + zsing = zsings; + zcosi = zcosis; + zsini = zsinis; + zcosh = cnodm; + zsinh = snodm; + cc = c1ss; + xnoi = 1.0 / nm; + + for (lsflg = 1; lsflg <= 2; lsflg++) + { + a1 = zcosg * zcosh + zsing * zcosi * zsinh; + a3 = -zsing * zcosh + zcosg * zcosi * zsinh; + a7 = -zcosg * zsinh + zsing * zcosi * zcosh; + a8 = zsing * zsini; + a9 = zsing * zsinh + zcosg * zcosi * zcosh; + a10 = zcosg * zsini; + a2 = cosim * a7 + sinim * a8; + a4 = cosim * a9 + sinim * a10; + a5 = -sinim * a7 + cosim * a8; + a6 = -sinim * a9 + cosim * a10; + + x1 = a1 * cosomm + a2 * sinomm; + x2 = a3 * cosomm + a4 * sinomm; + x3 = -a1 * sinomm + a2 * cosomm; + x4 = -a3 * sinomm + a4 * cosomm; + x5 = a5 * sinomm; + x6 = a6 * sinomm; + x7 = a5 * cosomm; + x8 = a6 * cosomm; + + z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3; + z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4; + z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4; + z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * emsq; + z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * emsq; + z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * emsq; + z11 = -6.0 * a1 * a5 + emsq * (-24.0 * x1 * x7-6.0 * x3 * x5); + z12 = -6.0 * (a1 * a6 + a3 * a5) + emsq * + (-24.0 * (x2 * x7 + x1 * x8) - 6.0 * (x3 * x6 + x4 * x5)); + z13 = -6.0 * a3 * a6 + emsq * (-24.0 * x2 * x8 - 6.0 * x4 * x6); + z21 = 6.0 * a2 * a5 + emsq * (24.0 * x1 * x5 - 6.0 * x3 * x7); + z22 = 6.0 * (a4 * a5 + a2 * a6) + emsq * + (24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8)); + z23 = 6.0 * a4 * a6 + emsq * (24.0 * x2 * x6 - 6.0 * x4 * x8); + z1 = z1 + z1 + betasq * z31; + z2 = z2 + z2 + betasq * z32; + z3 = z3 + z3 + betasq * z33; + s3 = cc * xnoi; + s2 = -0.5 * s3 / rtemsq; + s4 = s3 * rtemsq; + s1 = -15.0 * em * s4; + s5 = x1 * x3 + x2 * x4; + s6 = x2 * x3 + x1 * x4; + s7 = x2 * x4 - x1 * x3; + + /* ----------------------- do lunar terms ------------------- */ + if (lsflg == 1) + { + ss1 = s1; + ss2 = s2; + ss3 = s3; + ss4 = s4; + ss5 = s5; + ss6 = s6; + ss7 = s7; + sz1 = z1; + sz2 = z2; + sz3 = z3; + sz11 = z11; + sz12 = z12; + sz13 = z13; + sz21 = z21; + sz22 = z22; + sz23 = z23; + sz31 = z31; + sz32 = z32; + sz33 = z33; + zcosg = zcosgl; + zsing = zsingl; + zcosi = zcosil; + zsini = zsinil; + zcosh = zcoshl * cnodm + zsinhl * snodm; + zsinh = snodm * zcoshl - cnodm * zsinhl; + cc = c1l; + } + } + + zmol = floatmod(4.7199672 + 0.22997150 * day - gam, twopi); + zmos = floatmod(6.2565837 + 0.017201977 * day, twopi); + + /* ------------------------ do solar terms ---------------------- */ + se2 = 2.0 * ss1 * ss6; + se3 = 2.0 * ss1 * ss7; + si2 = 2.0 * ss2 * sz12; + si3 = 2.0 * ss2 * (sz13 - sz11); + sl2 = -2.0 * ss3 * sz2; + sl3 = -2.0 * ss3 * (sz3 - sz1); + sl4 = -2.0 * ss3 * (-21.0 - 9.0 * emsq) * zes; + sgh2 = 2.0 * ss4 * sz32; + sgh3 = 2.0 * ss4 * (sz33 - sz31); + sgh4 = -18.0 * ss4 * zes; + sh2 = -2.0 * ss2 * sz22; + sh3 = -2.0 * ss2 * (sz23 - sz21); + + /* ------------------------ do lunar terms ---------------------- */ + ee2 = 2.0 * s1 * s6; + e3 = 2.0 * s1 * s7; + xi2 = 2.0 * s2 * z12; + xi3 = 2.0 * s2 * (z13 - z11); + xl2 = -2.0 * s3 * z2; + xl3 = -2.0 * s3 * (z3 - z1); + xl4 = -2.0 * s3 * (-21.0 - 9.0 * emsq) * zel; + xgh2 = 2.0 * s4 * z32; + xgh3 = 2.0 * s4 * (z33 - z31); + xgh4 = -18.0 * s4 * zel; + xh2 = -2.0 * s2 * z22; + xh3 = -2.0 * s2 * (z23 - z21); + +//#include "debug2.cpp" +} // end dscom + +/*----------------------------------------------------------------------------- +* +* procedure dsinit +* +* this procedure provides deep space contributions to mean motion dot due +* to geopotential resonance with half day and one day orbits. +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* cosim, sinim- +* emsq - eccentricity squared +* argpo - argument of perigee +* s1, s2, s3, s4, s5 - +* ss1, ss2, ss3, ss4, ss5 - +* sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33 - +* t - time +* tc - +* gsto - greenwich sidereal time rad +* mo - mean anomaly +* mdot - mean anomaly dot (rate) +* no - mean motion +* nodeo - right ascension of ascending node +* nodedot - right ascension of ascending node dot (rate) +* xpidot - +* z1, z3, z11, z13, z21, z23, z31, z33 - +* eccm - eccentricity +* argpm - argument of perigee +* inclm - inclination +* mm - mean anomaly +* xn - mean motion +* nodem - right ascension of ascending node +* +* outputs : +* em - eccentricity +* argpm - argument of perigee +* inclm - inclination +* mm - mean anomaly +* nm - mean motion +* nodem - right ascension of ascending node +* irez - flag for resonance 0-none, 1-one day, 2-half day +* atime - +* d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - +* dedt - +* didt - +* dmdt - +* dndt - +* dnodt - +* domdt - +* del1, del2, del3 - +* ses , sghl , sghs , sgs , shl , shs , sis , sls +* theta - +* xfact - +* xlamo - +* xli - +* xni +* +* locals : +* ainv2 - +* aonv - +* cosisq - +* eoc - +* f220, f221, f311, f321, f322, f330, f441, f442, f522, f523, f542, f543 - +* g200, g201, g211, g300, g310, g322, g410, g422, g520, g521, g532, g533 - +* sini2 - +* temp - +* temp1 - +* theta - +* xno2 - +* +* coupling : +* getgravconst +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +static void dsinit + ( + gravconsttype whichconst, + double cosim, double emsq, double argpo, double s1, double s2, + double s3, double s4, double s5, double sinim, double ss1, + double ss2, double ss3, double ss4, double ss5, double sz1, + double sz3, double sz11, double sz13, double sz21, double sz23, + double sz31, double sz33, double t, double tc, double gsto, + double mo, double mdot, double no, double nodeo, double nodedot, + double xpidot, double z1, double z3, double z11, double z13, + double z21, double z23, double z31, double z33, double ecco, + double eccsq, double& em, double& argpm, double& inclm, double& mm, + double& nm, double& nodem, + int& irez, + double& atime, double& d2201, double& d2211, double& d3210, double& d3222, + double& d4410, double& d4422, double& d5220, double& d5232, double& d5421, + double& d5433, double& dedt, double& didt, double& dmdt, double& dndt, + double& dnodt, double& domdt, double& del1, double& del2, double& del3, + double& xfact, double& xlamo, double& xli, double& xni + ) +{ + /* --------------------- local variables ------------------------ */ + const double twopi = 2.0 * pi; + + double ainv2 , aonv=0.0, cosisq, eoc, f220 , f221 , f311 , + f321 , f322 , f330 , f441 , f442 , f522 , f523 , + f542 , f543 , g200 , g201 , g211 , g300 , g310 , + g322 , g410 , g422 , g520 , g521 , g532 , g533 , + ses , sgs , sghl , sghs , shs , shll , sis , + sini2 , sls , temp , temp1 , theta , xno2 , q22 , + q31 , q33 , root22, root44, root54, rptim , root32, + root52, x2o3 , xke , znl , emo , zns , emsqo, + tumin, mu, radiusearthkm, j2, j3, j4, j3oj2; + + q22 = 1.7891679e-6; + q31 = 2.1460748e-6; + q33 = 2.2123015e-7; + root22 = 1.7891679e-6; + root44 = 7.3636953e-9; + root54 = 2.1765803e-9; + rptim = 4.37526908801129966e-3; // this equates to 7.29211514668855e-5 rad/sec + root32 = 3.7393792e-7; + root52 = 1.1428639e-7; + x2o3 = 2.0 / 3.0; + znl = 1.5835218e-4; + zns = 1.19459e-5; + + // sgp4fix identify constants and allow alternate values + getgravconst( whichconst, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 ); + + /* -------------------- deep space initialization ------------ */ + irez = 0; + if ((nm < 0.0052359877) && (nm > 0.0034906585)) + irez = 1; + if ((nm >= 8.26e-3) && (nm <= 9.24e-3) && (em >= 0.5)) + irez = 2; + + /* ------------------------ do solar terms ------------------- */ + ses = ss1 * zns * ss5; + sis = ss2 * zns * (sz11 + sz13); + sls = -zns * ss3 * (sz1 + sz3 - 14.0 - 6.0 * emsq); + sghs = ss4 * zns * (sz31 + sz33 - 6.0); + shs = -zns * ss2 * (sz21 + sz23); + // sgp4fix for 180 deg incl + if ((inclm < 5.2359877e-2) || (inclm > pi - 5.2359877e-2)) + shs = 0.0; + if (sinim != 0.0) + shs = shs / sinim; + sgs = sghs - cosim * shs; + + /* ------------------------- do lunar terms ------------------ */ + dedt = ses + s1 * znl * s5; + didt = sis + s2 * znl * (z11 + z13); + dmdt = sls - znl * s3 * (z1 + z3 - 14.0 - 6.0 * emsq); + sghl = s4 * znl * (z31 + z33 - 6.0); + shll = -znl * s2 * (z21 + z23); + // sgp4fix for 180 deg incl + if ((inclm < 5.2359877e-2) || (inclm > pi - 5.2359877e-2)) + shll = 0.0; + domdt = sgs + sghl; + dnodt = shs; + if (sinim != 0.0) + { + domdt = domdt - cosim / sinim * shll; + dnodt = dnodt + shll / sinim; + } + + /* ----------- calculate deep space resonance effects -------- */ + dndt = 0.0; + theta = floatmod(gsto + tc * rptim, twopi); + em = em + dedt * t; + inclm = inclm + didt * t; + argpm = argpm + domdt * t; + nodem = nodem + dnodt * t; + mm = mm + dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + //if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + + /* -------------- initialize the resonance terms ------------- */ + if (irez != 0) + { + aonv = pow(nm / xke, x2o3); + + /* ---------- geopotential resonance for 12 hour orbits ------ */ + if (irez == 2) + { + cosisq = cosim * cosim; + emo = em; + em = ecco; + emsqo = emsq; + emsq = eccsq; + eoc = em * emsq; + g201 = -0.306 - (em - 0.64) * 0.440; + + if (em <= 0.65) + { + g211 = 3.616 - 13.2470 * em + 16.2900 * emsq; + g310 = -19.302 + 117.3900 * em - 228.4190 * emsq + 156.5910 * eoc; + g322 = -18.9068 + 109.7927 * em - 214.6334 * emsq + 146.5816 * eoc; + g410 = -41.122 + 242.6940 * em - 471.0940 * emsq + 313.9530 * eoc; + g422 = -146.407 + 841.8800 * em - 1629.014 * emsq + 1083.4350 * eoc; + g520 = -532.114 + 3017.977 * em - 5740.032 * emsq + 3708.2760 * eoc; + } + else + { + g211 = -72.099 + 331.819 * em - 508.738 * emsq + 266.724 * eoc; + g310 = -346.844 + 1582.851 * em - 2415.925 * emsq + 1246.113 * eoc; + g322 = -342.585 + 1554.908 * em - 2366.899 * emsq + 1215.972 * eoc; + g410 = -1052.797 + 4758.686 * em - 7193.992 * emsq + 3651.957 * eoc; + g422 = -3581.690 + 16178.110 * em - 24462.770 * emsq + 12422.520 * eoc; + if (em > 0.715) + g520 =-5149.66 + 29936.92 * em - 54087.36 * emsq + 31324.56 * eoc; + else + g520 = 1464.74 - 4664.75 * em + 3763.64 * emsq; + } + if (em < 0.7) + { + g533 = -919.22770 + 4988.6100 * em - 9064.7700 * emsq + 5542.21 * eoc; + g521 = -822.71072 + 4568.6173 * em - 8491.4146 * emsq + 5337.524 * eoc; + g532 = -853.66600 + 4690.2500 * em - 8624.7700 * emsq + 5341.4 * eoc; + } + else + { + g533 =-37995.780 + 161616.52 * em - 229838.20 * emsq + 109377.94 * eoc; + g521 =-51752.104 + 218913.95 * em - 309468.16 * emsq + 146349.42 * eoc; + g532 =-40023.880 + 170470.89 * em - 242699.48 * emsq + 115605.82 * eoc; + } + + sini2= sinim * sinim; + f220 = 0.75 * (1.0 + 2.0 * cosim+cosisq); + f221 = 1.5 * sini2; + f321 = 1.875 * sinim * (1.0 - 2.0 * cosim - 3.0 * cosisq); + f322 = -1.875 * sinim * (1.0 + 2.0 * cosim - 3.0 * cosisq); + f441 = 35.0 * sini2 * f220; + f442 = 39.3750 * sini2 * sini2; + f522 = 9.84375 * sinim * (sini2 * (1.0 - 2.0 * cosim- 5.0 * cosisq) + + 0.33333333 * (-2.0 + 4.0 * cosim + 6.0 * cosisq) ); + f523 = sinim * (4.92187512 * sini2 * (-2.0 - 4.0 * cosim + + 10.0 * cosisq) + 6.56250012 * (1.0+2.0 * cosim - 3.0 * cosisq)); + f542 = 29.53125 * sinim * (2.0 - 8.0 * cosim+cosisq * + (-12.0 + 8.0 * cosim + 10.0 * cosisq)); + f543 = 29.53125 * sinim * (-2.0 - 8.0 * cosim+cosisq * + (12.0 + 8.0 * cosim - 10.0 * cosisq)); + xno2 = nm * nm; + ainv2 = aonv * aonv; + temp1 = 3.0 * xno2 * ainv2; + temp = temp1 * root22; + d2201 = temp * f220 * g201; + d2211 = temp * f221 * g211; + temp1 = temp1 * aonv; + temp = temp1 * root32; + d3210 = temp * f321 * g310; + d3222 = temp * f322 * g322; + temp1 = temp1 * aonv; + temp = 2.0 * temp1 * root44; + d4410 = temp * f441 * g410; + d4422 = temp * f442 * g422; + temp1 = temp1 * aonv; + temp = temp1 * root52; + d5220 = temp * f522 * g520; + d5232 = temp * f523 * g532; + temp = 2.0 * temp1 * root54; + d5421 = temp * f542 * g521; + d5433 = temp * f543 * g533; + xlamo = floatmod(mo + nodeo + nodeo-theta - theta, twopi); + xfact = mdot + dmdt + 2.0 * (nodedot + dnodt - rptim) - no; + em = emo; + emsq = emsqo; + } + + /* ---------------- synchronous resonance terms -------------- */ + if (irez == 1) + { + g200 = 1.0 + emsq * (-2.5 + 0.8125 * emsq); + g310 = 1.0 + 2.0 * emsq; + g300 = 1.0 + emsq * (-6.0 + 6.60937 * emsq); + f220 = 0.75 * (1.0 + cosim) * (1.0 + cosim); + f311 = 0.9375 * sinim * sinim * (1.0 + 3.0 * cosim) - 0.75 * (1.0 + cosim); + f330 = 1.0 + cosim; + f330 = 1.875 * f330 * f330 * f330; + del1 = 3.0 * nm * nm * aonv * aonv; + del2 = 2.0 * del1 * f220 * g200 * q22; + del3 = 3.0 * del1 * f330 * g300 * q33 * aonv; + del1 = del1 * f311 * g310 * q31 * aonv; + xlamo = floatmod(mo + nodeo + argpo - theta, twopi); + xfact = mdot + xpidot - rptim + dmdt + domdt + dnodt - no; + } + + /* ------------ for sgp4, initialize the integrator ---------- */ + xli = xlamo; + xni = no; + atime = 0.0; + nm = no + dndt; + } + +//#include "debug3.cpp" +} // end dsinit + +/*----------------------------------------------------------------------------- +* +* procedure dspace +* +* this procedure provides deep space contributions to mean elements for +* perturbing third body. these effects have been averaged over one +* revolution of the sun and moon. for earth resonance effects, the +* effects have been averaged over no revolutions of the satellite. +* (mean motion) +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - +* dedt - +* del1, del2, del3 - +* didt - +* dmdt - +* dnodt - +* domdt - +* irez - flag for resonance 0-none, 1-one day, 2-half day +* argpo - argument of perigee +* argpdot - argument of perigee dot (rate) +* t - time +* tc - +* gsto - gst +* xfact - +* xlamo - +* no - mean motion +* atime - +* em - eccentricity +* ft - +* argpm - argument of perigee +* inclm - inclination +* xli - +* mm - mean anomaly +* xni - mean motion +* nodem - right ascension of ascending node +* +* outputs : +* atime - +* em - eccentricity +* argpm - argument of perigee +* inclm - inclination +* xli - +* mm - mean anomaly +* xni - +* nodem - right ascension of ascending node +* dndt - +* nm - mean motion +* +* locals : +* delt - +* ft - +* theta - +* x2li - +* x2omi - +* xl - +* xldot - +* xnddt - +* xndt - +* xomi - +* +* coupling : +* none - +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +static void dspace + ( + int irez, + double d2201, double d2211, double d3210, double d3222, double d4410, + double d4422, double d5220, double d5232, double d5421, double d5433, + double dedt, double del1, double del2, double del3, double didt, + double dmdt, double dnodt, double domdt, double argpo, double argpdot, + double t, double tc, double gsto, double xfact, double xlamo, + double no, + double& atime, double& em, double& argpm, double& inclm, double& xli, + double& mm, double& xni, double& nodem, double& dndt, double& nm + ) +{ + const double twopi = 2.0 * pi; + int iretn , iret; + double delt, ft, theta, x2li, x2omi, xl, xldot , xnddt, xndt, xomi, g22, g32, + g44, g52, g54, fasx2, fasx4, fasx6, rptim , step2, stepn , stepp; + + fasx2 = 0.13130908; + fasx4 = 2.8843198; + fasx6 = 0.37448087; + g22 = 5.7686396; + g32 = 0.95240898; + g44 = 1.8014998; + g52 = 1.0508330; + g54 = 4.4108898; + rptim = 4.37526908801129966e-3; // this equates to 7.29211514668855e-5 rad/sec + stepp = 720.0; + stepn = -720.0; + step2 = 259200.0; + + /* ----------- calculate deep space resonance effects ----------- */ + dndt = 0.0; + theta = floatmod(gsto + tc * rptim, twopi); + em = em + dedt * t; + + inclm = inclm + didt * t; + argpm = argpm + domdt * t; + nodem = nodem + dnodt * t; + mm = mm + dmdt * t; + + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + + /* - update resonances : numerical (euler-maclaurin) integration - */ + /* ------------------------- epoch restart ---------------------- */ + // sgp4fix for propagator problems + // the following integration works for negative time steps and periods + // the specific changes are unknown because the original code was so convoluted + + // sgp4fix take out atime = 0.0 and fix for faster operation + ft = 0.0; + if (irez != 0) + { + // sgp4fix streamline check + if ((atime == 0.0) || (t * atime <= 0.0) || (fabs(t) < fabs(atime)) ) + { + atime = 0.0; + xni = no; + xli = xlamo; + } + // sgp4fix move check outside loop + if (t > 0.0) + delt = stepp; + else + delt = stepn; + + iretn = 381; // added for do loop + iret = 0; // added for loop + while (iretn == 381) + { + /* ------------------- dot terms calculated ------------- */ + /* ----------- near - synchronous resonance terms ------- */ + if (irez != 2) + { + xndt = del1 * sin(xli - fasx2) + del2 * sin(2.0 * (xli - fasx4)) + + del3 * sin(3.0 * (xli - fasx6)); + xldot = xni + xfact; + xnddt = del1 * cos(xli - fasx2) + + 2.0 * del2 * cos(2.0 * (xli - fasx4)) + + 3.0 * del3 * cos(3.0 * (xli - fasx6)); + xnddt = xnddt * xldot; + } + else + { + /* --------- near - half-day resonance terms -------- */ + xomi = argpo + argpdot * atime; + x2omi = xomi + xomi; + x2li = xli + xli; + xndt = d2201 * sin(x2omi + xli - g22) + d2211 * sin(xli - g22) + + d3210 * sin(xomi + xli - g32) + d3222 * sin(-xomi + xli - g32)+ + d4410 * sin(x2omi + x2li - g44)+ d4422 * sin(x2li - g44) + + d5220 * sin(xomi + xli - g52) + d5232 * sin(-xomi + xli - g52)+ + d5421 * sin(xomi + x2li - g54) + d5433 * sin(-xomi + x2li - g54); + xldot = xni + xfact; + xnddt = d2201 * cos(x2omi + xli - g22) + d2211 * cos(xli - g22) + + d3210 * cos(xomi + xli - g32) + d3222 * cos(-xomi + xli - g32) + + d5220 * cos(xomi + xli - g52) + d5232 * cos(-xomi + xli - g52) + + 2.0 * (d4410 * cos(x2omi + x2li - g44) + + d4422 * cos(x2li - g44) + d5421 * cos(xomi + x2li - g54) + + d5433 * cos(-xomi + x2li - g54)); + xnddt = xnddt * xldot; + } + + /* ----------------------- integrator ------------------- */ + // sgp4fix move end checks to end of routine + if (fabs(t - atime) >= stepp) + { + iret = 0; + iretn = 381; + } + else // exit here + { + ft = t - atime; + iretn = 0; + } + + if (iretn == 381) + { + xli = xli + xldot * delt + xndt * step2; + xni = xni + xndt * delt + xnddt * step2; + atime = atime + delt; + } + } // while iretn = 381 + + nm = xni + xndt * ft + xnddt * ft * ft * 0.5; + xl = xli + xldot * ft + xndt * ft * ft * 0.5; + if (irez != 1) + { + mm = xl - 2.0 * nodem + 2.0 * theta; + dndt = nm - no; + } + else + { + mm = xl - nodem - argpm + theta; + dndt = nm - no; + } + nm = no + dndt; + } + +//#include "debug4.cpp" +} // end dsspace + +/*----------------------------------------------------------------------------- +* +* procedure initl +* +* this procedure initializes the spg4 propagator. all the initialization is +* consolidated here instead of having multiple loops inside other routines. +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* ecco - eccentricity 0.0 - 1.0 +* epoch - epoch time in days from jan 0, 1950. 0 hr +* inclo - inclination of satellite +* no - mean motion of satellite +* satn - satellite number +* +* outputs : +* ainv - 1.0 / a +* ao - semi major axis +* con41 - +* con42 - 1.0 - 5.0 cos(i) +* cosio - cosine of inclination +* cosio2 - cosio squared +* eccsq - eccentricity squared +* method - flag for deep space 'd', 'n' +* omeosq - 1.0 - ecco * ecco +* posq - semi-parameter squared +* rp - radius of perigee +* rteosq - square root of (1.0 - ecco*ecco) +* sinio - sine of inclination +* gsto - gst at time of observation rad +* no - mean motion of satellite +* +* locals : +* ak - +* d1 - +* del - +* adel - +* po - +* +* coupling : +* getgravconst +* gstime - find greenwich sidereal time from the julian date +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +static void initl + ( + int satn, gravconsttype whichconst, + double ecco, double epoch, double inclo, double& no, + char& method, + double& ainv, double& ao, double& con41, double& con42, double& cosio, + double& cosio2,double& eccsq, double& omeosq, double& posq, + double& rp, double& rteosq,double& sinio , double& gsto, + char opsmode + ) +{ + /* --------------------- local variables ------------------------ */ + double ak, d1, del, adel, po, x2o3, j2, xke, + tumin, mu, radiusearthkm, j3, j4, j3oj2; + + // sgp4fix use old way of finding gst + double ds70; + double ts70, tfrac, c1, thgr70, fk5r, c1p2p; + const double twopi = 2.0 * pi; + + /* ----------------------- earth constants ---------------------- */ + // sgp4fix identify constants and allow alternate values + getgravconst( whichconst, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 ); + x2o3 = 2.0 / 3.0; + + /* ------------- calculate auxillary epoch quantities ---------- */ + eccsq = ecco * ecco; + omeosq = 1.0 - eccsq; + rteosq = sqrt(omeosq); + cosio = cos(inclo); + cosio2 = cosio * cosio; + + /* ------------------ un-kozai the mean motion ----------------- */ + ak = pow(xke / no, x2o3); + d1 = 0.75 * j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq); + del = d1 / (ak * ak); + adel = ak * (1.0 - del * del - del * + (1.0 / 3.0 + 134.0 * del * del / 81.0)); + del = d1/(adel * adel); + no = no / (1.0 + del); + + ao = pow(xke / no, x2o3); + sinio = sin(inclo); + po = ao * omeosq; + con42 = 1.0 - 5.0 * cosio2; + con41 = -con42-cosio2-cosio2; + ainv = 1.0 / ao; + posq = po * po; + rp = ao * (1.0 - ecco); + method = 'n'; + + // sgp4fix modern approach to finding sidereal time + if (opsmode == 'a') + { + // sgp4fix use old way of finding gst + // count integer number of days from 0 jan 1970 + ts70 = epoch - 7305.0; + ds70 = floor(ts70 + 1.0e-8); + tfrac = ts70 - ds70; + // find greenwich location at epoch + c1 = 1.72027916940703639e-2; + thgr70= 1.7321343856509374; + fk5r = 5.07551419432269442e-15; + c1p2p = c1 + twopi; + gsto = floatmod( thgr70 + c1*ds70 + c1p2p*tfrac + ts70*ts70*fk5r, twopi); + if ( gsto < 0.0 ) + gsto = gsto + twopi; + } + else + gsto = gstime(epoch + 2433281.5); + + +//#include "debug5.cpp" +} // end initl + +/*----------------------------------------------------------------------------- +* +* procedure sgp4init +* +* this procedure initializes variables for sgp4. +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* opsmode - mode of operation afspc or improved 'a', 'i' +* whichconst - which set of constants to use 72, 84 +* satn - satellite number +* bstar - sgp4 type drag coefficient kg/m2er +* ecco - eccentricity +* epoch - epoch time in days from jan 0, 1950. 0 hr +* argpo - argument of perigee (output if ds) +* inclo - inclination +* mo - mean anomaly (output if ds) +* no - mean motion +* nodeo - right ascension of ascending node +* +* outputs : +* satrec - common values for subsequent calls +* return code - non-zero on error. +* 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er +* 2 - mean motion less than 0.0 +* 3 - pert elements, ecc < 0.0 or ecc > 1.0 +* 4 - semi-latus rectum < 0.0 +* 5 - epoch elements are sub-orbital +* 6 - satellite has decayed +* +* locals : +* cnodm , snodm , cosim , sinim , cosomm , sinomm +* cc1sq , cc2 , cc3 +* coef , coef1 +* cosio4 - +* day - +* dndt - +* em - eccentricity +* emsq - eccentricity squared +* eeta - +* etasq - +* gam - +* argpm - argument of perigee +* nodem - +* inclm - inclination +* mm - mean anomaly +* nm - mean motion +* perige - perigee +* pinvsq - +* psisq - +* qzms24 - +* rtemsq - +* s1, s2, s3, s4, s5, s6, s7 - +* sfour - +* ss1, ss2, ss3, ss4, ss5, ss6, ss7 - +* sz1, sz2, sz3 +* sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - +* tc - +* temp - +* temp1, temp2, temp3 - +* tsi - +* xpidot - +* xhdot1 - +* z1, z2, z3 - +* z11, z12, z13, z21, z22, z23, z31, z32, z33 - +* +* coupling : +* getgravconst- +* initl - +* dscom - +* dpper - +* dsinit - +* sgp4 - +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +bool sgp4init + ( + gravconsttype whichconst, char opsmode, const int satn, const double epoch, + const double xbstar, const double xecco, const double xargpo, + const double xinclo, const double xmo, const double xno, + const double xnodeo, elsetrec& satrec + ) +{ + /* --------------------- local variables ------------------------ */ + double ao, ainv, con42, cosio, sinio, cosio2, eccsq, + omeosq, posq, rp, rteosq, + cnodm , snodm , cosim , sinim , cosomm, sinomm, cc1sq , + cc2 , cc3 , coef , coef1 , cosio4, day , dndt , + em , emsq , eeta , etasq , gam , argpm , nodem , + inclm , mm , nm , perige, pinvsq, psisq , qzms24, + rtemsq, s1 , s2 , s3 , s4 , s5 , s6 , + s7 , sfour , ss1 , ss2 , ss3 , ss4 , ss5 , + ss6 , ss7 , sz1 , sz2 , sz3 , sz11 , sz12 , + sz13 , sz21 , sz22 , sz23 , sz31 , sz32 , sz33 , + tc , temp , temp1 , temp2 , temp3 , tsi , xpidot, + xhdot1, z1 , z2 , z3 , z11 , z12 , z13 , + z21 , z22 , z23 , z31 , z32 , z33, + qzms2t, ss, j2, j3oj2, j4, x2o3, r[3], v[3], + tumin, mu, radiusearthkm, xke, j3, delmotemp, qzms2ttemp, qzms24temp; + + /* ------------------------ initialization --------------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + const double temp4 = 1.5e-12; + + /* ----------- set all near earth variables to zero ------------ */ + satrec.isimp = 0; satrec.method = 'n'; satrec.aycof = 0.0; + satrec.con41 = 0.0; satrec.cc1 = 0.0; satrec.cc4 = 0.0; + satrec.cc5 = 0.0; satrec.d2 = 0.0; satrec.d3 = 0.0; + satrec.d4 = 0.0; satrec.delmo = 0.0; satrec.eta = 0.0; + satrec.argpdot = 0.0; satrec.omgcof = 0.0; satrec.sinmao = 0.0; + satrec.t = 0.0; satrec.t2cof = 0.0; satrec.t3cof = 0.0; + satrec.t4cof = 0.0; satrec.t5cof = 0.0; satrec.x1mth2 = 0.0; + satrec.x7thm1 = 0.0; satrec.mdot = 0.0; satrec.nodedot = 0.0; + satrec.xlcof = 0.0; satrec.xmcof = 0.0; satrec.nodecf = 0.0; + + /* ----------- set all deep space variables to zero ------------ */ + satrec.irez = 0; satrec.d2201 = 0.0; satrec.d2211 = 0.0; + satrec.d3210 = 0.0; satrec.d3222 = 0.0; satrec.d4410 = 0.0; + satrec.d4422 = 0.0; satrec.d5220 = 0.0; satrec.d5232 = 0.0; + satrec.d5421 = 0.0; satrec.d5433 = 0.0; satrec.dedt = 0.0; + satrec.del1 = 0.0; satrec.del2 = 0.0; satrec.del3 = 0.0; + satrec.didt = 0.0; satrec.dmdt = 0.0; satrec.dnodt = 0.0; + satrec.domdt = 0.0; satrec.e3 = 0.0; satrec.ee2 = 0.0; + satrec.peo = 0.0; satrec.pgho = 0.0; satrec.pho = 0.0; + satrec.pinco = 0.0; satrec.plo = 0.0; satrec.se2 = 0.0; + satrec.se3 = 0.0; satrec.sgh2 = 0.0; satrec.sgh3 = 0.0; + satrec.sgh4 = 0.0; satrec.sh2 = 0.0; satrec.sh3 = 0.0; + satrec.si2 = 0.0; satrec.si3 = 0.0; satrec.sl2 = 0.0; + satrec.sl3 = 0.0; satrec.sl4 = 0.0; satrec.gsto = 0.0; + satrec.xfact = 0.0; satrec.xgh2 = 0.0; satrec.xgh3 = 0.0; + satrec.xgh4 = 0.0; satrec.xh2 = 0.0; satrec.xh3 = 0.0; + satrec.xi2 = 0.0; satrec.xi3 = 0.0; satrec.xl2 = 0.0; + satrec.xl3 = 0.0; satrec.xl4 = 0.0; satrec.xlamo = 0.0; + satrec.zmol = 0.0; satrec.zmos = 0.0; satrec.atime = 0.0; + satrec.xli = 0.0; satrec.xni = 0.0; + + // sgp4fix - note the following variables are also passed directly via satrec. + // it is possible to streamline the sgp4init call by deleting the "x" + // variables, but the user would need to set the satrec.* values first. we + // include the additional assignments in case twoline2rv is not used. + satrec.bstar = xbstar; + satrec.ecco = xecco; + satrec.argpo = xargpo; + satrec.inclo = xinclo; + satrec.mo = xmo; + satrec.no = xno; + satrec.nodeo = xnodeo; + + // sgp4fix add opsmode + satrec.operationmode = opsmode; + + /* ------------------------ earth constants ----------------------- */ + // sgp4fix identify constants and allow alternate values + getgravconst( whichconst, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 ); + ss = 78.0 / radiusearthkm + 1.0; + // sgp4fix use multiply for speed instead of pow + qzms2ttemp = (120.0 - 78.0) / radiusearthkm; + qzms2t = qzms2ttemp * qzms2ttemp * qzms2ttemp * qzms2ttemp; + x2o3 = 2.0 / 3.0; + + satrec.init = 'y'; + satrec.t = 0.0; + + initl + ( + satn, whichconst, satrec.ecco, epoch, satrec.inclo, satrec.no, satrec.method, + ainv, ao, satrec.con41, con42, cosio, cosio2, eccsq, omeosq, + posq, rp, rteosq, sinio, satrec.gsto, satrec.operationmode + ); + satrec.error = 0; + + // sgp4fix remove this check as it is unnecessary + // the mrt check in sgp4 handles decaying satellite cases even if the starting + // condition is below the surface of te earth +// if (rp < 1.0) +// { +// printf("# *** satn%d epoch elts sub-orbital ***\n", satn); +// satrec.error = 5; +// } + + if ((omeosq >= 0.0 ) || ( satrec.no >= 0.0)) + { + satrec.isimp = 0; + if (rp < (220.0 / radiusearthkm + 1.0)) + satrec.isimp = 1; + sfour = ss; + qzms24 = qzms2t; + perige = (rp - 1.0) * radiusearthkm; + + /* - for perigees below 156 km, s and qoms2t are altered - */ + if (perige < 156.0) + { + sfour = perige - 78.0; + if (perige < 98.0) + sfour = 20.0; + // sgp4fix use multiply for speed instead of pow + qzms24temp = (120.0 - sfour) / radiusearthkm; + qzms24 = qzms24temp * qzms24temp * qzms24temp * qzms24temp; + sfour = sfour / radiusearthkm + 1.0; + } + pinvsq = 1.0 / posq; + + tsi = 1.0 / (ao - sfour); + satrec.eta = ao * satrec.ecco * tsi; + etasq = satrec.eta * satrec.eta; + eeta = satrec.ecco * satrec.eta; + psisq = fabs(1.0 - etasq); + coef = qzms24 * pow(tsi, 4.0); + coef1 = coef / pow(psisq, 3.5); + cc2 = coef1 * satrec.no * (ao * (1.0 + 1.5 * etasq + eeta * + (4.0 + etasq)) + 0.375 * j2 * tsi / psisq * satrec.con41 * + (8.0 + 3.0 * etasq * (8.0 + etasq))); + satrec.cc1 = satrec.bstar * cc2; + cc3 = 0.0; + if (satrec.ecco > 1.0e-4) + cc3 = -2.0 * coef * tsi * j3oj2 * satrec.no * sinio / satrec.ecco; + satrec.x1mth2 = 1.0 - cosio2; + satrec.cc4 = 2.0* satrec.no * coef1 * ao * omeosq * + (satrec.eta * (2.0 + 0.5 * etasq) + satrec.ecco * + (0.5 + 2.0 * etasq) - j2 * tsi / (ao * psisq) * + (-3.0 * satrec.con41 * (1.0 - 2.0 * eeta + etasq * + (1.5 - 0.5 * eeta)) + 0.75 * satrec.x1mth2 * + (2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * satrec.argpo))); + satrec.cc5 = 2.0 * coef1 * ao * omeosq * (1.0 + 2.75 * + (etasq + eeta) + eeta * etasq); + cosio4 = cosio2 * cosio2; + temp1 = 1.5 * j2 * pinvsq * satrec.no; + temp2 = 0.5 * temp1 * j2 * pinvsq; + temp3 = -0.46875 * j4 * pinvsq * pinvsq * satrec.no; + satrec.mdot = satrec.no + 0.5 * temp1 * rteosq * satrec.con41 + 0.0625 * + temp2 * rteosq * (13.0 - 78.0 * cosio2 + 137.0 * cosio4); + satrec.argpdot = -0.5 * temp1 * con42 + 0.0625 * temp2 * + (7.0 - 114.0 * cosio2 + 395.0 * cosio4) + + temp3 * (3.0 - 36.0 * cosio2 + 49.0 * cosio4); + xhdot1 = -temp1 * cosio; + satrec.nodedot = xhdot1 + (0.5 * temp2 * (4.0 - 19.0 * cosio2) + + 2.0 * temp3 * (3.0 - 7.0 * cosio2)) * cosio; + xpidot = satrec.argpdot+ satrec.nodedot; + satrec.omgcof = satrec.bstar * cc3 * cos(satrec.argpo); + satrec.xmcof = 0.0; + if (satrec.ecco > 1.0e-4) + satrec.xmcof = -x2o3 * coef * satrec.bstar / eeta; + satrec.nodecf = 3.5 * omeosq * xhdot1 * satrec.cc1; + satrec.t2cof = 1.5 * satrec.cc1; + // sgp4fix for divide by zero with xinco = 180 deg + if (fabs(cosio+1.0) > 1.5e-12) + satrec.xlcof = -0.25 * j3oj2 * sinio * (3.0 + 5.0 * cosio) / (1.0 + cosio); + else + satrec.xlcof = -0.25 * j3oj2 * sinio * (3.0 + 5.0 * cosio) / temp4; + satrec.aycof = -0.5 * j3oj2 * sinio; + // sgp4fix use multiply for speed instead of pow + delmotemp = 1.0 + satrec.eta * cos(satrec.mo); + satrec.delmo = delmotemp * delmotemp * delmotemp; + satrec.sinmao = sin(satrec.mo); + satrec.x7thm1 = 7.0 * cosio2 - 1.0; + + /* --------------- deep space initialization ------------- */ + if ((2*pi / satrec.no) >= 225.0) + { + satrec.method = 'd'; + satrec.isimp = 1; + tc = 0.0; + inclm = satrec.inclo; + + dscom + ( + epoch, satrec.ecco, satrec.argpo, tc, satrec.inclo, satrec.nodeo, + satrec.no, snodm, cnodm, sinim, cosim,sinomm, cosomm, + day, satrec.e3, satrec.ee2, em, emsq, gam, + satrec.peo, satrec.pgho, satrec.pho, satrec.pinco, + satrec.plo, rtemsq, satrec.se2, satrec.se3, + satrec.sgh2, satrec.sgh3, satrec.sgh4, + satrec.sh2, satrec.sh3, satrec.si2, satrec.si3, + satrec.sl2, satrec.sl3, satrec.sl4, s1, s2, s3, s4, s5, + s6, s7, ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3, + sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33, + satrec.xgh2, satrec.xgh3, satrec.xgh4, satrec.xh2, + satrec.xh3, satrec.xi2, satrec.xi3, satrec.xl2, + satrec.xl3, satrec.xl4, nm, z1, z2, z3, z11, + z12, z13, z21, z22, z23, z31, z32, z33, + satrec.zmol, satrec.zmos + ); + dpper + ( + satrec.e3, satrec.ee2, satrec.peo, satrec.pgho, + satrec.pho, satrec.pinco, satrec.plo, satrec.se2, + satrec.se3, satrec.sgh2, satrec.sgh3, satrec.sgh4, + satrec.sh2, satrec.sh3, satrec.si2, satrec.si3, + satrec.sl2, satrec.sl3, satrec.sl4, satrec.t, + satrec.xgh2,satrec.xgh3,satrec.xgh4, satrec.xh2, + satrec.xh3, satrec.xi2, satrec.xi3, satrec.xl2, + satrec.xl3, satrec.xl4, satrec.zmol, satrec.zmos, inclm, satrec.init, + satrec.ecco, satrec.inclo, satrec.nodeo, satrec.argpo, satrec.mo, + satrec.operationmode + ); + + argpm = 0.0; + nodem = 0.0; + mm = 0.0; + + dsinit + ( + whichconst, + cosim, emsq, satrec.argpo, s1, s2, s3, s4, s5, sinim, ss1, ss2, ss3, ss4, + ss5, sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33, satrec.t, tc, + satrec.gsto, satrec.mo, satrec.mdot, satrec.no, satrec.nodeo, + satrec.nodedot, xpidot, z1, z3, z11, z13, z21, z23, z31, z33, + satrec.ecco, eccsq, em, argpm, inclm, mm, nm, nodem, + satrec.irez, satrec.atime, + satrec.d2201, satrec.d2211, satrec.d3210, satrec.d3222 , + satrec.d4410, satrec.d4422, satrec.d5220, satrec.d5232, + satrec.d5421, satrec.d5433, satrec.dedt, satrec.didt, + satrec.dmdt, dndt, satrec.dnodt, satrec.domdt , + satrec.del1, satrec.del2, satrec.del3, satrec.xfact, + satrec.xlamo, satrec.xli, satrec.xni + ); + } + + /* ----------- set variables if not deep space ----------- */ + if (satrec.isimp != 1) + { + cc1sq = satrec.cc1 * satrec.cc1; + satrec.d2 = 4.0 * ao * tsi * cc1sq; + temp = satrec.d2 * tsi * satrec.cc1 / 3.0; + satrec.d3 = (17.0 * ao + sfour) * temp; + satrec.d4 = 0.5 * temp * ao * tsi * (221.0 * ao + 31.0 * sfour) * + satrec.cc1; + satrec.t3cof = satrec.d2 + 2.0 * cc1sq; + satrec.t4cof = 0.25 * (3.0 * satrec.d3 + satrec.cc1 * + (12.0 * satrec.d2 + 10.0 * cc1sq)); + satrec.t5cof = 0.2 * (3.0 * satrec.d4 + + 12.0 * satrec.cc1 * satrec.d3 + + 6.0 * satrec.d2 * satrec.d2 + + 15.0 * cc1sq * (2.0 * satrec.d2 + cc1sq)); + } + } // if omeosq = 0 ... + + /* finally propogate to zero epoch to initialize all others. */ + // sgp4fix take out check to let satellites process until they are actually below earth surface +// if(satrec.error == 0) + sgp4(whichconst, satrec, 0.0, r, v); + + satrec.init = 'n'; + +//#include "debug6.cpp" + //sgp4fix return boolean. satrec.error contains any error codes + return true; +} // end sgp4init + +/*----------------------------------------------------------------------------- +* +* procedure sgp4 +* +* this procedure is the sgp4 prediction model from space command. this is an +* updated and combined version of sgp4 and sdp4, which were originally +* published separately in spacetrack report #3. this version follows the +* methodology from the aiaa paper (2006) describing the history and +* development of the code. +* +* author : david vallado 719-573-2600 28 jun 2005 +* +* inputs : +* satrec - initialised structure from sgp4init() call. +* tsince - time eince epoch (minutes) +* +* outputs : +* r - position vector km +* v - velocity km/sec +* return code - non-zero on error. +* 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er +* 2 - mean motion less than 0.0 +* 3 - pert elements, ecc < 0.0 or ecc > 1.0 +* 4 - semi-latus rectum < 0.0 +* 5 - epoch elements are sub-orbital +* 6 - satellite has decayed +* +* locals : +* am - +* axnl, aynl - +* betal - +* cosim , sinim , cosomm , sinomm , cnod , snod , cos2u , +* sin2u , coseo1 , sineo1 , cosi , sini , cosip , sinip , +* cosisq , cossu , sinsu , cosu , sinu +* delm - +* delomg - +* dndt - +* eccm - +* emsq - +* ecose - +* el2 - +* eo1 - +* eccp - +* esine - +* argpm - +* argpp - +* omgadf - +* pl - +* r - +* rtemsq - +* rdotl - +* rl - +* rvdot - +* rvdotl - +* su - +* t2 , t3 , t4 , tc +* tem5, temp , temp1 , temp2 , tempa , tempe , templ +* u , ux , uy , uz , vx , vy , vz +* inclm - inclination +* mm - mean anomaly +* nm - mean motion +* nodem - right asc of ascending node +* xinc - +* xincp - +* xl - +* xlm - +* mp - +* xmdf - +* xmx - +* xmy - +* nodedf - +* xnode - +* nodep - +* np - +* +* coupling : +* getgravconst- +* dpper +* dpspace +* +* references : +* hoots, roehrich, norad spacetrack report #3 1980 +* hoots, norad spacetrack report #6 1986 +* hoots, schumacher and glover 2004 +* vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + +bool sgp4 + ( + gravconsttype whichconst, elsetrec& satrec, double tsince, + double r[3], double v[3] + ) +{ + double am , axnl , aynl , betal , cosim , cnod , + cos2u, coseo1, cosi , cosip , cosisq, cossu , cosu, + delm , delomg, em , emsq , ecose , el2 , eo1 , + ep , esine , argpm, argpp , argpdf, pl, mrt = 0.0, + mvt , rdotl , rl , rvdot , rvdotl, sinim , + sin2u, sineo1, sini , sinip , sinsu , sinu , + snod , su , t2 , t3 , t4 , tem5 , temp, + temp1, temp2 , tempa, tempe , templ , u , ux , + uy , uz , vx , vy , vz , inclm , mm , + nm , nodem, xinc , xincp , xl , xlm , mp , + xmdf , xmx , xmy , nodedf, xnode , nodep, tc , dndt, + twopi, x2o3 , j2 , j3 , tumin, j4 , xke , j3oj2, radiusearthkm, + mu, vkmpersec, delmtemp; + int ktr; + + /* ------------------ set mathematical constants --------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + const double temp4 = 1.5e-12; + twopi = 2.0 * pi; + x2o3 = 2.0 / 3.0; + // sgp4fix identify constants and allow alternate values + getgravconst( whichconst, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 ); + vkmpersec = radiusearthkm * xke/60.0; + + /* --------------------- clear sgp4 error flag ----------------- */ + satrec.t = tsince; + satrec.error = 0; + + /* ------- update for secular gravity and atmospheric drag ----- */ + xmdf = satrec.mo + satrec.mdot * satrec.t; + argpdf = satrec.argpo + satrec.argpdot * satrec.t; + nodedf = satrec.nodeo + satrec.nodedot * satrec.t; + argpm = argpdf; + mm = xmdf; + t2 = satrec.t * satrec.t; + nodem = nodedf + satrec.nodecf * t2; + tempa = 1.0 - satrec.cc1 * satrec.t; + tempe = satrec.bstar * satrec.cc4 * satrec.t; + templ = satrec.t2cof * t2; + + if (satrec.isimp != 1) + { + delomg = satrec.omgcof * satrec.t; + // sgp4fix use mutliply for speed instead of pow + delmtemp = 1.0 + satrec.eta * cos(xmdf); + delm = satrec.xmcof * + (delmtemp * delmtemp * delmtemp - + satrec.delmo); + temp = delomg + delm; + mm = xmdf + temp; + argpm = argpdf - temp; + t3 = t2 * satrec.t; + t4 = t3 * satrec.t; + tempa = tempa - satrec.d2 * t2 - satrec.d3 * t3 - + satrec.d4 * t4; + tempe = tempe + satrec.bstar * satrec.cc5 * (sin(mm) - + satrec.sinmao); + templ = templ + satrec.t3cof * t3 + t4 * (satrec.t4cof + + satrec.t * satrec.t5cof); + } + + nm = satrec.no; + em = satrec.ecco; + inclm = satrec.inclo; + if (satrec.method == 'd') + { + tc = satrec.t; + dspace + ( + satrec.irez, + satrec.d2201, satrec.d2211, satrec.d3210, + satrec.d3222, satrec.d4410, satrec.d4422, + satrec.d5220, satrec.d5232, satrec.d5421, + satrec.d5433, satrec.dedt, satrec.del1, + satrec.del2, satrec.del3, satrec.didt, + satrec.dmdt, satrec.dnodt, satrec.domdt, + satrec.argpo, satrec.argpdot, satrec.t, tc, + satrec.gsto, satrec.xfact, satrec.xlamo, + satrec.no, satrec.atime, + em, argpm, inclm, satrec.xli, mm, satrec.xni, + nodem, dndt, nm + ); + } // if method = d + + if (nm <= 0.0) + { +// printf("# error nm %f\n", nm); + satrec.error = 2; + // sgp4fix add return + return false; + } + am = pow((xke / nm),x2o3) * tempa * tempa; + nm = xke / pow(am, 1.5); + em = em - tempe; + + // fix tolerance for error recognition + // sgp4fix am is fixed from the previous nm check + if ((em >= 1.0) || (em < -0.001)/* || (am < 0.95)*/ ) + { +// printf("# error em %f\n", em); + satrec.error = 1; + // sgp4fix to return if there is an error in eccentricity + return false; + } + // sgp4fix fix tolerance to avoid a divide by zero + if (em < 1.0e-6) + em = 1.0e-6; + mm = mm + satrec.no * templ; + xlm = mm + argpm + nodem; + emsq = em * em; + temp = 1.0 - emsq; + + nodem = floatmod(nodem, twopi); + argpm = floatmod(argpm, twopi); + xlm = floatmod(xlm, twopi); + mm = floatmod(xlm - argpm - nodem, twopi); + + /* ----------------- compute extra mean quantities ------------- */ + sinim = sin(inclm); + cosim = cos(inclm); + + /* -------------------- add lunar-solar periodics -------------- */ + ep = em; + xincp = inclm; + argpp = argpm; + nodep = nodem; + mp = mm; + sinip = sinim; + cosip = cosim; + if (satrec.method == 'd') + { + dpper + ( + satrec.e3, satrec.ee2, satrec.peo, + satrec.pgho, satrec.pho, satrec.pinco, + satrec.plo, satrec.se2, satrec.se3, + satrec.sgh2, satrec.sgh3, satrec.sgh4, + satrec.sh2, satrec.sh3, satrec.si2, + satrec.si3, satrec.sl2, satrec.sl3, + satrec.sl4, satrec.t, satrec.xgh2, + satrec.xgh3, satrec.xgh4, satrec.xh2, + satrec.xh3, satrec.xi2, satrec.xi3, + satrec.xl2, satrec.xl3, satrec.xl4, + satrec.zmol, satrec.zmos, satrec.inclo, + 'n', ep, xincp, nodep, argpp, mp, satrec.operationmode + ); + if (xincp < 0.0) + { + xincp = -xincp; + nodep = nodep + pi; + argpp = argpp - pi; + } + if ((ep < 0.0 ) || ( ep > 1.0)) + { +// printf("# error ep %f\n", ep); + satrec.error = 3; + // sgp4fix add return + return false; + } + } // if method = d + + /* -------------------- long period periodics ------------------ */ + if (satrec.method == 'd') + { + sinip = sin(xincp); + cosip = cos(xincp); + satrec.aycof = -0.5*j3oj2*sinip; + // sgp4fix for divide by zero for xincp = 180 deg + if (fabs(cosip+1.0) > 1.5e-12) + satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) / (1.0 + cosip); + else + satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) / temp4; + } + axnl = ep * cos(argpp); + temp = 1.0 / (am * (1.0 - ep * ep)); + aynl = ep* sin(argpp) + temp * satrec.aycof; + xl = mp + argpp + nodep + temp * satrec.xlcof * axnl; + + /* --------------------- solve kepler's equation --------------- */ + u = floatmod(xl - nodep, twopi); + eo1 = u; + tem5 = 9999.9; + ktr = 1; + // sgp4fix for kepler iteration + // the following iteration needs better limits on corrections + while (( fabs(tem5) >= 1.0e-12) && (ktr <= 10) ) + { + sineo1 = sin(eo1); + coseo1 = cos(eo1); + tem5 = 1.0 - coseo1 * axnl - sineo1 * aynl; + tem5 = (u - aynl * coseo1 + axnl * sineo1 - eo1) / tem5; + if(fabs(tem5) >= 0.95) + tem5 = tem5 > 0.0 ? 0.95 : -0.95; + eo1 = eo1 + tem5; + ktr = ktr + 1; + } + + /* ------------- short period preliminary quantities ----------- */ + ecose = axnl*coseo1 + aynl*sineo1; + esine = axnl*sineo1 - aynl*coseo1; + el2 = axnl*axnl + aynl*aynl; + pl = am*(1.0-el2); + if (pl < 0.0) + { +// printf("# error pl %f\n", pl); + satrec.error = 4; + // sgp4fix add return + return false; + } + else + { + rl = am * (1.0 - ecose); + rdotl = sqrt(am) * esine/rl; + rvdotl = sqrt(pl) / rl; + betal = sqrt(1.0 - el2); + temp = esine / (1.0 + betal); + sinu = am / rl * (sineo1 - aynl - axnl * temp); + cosu = am / rl * (coseo1 - axnl + aynl * temp); + su = atan2(sinu, cosu); + sin2u = (cosu + cosu) * sinu; + cos2u = 1.0 - 2.0 * sinu * sinu; + temp = 1.0 / pl; + temp1 = 0.5 * j2 * temp; + temp2 = temp1 * temp; + + /* -------------- update for short period periodics ------------ */ + if (satrec.method == 'd') + { + cosisq = cosip * cosip; + satrec.con41 = 3.0*cosisq - 1.0; + satrec.x1mth2 = 1.0 - cosisq; + satrec.x7thm1 = 7.0*cosisq - 1.0; + } + mrt = rl * (1.0 - 1.5 * temp2 * betal * satrec.con41) + + 0.5 * temp1 * satrec.x1mth2 * cos2u; + su = su - 0.25 * temp2 * satrec.x7thm1 * sin2u; + xnode = nodep + 1.5 * temp2 * cosip * sin2u; + xinc = xincp + 1.5 * temp2 * cosip * sinip * cos2u; + mvt = rdotl - nm * temp1 * satrec.x1mth2 * sin2u / xke; + rvdot = rvdotl + nm * temp1 * (satrec.x1mth2 * cos2u + + 1.5 * satrec.con41) / xke; + + /* --------------------- orientation vectors ------------------- */ + sinsu = sin(su); + cossu = cos(su); + snod = sin(xnode); + cnod = cos(xnode); + sini = sin(xinc); + cosi = cos(xinc); + xmx = -snod * cosi; + xmy = cnod * cosi; + ux = xmx * sinsu + cnod * cossu; + uy = xmy * sinsu + snod * cossu; + uz = sini * sinsu; + vx = xmx * cossu - cnod * sinsu; + vy = xmy * cossu - snod * sinsu; + vz = sini * cossu; + + /* --------- position and velocity (in km and km/sec) ---------- */ + r[0] = (mrt * ux)* radiusearthkm; + r[1] = (mrt * uy)* radiusearthkm; + r[2] = (mrt * uz)* radiusearthkm; + v[0] = (mvt * ux + rvdot * vx) * vkmpersec; + v[1] = (mvt * uy + rvdot * vy) * vkmpersec; + v[2] = (mvt * uz + rvdot * vz) * vkmpersec; + } // if pl > 0 + + // sgp4fix for decaying satellites + if (mrt < 1.0) + { +// printf("# decay condition %11.6f \n",mrt); + satrec.error = 6; + return false; + } + +//#include "debug7.cpp" + return true; +} // end sgp4 + + +/* ----------------------------------------------------------------------------- +* +* function gstime +* +* this function finds the greenwich sidereal time. +* +* author : david vallado 719-573-2600 1 mar 2001 +* +* inputs description range / units +* jdut1 - julian date in ut1 days from 4713 bc +* +* outputs : +* gstime - greenwich sidereal time 0 to 2pi rad +* +* locals : +* temp - temporary variable for doubles rad +* tut1 - julian centuries from the +* jan 1, 2000 12 h epoch (ut1) +* +* coupling : +* none +* +* references : +* vallado 2004, 191, eq 3-45 +* --------------------------------------------------------------------------- */ + +double gstime + ( + double jdut1 + ) + { + const double twopi = 2.0 * pi; + const double deg2rad = pi / 180.0; + double temp, tut1; + + tut1 = (jdut1 - 2451545.0) / 36525.0; + temp = -6.2e-6* tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + + (876600.0*3600 + 8640184.812866) * tut1 + 67310.54841; // sec + temp = floatmod(temp * deg2rad / 240.0, twopi); //360/86400 = 1/240, to deg, to rad + + // ------------------------ check quadrants --------------------- + if (temp < 0.0) + temp += twopi; + + return temp; + } // end gstime + + +/* ----------------------------------------------------------------------------- +* +* function getgravconst +* +* this function gets constants for the propagator. note that mu is identified to +* facilitiate comparisons with newer models. the common useage is wgs72. +* +* author : david vallado 719-573-2600 21 jul 2006 +* +* inputs : +* whichconst - which set of constants to use wgs72old, wgs72, wgs84 +* +* outputs : +* tumin - minutes in one time unit +* mu - earth gravitational parameter +* radiusearthkm - radius of the earth in km +* xke - reciprocal of tumin +* j2, j3, j4 - un-normalized zonal harmonic values +* j3oj2 - j3 divided by j2 +* +* locals : +* +* coupling : +* none +* +* references : +* norad spacetrack report #3 +* vallado, crawford, hujsak, kelso 2006 + --------------------------------------------------------------------------- */ + +void getgravconst + ( + gravconsttype whichconst, + double& tumin, + double& mu, + double& radiusearthkm, + double& xke, + double& j2, + double& j3, + double& j4, + double& j3oj2 + ) + { + + switch (whichconst) + { + // -- wgs-72 low precision str#3 constants -- + case wgs72old: + mu = 398600.79964; // in km3 / s2 + radiusearthkm = 6378.135; // km + xke = 0.0743669161; + tumin = 1.0 / xke; + j2 = 0.001082616; + j3 = -0.00000253881; + j4 = -0.00000165597; + j3oj2 = j3 / j2; + break; + // ------------ wgs-72 constants ------------ + case wgs72: + mu = 398600.8; // in km3 / s2 + radiusearthkm = 6378.135; // km + xke = 60.0 / sqrt(radiusearthkm*radiusearthkm*radiusearthkm/mu); + tumin = 1.0 / xke; + j2 = 0.001082616; + j3 = -0.00000253881; + j4 = -0.00000165597; + j3oj2 = j3 / j2; + break; + case wgs84: + // ------------ wgs-84 constants ------------ + mu = 398600.5; // in km3 / s2 + radiusearthkm = 6378.137; // km + xke = 60.0 / sqrt(radiusearthkm*radiusearthkm*radiusearthkm/mu); + tumin = 1.0 / xke; + j2 = 0.00108262998905; + j3 = -0.00000253215306; + j4 = -0.00000161098761; + j3oj2 = j3 / j2; + break; + default: + //fprintf(stderr,"unknown gravity option (%d)\n",whichconst); + break; + } + + } // end getgravconst + + + + + diff --git a/lib/Sgp4/sgp4unit.h b/lib/Sgp4/sgp4unit.h new file mode 100644 index 0000000..c232aca --- /dev/null +++ b/lib/Sgp4/sgp4unit.h @@ -0,0 +1,132 @@ +#ifndef _sgp4unit_ +#define _sgp4unit_ +/* ---------------------------------------------------------------- +* +* sgp4unit.h +* +* this file contains the sgp4 procedures for analytical propagation +* of a satellite. the code was originally released in the 1980 and 1986 +* spacetrack papers. a detailed discussion of the theory and history +* may be found in the 2006 aiaa paper by vallado, crawford, hujsak, +* and kelso. +* +* companion code for +* fundamentals of astrodynamics and applications +* 2007 +* by david vallado +* +* (w) 719-573-2600, email dvallado@agi.com +* +* current : +* 30 Dec 11 david vallado +* consolidate updated code version +* 30 Aug 10 david vallado +* delete unused variables in initl +* replace pow inetger 2, 3 with multiplies for speed +* changes : +* 3 Nov 08 david vallado +* put returns in for error codes +* 29 sep 08 david vallado +* fix atime for faster operation in dspace +* add operationmode for afspc (a) or improved (i) +* performance mode +* 20 apr 07 david vallado +* misc fixes for constants +* 11 aug 06 david vallado +* chg lyddane choice back to strn3, constants, misc doc +* 15 dec 05 david vallado +* misc fixes +* 26 jul 05 david vallado +* fixes for paper +* note that each fix is preceded by a +* comment with "sgp4fix" and an explanation of +* what was changed +* 10 aug 04 david vallado +* 2nd printing baseline working +* 14 may 01 david vallado +* 2nd edition baseline +* 80 norad +* original baseline +* ---------------------------------------------------------------- */ + +#include +#include +#define SGP4Version "SGP4 Version 2011-12-30" + +#define pi 3.14159265358979323846 + +// -------------------------- structure declarations ---------------------------- +typedef enum +{ + wgs72old, + wgs72, + wgs84 +} gravconsttype; + +typedef struct elsetrec +{ + long int satnum; + int epochyr, epochtynumrev; + int error; + char operationmode; + char init, method; + + /* Near Earth */ + int isimp; + double aycof , con41 , cc1 , cc4 , cc5 , d2 , d3 , d4 , + delmo , eta , argpdot, omgcof , sinmao , t , t2cof, t3cof , + t4cof , t5cof , x1mth2 , x7thm1 , mdot , nodedot, xlcof , xmcof , + nodecf; + + /* Deep Space */ + int irez; + double d2201 , d2211 , d3210 , d3222 , d4410 , d4422 , d5220 , d5232 , + d5421 , d5433 , dedt , del1 , del2 , del3 , didt , dmdt , + dnodt , domdt , e3 , ee2 , peo , pgho , pho , pinco , + plo , se2 , se3 , sgh2 , sgh3 , sgh4 , sh2 , sh3 , + si2 , si3 , sl2 , sl3 , sl4 , gsto , xfact , xgh2 , + xgh3 , xgh4 , xh2 , xh3 , xi2 , xi3 , xl2 , xl3 , + xl4 , xlamo , zmol , zmos , atime , xli , xni; + + double a , altp , alta , epochdays, jdsatepoch , nddot , ndot , + bstar , rcse , inclo , nodeo , ecco , argpo , mo , + no; +} elsetrec; + + +// --------------------------- function declarations ---------------------------- +bool sgp4init + ( + gravconsttype whichconst, char opsmode, const int satn, const double epoch, + const double xbstar, const double xecco, const double xargpo, + const double xinclo, const double xmo, const double xno, + const double xnodeo, elsetrec& satrec + ); + +bool sgp4 + ( + gravconsttype whichconst, elsetrec& satrec, double tsince, + double r[3], double v[3] + ); + +double gstime + ( + double jdut1 + ); + +void getgravconst + ( + gravconsttype whichconst, + double& tumin, + double& mu, + double& radiusearthkm, + double& xke, + double& j2, + double& j3, + double& j4, + double& j3oj2 + ); + + +#endif + diff --git a/lib/Sgp4/visible.cpp b/lib/Sgp4/visible.cpp new file mode 100644 index 0000000..f7ffd23 --- /dev/null +++ b/lib/Sgp4/visible.cpp @@ -0,0 +1,203 @@ +#include "visible.h" +#include + +#define sunradius 695500 //km +#define earthradius 6378.137 //km +#define au 149597871 //km + +/* +This file contains miscellaneous functions required for calculating visible satellites. +Some functions were originally written for Matlab as companion code for "Fundamentals of Astrodynamics +and Applications" by David Vallado (2007). (w) 719-573-2600, email dvallado@agi.com + +Ported to C++ by Hopperpop with some modifications, November 2015. +*/ + +/* +% ------------------------------------------------------------------------------ +% +% function sun +% +% this function calculates the geocentric equatorial position vector +% the sun given the julian date. this is the low precision formula and +% is valid for years from 1950 to 2050. accuaracy of apparent coordinates +% is 0.01 degrees. notice many of the calculations are performed in +% degrees, and are not changed until later. this is due to the fact that +% the almanac uses degrees exclusively in their formulations. +% +% author : david vallado 719-573-2600 27 may 2002 +% +% revisions +% vallado - fix mean lon of sun 7 mat 2004 +% +% inputs description range / units +% jdC - julian date days from 4713 bc +% +% outputs : +% rsun - ijk position vector of the sun km + +% locals : +% meanlong - mean longitude +% meananomaly - mean anomaly +% eclplong - ecliptic longitude +% obliquity - mean obliquity of the ecliptic +% tut1 - julian centuries of ut1 from +% jan 1, 2000 12h +% ttdb - julian centuries of tdb from +% jan 1, 2000 12h +% hr - hours 0 .. 24 10 +% min - minutes 0 .. 59 15 +% sec - seconds 0.0 .. 59.99 30.00 +% temp - temporary variable +% deg - degrees +% +% coupling : +% none. +% +% references : +% vallado 2007, 281, alg 29, ex 5-1 +% +% [rsun,rtasc,decl] = sun ( jdC ); +% ------------------------------------------------------------------------------ +*/ + +void sun ( double jd, double rsun[3] ){ + + double twopi = 2.0*pi; + double deg2rad = pi/180.0; + + // ------------------------- implementation ----------------- + // ------------------- initialize values -------------------- + double tut1 = ( jd - 2451545.0 )/ 36525.0; + + double meanlong = 280.460 + 36000.77 * tut1; + meanlong = floatmod( meanlong, 360.0 ); //deg + + double meananomaly = 357.5277233 + 35999.05034 * tut1; + meananomaly = floatmod( meananomaly*deg2rad,twopi ); //rad + if ( meananomaly < 0.0 ){ + meananomaly= twopi + meananomaly; + } + + double eclplong= meanlong + 1.914666471 * sin(meananomaly)+ 0.019994643 * sin(2.0 *meananomaly); //deg + eclplong= floatmod( eclplong, 360.0 ); //deg + + double obliquity= 23.439291 - 0.0130042 * tut1; //deg + + eclplong = eclplong *deg2rad; + obliquity = obliquity *deg2rad; + + // --------- find magnitude of sun vector, ) components ------ + double magr= 1.000140612 - 0.016708617 *cos( meananomaly ) - 0.000139589 *cos( 2.0 *meananomaly ); // in au's + + rsun[0]= magr*cos( eclplong )*au; + rsun[1]= magr*cos(obliquity)*sin(eclplong)*au; + rsun[2]= magr*sin(obliquity)*sin(eclplong)*au; + +} + +//returns angle between sun surface and earth surface, from the viewpoint of the satellite +double Sgp4::visiblewrap(double jdCe) { + double rsun[3]; //vector between earth and sun + double razell[3]; + + sun(jdC, rsun); //calculate sun poistion vector + rv2azel(rsun, siteLatRad, siteLonRad, siteAlt, jdC, razell); //calc sun satEl + + double rsunsat[3]; //vector between sat and sun + double rearth[3]; + double magsunsat, magearth; + double phiearth, phisun, phi; + double rnomearth, rnomsun; + + sgp4wrap(jdCe); + + rearth[0] = -ro[0]; + rearth[1] = -ro[1]; + rearth[2] = -ro[2]; + + rsunsat[0] = rsun[0] + rearth[0]; + rsunsat[1] = rsun[1] + rearth[1]; + rsunsat[2] = rsun[2] + rearth[2]; + + magsunsat = mag(rsunsat); + magearth = mag(rearth); + + phiearth = asin(earthradius / magearth); + phisun = asin(sunradius / magsunsat); + + phi = acos(dot(rearth, rsunsat) / magsunsat / magearth); + + return phi - phisun - phiearth; ///grens op bijschaduw + //return -phiearth + phisun + phi; ///grens op echte schaduw + +} + + +//calculate if satellite is visible +int16_t Sgp4::visible(bool& notdark, double& deltaphi){ + + double rsun[3]; //vector between earth and sun + double razell[3]; + + sun(jdC, rsun); //calculate sun poistion vector + rv2azel(rsun, siteLatRad, siteLonRad, siteAlt, jdC, razell); //calc sun satEl + + sunEl = razell[2] * 180 / pi; + sunAz = razell[1] * 180 / pi; + notdark = (razell[2] > sunoffset); //sun aboven -6° => not dark enough + + double rsunsat[3]; //vector between sat and sun + double rearth[3]; + double magsunsat, magearth; + double phiearth, phisun, phi; + double rnomearth, rnomsun; + + rearth[0] = -ro[0]; + rearth[1] = -ro[1]; + rearth[2] = -ro[2]; + + rsunsat[0] = rsun[0] + rearth[0]; + rsunsat[1] = rsun[1] + rearth[1]; + rsunsat[2] = rsun[2] + rearth[2]; + + magsunsat = mag(rsunsat); + magearth = mag(rearth); + + phiearth = asin(earthradius/magearth); + phisun = asin(sunradius/magsunsat); + + phi = acos(dot(rearth,rsunsat)/magsunsat/magearth); + deltaphi = phi - phisun - phiearth; + + if (phiearth > phisun && phi < phiearth - phisun){ //umbral eclipse + return 0; + } + + if (phiearth < phisun && phi < phisun - phiearth){ //partial eclipse + return (int16_t)(( 1 - phiearth*phiearth/(phisun*phisun) )*1000); //approach to the surface coverage with a square sun and earth + } + + if (fabs(phiearth-phisun) < phi && phi < phiearth + phisun){ //penumbral eclipse + if (phiearth > phisun){ + return (int16_t)(( (phisun+phi-phiearth)/(phisun*2.0) )*1000); //approach to the surface coverage with a square sun and earth + }else{ + return (int16_t)(( 1 - phiearth*(phisun - phi + phiearth)/(2.0*phisun*phisun) )*1000); //approach to the surface coverage with a square sun and earth + } + } + + return 1000; //no eclipse => visible + +} + +int16_t Sgp4::visible() { + bool notdark; + double deltaphi; + int16_t viss = visible(notdark,deltaphi); + if (notdark) { + return -1; + } + else { + return viss; + } +} diff --git a/lib/Sgp4/visible.h b/lib/Sgp4/visible.h new file mode 100644 index 0000000..1fd9f16 --- /dev/null +++ b/lib/Sgp4/visible.h @@ -0,0 +1,20 @@ +/* +This file contains miscellaneous functions required for calculating visible satellits. +Functions were originally written for Matlab as companion code for "Fundamentals of Astrodynamics +and Applications" by David Vallado (2007). (w) 719-573-2600, email dvallado@agi.com + +Ported to C++ by Bram Gurdebeke with some modifications, November 2015. +*/ + +#ifndef _visible_ +#define _visible_ + +#include "sgp4unit.h" +#include "sgp4ext.h" +#include "sgp4pred.h" +#include + +void sun ( double jd, double rsun[3] ); //calculates sun coordinates + + +#endif diff --git a/partitions_16MB_dualboot.csv b/partitions_16MB_dualboot.csv new file mode 100644 index 0000000..bcfa7b6 --- /dev/null +++ b/partitions_16MB_dualboot.csv @@ -0,0 +1,33 @@ +# The Orb + Capsule Radar, dual-boot 16 MB layout. +# +# Derived from partitions_16MB_themeart.csv. The Orb keeps its 6.25 MB app slot and nvs keeps +# its stock offset and size, so stored WiFi credentials and settings survive the change. What +# moves: +# +# otadata (8 KB at 0xE000, the gap the old table left unused) — records which app slot the +# bootloader starts. The Orb's Settings > Flight radar writes it to start Capsule Radar, +# and Capsule Radar writes it back when its knob is pressed. +# +# app0 becomes ota_0 instead of factory. Same offset, same size, same image: only the +# subtype changes, so the boot-slot switch has two OTA slots to choose between. +# +# app1 (ota_1, 3.5 MB) — Capsule Radar. Its firmware is ~3.0 MB. +# +# themeart shrinks from 9.6 MB to 6.1 MB to pay for it. One rich theme is ~3.8 MB +# (theme_art.cpp FULL_THEME_BYTES = 4 MB), so the active theme still stays resident; fewer +# OTHER themes stay baked alongside it, so switching to one of those re-bakes once. +# theme_art.cpp finds the partition by name and sizes itself from the table, so nothing +# in the code has a number to change. The installer erases the first 64 KB of the new +# region, which is where theme_art keeps its index, so the first boot re-bakes cleanly +# instead of reading the old layout's pixels as an index. +# +# Wireless updates stay compiled out (ORB_OTA_ENABLED 0 in main.cpp): ota_1 is Capsule +# Radar's home, not a staging slot, and an OTA write would overwrite it. +# +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, 0x9000, 0x5000, +otadata, data, ota, 0xe000, 0x2000, +app0, app, ota_0, 0x10000, 0x640000, +app1, app, ota_1, 0x650000,0x380000, +themeart, data, 0x40, 0x9D0000,0x620000, +coredump, data, coredump,0xFF0000,0x10000, diff --git a/platformio.ini b/platformio.ini index e5b43fa..e9d288a 100644 --- a/platformio.ini +++ b/platformio.ini @@ -21,11 +21,9 @@ upload_speed = 921600 ; sim_main.cpp + sim_knob.cpp are desktop-only (own main() + SDL, and a software ; encoder that would clash with the real knob.cpp); native_http.cpp is the desktop ; libcurl transport (no libcurl on the ESP32 toolchain) — all three stay out of the firmware -; touch_cst9217.cpp is excluded on purpose: the Orb is knob-only (docs/ARCHITECTURE.md, -; and section 2 of orb-user-requirements.md). The driver stays in the repo, working and -; tested, so a future touch feature would not start from scratch, but it costs zero -; bytes while nothing registers a pointer indev. -build_src_filter = +<*> - - - - +; touch_cst9217.cpp is built again (ORB_TOUCH in config.h): main.cpp polls it for tap, +; drag, swipe and hold gestures that map onto the knob's. Still no LVGL pointer indev. +build_src_filter = +<*> - - - ; ESP32-S3R8: QIO flash + OPI PSRAM, 16 MB flash + matching partition table board_build.arduino.memory_type = qio_opi @@ -35,7 +33,7 @@ board_upload.flash_size = 16MB ; Stock default_16MB.csv with its never-used SPIFFS partition replaced by `themeart`: ; pre-baked RGB565 art, memory-mapped and drawn straight out of flash. nvs offset/size ; are byte-identical to the stock table, so saved WiFi credentials survive the switch. -board_build.partitions = partitions_16MB_themeart.csv +board_build.partitions = partitions_16MB_dualboot.csv ; TLS now uses mbedtls_platform_set_calloc_free() at boot (src/tls_memory.cpp), ; keeping stock libraries while explicitly allocating TLS buffers in PSRAM. @@ -97,7 +95,7 @@ platform = native ; so the simulator shows genuine RainViewer radar + real location data, not mock placeholders. ; wx_radar_client.cpp/roads.cpp/net_fetch.cpp/native_http.cpp are the fetch+decode+overlay ; pipeline; the weather client's own HTTP path branches the same way internally. -build_src_filter = -<*> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +build_src_filter = -<*> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ; PNGdec is a legacy Arduino-format library (library.properties, no library.json) — PIO's ; Library Dependency Finder drops it as "incompatible" with the native platform/no framework ; even though its source has zero Arduino dependency (verified: builds clean). Force it in. diff --git a/src/app_shell.h b/src/app_shell.h index 1bbbce9..757467d 100644 --- a/src/app_shell.h +++ b/src/app_shell.h @@ -88,13 +88,18 @@ namespace app_shell { enum Slot { APP_CLOCK = 0, APP_FLIGHT, -#if !APPS_LAUNCH_ONE +#if ORB_HAS_WEATHER APP_WEATHER, +#endif +#if !APPS_LAUNCH_ONE APP_SURVEILLANCE, #endif APP_INTEL, #if !APPS_LAUNCH_ONE APP_TICKER, +#endif +#if ORB_APP_SATS + APP_SATS, #endif APP_SETTINGS, APP_COUNT, diff --git a/src/config.h b/src/config.h index 5a0eeeb..3dd5f00 100644 --- a/src/config.h +++ b/src/config.h @@ -7,7 +7,7 @@ // "1.4.2", said "up to date", and left an Orb missing everything in that list. THEME_CAPS // exists because this stopped moving; it covers theme settings and nothing else, so a new // command or a deleted screen is invisible to it. Move this too. -#define FW_VERSION "2.18.01" // shown on the web config page + Stats screen +#define FW_VERSION "2.21.04" // shown on the web config page + Stats screen // Edit pins below: replace every -1 with the value from the Waveshare factory demo // (see docs/HARDWARE.md and docs/SETUP.md). Do NOT guess them. @@ -35,6 +35,17 @@ // device pretending it never understood them. #define APPS_LAUNCH_ONE 1 +// Owner's build (2026-11-17): the Weather Radar comes back, and two new things arrive. +// Each is its own switch so any one can be taken out again without touching the others. +// ORB_APP_WEATHER the weather map, on the menu whatever the theme's roster says (a theme +// made while the app was cut lists it as off, and the owner asked for it) +// ORB_APP_SATS Satellites: pass tracker (sat_tracker.*, sat_view.*) +// ORB_TOUCH the CST9217 touch panel: tap, swipe and drag (main.cpp, touch_*) +#define ORB_APP_WEATHER 1 +#define ORB_APP_SATS 1 +#define ORB_TOUCH 1 +#define ORB_HAS_WEATHER (!APPS_LAUNCH_ONE || ORB_APP_WEATHER) + // ---------- Home location ---------- // A PLACEHOLDER, and deliberately not a place. The device has exactly two location inputs // (UX-025): the network it joins, looked up at the end of WiFi setup and retried on any @@ -280,6 +291,11 @@ static const float RANGE_STEPS_KM[] = {10.0f, 20.0f, 30.0f, 50.0f, 100.0f}; #define I2C_ADDR_IMU 0x6B #define I2C_ADDR_RTC 0x51 #define I2C_ADDR_PMIC 0x34 +// TCA9554 I/O expander. The Orb drives nothing on it except the -G board's GPS reset line, +// which gps.cpp pulses (read-modify-write, P7 only) to recover a wedged LC76G. Taken from +// Capsule Radar's board_amoled_175.h, where it is field-verified. +#define I2C_ADDR_EXPANDER 0x20 +#define EXPANDER_GPS_RST_BIT 7 // EXIO7 -> LC76G RESET (active low) // Safety net: should never fire now that pins are filled in. Keeps future edits honest. #if (PIN_LCD_SCLK < 0) || (PIN_I2C_SDA < 0) diff --git a/src/gps.cpp b/src/gps.cpp index b99a742..483fe4f 100644 --- a/src/gps.cpp +++ b/src/gps.cpp @@ -11,56 +11,259 @@ // Wire.setBufferSize() at runtime fragments the internal heap and kills the mbedTLS handshake // (the ADS-B HTTPS feed). So we cap each read to one bufferful and let the rest come next poll. #include "gps.h" +#include "config.h" // I/O-expander address + GPS reset bit (1.75) #include #include #include #define GPS_ADDR_W 0x50 #define GPS_ADDR_R 0x54 +#define GPS_ADDR_DW 0x58 // data-write endpoint: command text goes here (see gps_write) #define GPS_SETTLE_MS 100 // settle between each protocol step (LC76G is fussy) -#define GPS_READ_MAX 720 // max bytes drained per transaction (kept small: a big Wire RX - // buffer steals the contiguous internal RAM the TLS feed needs) -#define GPS_BUF 768 // fixed Wire RX buffer (>= GPS_READ_MAX); set once, never resized -#define GPS_POLL_MS 2000 // poll often enough that a 720 B read keeps up with NMEA output -#define GPS_POLL_FIX_MS 60000 // once fixed, home is set — back right off (rare blocking hitch) -#define GPS_FIX_TTL_MS 70000 // how long a fix stays "valid" — must exceed GPS_POLL_FIX_MS so the - // fix doesn't expire between the 60 s polls (else it re-polls early) +// Read size + cadence reworked after issue #24 (@xatarsixnine-stack, field-verified): backing +// off to 60 s polls once fixed let the module's internal NMEA queue overflow, and a wedged +// LC76G stops answering until a full power cycle. The fix is to KEEP draining after the fix +// and to drain big enough to always outrun the NMEA output (multi-GNSS GSV bursts exceed +// 1 KB/s). 4 KB every 2 s is 4x that worst case. The bigger Wire RX buffer is still sized +// exactly once, in gps_begin() at boot BEFORE TLS comes up, and only on -G boards — the +// runtime-resize heap-fragmentation gotcha in the file header still stands. +// THE ORB: 2 KB rather than Capsule Radar's 4 KB. The Orb's internal heap is tighter (its TLS +// feed has needed every contiguous KB, see docs/memory.md), and once the sentence config below +// is acked the module only emits GGA + RMC (~150 B/s), so 2 KB per drain is >2x the 5 s +// cadence's worth. Before the ack the full-chatter bursts can exceed it briefly; the stall +// reset below recovers a module that overflows in that window. +#define GPS_READ_MAX 2048 // max bytes drained per transaction +#define GPS_BUF 2112 // fixed Wire RX buffer (>= GPS_READ_MAX); set once, never resized +#define GPS_POLL_MS 2000 // drain cadence until the sentence config is acked and we have a fix +#define GPS_POLL_SLOW_MS 5000 // THE ORB: cadence once trimmed + fixed. Each drain blocks loop() + // for ~300 ms of LC76G settle time, which the clock's hands and + // the knob feel; 5 s keeps that rare without starving the queue. +// The drain runs on the SAME core that serves the config web page, and a module that is +// absent, antenna-less or wedged makes every drain walk its slowest path (I2C timeouts, +// retries) — several BLOCKED seconds out of every two, which reads as "the web page will +// not save while GPS is on" (field report, v1.4.3). So: after a few drains in a row where +// the module never even answers, back off hard until one works. A healthy module keeps the +// full 2 s cadence and the #24 overflow fix intact. +#define GPS_POLL_DEAD_MS 30000 // cadence while the module is not answering at all +#define GPS_DEAD_TO_BACKOFF 3 // consecutive dead drains before backing off +#define GPS_FIX_TTL_MS 70000 // how long a fix stays "valid" without fresh sentences #define GPS_I2C_HZ 100000 // the read protocol is unreliable at the 400 kHz bus default #define GPS_BUS_HZ 400000 // restore the shared bus to this after each GPS transaction #define GPS_TIMEOUT_MS 1000 // the module clock-stretches while preparing data; 50 ms (default) times out #define BUS_TIMEOUT_MS 50 // restore the snappy default for touch/IMU/etc. +// Stuck-module recovery. A wedged LC76G (queue overflow, #24) streams nothing until it is +// restarted, and an OTA/soft reboot never power-cycles it (its VCC is the board's main 3V3 +// rail). On the 1.75 its RESET pin is on the TCA9554 expander, so we can restart it ourselves: +// once at every boot, and again whenever no NMEA has arrived for GPS_STALL_MS — which also +// covers "Use GPS" being switched back on after the module sat undrained and overflowed. +#define GPS_STALL_MS 30000 // no NMEA bytes for this long -> hardware reset +#define GPS_RESET_GAP_MS 60000 // at most one runtime reset a minute (a dead module can't loop us) +#define GPS_RESET_PULSE_MS 100 // RESET held low +#define GPS_BOOT_WAIT_MS 1500 // boot: wait up to this for the module to ACK again after reset +#define GPS_SETTLE_AFTER_MS 1000 // runtime: skip drains this long after a reset (module booting) +#define GPS_CFG_RETRY_MS 10000 // re-send the sentence config if not all acked by then +#define GPS_CFG_TRIES 3 // per reset. Keep writes rare: reportedly ~88 cumulative command + // writes can corrupt the module's parser (landracer/opendash) +#define GPS_CFG_MAX_PER_BOOT 10 // hard cap across ALL resets: a module that keeps re-wedging gets + // one reset a minute and one config write each, which would + // otherwise grind toward that limit over a long session +#define GPS_CFG_N 4 // commands in GPS_CFG_BODIES + +// TinyGPS++ only reads GGA + RMC. GSV (per-satellite detail, several sentences per +// constellation every second), GSA, GLL and VTG are dropped by the parser anyway, yet they are +// most of the I2C volume — the bursts that overflow the module's queue (#24) and stretch each +// blocking drain. Turn them off (Quectel $PAIR062,,0: 1 GLL, 2 GSA, 3 GSV, 5 VTG). Held in +// the module's backup RAM, so re-sent after every reset rather than saved to flash. +static const char *const GPS_CFG_BODIES[GPS_CFG_N] = { + "PAIR062,1,0", "PAIR062,2,0", "PAIR062,3,0", "PAIR062,5,0", +}; static const uint8_t QLEN[8] = { 0x08, 0x00, 0x51, 0xAA, 0x04, 0x00, 0x00, 0x00 }; // "how much is queued?" +static const uint8_t QFREE[8] = { 0x04, 0x00, 0x51, 0xAA, 0x04, 0x00, 0x00, 0x00 }; // "how much room to write?" static bool s_present = false; static TinyGPSPlus s_gps; +static uint8_t s_deadDrains = 0; // consecutive drains where the module never answered +static uint32_t s_lastDataMs = 0; // last drain that returned NMEA bytes +static uint32_t s_lastResetMs = 0; +static uint32_t s_settleUntil = 0; // no drains before this (module booting after a reset) +static uint16_t s_resets = 0; // hardware resets since boot (diagnostics) +static bool s_needCfg = false; // sentence config still to be sent/acked since the last reset +static uint8_t s_cfgTries = 0; +static uint8_t s_cfgWritesBoot = 0; // sentence-config writes since boot (see GPS_CFG_MAX_PER_BOOT) +static uint32_t s_cfgSentMs = 0; +static uint8_t s_cfgAcks = 0; // "$PAIR001,062,0" (success) replies seen since the last send +static bool s_cfgDone = false; // THE ORB: config acked since the last reset (slow cadence allowed) +static uint8_t s_ackPos = 0; // matcher state for those replies in the NMEA stream -// One blocking, uninterrupted drain of up to GPS_READ_MAX bytes into the parser. -// Returns bytes read (0 if nothing queued or a step failed). Caller has set 100 kHz + long timeout. -static int gps_drain() { - // 0) un-stick the module: other shared-bus traffic (LVGL polls the touch IC continuously - // between our calls) can leave the LC76G mid-response and unable to answer at 0x50; a - // stray 1-byte read at 0x54/0x58 kicks it back to normal (Quectel quirk). 1-byte reads, - // no extra RAM. +// ---------- hardware reset via the TCA9554 (1.75 board) ---------- +#ifdef I2C_ADDR_EXPANDER +static bool exp_read(uint8_t reg, uint8_t *v) { + Wire.beginTransmission(I2C_ADDR_EXPANDER); Wire.write(reg); + if (Wire.endTransmission() != 0) return false; + if (Wire.requestFrom((uint8_t)I2C_ADDR_EXPANDER, (uint8_t)1) != 1) return false; + *v = Wire.read(); + return true; +} +static bool exp_write(uint8_t reg, uint8_t v) { + Wire.beginTransmission(I2C_ADDR_EXPANDER); Wire.write(reg); Wire.write(v); + return Wire.endTransmission() == 0; +} +// Pulse the LC76G's RESET low. Read-modify-write so only P7 changes: the other EXIO pins are +// interrupt/status inputs. Released by returning P7 to an input (its power-on state; the +// module's own pull-up then holds RESET high). Returns false when there is no expander. +static bool gps_hw_reset() { + const uint8_t bit = (uint8_t)(1u << EXPANDER_GPS_RST_BIT); + uint8_t out, cfg; + if (!exp_read(0x01, &out) || !exp_read(0x03, &cfg)) return false; // 0x01 output, 0x03 config (1 = input) + if (!exp_write(0x01, out & ~bit)) return false; // latch LOW first so the switch to output can't glitch HIGH + if (!exp_write(0x03, cfg & ~bit)) return false; // P7 output -> RESET asserted + // Self-check via the input register (0x00), which reports the real pin level even for an + // output: LOW while asserted proves the writes reached P7 and it drives the line; HIGH after + // release proves the module's pull-up took it back. Logged every reset. + uint8_t in = 0xFF; + const bool lowOk = exp_read(0x00, &in) && !(in & bit); + delay(GPS_RESET_PULSE_MS); + bool released = false; // never leave RESET asserted: that would kill GPS + for (int t = 0; t < 3 && !released; ++t) released = exp_write(0x03, cfg | bit); + delay(2); + in = 0x00; + const bool highOk = released && exp_read(0x00, &in) && (in & bit); + Serial.printf("[gps] reset pulse: P7 low=%s released=%s\n", lowOk ? "ok" : "FAIL", highOk ? "ok" : "FAIL"); + return released; +} +#else +static bool gps_hw_reset() { return false; } // no reset line on this board +#endif + +// After a reset: fresh stall timer, forget the dead-drain backoff, and re-send the sentence config. +static void gps_after_reset(uint32_t now) { + ++s_resets; + s_lastResetMs = now; + s_lastDataMs = now; + s_deadDrains = 0; + s_needCfg = true; + s_cfgDone = false; + s_cfgTries = 0; + s_cfgAcks = 0; +} + +// Spot "$PAIR001,062,0" replies (command 062 accepted) in the byte stream. +static void gps_scan_ack(char c) { + static const char PFX[] = "$PAIR001,062,"; + if (s_ackPos == sizeof(PFX) - 1) { + if (c == '0' && s_cfgAcks < 255) ++s_cfgAcks; + s_ackPos = 0; + } else if (c == PFX[s_ackPos]) { + ++s_ackPos; + } else { + s_ackPos = (c == '$') ? 1 : 0; + } +} + +// Send raw command text to the module (Quectel I2C write, same settle rules as the read path): +// ask for free RX space at 0x50/0x54, announce the length at 0x50, then write the bytes to 0x58. +static bool gps_write(const uint8_t *data, uint32_t len) { + Wire.beginTransmission(GPS_ADDR_W); Wire.write(QFREE, sizeof(QFREE)); + if (Wire.endTransmission() != 0) return false; + delay(GPS_SETTLE_MS); + if (Wire.requestFrom((uint8_t)GPS_ADDR_R, (uint8_t)4) != 4) return false; + uint32_t room = (uint32_t)Wire.read(); + room |= (uint32_t)Wire.read() << 8; + room |= (uint32_t)Wire.read() << 16; + room |= (uint32_t)Wire.read() << 24; + if (room != 0 && room < len) { // 0 has been seen from modules that still accept the write + Serial.printf("[gps] cmd: only %lu bytes free, need %lu\n", (unsigned long)room, (unsigned long)len); + return false; + } + const uint8_t cw[8] = { 0x00, 0x10, 0x53, 0xAA, + (uint8_t)len, (uint8_t)(len >> 8), (uint8_t)(len >> 16), (uint8_t)(len >> 24) }; + delay(GPS_SETTLE_MS); + Wire.beginTransmission(GPS_ADDR_W); Wire.write(cw, sizeof(cw)); + if (Wire.endTransmission() != 0) return false; + delay(GPS_SETTLE_MS); + Wire.beginTransmission(GPS_ADDR_DW); Wire.write(data, len); + return Wire.endTransmission() == 0; +} + +// All config commands in ONE write (the module parses its RX stream like a UART), so each +// attempt costs a single command-write sequence. +static void gps_send_config(uint32_t now) { + char buf[128]; + size_t n = 0; + for (int i = 0; i < GPS_CFG_N; ++i) { + uint8_t cs = 0; + for (const char *p = GPS_CFG_BODIES[i]; *p; ++p) cs ^= (uint8_t)*p; + n += snprintf(buf + n, sizeof(buf) - n, "$%s*%02X\r\n", GPS_CFG_BODIES[i], cs); + } + ++s_cfgTries; + s_cfgSentMs = now; + s_cfgAcks = 0; + const bool ok = gps_write((const uint8_t *)buf, (uint32_t)n); + Serial.printf("[gps] sentence config (GGA+RMC only) sent: %s, try %u/%u\n", + ok ? "ok" : "FAILED", (unsigned)s_cfgTries, (unsigned)GPS_CFG_TRIES); +} + +// Un-stick the module: other shared-bus traffic (LVGL polls the touch IC continuously +// between our calls) can leave the LC76G mid-response and unable to answer at 0x50; a +// stray 1-byte read at 0x54/0x58 kicks it back to normal (Quectel quirk). 1-byte reads, +// no extra RAM. Costs up to two I2C timeouts against a dead module, so callers only run +// it when the quick path has actually failed. +static void gps_unstick() { Wire.requestFrom((uint8_t)GPS_ADDR_R, (uint8_t)1); while (Wire.available()) Wire.read(); Wire.requestFrom((uint8_t)0x58, (uint8_t)1); while (Wire.available()) Wire.read(); +} - // 1) query how many bytes are queued — retry, since prior shared-bus traffic can briefly - // leave the module unable to answer the first attempt. - uint32_t avail = 0; - for (int t = 0; t < 6; ++t) { +// Waits inside the read path. The LC76G needs the I2C bus to itself for the whole drain +// (other bus traffic between steps makes it stop answering), so during these waits only +// the idle hook runs: the display's sweep compositor, which uses QSPI and never touches +// I2C. Without a hook this is a plain delay(), as before. +static void (*s_idleHook)() = nullptr; +void gps_set_idle_hook(void (*hook)()) { s_idleHook = hook; } +static void gps_settle(uint32_t ms) { + if (!s_idleHook) { delay(ms); return; } + const uint32_t t0 = millis(); + while (millis() - t0 < ms) { s_idleHook(); delay(1); } +} + +// Ask how many bytes are queued. Retries, since prior shared-bus traffic can briefly +// leave the module unable to answer the first attempt. Returns true when the module +// answered (avail may legitimately be 0), false when it never did. +static bool gps_query_len(uint32_t *avail, int tries) { + for (int t = 0; t < tries; ++t) { Wire.beginTransmission(GPS_ADDR_W); Wire.write(QLEN, sizeof(QLEN)); if (Wire.endTransmission() != 0) { delay(15); continue; } - delay(GPS_SETTLE_MS); + gps_settle(GPS_SETTLE_MS); if (Wire.requestFrom((uint8_t)GPS_ADDR_R, (uint8_t)4) == 4) { - avail = (uint32_t)Wire.read(); - avail |= (uint32_t)Wire.read() << 8; - avail |= (uint32_t)Wire.read() << 16; - avail |= (uint32_t)Wire.read() << 24; - break; + uint32_t a = (uint32_t)Wire.read(); + a |= (uint32_t)Wire.read() << 8; + a |= (uint32_t)Wire.read() << 16; + a |= (uint32_t)Wire.read() << 24; + *avail = a; + return true; } delay(15); } + return false; +} + +// One blocking, uninterrupted drain of up to GPS_READ_MAX bytes into the parser. +// Returns bytes read, 0 when the module answered but had nothing usable queued, or -1 +// when it never answered (caller escalates toward the dead-module backoff). Caller has +// set 100 kHz + long timeout. `recovering` = the previous drain got no answer: lead with +// the un-stick reads and be more patient; the healthy path skips them and only falls +// back to them if the quick length query fails. +static int gps_drain(bool recovering) { + uint32_t avail = 0; + bool answered = false; + if (recovering) { + gps_unstick(); + answered = gps_query_len(&avail, 6); + } else { + answered = gps_query_len(&avail, 3); + if (!answered) { gps_unstick(); answered = gps_query_len(&avail, 3); } + } + if (!answered) return -1; if (avail == 0 || avail > 200000) return 0; // nothing queued / garbage length // 2) ask for at most one bufferful; the command echoes the count we will read. @@ -68,24 +271,46 @@ static int gps_drain() { const uint8_t cmd[8] = { 0x00, 0x20, 0x51, 0xAA, (uint8_t)want, (uint8_t)(want >> 8), (uint8_t)(want >> 16), (uint8_t)(want >> 24) }; - delay(GPS_SETTLE_MS); // <-- without this gap the cmd write gets NACKed + gps_settle(GPS_SETTLE_MS); // <-- without this gap the cmd write gets NACKed Wire.beginTransmission(GPS_ADDR_W); Wire.write(cmd, sizeof(cmd)); if (Wire.endTransmission() != 0) return 0; // 3) read straight into the NMEA parser (no Wire.setBufferSize here — see file header) - delay(GPS_SETTLE_MS); + gps_settle(GPS_SETTLE_MS); const int got = Wire.requestFrom((uint8_t)GPS_ADDR_R, (size_t)want); - for (int i = 0; i < got; ++i) s_gps.encode((char)Wire.read()); + for (int i = 0; i < got; ++i) { + const char c = (char)Wire.read(); + gps_scan_ack(c); + s_gps.encode(c); + } return got; } +static bool gps_ack() { // does anything answer at 0x50? (only the -G variant's LC76G does) + Wire.beginTransmission(GPS_ADDR_W); + Wire.write(QLEN, sizeof(QLEN)); + return Wire.endTransmission() == 0; +} + bool gps_begin() { // probe with the default buffer first; only bump it on a real -G board (and only once, // here at boot before TLS comes up) so non-GPS boards keep their small internal footprint. - Wire.beginTransmission(GPS_ADDR_W); - Wire.write(QLEN, sizeof(QLEN)); - s_present = (Wire.endTransmission() == 0); // 0x50 ACKs only on the -G variant + s_present = gps_ack(); + // Restart the module on every boot: one wedged before an OTA/soft reboot may still ACK but + // never stream again, or stop ACKing entirely. Then wait for it to come back up. Boards + // without the expander skip this; a 1.75 without GPS pays GPS_BOOT_WAIT_MS once. + const uint32_t t0 = millis(); + if (gps_hw_reset()) { + do { delay(50); s_present = gps_ack(); } while (!s_present && millis() - t0 < GPS_BOOT_WAIT_MS); + if (s_present) { + gps_after_reset(millis()); + s_settleUntil = millis() + GPS_SETTLE_AFTER_MS; + Serial.printf("[gps] reset via expander; module answered after %lu ms\n", + (unsigned long)(millis() - t0)); + } + } if (s_present) Wire.setBufferSize(GPS_BUF); // sized ONCE; never resized at runtime + s_lastDataMs = millis(); // stall timer starts now Serial.printf("[gps] LC76G %s\n", s_present ? "detected on I2C" : "not present"); return s_present; } @@ -96,22 +321,65 @@ void gps_poll() { if (!s_present) return; static uint32_t last = 0; const uint32_t now = millis(); - const uint32_t interval = gps_has_fix() ? GPS_POLL_FIX_MS : GPS_POLL_MS; + // Same cadence with or without a fix: the module never stops emitting NMEA, so WE must + // never stop draining it, or its queue overflows and it wedges until power-cycled (#24). + // Exception: a module that is not answering AT ALL has nothing to overflow — hammering + // it just blocks this core (and the config web page) on I2C timeouts, so back off. + const uint32_t interval = (s_deadDrains >= GPS_DEAD_TO_BACKOFF) ? GPS_POLL_DEAD_MS + : (s_cfgDone && gps_has_fix()) ? GPS_POLL_SLOW_MS + : GPS_POLL_MS; if (last != 0 && now - last < interval) return; + if ((int32_t)(now - s_settleUntil) < 0) return; // still booting after a reset last = now; + // Stuck module: nothing for GPS_STALL_MS (answering or not) -> restart it via its RESET line. + if (now - s_lastDataMs > GPS_STALL_MS && now - s_lastResetMs > GPS_RESET_GAP_MS) { + Serial.printf("[gps] no NMEA for %lu s: resetting the module\n", + (unsigned long)((now - s_lastDataMs) / 1000)); + if (gps_hw_reset()) { + gps_after_reset(now); + s_settleUntil = now + GPS_RESET_PULSE_MS + GPS_SETTLE_AFTER_MS; + return; + } + s_lastResetMs = now; // no reset line: don't retry (or log) on every poll + } + Wire.setClock(GPS_I2C_HZ); Wire.setTimeOut(GPS_TIMEOUT_MS); // LC76G read path: 100 kHz + tolerate clock-stretch - gps_drain(); + const int got = gps_drain(s_deadDrains > 0); + if (got > 0) s_lastDataMs = now; + // Trim the output once the module is streaming again (bytes arriving = it's up and parsing). + if (s_needCfg) { + if (s_cfgAcks >= GPS_CFG_N) { + s_needCfg = false; + s_cfgDone = true; + Serial.printf("[gps] sentence config acked (%u/%u)\n", (unsigned)s_cfgAcks, (unsigned)GPS_CFG_N); + } else if (got > 0 && (s_cfgTries == 0 || now - s_cfgSentMs > GPS_CFG_RETRY_MS)) { + if (s_cfgWritesBoot >= GPS_CFG_MAX_PER_BOOT) { + s_needCfg = false; // the module still works, it just keeps its default (chattier) output + Serial.printf("[gps] sentence config: per-boot cap of %u writes reached, not sending\n", + (unsigned)GPS_CFG_MAX_PER_BOOT); + } else if (s_cfgTries < GPS_CFG_TRIES) { + ++s_cfgWritesBoot; + gps_send_config(now); + } else { + s_needCfg = false; + Serial.printf("[gps] sentence config: only %u/%u acked, giving up\n", + (unsigned)s_cfgAcks, (unsigned)GPS_CFG_N); + } + } + } Wire.setTimeOut(BUS_TIMEOUT_MS); Wire.setClock(GPS_BUS_HZ); // hand the shared bus back to touch/IMU/RTC/PMIC + if (got < 0) { if (s_deadDrains < 255) ++s_deadDrains; } + else s_deadDrains = 0; // Diagnostic ladder (every ~8 s): chars=0 -> no NMEA arriving; sent>0 but fix=0 -> valid // data, just no satellite lock yet (needs clear sky / a few min on a cold start). static uint32_t lg = 0; if (now - lg > 8000) { lg = now; - Serial.printf("[gps] chars=%lu sent=%lu csErr=%lu sats=%d fix=%d\n", + Serial.printf("[gps] chars=%lu sent=%lu csErr=%lu sats=%d fix=%d resets=%u\n", (unsigned long)s_gps.charsProcessed(), (unsigned long)s_gps.sentencesWithFix(), (unsigned long)s_gps.failedChecksum(), (int)s_gps.satellites.value(), - (int)gps_has_fix()); + (int)gps_has_fix(), (unsigned)s_resets); } } @@ -129,3 +397,23 @@ bool gps_location(double *lat, double *lon) { int gps_satellites() { return s_gps.satellites.isValid() ? (int)s_gps.satellites.value() : 0; } + +bool gps_utc(long long *unixSecs) { + if (!s_present || !s_gps.date.isValid() || !s_gps.time.isValid()) return false; + if (s_gps.time.age() > 3000 || s_gps.date.age() > 3000) return false; + const int y = s_gps.date.year(), m = s_gps.date.month(), d = s_gps.date.day(); + if (y < 2024 || m < 1 || m > 12 || d < 1 || d > 31) return false; + // days from civil (Howard Hinnant): no time zone involved anywhere + const int yy = y - (m <= 2); + const int era = (yy >= 0 ? yy : yy - 399) / 400; + const unsigned yoe = (unsigned)(yy - era * 400); + const unsigned doy = (153u * (unsigned)(m + (m > 2 ? -3 : 9)) + 2u) / 5u + (unsigned)d - 1u; + const unsigned doe = yoe * 365u + yoe / 4u - yoe / 100u + doy; + const long long days = (long long)era * 146097LL + (long long)doe - 719468LL; + *unixSecs = days * 86400LL + s_gps.time.hour() * 3600LL + s_gps.time.minute() * 60LL + s_gps.time.second(); + return true; +} + +float gps_altitude_m() { + return s_gps.altitude.isValid() ? (float)s_gps.altitude.meters() : NAN; +} diff --git a/src/gps.h b/src/gps.h index f01a9d8..0406e18 100644 --- a/src/gps.h +++ b/src/gps.h @@ -9,7 +9,13 @@ bool gps_begin(); // probe for the LC76G; false if absent bool gps_present(); +void gps_set_idle_hook(void (*hook)()); // run during the drain's settle waits; must not touch I2C void gps_poll(); // non-blocking state machine; call every loop() bool gps_has_fix(); // a recent, valid position fix bool gps_location(double *lat, double *lon); // last fix (false if none) int gps_satellites(); // satellites in use/view (0 if none/unknown) +float gps_altitude_m(); // GPS altitude in metres (NAN if unknown) +// UTC from the most recent RMC/ZDA the parser saw, as unix seconds, if it is fresh (parsed in +// the last 3 s) and plausible. The drain reads every queued sentence, so the newest one is +// within about a second of the module's own clock; callers correct only drift over 2 s. +bool gps_utc(long long *unixSecs); diff --git a/src/main.cpp b/src/main.cpp index e47c12c..e366ef3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -47,6 +47,14 @@ #include "rtc_pcf85063.h" // PCF85063 RTC (offline clock + date) #include "audio.h" // ES8311 alert pings #include "knob.h" // rotary encoder on the 8-pin header +#include "gps.h" // LC76G GNSS on the -G board (Settings > Location > GPS) +#include "sat_tracker.h" // Satellites: TLEs + pass prediction +#include "sat_view.h" // Satellites: the sky dial +#if ORB_TOUCH +#include "touch_cst9217.h" // CST9217 touch panel +#endif +#include // boot-slot switch to Capsule Radar (ota_1) +#include // esp_sntp_stop(): GPS as the time source #include "app_shell.h" // "channel changer": knob flips between apps #include "input_router.h" // shared knob->app_shell routing (device + sim) #include "diag_log.h" // RTC-memory event ring buffer, survives a reboot @@ -72,8 +80,8 @@ #include // configuration web page #include // http://theorb.local // Wireless firmware update (ArduinoOTA + the browser upload page). Needs a second app -// partition to write the incoming image into, and partitions_16MB_themeart.csv gives -// that 6.25 MB to pre-baked theme art instead. Flip this and the partition table +// partition to write the incoming image into, and partitions_16MB_dualboot.csv gives +// the second slot to Capsule Radar (and the rest to pre-baked theme art) instead. Flip this and the partition table // together, never one alone: with no OTA partition present the code below would compile // and run but fail at the first write, which is worse than not offering it. #define ORB_OTA_ENABLED 0 @@ -194,6 +202,20 @@ static String g_tz = TZ_STR; // POSIX ti // a position MEANS rather than the position itself. Empty until something names it, which is // the honest state for a device handed bare coordinates. THEME_CAPS 54. static String g_locName; +// GPS as a location source (Settings > Location > GPS, NVS "gpsLoc"). Only meaningful on the +// -G board; on any other board gps_present() is false and none of this runs. Defaults ON so a +// -G Orb finds itself without being asked, and is switched OFF by any location the owner picks +// by hand, so the manual choice still wins (UX-025): picking a city is the owner saying where +// the Orb is, and a fix that quietly moved it afterwards would be the device overruling them. +static bool g_useGps = true; +// Flight Tracker opens Capsule Radar (the second app slot) instead of the Orb's own scope. +static bool g_flightCapsule = false; +// Where the clock gets its time: 0 = the internet (NTP over WiFi), 1 = GPS (Settings > +// Location > Time, NVS "timeSrc"). The RTC carries the time across power-off either way. +static volatile int g_timeSrc = 0; +static bool g_gpsTimeSet = false; // GPS has set the clock this session +bool host_flight_capsule(); +bool host_capsule_launch(); static volatile bool g_weatherDirty = false; static volatile bool g_wxRadarDirty = false; static volatile bool g_wxAnimDirty = false; // new Weather app: frame set ready @@ -312,7 +334,9 @@ static void adsb_task(void*) { WiFi.setSleep(false); Serial.printf("[adsb] WiFi up, IP %s\n", WiFi.localIP().toString().c_str()); diag::log("wifi up %s", WiFi.localIP().toString().c_str()); - configTzTime(g_tz.c_str(), "pool.ntp.org", "time.nist.gov"); // local time (web-configurable TZ) + // The internet sets the clock only when it is the chosen time source; with GPS + // chosen the zone still applies, the servers are simply not asked. + if (g_timeSrc == 0) configTzTime(g_tz.c_str(), "pool.ntp.org", "time.nist.gov"); Serial.println("[web] config: http://" ORB_MDNS_ADDR "/ (or the IP above)"); nextWeatherAt = millis() + 5000UL; // let the first ADS-B poll complete before weather TLS nextWxRadarAt = millis() + 12000UL; @@ -481,8 +505,10 @@ static void adsb_task(void*) { if (g_wxOpened) { g_wxOpened = false; wx_phase_set(WX_PHASE_BUFFERS); -#if !APPS_LAUNCH_ONE - if (theme_style::apps().weather) wx_radar_begin(); +#if ORB_HAS_WEATHER + // ORB_APP_WEATHER shows the app whatever the theme's roster says (config.h), + // so the buffers follow the app being on the menu, not the theme's flag. + if (ORB_APP_WEATHER || theme_style::apps().weather) wx_radar_begin(); #endif wxFillIdx = 0; ++wxGen; nextWxRadarAt = nowMs; wx_phase_set(WiFi.status() == WL_CONNECTED ? WX_PHASE_INDEX : WX_PHASE_NO_WIFI); @@ -565,6 +591,11 @@ static void adsb_task(void*) { // a kilobyte, so there is nothing to spread over several cycles. fetchStep() owns its own timing and returns immediately when // nothing is due, which is almost every pass through this loop. if (intelview::fetchStep()) g_intelDirty = true; +#if ORB_APP_SATS + // Satellite TLEs (one CelesTrak request at most, every 12 h per satellite) and + // pass prediction (one satellite per pass through here, tens of ms). + sats::step(WiFi.status() == WL_CONNECTED); +#endif // Quotes, through the same gateway and for the same reason. Well under a // kilobyte for a whole watchlist, so like the headlines there is nothing here // worth spreading over several passes; the step owns its own timing and returns @@ -664,6 +695,9 @@ static void loadSettings() { // stopped their feed on the strength of a key this build invented. A stored coordinate IS // an established location; only a device that has never had one gets the new state. g_locationSet = p.getBool("locSet", p.isKey("homeLat")); + g_useGps = p.getBool("gpsLoc", true); + g_flightCapsule = p.getBool("flightCap", false); + g_timeSrc = p.getInt("timeSrc", 0) == 1 ? 1 : 0; // Range, and below it max-aircraft, are read from the owner's saved settings here and // may then be overridden by the active theme in applyThemeSettings(), which runs after // this. The CUSTOM_RADAR_RANGE_KM / CUSTOM_RADAR_MAXAC blocks that used to sit in @@ -885,6 +919,10 @@ static void radar_hide_weather() { // Flight Tracker's baked plate/overlay (~1.3MB of decoded PSRAM) is freed on exit // via knobExit(), same discipline as clockview::onExit. static void radar_show_home_custom() { + // Flight radar style "Capsule Radar" (Settings > Flight radar). Not in the first 15 s + // after boot, so a design that boots straight into the Flight Tracker cannot bounce the + // Orb between the two firmwares; from then on, opening the Flight Tracker is the switch. + if (host_flight_capsule() && millis() > 15000) host_capsule_launch(); // returns only on failure radar_show_home(); radar::knobEnter(); // re-attach style + land in the default view (knob released) g_radarViewActive = true; // adsb_task may now poll; see g_radarViewActive above @@ -1079,6 +1117,161 @@ void host_location_reset() { "Settings > Location, to restore it."); } +// ---- GPS (the -G board) ----------------------------------------------------------------- +static void gps_store_enabled(bool on) { + g_useGps = on; + Preferences p; + p.begin("capsuleradar", false); + p.putBool("gpsLoc", on); + p.end(); +} +bool host_gps_present() { return gps_present(); } +bool host_gps_enabled() { return gps_present() && g_useGps; } +void host_gps_set_enabled(bool on) { + gps_store_enabled(on); + Serial.printf("[gps] location source %s\n", on ? "ON" : "OFF"); +} +void host_gps_status(char *out, size_t n) { + if (!n) return; + if (!gps_present()) { snprintf(out, n, "not fitted"); return; } + if (!g_useGps) { snprintf(out, n, "OFF"); return; } + if (gps_has_fix()) snprintf(out, n, "ON %d sats", gps_satellites()); + else snprintf(out, n, "ON searching"); +} +// ---- Time source: WiFi (NTP) or GPS -------------------------------------------------------- +bool host_time_src_gps() { return g_timeSrc == 1; } +void host_set_time_src_gps(bool gps) { + if (gps && !gps_present()) gps = false; // nothing to take time from + g_timeSrc = gps ? 1 : 0; + Preferences p; + p.begin("capsuleradar", false); + p.putInt("timeSrc", g_timeSrc); + p.end(); + if (gps) { + esp_sntp_stop(); // the internet stops adjusting the clock + g_gpsTimeSet = false; // take the next good fix straight away + } else if (WiFi.status() == WL_CONNECTED) { + configTzTime(g_tz.c_str(), "pool.ntp.org", "time.nist.gov"); + } + Serial.printf("[time] source: %s\n", gps ? "GPS" : "WiFi (NTP)"); +} +void host_time_status(char *out, size_t n) { + if (g_timeSrc == 1) snprintf(out, n, g_gpsTimeSet ? "GPS" : "GPS (waiting)"); + else snprintf(out, n, "WiFi"); +} +// Called from loop(): with GPS chosen, set the system clock from the fix the first time one +// arrives and whenever it drifts more than 2 s, and keep the RTC in step hourly. +static void gps_time_service() { + if (g_timeSrc != 1 || !gps_present()) return; + static uint32_t last = 0, lastRtc = 0; + if (last && millis() - last < 5000) return; + last = millis(); + long long g; + if (!gps_utc(&g)) return; + const long long sys = (long long)time(nullptr); + if (!g_gpsTimeSet || llabs(sys - g) > 2) { + struct timeval tv = { (time_t)g, 0 }; + settimeofday(&tv, nullptr); + Serial.printf("[time] set from GPS (was %+lld s)\n", sys - g); + g_gpsTimeSet = true; + lastRtc = 0; + } + if (!lastRtc || millis() - lastRtc > 3600000UL) { + const time_t now = time(nullptr); + struct tm utc; gmtime_r(&now, &utc); + if (rtc_write(&utc)) { lastRtc = millis(); g_rtcSynced = true; } + } +} + +// Where the Satellites screen observes from: the scope's centre (which GPS keeps current on +// the -G board), at the GPS altitude when there is one. +static bool host_sat_observer(double *lat, double *lon, double *altM) { + if (!g_locationSet) return false; + *lat = g_settings.homeLat; + *lon = g_settings.homeLon; + const float a = gps_has_fix() ? gps_altitude_m() : NAN; + *altM = isfinite(a) ? (double)a : 0.0; + return true; +} + +// A location the owner chose by hand. Called from every manual path (Settings, the web page +// when its coordinates actually changed, Orb Studio) so the choice is not undone by the next fix. +static void gps_manual_override() { + if (g_useGps && gps_present()) { + gps_store_enabled(false); + Serial.println("[gps] manual location chosen: GPS location source switched OFF"); + } +} +// Called from loop(). Moves the scope to the fix when it is the first location this Orb has +// had, or when the fix has moved more than GPS_RECENTRE_KM from the centre in use. Live, with +// no restart (apply_location_live), and persisted so the next boot starts in the right place. +#define GPS_RECENTRE_KM 1.0 +static void gps_service_location() { + if (!g_useGps || !gps_present()) return; + static uint32_t lastCheck = 0; + if (millis() - lastCheck < 3000) return; + lastCheck = millis(); + double lat, lon; + if (!gps_location(&lat, &lon)) return; + if (lat == 0.0 && lon == 0.0) return; // a parser's "no data", never a place + const double moved = geo::haversineKm(g_settings.homeLat, g_settings.homeLon, lat, lon); + if (g_locationSet && moved < GPS_RECENTRE_KM) return; + g_locName = "GPS"; + { + Preferences p; + p.begin("capsuleradar", false); + p.putString("homeName", "GPS"); + p.end(); + } + persist_location(lat, lon); + apply_location_live(lat, lon); + Serial.printf("[gps] re-centred to %.5f, %.5f (moved %.2f km, %d sats)\n", + lat, lon, moved, gps_satellites()); +} + +// ---- Capsule Radar, in the second app slot ------------------------------------------------ +// partitions_16MB_dualboot.csv gives ota_1 to Capsule Radar (socquique/capsule-radar, built +// with the patches in tools/capsule-radar/). Switching is a boot-slot change plus a restart; +// Capsule Radar switches back the same way when its knob is pressed. +static const esp_partition_t *capsule_partition() { + const esp_partition_t *run = esp_ota_get_running_partition(); + const esp_partition_t *p = esp_partition_find_first(ESP_PARTITION_TYPE_APP, + ESP_PARTITION_SUBTYPE_APP_OTA_1, nullptr); + if (!p || p == run) return nullptr; + return p; +} +bool host_capsule_installed() { + static int cached = -1; // the slot cannot change while this firmware runs + if (cached >= 0) return cached == 1; + const esp_partition_t *p = capsule_partition(); + esp_app_desc_t d; + cached = (p && esp_ota_get_partition_description(p, &d) == ESP_OK) ? 1 : 0; + if (cached) Serial.printf("[capsule] slot %s holds %s %s\n", p->label, d.project_name, d.version); + return cached == 1; +} +bool host_flight_capsule() { return g_flightCapsule && host_capsule_installed(); } +void host_flight_set_capsule(bool on) { + g_flightCapsule = on; + Preferences p; + p.begin("capsuleradar", false); + p.putBool("flightCap", on); + p.end(); +} +bool host_capsule_launch() { + const esp_partition_t *p = capsule_partition(); + if (!p || !host_capsule_installed()) return false; + const esp_err_t e = esp_ota_set_boot_partition(p); // verifies the image before switching + if (e != ESP_OK) { + Serial.printf("[capsule] cannot boot %s: %s\n", p->label, esp_err_to_name(e)); + return false; + } + Serial.println("[capsule] switching to Capsule Radar"); + Serial.flush(); + delay(150); + ESP.restart(); + return true; // not reached +} + // Set home location from the Settings menu and reboot to re-center radar + weather // (mirrors the web /save handler, which also restarts). Reuses the hold-warning overlay // (built in build_hold_warning()) for a visible countdown first — a silent 250ms-later @@ -1089,6 +1282,7 @@ void host_location_reset() { // countdown does. The boot-time lookup uses persist_location() + apply_location_live() // instead, because nobody asked it for anything. void host_set_location(double lat, double lon) { + gps_manual_override(); persist_location(lat, lon); if (g_holdWarning && g_holdWarningLbl) { @@ -1319,6 +1513,7 @@ static bool ip_lookup_location(double &lat, double &lon) { // be applied without a restart, and the boot-time lookup already uses them that way. void host_set_location_from_studio(const char *name, double lat, double lon, long tzOffsetSec, bool haveTz) { + gps_manual_override(); if (name && name[0]) { host_recents_add(name, lat, lon); persist_location_name(name); } // The browser's own timezone, which beats the IP lookup's guess for the same reason the // position does. Stored the same way and in the same format; the clock reads local from @@ -2007,6 +2202,13 @@ static void handleSave() { for (int i = 0; i < g_web.args(); ++i) Serial.printf("[web] %s = %s\n", g_web.argName(i).c_str(), g_web.arg(i).c_str()); // Reject out-of-range coordinates so a typo can't leave the radar unusable. + // The form always posts its lat/lon boxes, so only a real change counts as the owner + // picking a place by hand (which hands location back from GPS, see gps_manual_override). + if (g_web.hasArg("lat") && g_web.hasArg("lon") && + (fabs(g_web.arg("lat").toDouble() - g_settings.homeLat) > 0.0005 || + fabs(g_web.arg("lon").toDouble() - g_settings.homeLon) > 0.0005)) { + gps_manual_override(); + } if (g_web.hasArg("lat")) { const double lat = g_web.arg("lat").toDouble(); if (lat >= -90.0 && lat <= 90.0) { @@ -2913,8 +3115,11 @@ void setup() { // than anywhere else. See the residency note in app_shell.h. app_shell::add(clockview::screen(), theme_style::names().clock, nullptr, nullptr, false, clockview::onEnter, clockview::onExit, !theme_style::apps().clock); app_shell::add(radarScreen, theme_style::names().flight, radar_press_custom_or_theme, radar_turn_select, false, radar_show_home_custom, radar_exit_release_style, !theme_style::apps().flight); +#if ORB_HAS_WEATHER + app_shell::add(radarScreen, theme_style::names().weather, weather_press_cycle, nullptr, false, radar_show_weather, radar_hide_weather, + ORB_APP_WEATHER ? false : !theme_style::apps().weather); +#endif #if !APPS_LAUNCH_ONE - app_shell::add(radarScreen, theme_style::names().weather, weather_press_cycle, nullptr, false, radar_show_weather, radar_hide_weather, !theme_style::apps().weather); spycamview::init(); psram_mark("after spycamview"); #endif @@ -2939,6 +3144,14 @@ void setup() { app_shell::add(tickerview::screen(), theme_style::names().ticker, tickerview::onPress, tickerview::onTurn, false, tickerview::onEnter, tickerview::onExit, !theme_style::apps().ticker); // turn steps the watchlist; onEnter takes the strip canvas only when the design curves it +#endif +#if ORB_APP_SATS + // Satellites, built on demand like Headlines. The data side (TLEs, passes) runs from + // adsb_task whether or not the screen exists, so it is current when it is opened. + sats::begin(host_sat_observer); + app_shell::addLazy("Satellites", satview::build, satview::destroy, + satview::onPress, nullptr, false, + satview::onEnter, satview::onExit, false); #endif // Settings is built the first time somebody opens it, not here. It was the single // largest holder of internal RAM on the device — 909 LVGL allocations and ~24 KB, @@ -2961,7 +3174,9 @@ void setup() { { const theme_style::Apps &ta = theme_style::apps(); const struct { bool want; const char *name; } cut[] = { +#if !ORB_HAS_WEATHER { ta.weather, "Weather Radar" }, +#endif { ta.surveillance, "Surveillance" }, { ta.ticker, "Stock Ticker" }, }; @@ -3024,6 +3239,13 @@ void setup() { setenv("TZ", g_tz.c_str(), 1); tzset(); // local time for display even before NTP (loadSettings ran above) rtc_begin(); + // LC76G on the -G board. Here, with the other shared-bus devices and BEFORE WiFi/TLS: + // gps_begin() sizes the Wire RX buffer once, and that allocation must not land after the + // TLS handshake has carved up internal RAM (see the header of gps.cpp). A no-op elsewhere. +#if ORB_TOUCH + touch_begin(); // CST9217: reset + comms check. Before gps_begin, which sizes the Wire buffer +#endif + gps_begin(); rtc_seed_clock(); // offline clock/date from the PCF85063 clock_wind::begin(); // the stored wind, before any screen asks about it chime_library::begin(); // every chime on the card, and which one was chosen @@ -3626,6 +3848,87 @@ void setup() { freshFirmware ? "first boot after an update" : "already seen this build"); } +// ---- Touch ------------------------------------------------------------------------------- +// The CST9217 polled every 20 ms from loop() (not an LVGL pointer device: the Orb's screens +// are drawn for the knob and have no clickable widgets). Gestures map onto the knob's, so +// every screen already knows what to do with them: +// tap the knob's push. On the Flight Tracker it selects the aircraft under the +// finger instead (radar::tapSelect), or clears the selection on empty sky. +// drag up/down a knob turn per 40 px (up = clockwise), so lists and Settings scroll. +// swipe left/right next / previous app. +// hold 0.7 s opens the app menu, like the knob's rock. +// Any touch counts as activity and wakes a dimmed screen. +static void touch_service() { +#if ORB_TOUCH + static uint32_t lastPoll = 0; + if (millis() - lastPoll < 20) return; + lastPoll = millis(); + static bool down = false, moved = false, held = false; + static int x0 = 0, y0 = 0, xl = 0, yl = 0, dyAcc = 0; + static uint32_t t0 = 0; + uint16_t x = 0, y = 0; + const int st = touch_poll(&x, &y); + if (st < 0) return; // no answer this time: not a lift + const bool pressed = (st == 1); + if (pressed) { + display::noteActivity(); + if (g_idle) { g_idle = false; applyBrightness(); } + if (g_asleep) return; // face-down: the screen is off on purpose + if (!down) { down = true; moved = held = false; x0 = xl = x; y0 = yl = y; t0 = millis(); dyAcc = 0; return; } + const int dx = (int)x - x0, dy = (int)y - y0; + if (abs(dx) > 18 || abs(dy) > 18) moved = true; + if (moved && abs(dy) > abs(dx)) { + dyAcc += yl - (int)y; // finger moving up -> positive -> clockwise + while (dyAcc >= 40) { input_router::dispatch(1, false); dyAcc -= 40; } + while (dyAcc <= -40) { input_router::dispatch(-1, false); dyAcc += 40; } + } + if (!moved && !held && millis() - t0 > 700) { + held = true; + if (!app_shell::browsing()) app_shell::openSwitcher(); + } + xl = x; yl = y; + return; + } + if (!down) return; + down = false; + if (held || g_asleep) return; + const int dx = xl - x0, dy = yl - y0; + if (!moved) { + Serial.printf("[touch] tap %d,%d on %s\n", x0, y0, app_shell::name()); + if (app_shell::browsing()) app_shell::browsePress(); + else if (app_shell::index() == app_shell::APP_FLIGHT) radar::tapSelect(x0, y0); + else input_router::dispatch(0, true); + } else if (abs(dx) > 80 && abs(dx) > 2 * abs(dy)) { + Serial.printf("[touch] swipe %s\n", dx < 0 ? "left" : "right"); + if (app_shell::browsing()) app_shell::browseTurn(dx < 0 ? 1 : -1); + else if (!app_shell::captured()) { if (dx < 0) app_shell::next(); else app_shell::prev(); } + } +#endif +} + +// A chime when a satellite rises for a pass worth looking up for (peak 30 degrees or more), +// if Radar sounds are on. Checked once a second; each pass chimes once. +static void sat_alert_service() { +#if ORB_APP_SATS + static uint32_t last = 0; + if (millis() - last < 1000) return; + last = millis(); + if (!g_soundRadar || !audio_present()) return; + static uint32_t chimed[sats::MAX_SATS] = { 0 }; + const time_t now = time(nullptr); + for (int i = 0; i < sats::count(); ++i) { + sats::Sat s; + if (!sats::snapshot(i, s) || s.nPass == 0 || s.pass[0].maxEl < 30.0f) continue; + const uint32_t aos = (uint32_t)llround(sats::unixFromJd(s.pass[0].jdStart)); + if ((uint32_t)now >= aos && (uint32_t)now - aos < 10 && chimed[i] != aos) { + chimed[i] = aos; + audio_play(AUDIO_ALERT); + Serial.printf("[sats] %s rising, peak %.0f deg\n", s.name, (double)s.pass[0].maxEl); + } + } +#endif +} + void loop() { uint32_t lpT[LP_N + 1]; lpT[0] = micros(); @@ -3636,6 +3939,34 @@ void loop() { // moved: two frames of latency on every turn, which is what made the knob feel // sluggish. Handling it first means a turn is acted on by the very next render. knob::poll(); // drain detents/presses accumulated by the ISR + // GPS drain (the -G board, location source switched on). Each drain blocks this loop for + // ~300 ms of LC76G settle time, so it waits while the knob is being turned or held: a + // drain is never more than a few seconds late, and a hand on the knob never feels one. + if ((g_useGps || g_timeSrc == 1) && gps_present()) { + static int32_t lastRaw = 0; + static uint32_t lastTurn = 0; + const int32_t raw = knob::rawPosition(); + if (raw != lastRaw || knob::heldMs() > 0) { lastRaw = raw; lastTurn = millis(); } + if (millis() - lastTurn > 1500) gps_poll(); + } + touch_service(); + sat_alert_service(); + gps_time_service(); + // One line a minute of where memory stands, so a serial log always answers "how much is + // free" without a debugger: internal heap (what TLS and LVGL objects live in) and PSRAM. + { + static uint32_t lastMem = 0; + if (millis() - lastMem > 60000UL) { + lastMem = millis(); + Serial.printf("[mem] internal free %u B (largest %u B, low-water %u B) | PSRAM free %u KB of %u KB (largest %u KB) | app %s\n", + (unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL), + (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), + (unsigned)heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL), + (unsigned)(ESP.getFreePsram() / 1024), (unsigned)(ESP.getPsramSize() / 1024), + (unsigned)(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024), + app_shell::name()); + } + } // Before the input is routed, so a clock that ran out one second ago is already asking // by the time the next detent arrives rather than one frame later. Cheap: it compares // two integers unless the answer has actually changed. @@ -3967,6 +4298,9 @@ void loop() { // is. Here rather than in setup() because WiFi associates seconds after boot, and // once per boot rather than on a timer because a network that refuses the lookup // will keep refusing it and the owner can always pick a place in Settings instead. + // GPS first, when fitted and switched on: a fix outranks the network's guess, and a + // first fix on a never-located Orb is what sets it. + gps_service_location(); if (!g_locateTried && wifiUp && !g_locationSet) { g_locateTried = true; host_locate_if_unset(); diff --git a/src/radar_view.cpp b/src/radar_view.cpp index a2ceb52..6df2b34 100644 --- a/src/radar_view.cpp +++ b/src/radar_view.cpp @@ -268,6 +268,10 @@ static uint32_t s_selActivityMs = 0; // lv_tick_get() of the last knob i // lookup used TLS this board cannot do, see route_client.cpp), but it is still a network // round trip, and five seconds was a window you had to race. static constexpr uint32_t SELECT_IDLE_MS = 5000; +// A selection made by TOUCH stays up longer: a finger landed on that exact contact, so +// the person is reading its card, not scrubbing past it with the knob. +static constexpr uint32_t SELECT_IDLE_TOUCH_MS = 15000; +static uint32_t s_selIdleMs = SELECT_IDLE_MS; static void radar_exit_select(); // -> default view (deselect + release knob); defined below // Called when late-arriving detail (the route) reaches a card that is already up. Restarts // the idle countdown, because the thing worth reading only just appeared: without this the @@ -999,7 +1003,7 @@ static void sweep_timer_cb(lv_timer_t *t) { // Selection mode auto-times-out: 5s with no knob input drops back to the // populated default view (deselect + release the knob) so the scope doesn't // stay pinned on one aircraft. Runs before the early returns below. - if (s_selectMode && (uint32_t)(lv_tick_get() - s_selActivityMs) >= SELECT_IDLE_MS) radar_exit_select(); + if (s_selectMode && (uint32_t)(lv_tick_get() - s_selActivityMs) >= s_selIdleMs) radar_exit_select(); { // aircraft glyph motion, throttled: see AC_INTERP_MS for why this is slow on purpose static uint32_t s_lastInterpMs = 0; const uint32_t nowIms = lv_tick_get(); @@ -3148,6 +3152,7 @@ void knobPress() {} // an arbitrary index, so the box lands somewhere sensible. After SELECT_IDLE_MS of stillness // it clears itself; the Rock gesture leaves the app entirely and clears it on the way out. void knobTurn(int dir) { + s_selIdleMs = SELECT_IDLE_MS; if (!s_selectMode) { if (countInRange() <= 0) return; // an empty sky has nothing to select s_selectMode = true; @@ -3158,6 +3163,21 @@ void knobTurn(int dir) { s_selActivityMs = lv_tick_get(); } +// Touch: select the contact nearest the finger (hitTest's tap radius), or clear the +// selection when the tap lands on empty scope. Same selection mode the knob uses, so a +// turn afterwards steps on from the tapped aircraft. +void tapSelect(int x, int y) { + const int idx = hitTest(x, y); + if (idx < 0) { + if (s_selectMode) radar_exit_select(); + return; + } + s_selectMode = true; + s_selIdleMs = SELECT_IDLE_TOUCH_MS; + select(idx); + s_selActivityMs = lv_tick_get(); +} + // onExit: free the decoded plate/overlay PSRAM and drop selection mode so the idle // timer can't fire against a scope that's no longer on screen. void knobExit() { diff --git a/src/radar_view.h b/src/radar_view.h index 63ff3aa..7023675 100644 --- a/src/radar_view.h +++ b/src/radar_view.h @@ -82,6 +82,8 @@ void knobEnter(); void knobPress(); void knobTurn(int dir); void knobExit(); +// Touch: select the aircraft nearest (x,y) in screen px, or clear the selection on empty scope. +void tapSelect(int x, int y); // Snapshot access for the list / stats views. int count(); diff --git a/src/sat_tracker.cpp b/src/sat_tracker.cpp new file mode 100644 index 0000000..cb9ded0 --- /dev/null +++ b/src/sat_tracker.cpp @@ -0,0 +1,431 @@ +// Satellite pass tracker: TLEs, pass prediction and live positions. See sat_tracker.h. +#include "sat_tracker.h" +#include "net_fetch.h" +#include "config.h" // ORB_USER_AGENT +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef ARDUINO +#include +#include +#include +#include +#define SAT_LOG(...) Serial.printf(__VA_ARGS__) +static void *sat_alloc(size_t n) { + void *p = heap_caps_calloc(1, n, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT); + return p ? p : calloc(1, n); +} +static void net_free(uint8_t *p) { heap_caps_free(p); } +static uint32_t ms_now() { return millis(); } +#else +#include +#define SAT_LOG(...) printf(__VA_ARGS__) +static void *sat_alloc(size_t n) { return calloc(1, n); } +static void net_free(uint8_t *p) { free(p); } +static uint32_t ms_now() { + using namespace std::chrono; + return (uint32_t)duration_cast(steady_clock::now().time_since_epoch()).count(); +} +#endif + +namespace sats { + +namespace { + +// The default list. Catalogue numbers are stable; names are only what is shown until +// CelesTrak's own name arrives with the first TLE. +struct Default { uint32_t norad; const char *name; }; +const Default DEFAULTS[] = { + { 25544, "ISS" }, + { 48274, "Tiangong" }, + { 20580, "Hubble" }, + { 27607, "SO-50" }, + { 44909, "RS-44" }, + { 43678, "PO-101" }, +}; + +constexpr uint32_t TLE_REFRESH_S = 12UL * 3600UL; // CelesTrak: no more often than every 2 h +constexpr uint32_t FETCH_GAP_MS = 4000; // between two TLE requests +constexpr uint32_t FETCH_RETRY_MS = 10UL * 60UL * 1000UL; +constexpr double OBS_MOVE_DEG = 0.02; // ~2 km: re-predict when the observer moves +constexpr double PRED_SPAN_DAYS = 2.0; + +struct Store { + int n; + Sat sat[MAX_SATS]; + char l1[MAX_SATS][72]; + char l2[MAX_SATS][72]; + uint32_t fetchedAt[MAX_SATS]; // unix seconds of the TLE we hold (0 = never) + uint32_t tleGen[MAX_SATS]; // bumps on every new TLE + uint32_t predGen[MAX_SATS]; // tleGen the passes were computed from + double predLat[MAX_SATS], predLon[MAX_SATS]; + uint32_t retryAt[MAX_SATS]; // ms_now() before which a failed fetch is not retried +}; + +Store *S = nullptr; +std::mutex s_lock; +uint32_t s_gen = 1; +observer_fn s_obs = nullptr; +uint32_t s_lastFetchMs = 0; +int s_cursorFetch = 0, s_cursorPred = 0; + +// UI-thread propagators, one per satellite, re-initialised when that satellite's TLE changes. +Sgp4 *s_live[MAX_SATS] = { nullptr }; +uint32_t s_liveGen[MAX_SATS] = { 0 }; + +bool clock_ok(time_t t) { return t > 1700000000L; } + +void trim(char *s) { + size_t n = strlen(s); + while (n && (s[n - 1] == '\r' || s[n - 1] == '\n' || s[n - 1] == ' ')) s[--n] = 0; + char *p = s; while (*p == ' ') ++p; + if (p != s) memmove(s, p, strlen(p) + 1); +} + +#ifdef ARDUINO +void nvs_load(int i) { + Preferences p; + if (!p.begin("sats", true)) return; + char key[12]; snprintf(key, sizeof(key), "t%u", (unsigned)S->sat[i].norad); + char blob[24 + 72 + 72 + 8]; + const size_t got = p.getBytes(key, blob, sizeof(blob)); + p.end(); + if (got != sizeof(blob)) return; + memcpy(S->sat[i].name, blob, 24); S->sat[i].name[23] = 0; + memcpy(S->l1[i], blob + 24, 72); S->l1[i][71] = 0; + memcpy(S->l2[i], blob + 96, 72); S->l2[i][71] = 0; + memcpy(&S->fetchedAt[i], blob + 168, 4); + if (S->l1[i][0] == '1' && S->l2[i][0] == '2') { + S->sat[i].haveTle = true; + S->tleGen[i]++; + } +} +void nvs_save(int i) { + Preferences p; + if (!p.begin("sats", false)) return; + char key[12]; snprintf(key, sizeof(key), "t%u", (unsigned)S->sat[i].norad); + char blob[24 + 72 + 72 + 8] = {}; + memcpy(blob, S->sat[i].name, 24); + memcpy(blob + 24, S->l1[i], 72); + memcpy(blob + 96, S->l2[i], 72); + memcpy(blob + 168, &S->fetchedAt[i], 4); + p.putBytes(key, blob, sizeof(blob)); + p.end(); +} +// /satellites.txt on the SD card: " [name]" per line, '#' comments. +int sd_list(Default *out, char names[][24], int maxN) { + File f = SD.open("/satellites.txt"); + if (!f) return 0; + int n = 0; + char line[64]; + while (f.available() && n < maxN) { + const int len = f.readBytesUntil('\n', line, sizeof(line) - 1); + line[len] = 0; + trim(line); + if (!line[0] || line[0] == '#') continue; + char *end = nullptr; + const unsigned long id = strtoul(line, &end, 10); + if (!id || end == line) continue; + while (*end == ' ' || *end == '\t') ++end; + snprintf(names[n], 24, "%s", *end ? end : ""); + out[n].norad = (uint32_t)id; + out[n].name = names[n]; + ++n; + } + f.close(); + return n; +} +#else +void nvs_load(int) {} +void nvs_save(int) {} +// The simulator reads sim/sats.tle (three-line TLE sets) if it is there, so the screen can be +// built and photographed offline. +void sim_load_file() { + FILE *f = fopen("sim/sats.tle", "r"); + if (!f) return; + char a[80], b[80], c[80]; + auto next = [&](char *dst) { // next non-comment, non-blank line + while (fgets(dst, 80, f)) { trim(dst); if (dst[0] && dst[0] != '#') return true; } + return false; + }; + while (next(a) && next(b) && next(c)) { + if (b[0] != '1' || c[0] != '2') continue; + const uint32_t id = (uint32_t)strtoul(b + 2, nullptr, 10); + for (int i = 0; i < S->n; ++i) if (S->sat[i].norad == id) { + snprintf(S->sat[i].name, sizeof(S->sat[i].name), "%s", a); + snprintf(S->l1[i], 72, "%s", b); + snprintf(S->l2[i], 72, "%s", c); + S->sat[i].haveTle = true; + S->fetchedAt[i] = (uint32_t)time(nullptr); + S->tleGen[i]++; + } + } + fclose(f); +} +#endif + +// One TLE from CelesTrak. Runs on the network task without the lock held. +// Scratch for fetch_one(), predict() and step(): in PSRAM, not on the stack and not in +// internal .bss. All three run only on the network task (adsb_task), whose 7 KB stack had +// ~1.1 KB left at its peak with these on it (the [memdbg] stacks figure), and internal RAM +// is the scarcer of the two. One task, so no two calls ever use it at once. +struct Scratch { + char url[96]; + char text[600]; + char pl1[130], pl2[130]; + char name[24], l1[72], l2[72]; + Sat tmp; +}; +Scratch *X = nullptr; + +bool fetch_one(uint32_t norad, char *name, char *l1, char *l2) { + char *url = X->url; + snprintf(url, sizeof(X->url), "https://celestrak.org/NORAD/elements/gp.php?CATNR=%u&FORMAT=TLE", + (unsigned)norad); + uint8_t *buf = nullptr; size_t len = 0; + if (!net_fetch_psram(url, ORB_USER_AGENT, &buf, &len, 2048, 6000, 10000)) return false; + char *text = X->text; + const size_t n = len < sizeof(X->text) - 1 ? len : sizeof(X->text) - 1; + memcpy(text, buf, n); text[n] = 0; + net_free(buf); + char *lines[3] = { nullptr, nullptr, nullptr }; + int k = 0; + for (char *tok = strtok(text, "\n"); tok && k < 3; tok = strtok(nullptr, "\n")) { + trim(tok); + if (*tok) lines[k++] = tok; + } + if (k < 3 || lines[1][0] != '1' || lines[2][0] != '2' || + strlen(lines[1]) < 69 || strlen(lines[2]) < 69) { + SAT_LOG("[sats] %u: no TLE in CelesTrak's answer\n", (unsigned)norad); + return false; + } + snprintf(name, 24, "%s", lines[0]); + snprintf(l1, 72, "%s", lines[1]); + snprintf(l2, 72, "%s", lines[2]); + return true; +} + +// Passes for one satellite, from its own temporary propagator. Network task, no lock held. +void predict(const char *name, const char *l1in, const char *l2in, + double lat, double lon, double altM, double jdNow, Sat &out) { + void *mem = sat_alloc(sizeof(Sgp4)); + if (!mem) return; + Sgp4 *s = new (mem) Sgp4(); + char *l1 = X->pl1, *l2 = X->pl2; + snprintf(l1, sizeof(X->pl1), "%s", l1in); + snprintf(l2, sizeof(X->pl2), "%s", l2in); + s->site(lat, lon, altM); + s->init(name, l1, l2); + out.nPass = 0; + out.nPath = 0; + // Start half an orbit back, so a pass already under way is found rather than skipped: + // initpredpoint() lands on the previous maximum, and nextpass() steps on one orbit. + const double orbitDays = 1.0 / (s->revpday > 0 ? s->revpday : 15.5); + if (s->initpredpoint(jdNow - 0.6 * orbitDays, 0.0)) { + passinfo p; + for (int guard = 0; guard < 60 && out.nPass < MAX_PASSES; ++guard) { + if (!s->nextpass(&p, 20, false, MIN_PASS_EL)) break; + if (p.jdstart > jdNow + PRED_SPAN_DAYS) break; + if (p.jdstop < jdNow) continue; // already over + Pass &q = out.pass[out.nPass++]; + q.jdStart = p.jdstart; q.jdMax = p.jdmax; q.jdStop = p.jdstop; + q.maxEl = (float)p.maxelevation; + q.azStart = (float)p.azstart; q.azStop = (float)p.azstop; + q.sunlit = (p.sight == lighted); + } + } + if (out.nPass > 0) { + const Pass &q = out.pass[0]; + for (int k = 0; k < PATH_PTS; ++k) { + const double jd = q.jdStart + (q.jdStop - q.jdStart) * k / (PATH_PTS - 1); + s->findsat(jd); + out.pathAz[k] = (float)s->satAz; + out.pathEl[k] = (float)(s->satEl < 0 ? 0 : s->satEl); + } + out.nPath = PATH_PTS; + } + s->~Sgp4(); +#ifdef ARDUINO + heap_caps_free(mem); +#else + free(mem); +#endif +} + +} // namespace + +double jdFromUnix(double u) { return u / 86400.0 + 2440587.5; } +double unixFromJd(double jd) { return (jd - 2440587.5) * 86400.0; } + +void begin(observer_fn obs) { + s_obs = obs; + if (S) return; + S = (Store *)sat_alloc(sizeof(Store)); + X = (Scratch *)sat_alloc(sizeof(Scratch)); + if (!S || !X) { SAT_LOG("[sats] no memory\n"); S = nullptr; return; } + new (X) Scratch(); + new (S) Store(); + Default list[MAX_SATS]; + int n = 0; +#ifdef ARDUINO + static char sdNames[MAX_SATS][24]; + n = sd_list(list, sdNames, MAX_SATS); + if (n) SAT_LOG("[sats] %d satellite(s) from /satellites.txt\n", n); +#endif + if (!n) { + n = (int)(sizeof(DEFAULTS) / sizeof(DEFAULTS[0])); + if (n > MAX_SATS) n = MAX_SATS; + for (int i = 0; i < n; ++i) list[i] = DEFAULTS[i]; + } + S->n = n; + for (int i = 0; i < n; ++i) { + S->sat[i].norad = list[i].norad; + snprintf(S->sat[i].name, sizeof(S->sat[i].name), "%s", + (list[i].name && list[i].name[0]) ? list[i].name : "?"); + nvs_load(i); + } +#ifndef ARDUINO + sim_load_file(); +#endif + SAT_LOG("[sats] tracking %d satellite(s)\n", n); +} + +int count() { return S ? S->n : 0; } +uint32_t generation() { return s_gen; } + +int status() { + if (!S) return 3; + if (!clock_ok(time(nullptr))) return 1; + double la, lo, al; + if (!s_obs || !s_obs(&la, &lo, &al)) return 2; + for (int i = 0; i < S->n; ++i) if (S->sat[i].haveTle) return 0; + return 3; +} + +bool snapshot(int i, Sat &out) { + if (!S || i < 0 || i >= S->n) return false; + std::lock_guard g(s_lock); + out = S->sat[i]; + return true; +} + +bool step(bool netUp) { + if (!S || !S->n) return false; + const time_t now = time(nullptr); + if (!clock_ok(now)) return false; + bool changed = false; + + // 1) at most one TLE fetch per call, spaced FETCH_GAP_MS apart + if (netUp && ms_now() - s_lastFetchMs > FETCH_GAP_MS) { + for (int k = 0; k < S->n; ++k) { + const int i = (s_cursorFetch + k) % S->n; + const bool stale = !S->sat[i].haveTle || (uint32_t)now - S->fetchedAt[i] > TLE_REFRESH_S; + if (!stale || (int32_t)(ms_now() - S->retryAt[i]) < 0) continue; + s_cursorFetch = (i + 1) % S->n; + s_lastFetchMs = ms_now(); + char *name = X->name, *l1 = X->l1, *l2 = X->l2; + if (fetch_one(S->sat[i].norad, name, l1, l2)) { + { + std::lock_guard g(s_lock); + snprintf(S->sat[i].name, sizeof(S->sat[i].name), "%s", name); + memcpy(S->l1[i], l1, 72); + memcpy(S->l2[i], l2, 72); + S->fetchedAt[i] = (uint32_t)now; + S->sat[i].haveTle = true; + S->tleGen[i]++; + s_gen++; + } + nvs_save(i); + SAT_LOG("[sats] TLE %u %s\n", (unsigned)S->sat[i].norad, name); + changed = true; + } else { + S->retryAt[i] = ms_now() + FETCH_RETRY_MS; + } + break; + } + } + + // 2) at most one prediction per call + double lat, lon, alt; + if (!s_obs || !s_obs(&lat, &lon, &alt)) return changed; + const double jdNow = jdFromUnix((double)now); + for (int k = 0; k < S->n; ++k) { + const int i = (s_cursorPred + k) % S->n; + if (!S->sat[i].haveTle) continue; + const Sat &cur = S->sat[i]; + const bool due = S->predGen[i] != S->tleGen[i] || + cur.nPass == 0 || + cur.pass[0].jdStop < jdNow || + fabs(S->predLat[i] - lat) > OBS_MOVE_DEG || + fabs(S->predLon[i] - lon) > OBS_MOVE_DEG; + // An empty result is only retried every few minutes (a satellite that never rises + // high enough here would otherwise be recomputed on every call). + static uint32_t emptyAt[MAX_SATS] = { 0 }; + if (!due) continue; + if (cur.nPass == 0 && S->predGen[i] == S->tleGen[i] && ms_now() - emptyAt[i] < 300000) continue; + s_cursorPred = (i + 1) % S->n; + char *name = X->name, *l1 = X->l1, *l2 = X->l2; + { std::lock_guard g(s_lock); memcpy(name, cur.name, 24); memcpy(l1, S->l1[i], 72); memcpy(l2, S->l2[i], 72); } + Sat &tmp = X->tmp; + const uint32_t t0 = ms_now(); + predict(name, l1, l2, lat, lon, alt, jdNow, tmp); + { + std::lock_guard g(s_lock); + Sat &dst = S->sat[i]; + dst.nPass = tmp.nPass; + memcpy(dst.pass, tmp.pass, sizeof(dst.pass)); + dst.nPath = tmp.nPath; + memcpy(dst.pathAz, tmp.pathAz, sizeof(dst.pathAz)); + memcpy(dst.pathEl, tmp.pathEl, sizeof(dst.pathEl)); + S->predGen[i] = S->tleGen[i]; + S->predLat[i] = lat; S->predLon[i] = lon; + s_gen++; + } + if (tmp.nPass == 0) emptyAt[i] = ms_now(); + SAT_LOG("[sats] %s: %d pass(es) in %lu ms\n", name, tmp.nPass, (unsigned long)(ms_now() - t0)); + changed = true; + break; + } + return changed; +} + +bool live(int i, double unixNow, Live &out) { + out.valid = false; + if (!S || i < 0 || i >= S->n || !S->sat[i].haveTle) return false; + double lat, lon, alt; + if (!s_obs || !s_obs(&lat, &lon, &alt)) return false; + if (!s_live[i]) { + void *mem = sat_alloc(sizeof(Sgp4)); + if (!mem) return false; + s_live[i] = new (mem) Sgp4(); + } + Sgp4 *s = s_live[i]; + if (s_liveGen[i] != S->tleGen[i]) { + char name[24], l1[130], l2[130]; + { + std::lock_guard g(s_lock); + memcpy(name, S->sat[i].name, 24); + snprintf(l1, sizeof(l1), "%s", S->l1[i]); + snprintf(l2, sizeof(l2), "%s", S->l2[i]); + } + s->line1[0] = 0; // init() skips a TLE whose line 1 it already holds + s->init(name, l1, l2); + s_liveGen[i] = S->tleGen[i]; + } + s->site(lat, lon, alt); + s->findsat(jdFromUnix(unixNow)); + out.az = (float)s->satAz; + out.el = (float)s->satEl; + out.rangeKm = (float)s->satDist; + out.altKm = (float)s->satAlt; + out.valid = true; + return true; +} + +} // namespace sats diff --git a/src/sat_tracker.h b/src/sat_tracker.h new file mode 100644 index 0000000..0ce73ba --- /dev/null +++ b/src/sat_tracker.h @@ -0,0 +1,70 @@ +#pragma once +// Satellite pass tracker: the data half (TLEs, pass prediction, live position). The screen +// is sat_view.*. Portable: builds for the device and the native simulator. +// +// Where things run +// step() the network task (device: adsb_task on core 0; sim: the main loop). Fetches +// one due TLE per call from CelesTrak and recomputes one satellite's passes +// per call, so neither ever holds that task for long. +// live() core 1 / the UI. Its own SGP4 objects, separate from the ones step() uses, +// so the two never touch the same propagator state. +// snapshot() any thread; copies under the lock. +// +// Which satellites: NORAD catalogue numbers. The default list is the ISS, China's space +// station, Hubble and three amateur-radio satellites people actually work. On the device a +// file /satellites.txt on the SD card replaces it: one catalogue number per line, an +// optional name after it ("25544 ISS"), '#' comments. +// +// CelesTrak asks that a TLE is not fetched more often than every two hours; this refreshes +// every 12 h and keeps the last good set in NVS (device) so a reboot needs no network. +#include +#include + +namespace sats { + +constexpr int MAX_SATS = 8; +constexpr int MAX_PASSES = 3; +constexpr int PATH_PTS = 24; +constexpr float MIN_PASS_EL = 10.0f; // passes lower than this are not worth listing + +struct Pass { + double jdStart = 0, jdMax = 0, jdStop = 0; // Julian dates (UTC) + float maxEl = 0, azStart = 0, azStop = 0; // degrees + bool sunlit = false; // satellite lit while the observer is in darkness (naked-eye) +}; + +struct Sat { + uint32_t norad = 0; + char name[24] = ""; + bool haveTle = false; + int nPass = 0; + Pass pass[MAX_PASSES]; + int nPath = 0; // sky track of pass[0], az/el in degrees + float pathAz[PATH_PTS]; + float pathEl[PATH_PTS]; +}; + +struct Live { + bool valid = false; + float az = 0, el = 0, rangeKm = 0, altKm = 0; +}; + +// Observer: supplied by the host (main.cpp / sim_main.cpp). False until a location is set. +typedef bool (*observer_fn)(double *latDeg, double *lonDeg, double *altM); + +void begin(observer_fn obs); +// Network-task step. netUp: WiFi is connected. Returns true when anything the screen shows +// changed (new TLEs or new passes). +bool step(bool netUp); +int count(); +bool snapshot(int i, Sat &out); +uint32_t generation(); // bumps whenever snapshot() data changes +// Current az/el for satellite i at unix time t (UI thread only). +bool live(int i, double unixNow, Live &out); +// Status for an empty screen: 0 ok, 1 no clock yet, 2 no location, 3 no TLEs yet. +int status(); + +double jdFromUnix(double unixSecs); +double unixFromJd(double jd); + +} // namespace sats diff --git a/src/sat_view.cpp b/src/sat_view.cpp new file mode 100644 index 0000000..0f20c11 --- /dev/null +++ b/src/sat_view.cpp @@ -0,0 +1,288 @@ +// Satellites screen. See sat_view.h. +#include "sat_view.h" +#include "sat_tracker.h" +#include "config.h" +#include +#include +#include +#include + +namespace satview { + +namespace { + +constexpr int CX = SCREEN_W / 2; +constexpr int CY = 192; // sky dial centre (above the text block) +constexpr int R = 140; // horizon radius + +const lv_color_t C_BG = lv_color_hex(0x000000); +const lv_color_t C_GRID = lv_color_hex(0x24323F); +const lv_color_t C_DIM = lv_color_hex(0x6B7A88); +const lv_color_t C_INK = lv_color_hex(0xEAF2F8); +const lv_color_t C_OTHER = lv_color_hex(0x3CE0FF); +const lv_color_t C_SEL = lv_color_hex(0xFFB23C); +const lv_color_t C_PATH = lv_color_hex(0x8A5A14); + +lv_obj_t *s_scr = nullptr; +lv_obj_t *s_path = nullptr; +lv_point_t s_pathPts[sats::PATH_PTS]; +lv_obj_t *s_dot[sats::MAX_SATS] = { nullptr }; +lv_obj_t *s_dotLbl[sats::MAX_SATS] = { nullptr }; +lv_obj_t *s_name = nullptr, *s_line1 = nullptr, *s_line2 = nullptr; +lv_timer_t *s_timer = nullptr; +uint32_t s_selNorad = 0; + +void sky_xy(float az, float el, lv_coord_t &x, lv_coord_t &y) { + if (el < 0) el = 0; + const float r = R * (90.0f - el) / 90.0f; + const float a = az * (float)M_PI / 180.0f; + x = (lv_coord_t)lroundf(CX + r * sinf(a)); + y = (lv_coord_t)lroundf(CY - r * cosf(a)); +} + +const char *compass(float az) { + static const char *P[16] = { "N","NNE","NE","ENE","E","ESE","SE","SSE", + "S","SSW","SW","WSW","W","WNW","NW","NNW" }; + int i = (int)lroundf(fmodf(az + 360.0f, 360.0f) / 22.5f) % 16; + return P[i]; +} + +void fmt_dur(char *out, size_t n, long secs) { + if (secs < 0) secs = 0; + const long h = secs / 3600, m = (secs % 3600) / 60, s = secs % 60; + if (h > 0) snprintf(out, n, "%ldh %02ldm", h, m); + else if (m > 0) snprintf(out, n, "%ldm %02lds", m, s); + else snprintf(out, n, "%lds", s); +} + +void fmt_clock(char *out, size_t n, double jd) { + const time_t t = (time_t)llround(sats::unixFromJd(jd)); + struct tm lt; + localtime_r(&t, <); + int h = lt.tm_hour % 12; if (h == 0) h = 12; + snprintf(out, n, "%d:%02d %s", h, lt.tm_min, lt.tm_hour < 12 ? "AM" : "PM"); +} + +lv_obj_t *mk_ring(lv_obj_t *p, int r) { + lv_obj_t *o = lv_obj_create(p); + lv_obj_remove_style_all(o); + lv_obj_set_size(o, r * 2, r * 2); + lv_obj_set_pos(o, CX - r, CY - r); + lv_obj_set_style_radius(o, LV_RADIUS_CIRCLE, 0); + lv_obj_set_style_border_width(o, 1, 0); + lv_obj_set_style_border_color(o, C_GRID, 0); + lv_obj_set_style_border_opa(o, LV_OPA_COVER, 0); + lv_obj_clear_flag(o, LV_OBJ_FLAG_SCROLLABLE | LV_OBJ_FLAG_CLICKABLE); + return o; +} + +lv_obj_t *mk_label(lv_obj_t *p, const lv_font_t *f, lv_color_t c) { + lv_obj_t *l = lv_label_create(p); + lv_obj_set_style_text_font(l, f, 0); + lv_obj_set_style_text_color(l, c, 0); + lv_obj_set_style_text_align(l, LV_TEXT_ALIGN_CENTER, 0); + lv_label_set_text(l, ""); + return l; +} + +// Order the dial cycles through: up now (highest first), then soonest to rise. +int ordered(int out[], double jdNow) { + struct K { int i; double key; } k[sats::MAX_SATS]; + int n = 0; + for (int i = 0; i < sats::count(); ++i) { + sats::Sat s; + if (!sats::snapshot(i, s) || !s.haveTle) continue; + double key = 1e9; + if (s.nPass > 0) key = (s.pass[0].jdStart <= jdNow) ? -1.0 + (s.pass[0].jdStart - jdNow) + : s.pass[0].jdStart - jdNow; + k[n++] = { i, key }; + } + for (int a = 1; a < n; ++a) // tiny list: insertion sort + for (int b = a; b > 0 && k[b].key < k[b - 1].key; --b) { K t = k[b]; k[b] = k[b - 1]; k[b - 1] = t; } + for (int a = 0; a < n; ++a) out[a] = k[a].i; + return n; +} + +void refresh(lv_timer_t *) { + if (!s_scr) return; + const time_t nowT = time(nullptr); + const double now = (double)nowT; + const double jdNow = sats::jdFromUnix(now); + + const int st = sats::status(); + if (st != 0) { + for (int i = 0; i < sats::MAX_SATS; ++i) { lv_obj_add_flag(s_dot[i], LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(s_dotLbl[i], LV_OBJ_FLAG_HIDDEN); } + lv_obj_add_flag(s_path, LV_OBJ_FLAG_HIDDEN); + lv_label_set_text(s_name, "Satellites"); + lv_label_set_text(s_line1, st == 1 ? "Waiting for the clock" : + st == 2 ? "Location not set" : "Fetching orbits..."); + lv_label_set_text(s_line2, st == 3 ? "from CelesTrak, needs WiFi" : ""); + return; + } + + int order[sats::MAX_SATS]; + const int n = ordered(order, jdNow); + int selIdx = -1; + for (int k = 0; k < n; ++k) { + sats::Sat s; sats::snapshot(order[k], s); + if (s.norad == s_selNorad) { selIdx = order[k]; break; } + } + if (selIdx < 0 && n > 0) { selIdx = order[0]; sats::Sat s; sats::snapshot(selIdx, s); s_selNorad = s.norad; } + + // Dots for everything above the horizon. + for (int i = 0; i < sats::MAX_SATS; ++i) { + sats::Live lv; + sats::Sat s; + const bool up = i < sats::count() && sats::snapshot(i, s) && sats::live(i, now, lv) && lv.el > 0; + if (!up) { lv_obj_add_flag(s_dot[i], LV_OBJ_FLAG_HIDDEN); lv_obj_add_flag(s_dotLbl[i], LV_OBJ_FLAG_HIDDEN); continue; } + const bool sel = (i == selIdx); + lv_coord_t x, y; sky_xy(lv.az, lv.el, x, y); + const int d = sel ? 16 : 10; + lv_obj_set_size(s_dot[i], d, d); + lv_obj_set_pos(s_dot[i], x - d / 2, y - d / 2); + lv_obj_set_style_bg_color(s_dot[i], sel ? C_SEL : C_OTHER, 0); + lv_obj_clear_flag(s_dot[i], LV_OBJ_FLAG_HIDDEN); + lv_label_set_text(s_dotLbl[i], s.name); + lv_obj_set_style_text_color(s_dotLbl[i], sel ? C_SEL : C_OTHER, 0); + lv_obj_align_to(s_dotLbl[i], s_dot[i], x > CX ? LV_ALIGN_OUT_LEFT_MID : LV_ALIGN_OUT_RIGHT_MID, + x > CX ? -4 : 4, 0); + lv_obj_clear_flag(s_dotLbl[i], LV_OBJ_FLAG_HIDDEN); + } + + if (selIdx < 0) { + lv_obj_add_flag(s_path, LV_OBJ_FLAG_HIDDEN); + lv_label_set_text(s_name, "Satellites"); + lv_label_set_text(s_line1, "Fetching orbits..."); + lv_label_set_text(s_line2, ""); + return; + } + + sats::Sat s; sats::snapshot(selIdx, s); + sats::Live lv; sats::live(selIdx, now, lv); + lv_label_set_text(s_name, s.name); + + // The selected satellite's current or next pass, across the sky. + if (s.nPass > 0 && s.nPath > 1) { + for (int k = 0; k < s.nPath; ++k) sky_xy(s.pathAz[k], s.pathEl[k], s_pathPts[k].x, s_pathPts[k].y); + lv_line_set_points(s_path, s_pathPts, s.nPath); + lv_obj_clear_flag(s_path, LV_OBJ_FLAG_HIDDEN); + } else { + lv_obj_add_flag(s_path, LV_OBJ_FLAG_HIDDEN); + } + + char a[64], b[64], t1[16], t2[16]; + if (lv.valid && lv.el > 0) { + snprintf(a, sizeof(a), "UP NOW %.0f\xC2\xB0 %s", (double)lv.el, compass(lv.az)); + if (s.nPass > 0 && s.pass[0].jdStart <= jdNow) { + fmt_dur(t1, sizeof(t1), (long)(sats::unixFromJd(s.pass[0].jdStop) - now)); + snprintf(b, sizeof(b), "sets %s in %s \xE2\x80\xA2 %.0f km", + compass(s.pass[0].azStop), t1, (double)lv.rangeKm); + } else { + snprintf(b, sizeof(b), "%.0f km away", (double)lv.rangeKm); + } + } else if (s.nPass > 0) { + const sats::Pass &p = s.pass[0]; + fmt_clock(t1, sizeof(t1), p.jdStart); + fmt_dur(t2, sizeof(t2), (long)(sats::unixFromJd(p.jdStart) - now)); + snprintf(a, sizeof(a), "Rises %s (in %s)", t1, t2); + snprintf(b, sizeof(b), "%s to %s \xE2\x80\xA2 peak %.0f\xC2\xB0 \xE2\x80\xA2 %.0f min%s", + compass(p.azStart), compass(p.azStop), (double)p.maxEl, + (p.jdStop - p.jdStart) * 1440.0, p.sunlit ? " \xE2\x80\xA2 visible" : ""); + } else { + snprintf(a, sizeof(a), "No pass above %.0f\xC2\xB0", (double)sats::MIN_PASS_EL); + snprintf(b, sizeof(b), "in the next 48 hours"); + } + lv_label_set_text(s_line1, a); + lv_label_set_text(s_line2, b); +} + +} // namespace + +lv_obj_t *build() { + if (s_scr) return s_scr; + s_scr = lv_obj_create(nullptr); + lv_obj_remove_style_all(s_scr); + lv_obj_set_size(s_scr, SCREEN_W, SCREEN_H); + lv_obj_set_style_bg_color(s_scr, C_BG, 0); + lv_obj_set_style_bg_opa(s_scr, LV_OPA_COVER, 0); + lv_obj_clear_flag(s_scr, LV_OBJ_FLAG_SCROLLABLE); + + mk_ring(s_scr, R); + mk_ring(s_scr, R * 2 / 3); + mk_ring(s_scr, R / 3); + static lv_point_t hl[2] = { { CX - R, CY }, { CX + R, CY } }; + static lv_point_t vl[2] = { { CX, CY - R }, { CX, CY + R } }; + lv_point_t *axes[2] = { hl, vl }; + for (lv_point_t *pts : axes) { + lv_obj_t *l = lv_line_create(s_scr); + lv_line_set_points(l, pts, 2); + lv_obj_set_style_line_color(l, C_GRID, 0); + lv_obj_set_style_line_width(l, 1, 0); + } + const struct { const char *t; int dx, dy; } card[] = { + { "N", 0, -R - 14 }, { "S", 0, R + 14 }, { "E", R + 14, 0 }, { "W", -R - 14, 0 } }; + for (const auto &c : card) { + lv_obj_t *l = mk_label(s_scr, &lv_font_montserrat_14, C_DIM); + lv_label_set_text(l, c.t); + lv_obj_align(l, LV_ALIGN_TOP_LEFT, 0, 0); + lv_obj_update_layout(l); + lv_obj_set_pos(l, CX + c.dx - lv_obj_get_width(l) / 2, CY + c.dy - lv_obj_get_height(l) / 2); + } + + s_path = lv_line_create(s_scr); + lv_obj_set_style_line_color(s_path, C_PATH, 0); + lv_obj_set_style_line_width(s_path, 3, 0); + lv_obj_set_style_line_rounded(s_path, true, 0); + lv_obj_add_flag(s_path, LV_OBJ_FLAG_HIDDEN); + + for (int i = 0; i < sats::MAX_SATS; ++i) { + s_dot[i] = lv_obj_create(s_scr); + lv_obj_remove_style_all(s_dot[i]); + lv_obj_set_style_radius(s_dot[i], LV_RADIUS_CIRCLE, 0); + lv_obj_set_style_bg_opa(s_dot[i], LV_OPA_COVER, 0); + lv_obj_add_flag(s_dot[i], LV_OBJ_FLAG_HIDDEN); + s_dotLbl[i] = mk_label(s_scr, &lv_font_montserrat_12, C_OTHER); + lv_obj_add_flag(s_dotLbl[i], LV_OBJ_FLAG_HIDDEN); + } + + s_name = mk_label(s_scr, &lv_font_montserrat_24, C_INK); + s_line1 = mk_label(s_scr, &lv_font_montserrat_16, C_SEL); + s_line2 = mk_label(s_scr, &lv_font_montserrat_14, C_DIM); + lv_obj_align(s_name, LV_ALIGN_TOP_MID, 0, 352); + lv_obj_align(s_line1, LV_ALIGN_TOP_MID, 0, 384); + lv_obj_align(s_line2, LV_ALIGN_TOP_MID, 0, 408); + lv_label_set_text(s_name, "Satellites"); + return s_scr; +} + +void destroy() { + onExit(); + if (s_scr) lv_obj_del(s_scr); + s_scr = nullptr; s_path = nullptr; s_name = s_line1 = s_line2 = nullptr; + memset(s_dot, 0, sizeof(s_dot)); + memset(s_dotLbl, 0, sizeof(s_dotLbl)); +} + +void onEnter() { + if (!s_timer) s_timer = lv_timer_create(refresh, 1000, nullptr); + refresh(nullptr); +} + +void onExit() { + if (s_timer) { lv_timer_del(s_timer); s_timer = nullptr; } +} + +void onPress() { + if (!s_scr) return; + const double jdNow = sats::jdFromUnix((double)time(nullptr)); + int order[sats::MAX_SATS]; + const int n = ordered(order, jdNow); + if (n == 0) return; + int pos = -1; + for (int k = 0; k < n; ++k) { sats::Sat s; sats::snapshot(order[k], s); if (s.norad == s_selNorad) { pos = k; break; } } + sats::Sat s; sats::snapshot(order[(pos + 1) % n], s); + s_selNorad = s.norad; + refresh(nullptr); +} + +} // namespace satview diff --git a/src/sat_view.h b/src/sat_view.h new file mode 100644 index 0000000..7b718d8 --- /dev/null +++ b/src/sat_view.h @@ -0,0 +1,18 @@ +#pragma once +// Satellites: a sky dial of the satellites in sat_tracker's list. Zenith in the middle, the +// horizon at the rim, north up. Satellites above the horizon are dots; the selected one is +// amber, with the track of its current or next pass drawn across the sky and its next rise +// time, peak elevation and duration underneath. Push the knob (or tap) for the next one. +// +// Built on demand (app_shell::addLazy), so it costs nothing while it is not on the dial. +// Uses the system chrome (stock Montserrat, fixed colours), not a theme surface: Orb Studio +// has no controls for it yet. See docs/adding-a-screen.md for what that would take. +#include + +namespace satview { + lv_obj_t *build(); + void destroy(); + void onEnter(); + void onExit(); + void onPress(); +} diff --git a/src/settings_view.cpp b/src/settings_view.cpp index 683c31e..fdfb27d 100644 --- a/src/settings_view.cpp +++ b/src/settings_view.cpp @@ -67,6 +67,18 @@ extern void host_wx_units_set(int mode); // the on-screen zoom button in ui.cpp, which was the only way to change range and died // with the touchscreen. host_set_range_km() persists to NVS and re-renders, exactly as // that button's callback did. +// GPS (the -G board's LC76G) and the Capsule Radar second app slot. See main.cpp. +extern bool host_gps_present(); +extern bool host_gps_enabled(); +extern void host_gps_set_enabled(bool on); +extern void host_gps_status(char *out, size_t n); // "ON 8 sats" / "ON searching" / "OFF" +extern bool host_time_src_gps(); +extern void host_set_time_src_gps(bool gps); +extern void host_time_status(char *out, size_t n); // "WiFi" / "GPS" / "GPS (waiting)" +extern bool host_capsule_installed(); +extern bool host_flight_capsule(); // Flight Tracker opens Capsule Radar +extern void host_flight_set_capsule(bool on); +extern bool host_capsule_launch(); // switch boot slot + restart; false = not installed extern float host_get_range_km(); extern void host_set_range_km(float km); @@ -84,7 +96,7 @@ namespace { // "default selection", so an older theme may now open Settings on a neighbouring // item. Cosmetic only, and DEFAULT_SEL below still clamps anything out of range. enum { ITEM_DISPLAY = 0, ITEM_LOCATION, ITEM_SOUND, ITEM_UNITS, ITEM_RANGE, ITEM_WIFI, ITEM_DESIGN, ITEM_ABOUT, ITEM_RESET, ITEM_BACK, ITEM_COUNT }; - const char *ITEM_LABELS[ITEM_COUNT] = { "Display", "Location", "Sound", "Units", "Range", "WiFi", "Theme", "About", "Reset", "Back" }; + const char *ITEM_LABELS[ITEM_COUNT] = { "Display", "Location", "Sound", "Units", "Flight radar", "WiFi", "Theme", "About", "Reset", "Back" }; // A Launch Kit push's "Default selection" (was editor-preview-only; now baked // in) — which item the main menu opens on, both at first boot and every time // the app switcher hands control back to Settings. Out-of-range (a stale @@ -99,7 +111,9 @@ namespace { enum { UNIT_MODE = 0, UNIT_BACK, UNIT_COUNT }; // --- range submenu (Flight Tracker display range; steps come from config.h) --- - enum { RNG_VALUE = 0, RNG_BACK, RNG_COUNT }; + // Grew from Range/Back to also carry the flight-radar style: the built-in Orb scope, or + // Capsule Radar booted from the second app slot (partitions_16MB_dualboot.csv). + enum { RNG_VALUE = 0, RNG_STYLE, RNG_CAPSULE, RNG_BACK, RNG_COUNT }; const int RANGE_N = (int)(sizeof(RANGE_STEPS_KM) / sizeof(RANGE_STEPS_KM[0])); // --- display submenu (screen timeout + brightness) --- @@ -210,8 +224,8 @@ namespace { constexpr int CHIME_UI_MAX = theme_select::MAX_THEMES + 4; // --- location submenu --- - enum { LM_CURRENT = 0, LM_SEARCH, LM_RECENT, LM_BACK, LM_COUNT }; - const char *LM_LABELS[LM_COUNT] = { "Current location", "Search city", "Recent cities", "Back" }; + enum { LM_CURRENT = 0, LM_SEARCH, LM_RECENT, LM_GPS, LM_TIME, LM_BACK, LM_COUNT }; + const char *LM_LABELS[LM_COUNT] = { "Current location", "Search city", "Recent cities", "GPS", "Time", "Back" }; // Seed the recents list once (first boot) so "Recent cities" isn't empty. struct City { const char *name; double lat; double lon; }; @@ -818,6 +832,14 @@ namespace { char b[36]; snprintf(b, sizeof(b), "Range %.0f km", (double)host_get_range_km()); lv_label_set_text(s_rangeItems[RNG_VALUE], b); + if (!host_capsule_installed()) { + lv_label_set_text(s_rangeItems[RNG_STYLE], "Style Orb"); + lv_label_set_text(s_rangeItems[RNG_CAPSULE], "Capsule Radar: not installed"); + } else { + lv_label_set_text(s_rangeItems[RNG_STYLE], + host_flight_capsule() ? "Style Capsule Radar" : "Style Orb"); + lv_label_set_text(s_rangeItems[RNG_CAPSULE], "Open Capsule Radar"); + } lv_label_set_text(s_rangeItems[RNG_BACK], "Back"); wheel_layout(s_rangeItems, RNG_COUNT, s_rangeSel, s_rangeHl); } @@ -850,6 +872,18 @@ namespace { lv_obj_add_flag(s_lmCity, LV_OBJ_FLAG_HIDDEN); } } + if (s_lmItems[LM_GPS]) { + char g[40]; + if (!host_gps_present()) snprintf(g, sizeof(g), "GPS not fitted"); + else { char st[28]; host_gps_status(st, sizeof(st)); snprintf(g, sizeof(g), "GPS %s", st); } + lv_label_set_text(s_lmItems[LM_GPS], g); + } + if (s_lmItems[LM_TIME]) { + char st[24], t[40]; + host_time_status(st, sizeof(st)); + snprintf(t, sizeof(t), "Time from %s", st); + lv_label_set_text(s_lmItems[LM_TIME], t); + } wheel_layout(s_lmItems, LM_COUNT, s_lmSel, s_lmHl); } @@ -1561,6 +1595,16 @@ void settingsview::onPress() { } host_set_range_km(RANGE_STEPS_KM[(best + 1) % RANGE_N]); refresh_range(); + } else if (s_rangeSel == RNG_STYLE) { + if (host_capsule_installed()) host_flight_set_capsule(!host_flight_capsule()); + refresh_range(); + } else if (s_rangeSel == RNG_CAPSULE) { + if (host_capsule_installed()) { + lv_label_set_text(s_rangeItems[RNG_CAPSULE], "Starting Capsule Radar..."); + lv_refr_now(nullptr); + host_capsule_launch(); // restarts on success; returns only on failure + } + refresh_range(); } else { // Back -> exit Settings to the app switcher app_shell::setCaptured(false); app_shell::openSwitcher(); @@ -1637,6 +1681,12 @@ void settingsview::onPress() { } else if (s_lmSel == LM_RECENT) { load_recents(); show_page(MODE_RECENT); + } else if (s_lmSel == LM_GPS) { + if (host_gps_present()) host_gps_set_enabled(!host_gps_enabled()); + refresh_locmenu(); + } else if (s_lmSel == LM_TIME) { + if (host_gps_present()) host_set_time_src_gps(!host_time_src_gps()); + refresh_locmenu(); } else { // Back -> exit Settings to the app switcher app_shell::setCaptured(false); app_shell::openSwitcher(); @@ -2143,7 +2193,7 @@ void settingsview::init() { lv_obj_set_size(s_rangePage, SCREEN_W, SCREEN_H); lv_obj_center(s_rangePage); lv_obj_clear_flag(s_rangePage, LV_OBJ_FLAG_SCROLLABLE); lv_obj_t *rangetitle = lv_label_create(s_rangePage); - lv_label_set_text(rangetitle, "Range"); + lv_label_set_text(rangetitle, "Flight radar"); lv_obj_set_style_text_color(rangetitle, C_DIM, 0); lv_obj_set_style_text_font(rangetitle, &lv_font_montserrat_16, 0); lv_obj_align(rangetitle, LV_ALIGN_CENTER, 0, -122); @@ -2156,10 +2206,10 @@ void settingsview::init() { // Font, opacity, position: wheel_layout(), called from refresh_range(). } lv_obj_t *rangehint = lv_label_create(s_rangePage); - lv_label_set_text(rangehint, "push to cycle how far the scope sees"); + lv_label_set_text(rangehint, "Capsule Radar: press the knob to come back"); lv_obj_set_style_text_color(rangehint, C_GREY, 0); lv_obj_set_style_text_font(rangehint, &lv_font_montserrat_14, 0); - lv_obj_align(rangehint, LV_ALIGN_CENTER, 0, 122); + lv_obj_align(rangehint, LV_ALIGN_CENTER, 0, 150); // --- units menu page (Auto/Metric/Imperial cycle / Back) --- s_unitsPage = lv_obj_create(s_screen); diff --git a/src/sim_main.cpp b/src/sim_main.cpp index ea3995d..afb2007 100644 --- a/src/sim_main.cpp +++ b/src/sim_main.cpp @@ -47,6 +47,8 @@ #include "knob.h" // consumed-input API (implemented by sim_knob.cpp on native) #include "sim_knob.h" // inject SDL events into the knob:: backend #include "input_router.h" // shared knob->app_shell routing (same as the device) +#include "sat_tracker.h" // Satellites: data +#include "sat_view.h" // Satellites: screen #include "native_http.h" #include #include @@ -221,6 +223,19 @@ void host_wx_units_set(int) {} // holds the value and re-renders, which is enough to exercise the menu and the scope. static float s_simRangeKm = RANGE_KM_DEFAULT; float host_get_range_km() { return s_simRangeKm; } +// GPS and the Capsule Radar slot are device-only. The simulator has neither: Settings shows +// "GPS not fitted" and "Capsule Radar: not installed", and every action is a no-op. +bool host_gps_present() { return false; } +bool host_gps_enabled() { return false; } +void host_gps_set_enabled(bool) {} +void host_gps_status(char *out, size_t n) { if (n) snprintf(out, n, "not fitted"); } +bool host_capsule_installed() { return false; } +bool host_flight_capsule() { return false; } +void host_flight_set_capsule(bool) {} +bool host_capsule_launch() { return false; } +bool host_time_src_gps() { return false; } +void host_set_time_src_gps(bool) {} +void host_time_status(char *out, size_t n) { if (n) snprintf(out, n, "WiFi"); } void host_set_range_km(float km); // defined below, once g_set/g_mockAcs are in scope #include #include @@ -648,10 +663,13 @@ static void sim_register_apps(lv_obj_t *radarScreen) { []() { ui_show_view(0); radar::knobEnter(); }, // onEnter: show scope, then land in default view radar::knobExit, // onExit: free style + reset selection !theme_style::apps().flight); -#if !APPS_LAUNCH_ONE +#if ORB_HAS_WEATHER app_shell::add(radarScreen, theme_style::names().weather, []() { static bool fc = false; fc = !fc; ui_set_weather_forecast(fc); }, // push toggles WX/forecast - nullptr, false, []() { wx_map_prepare(g_set.homeLat, g_set.homeLon, 0); ui_weather_art_attach(); ui_show_view(1); }, nullptr, !theme_style::apps().weather); + nullptr, false, []() { wx_map_prepare(g_set.homeLat, g_set.homeLon, 0); ui_weather_art_attach(); ui_show_view(1); }, nullptr, + ORB_APP_WEATHER ? false : !theme_style::apps().weather); +#endif +#if !APPS_LAUNCH_ONE app_shell::add(survScreen, theme_style::names().surveillance, nullptr, nullptr, false, nullptr, nullptr, !theme_style::apps().surveillance); #else (void)survScreen; // built above; not on launch one's roster (CUT-01) @@ -680,6 +698,11 @@ static void sim_register_apps(lv_obj_t *radarScreen) { app_shell::add(tickerview::screen(), theme_style::names().ticker, tickerview::onPress, tickerview::onTurn, false, tickerview::onEnter, tickerview::onExit, !theme_style::apps().ticker); +#endif +#if ORB_APP_SATS + sats::begin([](double *la, double *lo, double *al) { *la = g_set.homeLat; *lo = g_set.homeLon; *al = 0; return true; }); + app_shell::add(satview::build(), "Satellites", satview::onPress, nullptr, false, + satview::onEnter, satview::onExit, false); #endif // After the Ticker, matching main.cpp. The selftests below address apps by index, so the // two lineups have to stay in the same order or the simulator stops standing in for the @@ -814,6 +837,9 @@ int main(int argc, char **argv) { // seconds of stillness, and the briefing needs a real answer from the gateway to have // anything in it. This makes the same two round trips the Orb makes. const char *newsShot = (argc >= 3 && strcmp(argv[1], "--newsshot") == 0) ? argv[2] : NULL; + // --satshot : the Satellites sky dial, then again after a push selects the next + // satellite. Offline TLEs come from sim/sats.tle when CelesTrak cannot be reached. + const char *satShot = (argc >= 3 && strcmp(argv[1], "--satshot") == 0) ? argv[2] : NULL; // --settingsshot walks the Settings wheel to the bottom of the list and // captures it. The bug this exists for only appears at the far end of a long list, and // it appears there because rows more than a quarter turn away were CLAMPED onto the top @@ -1856,6 +1882,12 @@ int main(int argc, char **argv) { // Only when the apps were actually registered. The headless capture modes put a // single screen up directly and never build the shell, so there is nothing here for // a fetched headline to be drawn into, and no reason to spend the request. +#if ORB_APP_SATS + if (interactive || satShot) { + static Uint32 lastSat = 0; + if (now - lastSat > 300) { lastSat = now; sats::step(true); } + } +#endif if (interactive || newsShot) { static Uint32 lastNet = 0; if (now - lastNet > 400) { @@ -2226,7 +2258,7 @@ int main(int argc, char **argv) { static Uint32 wxAt = 0; if (wxShot) { if (wxStep == 0 && now - start > 3000) { -#if APPS_LAUNCH_ONE +#if !ORB_HAS_WEATHER // The weather map is not on this build's roster (CUT-01), so there is // nothing for this harness to photograph. Said rather than silently // capturing whatever screen happens to be up, which is how the --shot @@ -2279,6 +2311,25 @@ int main(int argc, char **argv) { } } +#if ORB_APP_SATS + static int satStep = 0; + static Uint32 satAt = 0; + if (satShot) { + if (satStep == 0 && now - start > 2500) { + app_shell::selectApp(app_shell::APP_SATS); + satStep = 1; satAt = now; + } else if (satStep == 1 && now - satAt > 2500) { + char path[300]; snprintf(path, sizeof(path), "%s-a.bmp", satShot); + sim_save_frame(path); + input_router::dispatch(0, true); // push: next satellite + satStep = 2; satAt = now; + } else if (satStep == 2 && now - satAt > 1500) { + char path[300]; snprintf(path, sizeof(path), "%s-b.bmp", satShot); + sim_save_frame(path); + run = false; + } + } +#endif static int newsStep = 0; static Uint32 newsAt = 0; if (newsShot) { diff --git a/src/touch_cst9217.cpp b/src/touch_cst9217.cpp index 70a553f..1e3eb7d 100644 --- a/src/touch_cst9217.cpp +++ b/src/touch_cst9217.cpp @@ -43,14 +43,18 @@ bool touch_begin() { return true; } -bool touch_read(uint16_t *ox, uint16_t *oy) { +bool touch_read(uint16_t *ox, uint16_t *oy) { return touch_poll(ox, oy) == 1; } + +// Tri-state, from Capsule Radar's version of this driver: a failed or unacknowledged read is +// NOT a release. Treating it as one split a drag into two touches and made phantom taps. +int touch_poll(uint16_t *ox, uint16_t *oy) { uint8_t d[CST9217_DATA_LEN]; - if (!cst_read_reg(CST9217_REG_DATA, d, CST9217_DATA_LEN)) return false; - if (d[6] != CST9217_ACK) return false; + if (!cst_read_reg(CST9217_REG_DATA, d, CST9217_DATA_LEN)) return -1; + if (d[6] != CST9217_ACK) return -1; const uint8_t points = d[5] & 0x7F; - if (points == 0) return false; - if ((d[0] & 0x0F) != 0x06) return false; // status of point 0 must be "down" + if (points == 0) return 0; + if ((d[0] & 0x0F) != 0x06) return 0; // status of point 0 must be "down" uint16_t x = ((uint16_t)d[1] << 4) | (d[3] >> 4); uint16_t y = ((uint16_t)d[2] << 4) | (d[3] & 0x0F); @@ -62,5 +66,5 @@ bool touch_read(uint16_t *ox, uint16_t *oy) { *ox = x; *oy = y; - return true; + return 1; } diff --git a/src/touch_cst9217.h b/src/touch_cst9217.h index e166cf5..ee15292 100644 --- a/src/touch_cst9217.h +++ b/src/touch_cst9217.h @@ -5,3 +5,4 @@ bool touch_begin(); // I2C + hardware reset; logs comms status bool touch_read(uint16_t *x, uint16_t *y); // true if currently pressed (x,y in screen px) +int touch_poll(uint16_t *x, uint16_t *y); // 1 down (x,y set), 0 up, -1 no answer (keep the last state) diff --git a/src/ui.cpp b/src/ui.cpp index b44394c..35dd9f5 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -434,8 +434,12 @@ static void wx_anim_cb(lv_timer_t *t) { // fact {age} and {updated} now give a design to place where it wants. So a theme // composing its own text gets the bare source name and nothing else. char attr[64]; - if (wx_slots_active()) snprintf(attr, sizeof(attr), "RAINVIEWER"); - else snprintf(attr, sizeof(attr), "RADAR %s | RAINVIEWER", stamp); + // Whether the newest frame held any rain, so a clear map reads as a clear sky and not + // as a radar that has stopped working. + const char *rain = !wx_radar_latest_time() ? "" : + wx_radar_latest_rain_px() ? " RAIN" : " NO RAIN"; + if (wx_slots_active()) snprintf(attr, sizeof(attr), "RAINVIEWER%s", rain); + else snprintf(attr, sizeof(attr), "RADAR %s%s | RAINVIEWER", stamp, rain); lv_label_set_text(s_wxAttrib, attr); } } @@ -486,6 +490,24 @@ static void wx_status_timer_cb(lv_timer_t *) { // // An unknown token comes out empty, which reads as a typo. Leaving "{tmp}" on the glass // would read as the firmware being broken. +// The Montserrat on the compiled ladder closest to `factor` times a font's line height. A +// theme font is baked at one size and cannot be scaled, so a resized line changes face. +static const lv_font_t *wx_bigger_font(const lv_font_t *f, float factor) { + static const lv_font_t *const LADDER[] = { + &lv_font_montserrat_14, &lv_font_montserrat_16, &lv_font_montserrat_18, &lv_font_montserrat_20, + &lv_font_montserrat_22, &lv_font_montserrat_24, &lv_font_montserrat_26, &lv_font_montserrat_28, + &lv_font_montserrat_32, &lv_font_montserrat_36, &lv_font_montserrat_40, &lv_font_montserrat_44, + &lv_font_montserrat_48 }; + const int want = f ? (int)lroundf(f->line_height * factor) : 22; + const lv_font_t *best = LADDER[0]; + int bestD = 1 << 30; + for (const lv_font_t *c : LADDER) { + const int d = abs((int)c->line_height - want); + if (d < bestD) { bestD = d; best = c; } + } + return best; +} + static void wx_text_refresh(void) { const theme_style::Weather &ws = theme_style::weather(); if (!wx_slots_active()) { @@ -569,14 +591,20 @@ static void wx_text_refresh(void) { const char *condN[4]; for (int d = 0; d < 4; ++d) { const bool ok = have && d < w.dayCount; - snprintf(dayS[d], sizeof(dayS[d]), "%s", ok ? weather_day_name(w.days[d].date) : ""); - snprintf(highS[d], sizeof(highS[d]), ok ? "%.0f" : "%s", - ok ? (double)weather_temp(w.days[d].tempMaxC) : 0.0); - snprintf(lowS[d], sizeof(lowS[d]), ok ? "%.0f" : "%s", - ok ? (double)weather_temp(w.days[d].tempMinC) : 0.0); - snprintf(rainS[d], sizeof(rainS[d]), ok ? "%d" : "%s", ok ? w.days[d].rainChance : 0); - if (!ok) { highS[d][0] = 0; lowS[d][0] = 0; rainS[d][0] = 0; } + // Blank until the forecast is in. This used to pick the FORMAT by `ok` ("%.0f" or + // "%s") but always pass a number, so before the first forecast arrived "%s" was + // handed 0.0 and dereferenced it: a LoadProhibited in _svfprintf_r and a reset every + // time the Weather Radar opened early (coredump, 2026-11-18). Never mix formats. + dayS[d][0] = highS[d][0] = lowS[d][0] = rainS[d][0] = 0; + if (ok) { + const char *dn = weather_day_name(w.days[d].date); + snprintf(dayS[d], sizeof(dayS[d]), "%s", dn ? dn : ""); + snprintf(highS[d], sizeof(highS[d]), "%.0f", (double)weather_temp(w.days[d].tempMaxC)); + snprintf(lowS[d], sizeof(lowS[d]), "%.0f", (double)weather_temp(w.days[d].tempMinC)); + snprintf(rainS[d], sizeof(rainS[d]), "%d", w.days[d].rainChance); + } condN[d] = ok ? weather_condition(w.days[d].code) : ""; + if (!condN[d]) condN[d] = ""; } const text_tokens::Tok toks[] = { @@ -595,15 +623,38 @@ static void wx_text_refresh(void) { const size_t nToks = sizeof(toks) / sizeof(toks[0]); const curved_text::Target dst = { (uint8_t *)s_wxTextBuf, SCREEN_W, SCREEN_H }; + // Owner's request (2026-11-17): the temperature and condition lines read too dim against + // the map. They take the WIND line's colour and opacity, and draw 25% larger. A theme + // font is baked at one size and cannot be scaled, so the larger size is the nearest + // Montserrat on the compiled ladder (wx_bigger_font). Lines that also carry {wind} are + // left exactly as the theme set them. + int windSlot = -1; + for (int i = 0; i < 4; ++i) + if (ws.text[i].show && strstr(ws.text[i].fmt, "{wind")) { windSlot = i; break; } for (int i = 0; i < 4; ++i) { - const theme_style::TextSlot &t = ws.text[i]; + theme_style::TextSlot t = ws.text[i]; if (!t.show) continue; + const bool tempLine = !strstr(t.fmt, "{wind") && + (strstr(t.fmt, "{temp") || strstr(t.fmt, "{cond") || strstr(t.fmt, "{feels")); + // Owner's sizes (2026-11-18), relative to the theme's own font for the line: + // temperature / condition +12.5% (was +25%, then asked 10% smaller) + // range readout ("50 MI") +20% + // last-updated / age line +20% + float scale = 1.0f; + if (tempLine) scale = 1.125f; + else if (strstr(t.fmt, "{range")) scale = 1.20f; + else if (strstr(t.fmt, "{updated") || strstr(t.fmt, "{age")) scale = 1.20f; + if (tempLine) { + if (windSlot >= 0) { t.color = ws.text[windSlot].color; t.opa = ws.text[windSlot].opa; } + else t.opa = 255; + } char buf[96]; text_tokens::expand(buf, sizeof(buf), t.fmt, toks, nToks); if (!buf[0]) continue; // After the tokens, so {temp} and {cond} are caps too. THEME_CAPS 53. if (t.upper) orb_upper(buf); const lv_font_t *font = theme_font::weather_text(i); + if (scale != 1.0f) font = wx_bigger_font(font, scale); if (t.curved) { // The SCREEN centre, like every other curved line on the device. // @@ -637,7 +688,7 @@ static void wx_text_refresh(void) { // how the curved one starts telling a different time from the straight one. const char *credit = s_wxAttrib ? lv_label_get_text(s_wxAttrib) : nullptr; if (credit && credit[0]) { - curved_text::draw_arc(dst, F14(), credit, + curved_text::draw_arc(dst, wx_bigger_font(F14(), 1.2f), credit, // +20% (owner, 2026-11-18) (float)(SCREEN_W / 2), (float)(SCREEN_H / 2), (float)ws.credit.curveR, (float)ws.credit.arcDeg, lv_color_hex(ws.credit.color), 0, lv_color_black(), @@ -1431,11 +1482,13 @@ void ui_create(void) { // pixels it is actually protecting. s_wxFooter = lv_label_create(wp); lv_obj_set_width(s_wxFooter, LV_SIZE_CONTENT); - lv_obj_set_style_text_font(s_wxFooter, F16(), 0); - lv_obj_set_style_text_color(s_wxFooter, UI_INK, 0); + // 25% larger than it was (F16 -> 20 px) and in the wind line's colour: it read too dim + // against the map (owner, 2026-11-17). + lv_obj_set_style_text_font(s_wxFooter, s_bigText ? &lv_font_montserrat_24 : &lv_font_montserrat_20, 0); + lv_obj_set_style_text_color(s_wxFooter, UI_SOFT, 0); lv_obj_set_style_text_align(s_wxFooter, LV_TEXT_ALIGN_CENTER, 0); lv_label_set_text(s_wxFooter, "WEATHER DATA PENDING"); - lv_obj_align(s_wxFooter, LV_ALIGN_TOP_MID, 0, 326); + lv_obj_align(s_wxFooter, LV_ALIGN_TOP_MID, 0, 318); // up 8 px for its larger type lv_obj_set_style_bg_color(s_wxFooter, lv_color_black(), 0); lv_obj_set_style_bg_opa(s_wxFooter, 185, 0); lv_obj_set_style_pad_hor(s_wxFooter, 8, 0); @@ -1445,11 +1498,11 @@ void ui_create(void) { lv_obj_set_style_radius(s_wxFooter, 7, 0); s_wxMeta = lv_label_create(wp); lv_obj_set_width(s_wxMeta, LV_SIZE_CONTENT); - lv_obj_set_style_text_font(s_wxMeta, F14(), 0); + lv_obj_set_style_text_font(s_wxMeta, s_bigText ? &lv_font_montserrat_22 : &lv_font_montserrat_18, 0); // +25% lv_obj_set_style_text_color(s_wxMeta, UI_SOFT, 0); lv_obj_set_style_text_align(s_wxMeta, LV_TEXT_ALIGN_CENTER, 0); lv_label_set_text(s_wxMeta, ""); - lv_obj_align(s_wxMeta, LV_ALIGN_TOP_MID, 0, 351); + lv_obj_align(s_wxMeta, LV_ALIGN_TOP_MID, 0, 348); // clears the credit line at 376 at its larger size lv_obj_set_style_bg_color(s_wxMeta, lv_color_black(), 0); lv_obj_set_style_bg_opa(s_wxMeta, 185, 0); lv_obj_set_style_pad_hor(s_wxMeta, 8, 0); @@ -1467,7 +1520,7 @@ void ui_create(void) { lv_obj_clear_flag(s_wxTextCanvas, LV_OBJ_FLAG_CLICKABLE); s_wxAttrib = lv_label_create(wp); - lv_obj_set_style_text_font(s_wxAttrib, F12(), 0); + lv_obj_set_style_text_font(s_wxAttrib, wx_bigger_font(F12(), 1.2f), 0); // +20% (owner, 2026-11-18) lv_obj_set_style_text_color(s_wxAttrib, UI_DIM, 0); lv_label_set_text(s_wxAttrib, "WAITING FOR RADAR DATA"); lv_obj_align(s_wxAttrib, LV_ALIGN_TOP_MID, 0, 376); diff --git a/src/wx_radar.h b/src/wx_radar.h index 8bdf078..f3f805a 100644 --- a/src/wx_radar.h +++ b/src/wx_radar.h @@ -31,6 +31,10 @@ // churn that starves the weather radar's own TLS handshake (-32512). void wx_radar_begin(void); // take the frame buffers +// The newest frame fetched: precipitation pixels it decoded (0 = a dry sky, not a fault) and +// its timestamp (0 = nothing fetched yet). Read by the UI for the "NO RAIN" readout. +uint32_t wx_radar_latest_rain_px(); +uint32_t wx_radar_latest_time(); // Give them back. MUST be called from the network task only: see the note in wx_radar.cpp. // The UI asks for this by flag; it never calls it. void wx_radar_release(void); diff --git a/src/wx_radar_client.cpp b/src/wx_radar_client.cpp index c48ed7f..b2fe6a8 100644 --- a/src/wx_radar_client.cpp +++ b/src/wx_radar_client.cpp @@ -38,6 +38,13 @@ static void heap_caps_free(void *p) { free(p); } static PNG *s_png = nullptr; static uint32_t s_decodedPixels = 0; +// What the newest frame held, for the screen to say out loud. On a dry day the radar map is +// indistinguishable from a broken one, so the screen reports "NO RAIN" for a frame that +// arrived and decoded with nothing in it, as opposed to saying nothing at all. +static volatile uint32_t s_lastRainPx = 0; +static volatile uint32_t s_lastFrameTime = 0; +uint32_t wx_radar_latest_rain_px() { return s_lastRainPx; } +uint32_t wx_radar_latest_time() { return s_lastFrameTime; } static uint32_t s_sourcePixels = 0; static int s_minX = WX_RADAR_SOURCE_SIZE, s_minY = WX_RADAR_SOURCE_SIZE; static int s_maxX = -1, s_maxY = -1; @@ -652,6 +659,7 @@ int wx_radar_fetch_frame(double lat, double lon, int zoomTier, uint32_t gen, int draw_rings(wx_radar_back_buffer()); // over the rain, under the keep-out areas wx_apply_zones(wx_radar_back_buffer()); wx_radar_commit_frame(slot, gen, s_times[slot], lat, lon); + if (s_times[slot] >= s_lastFrameTime) { s_lastFrameTime = s_times[slot]; s_lastRainPx = s_decodedPixels; } Serial.printf("[wxradar] gen %lu frame %d/%d @%lu (tier=%d, %lu px)\n", (unsigned long)gen, slot + 1, s_availFrames, (unsigned long)s_times[slot], zoomTier, (unsigned long)s_decodedPixels); diff --git a/tools/capsule-radar/.gitignore b/tools/capsule-radar/.gitignore new file mode 100644 index 0000000..4e2c79f --- /dev/null +++ b/tools/capsule-radar/.gitignore @@ -0,0 +1,2 @@ +out/ +.work/ diff --git a/tools/capsule-radar/build.sh b/tools/capsule-radar/build.sh new file mode 100644 index 0000000..1af56aa --- /dev/null +++ b/tools/capsule-radar/build.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Build Capsule Radar for The Orb's second app slot (ota_1, partitions_16MB_dualboot.csv). +# +# Clones socquique/capsule-radar at a pinned commit, applies orb-slot.patch (own NVS namespace +# seeded from the Orb, knob press = back to The Orb, knob turn = zoom, OTA off, GPS on by +# default) and builds the 1.75 env. Output: tools/capsule-radar/out/capsule-radar.bin +# +# To move to a newer Capsule Radar: change UPSTREAM_REF, run this, fix any patch rejects. +set -euo pipefail +UPSTREAM_REF="${UPSTREAM_REF:-d8267b1}" +HERE="$(cd "$(dirname "$0")" && pwd)" +WORK="$HERE/.work" +OUT="$HERE/out" +mkdir -p "$OUT" +if [ ! -d "$WORK/.git" ]; then + git clone https://github.com/socquique/capsule-radar "$WORK" +fi +git -C "$WORK" fetch -q origin +git -C "$WORK" checkout -q -f "$UPSTREAM_REF" +git -C "$WORK" clean -qfd src +git -C "$WORK" apply "$HERE/orb-slot.patch" +( cd "$WORK" && pio run -e esp32-s3-amoled-175 ) +cp "$WORK/.pio/build/esp32-s3-amoled-175/firmware.bin" "$OUT/capsule-radar.bin" +SIZE=$(stat -c %s "$OUT/capsule-radar.bin" 2>/dev/null || stat -f %z "$OUT/capsule-radar.bin") +LIMIT=$((0x380000)) +if [ "$SIZE" -gt "$LIMIT" ]; then + echo "capsule-radar.bin is $SIZE bytes; the ota_1 slot is $LIMIT. Grow app1 in partitions_16MB_dualboot.csv." >&2 + exit 1 +fi +echo "OK: $OUT/capsule-radar.bin ($SIZE bytes, slot $LIMIT)" diff --git a/tools/capsule-radar/orb-slot.patch b/tools/capsule-radar/orb-slot.patch new file mode 100644 index 0000000..0a980ad --- /dev/null +++ b/tools/capsule-radar/orb-slot.patch @@ -0,0 +1,477 @@ +diff --git a/src/config.h b/src/config.h +index 3fe1fa4..8fb2757 100644 +--- a/src/config.h ++++ b/src/config.h +@@ -1,7 +1,7 @@ + #pragma once + // Capsule Radar — build & user configuration. + +-#define FW_VERSION "1.9.0" // shown on the web config page + Stats screen; bump on release ++#define FW_VERSION "1.9.0-orb1" // shown on the web config page + Stats screen; bump on release + + // ---------- Home location (default: Dénia, Spain) ---------- + // Overridable at runtime via the captive portal (stored in NVS). +diff --git a/src/main.cpp b/src/main.cpp +index c508640..cd7c813 100644 +--- a/src/main.cpp ++++ b/src/main.cpp +@@ -25,6 +25,7 @@ + #include "imu_qmi8658.h" // face-down sleep: accelerometer reads + #include "facedown_sleep.h" // face-down sleep: the decision + #include "gps.h" // LC76G GNSS (-G variant only) ++#include "orb_slot.h" // THE ORB: second-slot glue (own NVS, knob, back to The Orb) + #include "battery.h" // AXP2101 battery gauge + #include "rtc_pcf85063.h" // PCF85063 RTC (offline clock + date) + #include "audio.h" // ES8311 alert pings +@@ -299,8 +300,9 @@ static void adsb_task(void*) { + } + + static void loadSettings() { ++ orb_slot::seedFromOrbOnce(); // THE ORB: first run picks up the Orb's location, tz and range + Preferences p; +- p.begin("capsuleradar", true); ++ p.begin(ORB_CR_NVS_NS, true); + g_settings.homeLat = p.getDouble("homeLat", HOME_LAT_DEFAULT); + g_settings.homeLon = p.getDouble("homeLon", HOME_LON_DEFAULT); + // Repair a value that can't work: an old install may hold the 250 km the web page once +@@ -312,7 +314,7 @@ static void loadSettings() { + g_muted = p.getBool("mute", false); + g_alertMode = constrain(p.getInt("alertmode", 2), 0, 3); + g_proximityKm = p.getFloat("proxkm", 0.0f); +- g_useGps = p.getBool("usegps", false); ++ g_useGps = p.getBool("usegps", true); // THE ORB: on by default (no-op without the -G module) + g_trailLen = p.getInt("traillen", 2); + g_maxAc = p.getInt("maxac", 20); + g_idleDimMs = p.getUInt("idledim", IDLE_DIM_MS); +@@ -404,7 +406,7 @@ static float queryRadiusKm() { + static void onRangeChange(float km) { + g_settings.rangeKm = km; + Preferences p; +- p.begin("capsuleradar", false); ++ p.begin(ORB_CR_NVS_NS, false); + p.putFloat("rangeKm", km); + p.end(); + g_requeryKm = queryRadiusKm(); +@@ -417,7 +419,7 @@ static void onRangeChange(float km) { + // Persist the visual theme in NVS (called when the user holds the radar to switch it). + static void saveTheme(int t) { + Preferences p; +- p.begin("capsuleradar", false); ++ p.begin(ORB_CR_NVS_NS, false); + p.putInt("theme", t); + p.end(); + } +@@ -742,7 +744,8 @@ static void handleRoot() { + "
Network
" + "

Forget the saved WiFi and reopen the setup portal.

" + "
" +- "

Reach me at capsuleradar.local · Firmware update · v" FW_VERSION "

" ++ "

Reach me at capsuleradar.local · v" FW_VERSION " (The Orb slot)

" ++ "
" + "