forked from rail-berkeley/oculus_reader
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreader.py
More file actions
231 lines (205 loc) · 8.44 KB
/
reader.py
File metadata and controls
231 lines (205 loc) · 8.44 KB
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
from oculus_reader.FPS_counter import FPSCounter
from oculus_reader.buttons_parser import parse_buttons
import numpy as np
import threading
import time
import os
from ppadb.client import Client as AdbClient
import sys
def eprint(*args, **kwargs):
RED = "\033[1;31m"
sys.stderr.write(RED)
print(*args, file=sys.stderr, **kwargs)
RESET = "\033[0;0m"
sys.stderr.write(RESET)
class OculusReader:
def __init__(self,
ip_address=None,
port = 5555,
APK_name='com.rail.oculus.teleop',
print_FPS=False,
run=True
):
self.running = False
self.last_transforms = {}
self.last_buttons = {}
self._lock = threading.Lock()
self.tag = 'wE9ryARX'
self.ip_address = ip_address
self.port = port
self.APK_name = APK_name
self.print_FPS = print_FPS
if self.print_FPS:
self.fps_counter = FPSCounter()
self.device = self.get_device()
self.install(verbose=False)
if run:
self.run()
def __del__(self):
self.stop()
def run(self):
self.running = True
self.device.shell('am start -n "com.rail.oculus.teleop/com.rail.oculus.teleop.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER')
self.thread = threading.Thread(target=self.device.shell, args=("logcat -T 0", self.read_logcat_by_line))
self.thread.start()
def stop(self):
self.running = False
if hasattr(self, 'thread'):
self.thread.join()
def get_network_device(self, client, retry=0):
try:
client.remote_connect(self.ip_address, self.port)
except RuntimeError:
os.system('adb devices')
client.remote_connect(self.ip_address, self.port)
device = client.device(self.ip_address + ':' + str(self.port))
if device is None:
if retry==1:
os.system('adb tcpip ' + str(self.port))
if retry==2:
eprint('Make sure that device is running and is available at the IP address specified as the OculusReader argument `ip_address`.')
eprint('Currently provided IP address:', self.ip_address)
eprint('Run `adb shell ip route` to verify the IP address.')
exit(1)
else:
self.get_device(client=client, retry=retry+1)
return device
def get_usb_device(self, client):
try:
devices = client.devices()
except RuntimeError:
os.system('adb devices')
devices = client.devices()
for device in devices:
if device.serial.count('.') < 3:
return device
eprint('Device not found. Make sure that device is running and is connected over USB')
eprint('Run `adb devices` to verify that the device is visible.')
exit(1)
def get_device(self):
# Default is "127.0.0.1" and 5037
client = AdbClient(host="127.0.0.1", port=5037)
if self.ip_address is not None:
return self.get_network_device(client)
else:
return self.get_usb_device(client)
def install(self, APK_path=None, verbose=True, reinstall=False):
try:
installed = self.device.is_installed(self.APK_name)
if not installed or reinstall:
if APK_path is None:
APK_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'APK', 'teleop-debug.apk')
success = self.device.install(APK_path, test=True, reinstall=reinstall)
installed = self.device.is_installed(self.APK_name)
if installed and success:
print('APK installed successfully.')
else:
eprint('APK install failed.')
elif verbose:
print('APK is already installed.')
except RuntimeError:
eprint('Device is visible but could not be accessed.')
eprint('Run `adb devices` to verify that the device is visible and accessible.')
eprint('If you see "no permissions" next to the device serial, please put on the Oculus Quest and allow the access.')
exit(1)
def uninstall(self, verbose=True):
try:
installed = self.device.is_installed(self.APK_name)
if installed:
success = self.device.uninstall(self.APK_name)
installed = self.device.is_installed(self.APK_name)
if not installed and success:
print('APK uninstall finished.')
print('Please verify if the app disappeared from the list as described in "UNINSTALL.md".')
print('For the resolution of this issue, please follow https://github.com/Swind/pure-python-adb/issues/71.')
else:
eprint('APK uninstall failed')
elif verbose:
print('APK is not installed.')
except RuntimeError:
eprint('Device is visible but could not be accessed.')
eprint('Run `adb devices` to verify that the device is visible and accessible.')
eprint('If you see "no permissions" next to the device serial, please put on the Oculus Quest and allow the access.')
exit(1)
@staticmethod
def process_data(string):
try:
transforms_string, buttons_string = string.split('&')
except ValueError:
return None, None
split_transform_strings = transforms_string.split('|')
transforms = {}
for pair_string in split_transform_strings:
transform = np.empty((4,4))
pair = pair_string.split(':')
if len(pair) != 2:
continue
left_right_char = pair[0] # is r or l
transform_string = pair[1]
values = transform_string.split(' ')
c = 0
r = 0
count = 0
for value in values:
if not value:
continue
transform[r][c] = float(value)
c += 1
if c >= 4:
c = 0
r += 1
count += 1
if count == 16:
transforms[left_right_char] = transform
buttons = parse_buttons(buttons_string)
return transforms, buttons
def extract_data(self, line):
output = ''
if self.tag in line:
try:
output += line.split(self.tag + ': ')[1]
except ValueError:
pass
return output
def get_transformations_and_buttons(self):
with self._lock:
return self.last_transforms, self.last_buttons
def read_logcat_by_line(self, connection):
file_obj = connection.socket.makefile()
while self.running:
try:
line = file_obj.readline().strip()
data = self.extract_data(line)
if data:
transforms, buttons = OculusReader.process_data(data)
with self._lock:
self.last_transforms, self.last_buttons = transforms, buttons
if self.print_FPS:
self.fps_counter.getAndPrintFPS()
except UnicodeDecodeError:
pass
file_obj.close()
connection.close()
def main():
import rerun as rr
import json
rr.init("oculus_demo", spawn=True)
rr.log("headset", rr.Transform3D(translation=[0, 0, 0], mat3x3=np.eye(3), axis_length=0.1), static=True)
oculus_reader = OculusReader()
try:
while True:
time.sleep(0.1)
transforms, buttons = oculus_reader.get_transformations_and_buttons()
if transforms:
left_transform = transforms['l']
rr.log("left", rr.Transform3D(translation=left_transform[:3, 3], mat3x3=left_transform[:3, :3], axis_length=0.05))
right_transform = transforms['r']
rr.log("right", rr.Transform3D(translation=right_transform[:3, 3], mat3x3=right_transform[:3, :3], axis_length=0.05))
if buttons:
button_str = json.dumps(buttons, indent=2, default=str)
rr.log("buttons", rr.TextDocument(f"```\n{button_str}```"))
except KeyboardInterrupt:
print("\nShutting down...")
oculus_reader.stop()
if __name__ == '__main__':
main()