#!/usr/bin/env python3
"""Find how an XREAL's IMU axes sit on the head, for imu.c's axis map.
Run it in XR, where the terminal is in the glasses, and
follow the prompts: look level, turn your head left, then nod down. Prints the C8_XR_AXES string to try (head x right,
y up, z back, each as a signed sensor axis).
"""
import math
import socket
import struct
import subprocess
import sys
import time
HEADER = bytes.fromhex("283600000080")
def glasses_link():
out = subprocess.run(["ip", "-o", "-4", "addr"], capture_output=True,
text=True).stdout
for line in out.splitlines():
f = line.split()
if f[3].startswith("169.254.2.") and not f[3].startswith("169.254.2.1/"):
return f[1]
sys.exit("No glasses link (169.254.2.x) found")
def stream():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE,
glasses_link().encode())
s.settimeout(3)
s.connect(("169.254.2.1", 52998))
buf = b""
while True:
buf += s.recv(65536)
while len(buf) >= 134:
i = buf.find(HEADER)
if i < 0:
buf = buf[-5:]
break
if len(buf) - i < 134:
buf = buf[i:]
break
f = buf[i:i + 134]
buf = buf[i + 134:]
if f[30] == 11:
g = struct.unpack_from("<3f", f, 34)
a = struct.unpack_from("<3f", f, 46)
if all(map(math.isfinite, g + a)):
yield g, a
def say(text):
# Big and with a bell: read in the glasses (XR), or heard
print(f"\a\n\n >>> {text.upper()}\n", flush=True)
time.sleep(1.5) # time to read it before the clock starts
def phase(src, prompt, seconds):
say(prompt)
for _ in src: # what came while speaking is stale
break
end = time.time() + seconds
out = []
for g, a in src:
out.append((g, a))
if time.time() > end:
return out
def dominant(v):
i = max(range(3), key=lambda k: abs(v[k]))
return ("-" if v[i] < 0 else "") + "xyz"[i], i, v
def mean(rows, k):
return [sum(r[k][j] for r in rows) / len(rows) for j in range(3)]
def integral(rows):
# gyro summed, ~1 ms a sample: the turn about each sensor axis, radians
return [sum(r[0][j] for r in rows) / 1000 for j in range(3)]
say("Starting in five seconds.")
time.sleep(5)
src = stream()
level = phase(src, "Look straight ahead, head level, and keep still.", 3)
left = phase(src, "Now turn your head to the left, a long way, and hold.", 4)
phase(src, "Back to straight ahead.", 3)
down = phase(src, "Now look down at the floor, and hold.", 4)
say("Done. You can take the glasses off.")
up_name, up_i, acc = dominant(mean(level, 1))
# Turning left is +y about the head's up; nodding down is -x about its right
yaw_name, yaw_i, yaw = dominant(integral(left))
pitch_name, pitch_i, pitch = dominant(integral(down))
print(f"gravity felt (level): {[round(x, 2) for x in acc]} -> up = {up_name}")
print(f"turn left: {[round(math.degrees(x)) for x in yaw]}° -> up = {yaw_name}")
if max(map(abs, yaw)) < math.radians(15) or \
max(map(abs, pitch)) < math.radians(10):
say("The turns were too small to tell. Please run it again.")
sys.exit(1)
print(f"nod down: {[round(math.degrees(x)) for x in pitch]}° -> right = "
f"{pitch_name[1:] if pitch_name[0] == '-' else '-' + pitch_name}")
def neg(n):
return n[1:] if n.startswith("-") else "-" + n
right = neg(pitch_name)
up = up_name
if up_i == pitch_i:
sys.exit("Up and right came out the same axis: try again more clearly")
# z (back) = x cross y, right-handed
vec = {}
for name, axis in (("r", right), ("u", up)):
v = [0, 0, 0]
v["xyz".index(axis[-1])] = -1 if axis.startswith("-") else 1
vec[name] = v
r, u = vec["r"], vec["u"]
b = [r[1] * u[2] - r[2] * u[1], r[2] * u[0] - r[0] * u[2],
r[0] * u[1] - r[1] * u[0]]
bi = max(range(3), key=lambda k: abs(b[k]))
back = ("-" if b[bi] < 0 else "") + "xyz"[bi]
print(f"\nC8_XR_AXES={right},{up},{back}")
if yaw_name != up_name:
print("(the turn and gravity disagree about up: the result is a guess)")