-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
328 lines (295 loc) · 8.93 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import React, { useState, useEffect } from "react";
import { Text, View, Dimensions, Image } from "react-native";
import Svg, {
Circle,
Line,
G,
Text as SvgText,
SvgUri,
} from "react-native-svg";
import * as Location from "expo-location";
import { DeviceMotion, DeviceMotionMeasurement } from "expo-sensors";
import { Camera, CameraType } from "expo-camera";
import { styles } from "./style";
import { generateSolarTable, SolarTable, SolarPosition } from "./solar";
import { LogBox } from "react-native";
// Some bug in Expo
LogBox.ignoreLogs([
`Constants.platform.ios.model has been deprecated in favor of expo-device's Device.modelName property. This API will be removed in SDK 45.`,
]);
const halfPI = Math.PI / 2;
type Orientation = {
heading: number;
pitch: number;
};
function toDegrees(radians: number) {
return (radians * 180) / Math.PI;
}
function padTime(n: number | undefined) {
if (n == undefined) {
return "--";
}
return n.toString().padStart(2, "0");
}
function formatTime(date: Date | undefined) {
return padTime(date?.getHours()) + ":" + padTime(date?.getMinutes());
}
function SolarTime(props: { position: SolarPosition; style?: object }) {
return (
<Text style={[styles.paragraph, props.style]}>
{formatTime(props.position?.time)}
</Text>
);
}
function SolarElevation(props: { position: SolarPosition; style?: object }) {
return (
<Text style={[styles.paragraph, props.style]}>
☀️ {props.position?.elevation || "--"}º
</Text>
);
}
function CompassPoint(props: { heading: number; style?: object }) {
const abbreviations = [
"N",
"NNE",
"NE",
"ENE",
"E",
"ESE",
"SE",
"SSE",
"S",
"SSW",
"SW",
"WSW",
"W",
"WNW",
"NW",
"NNW",
];
function abbreviate(angle: number) {
return abbreviations[Math.floor(angle / (360 / abbreviations.length))];
}
return (
<Text style={[styles.paragraph, props.style]}>
{abbreviate(props.heading)}
</Text>
);
}
function Heading(props: { heading: number; style?: object }) {
return (
<Text style={[styles.paragraph, props.style]}>
{props.heading.toFixed(0)}º
</Text>
);
}
function HeadUpDisplay(props: {
orientation: Orientation;
solarPosition: SolarPosition;
}) {
const { height, width } = Dimensions.get("window");
const iconSize = width / 8;
const textSize = 32;
const degPerPixel = height / 60; // assuming FOV=60º for now
const relativeElevation =
props.orientation.pitch - props.solarPosition.elevation;
const sun = {
x: 0,
y: relativeElevation * degPerPixel,
};
const horizon = { y: props.orientation.pitch * degPerPixel };
const isSunVisible =
sun.y > height / 2 + iconSize || sun.y + iconSize + textSize < -height / 2;
const arrowTransform =
sun.y < 0
? `translate(${
width / 2 - iconSize
} ${iconSize}) rotate(180 ${iconSize} ${iconSize})`
: `translate(${width / 2 - iconSize} ${(height * 3) / 4 - iconSize})`;
const Arrow = require("./assets/arrow.svg");
return (
<Svg
width="100%"
height="100%"
fill="none"
style={[styles.fullScreen, { zIndex: 1 }]}
>
<G transform={`translate(${width / 2} ${height / 2})`}>
<Circle cx={sun.x} cy={sun.y} r={iconSize} fill="rgba(255,255,0,0.5)" />
<Line
x1={-width / 2}
y1={horizon.y}
x2={width / 2}
y2={horizon.y}
stroke="rgba(255,255,255,0.5)"
strokeWidth="5"
/>
<SvgText
x={sun.x}
y={sun.y + iconSize + textSize}
textAnchor="middle"
stroke={"rgb(255,255,255)"}
fill={"rgb(255,255,255)"}
fontSize={textSize}
fontFamily="Baskerville"
fontWeight="bold"
>
{formatTime(props.solarPosition.time)}
</SvgText>
</G>
{isSunVisible ? (
<G transform={arrowTransform}>
<SvgUri
uri={Image.resolveAssetSource(Arrow).uri}
width={width / 4}
height={width / 4}
stroke={"rgba(0,0,0,0.5)"}
fill={"rgba(255,255,255,0.25)"}
/>
</G>
) : (
""
)}
</Svg>
);
}
export default function App() {
const [location, setLocation] = useState<Location.LocationObjectCoords>();
const [orientation, setOrientation] = useState({ heading: 0, pitch: 0 });
const [solarPosition, setSolarPosition] = useState<SolarPosition>({
time: new Date(),
elevation: 0,
});
const [_errorMsg, setErrorMsg] = useState("");
const [cameraReady, setCameraReady] = useState(false);
const subscriptions: { remove: () => void }[] = [];
let motionReading: DeviceMotionMeasurement,
compassReading: Location.LocationHeadingObject,
priorOrientation: Orientation | undefined;
let solarTable: SolarTable;
const smoothValues = (
prior: number,
next: number,
smoothing: number = 0.5
) => {
return prior * smoothing + next * (1 - smoothing);
};
const updateOrientation = () => {
if (!motionReading || !compassReading || !solarTable) return;
const { beta, gamma } = motionReading.rotation;
const azimuth = compassReading.trueHeading;
// Make pitch be 0º at the horizon and +/- depending on up or down
// This math requires orientation close to portrait. Would be nice
// to make it more resilient to roll axis.
const upwards = Math.abs(gamma) > halfPI;
const absBeta = Math.abs(beta);
let pitch = toDegrees(upwards ? halfPI - absBeta : absBeta - halfPI);
// For whatever reason the magnetometer flips orientation when
// the device pitches ~roughly~ 45º above the horizon?
// TODO: Make sure this doesn't flap right around 45º elevation.
let heading = pitch < 45 ? azimuth : (azimuth + 180) % 360;
if (priorOrientation) {
pitch = smoothValues(priorOrientation.pitch, pitch);
heading = smoothValues(priorOrientation.heading, heading);
}
setOrientation({ pitch, heading });
priorOrientation = { pitch, heading };
const tableEntry = Math.floor(heading);
setSolarPosition(solarTable[tableEntry]);
};
useEffect(() => {
(async () => {
const locationPerms = await Location.requestForegroundPermissionsAsync();
if (locationPerms.status !== "granted") {
setErrorMsg("Permission to access location was denied");
console.log("Location permission denied");
return;
}
const cameraPerms = await Camera.requestCameraPermissionsAsync();
if (cameraPerms.status === "granted") {
setCameraReady(true);
} else {
setErrorMsg("Permission to access camera was denied");
console.log("Camera permission denied");
}
// Get position fix (we only need it once)
const lastKnownLocation = await Location.getLastKnownPositionAsync();
if (!lastKnownLocation) {
setErrorMsg("Can't determine last known location");
return;
}
setLocation(lastKnownLocation.coords);
if (!solarTable) {
solarTable = generateSolarTable(lastKnownLocation.coords);
}
// Start watching the device's compass heading
subscriptions.push(
await Location.watchHeadingAsync((reading) => {
compassReading = reading;
updateOrientation();
})
);
})();
subscriptions.push(
DeviceMotion.addListener((reading) => {
motionReading = reading;
updateOrientation();
})
);
return () => {
subscriptions.forEach((sub) => {
sub.remove();
});
};
}, []);
return (
<View style={styles.container}>
{cameraReady ? (
<Camera
type={CameraType.back}
style={[styles.fullScreen, { zIndex: 0 }]}
/>
) : (
""
)}
<HeadUpDisplay orientation={orientation} solarPosition={solarPosition} />
<View style={[styles.container, { flex: 7 }]} />
<View
style={[
styles.container,
styles.widget,
{
flexDirection: "row",
flexGrow: 1,
alignItems: "stretch",
},
]}
>
<View style={styles.container}>
<CompassPoint
heading={orientation.heading}
style={{ fontSize: 32, fontFamily: "Baskerville" }}
/>
{/*
<SolarTime position={solarPosition} style={{ fontSize: 32 }} />
<SolarElevation position={solarPosition} style={{ fontSize: 16 }} />
*/}
</View>
{/*}
<View style={styles.container}>
<Text style={styles.paragraph}>
↕️ {orientation.pitch.toFixed()}º
</Text>
</View>*/}
</View>
{/*
<View style={[styles.container, styles.widget, { alignSelf: "stretch" }]}>
<Text style={{ ...styles.paragraph, fontSize: 16 }}>
{location?.latitude.toFixed(4)}ºN
{location?.longitude.toFixed(4)}ºE
</Text>
</View>
*/}
</View>
);
}