hex-util-runtime 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hex_util_runtime/__init__.py +37 -0
- hex_util_runtime/buffer_utils.py +177 -0
- hex_util_runtime/env_util.py +50 -0
- hex_util_runtime/file_utils.py +20 -0
- hex_util_runtime/time_utils.py +127 -0
- hex_util_runtime-0.0.1.dist-info/METADATA +184 -0
- hex_util_runtime-0.0.1.dist-info/RECORD +10 -0
- hex_util_runtime-0.0.1.dist-info/WHEEL +5 -0
- hex_util_runtime-0.0.1.dist-info/licenses/LICENSE +201 -0
- hex_util_runtime-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding:utf-8 -*-
|
|
3
|
+
################################################################
|
|
4
|
+
# Copyright 2026 Dong Zhaorui. All rights reserved.
|
|
5
|
+
# Author: Dong Zhaorui 847235539@qq.com
|
|
6
|
+
# Date : 2026-03-23
|
|
7
|
+
################################################################
|
|
8
|
+
|
|
9
|
+
from .buffer_utils import HexThreadingVar, HexShmRingBuffer, deque_helper
|
|
10
|
+
from .env_util import get_env_str, get_env_int, get_env_bool, get_env_float, get_env_ndarray
|
|
11
|
+
from .file_utils import hex_rmtree
|
|
12
|
+
from .time_utils import HexRate, hex_ts_to_ns, ns_to_hex_ts, ns_now, hex_ts_now, hex_ts_delta_ms
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
# buffer_utils
|
|
16
|
+
"HexThreadingVar",
|
|
17
|
+
"HexShmRingBuffer",
|
|
18
|
+
"deque_helper",
|
|
19
|
+
|
|
20
|
+
# env_util
|
|
21
|
+
"get_env_str",
|
|
22
|
+
"get_env_int",
|
|
23
|
+
"get_env_bool",
|
|
24
|
+
"get_env_float",
|
|
25
|
+
"get_env_ndarray",
|
|
26
|
+
|
|
27
|
+
# file_utils
|
|
28
|
+
"hex_rmtree",
|
|
29
|
+
|
|
30
|
+
# time_utils
|
|
31
|
+
"HexRate",
|
|
32
|
+
"hex_ts_to_ns",
|
|
33
|
+
"ns_to_hex_ts",
|
|
34
|
+
"ns_now",
|
|
35
|
+
"hex_ts_now",
|
|
36
|
+
"hex_ts_delta_ms",
|
|
37
|
+
]
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding:utf-8 -*-
|
|
3
|
+
################################################################
|
|
4
|
+
# Copyright 2026 Dong Zhaorui. All rights reserved.
|
|
5
|
+
# Author: Dong Zhaorui 847235539@qq.com
|
|
6
|
+
# Date : 2026-03-23
|
|
7
|
+
################################################################
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
import numpy as np
|
|
11
|
+
from collections import deque
|
|
12
|
+
from typing import Any
|
|
13
|
+
from multiprocessing import shared_memory, Event as mp_Event
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class HexThreadingVar:
|
|
17
|
+
|
|
18
|
+
def __init__(self, value: Any):
|
|
19
|
+
self.__value = value
|
|
20
|
+
self.lock = threading.Lock()
|
|
21
|
+
|
|
22
|
+
def get(self) -> Any:
|
|
23
|
+
with self.lock:
|
|
24
|
+
return self.__value
|
|
25
|
+
|
|
26
|
+
def set(self, value: Any):
|
|
27
|
+
with self.lock:
|
|
28
|
+
self.__value = value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class HexShmRingBuffer:
|
|
32
|
+
"""
|
|
33
|
+
Lock-free SPSC shared memory ring buffer
|
|
34
|
+
optimized for high-frequency (2kHz–5kHz+) streaming
|
|
35
|
+
|
|
36
|
+
Design:
|
|
37
|
+
- single producer
|
|
38
|
+
- single consumer
|
|
39
|
+
- overwrite allowed
|
|
40
|
+
- latest read (no FIFO guarantee)
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, capacity: int, dtype):
|
|
44
|
+
self.capacity = capacity
|
|
45
|
+
self.dtype = np.dtype(dtype)
|
|
46
|
+
self.item_size = self.dtype.itemsize
|
|
47
|
+
|
|
48
|
+
self.work_event = mp_Event()
|
|
49
|
+
|
|
50
|
+
# =========================
|
|
51
|
+
# data buffer
|
|
52
|
+
# =========================
|
|
53
|
+
self.shm = shared_memory.SharedMemory(
|
|
54
|
+
create=True,
|
|
55
|
+
size=capacity * self.item_size,
|
|
56
|
+
)
|
|
57
|
+
self.buf = self.shm.buf
|
|
58
|
+
|
|
59
|
+
# =========================
|
|
60
|
+
# index buffer (lock-free)
|
|
61
|
+
# =========================
|
|
62
|
+
self.idx_shm = shared_memory.SharedMemory(create=True, size=16)
|
|
63
|
+
self.idx = np.ndarray((2, ), dtype=np.int64, buffer=self.idx_shm.buf)
|
|
64
|
+
|
|
65
|
+
# idx[0] = write_idx
|
|
66
|
+
# idx[1] = read_idx (optional, mostly unused in latest mode)
|
|
67
|
+
self.idx[:] = 0
|
|
68
|
+
self.last_latest_idx = None
|
|
69
|
+
|
|
70
|
+
# set work_event to True
|
|
71
|
+
self.work_event.set()
|
|
72
|
+
|
|
73
|
+
# =========================
|
|
74
|
+
# lifecycle
|
|
75
|
+
# =========================
|
|
76
|
+
def close(self):
|
|
77
|
+
if not self.work_event.is_set():
|
|
78
|
+
return
|
|
79
|
+
|
|
80
|
+
self.work_event.clear()
|
|
81
|
+
if self.shm:
|
|
82
|
+
self.shm.close()
|
|
83
|
+
self.shm.unlink()
|
|
84
|
+
self.shm = None
|
|
85
|
+
if self.idx_shm:
|
|
86
|
+
self.idx_shm.close()
|
|
87
|
+
self.idx_shm.unlink()
|
|
88
|
+
self.idx_shm = None
|
|
89
|
+
|
|
90
|
+
# =========================
|
|
91
|
+
# WRITE (lock-free)
|
|
92
|
+
# =========================
|
|
93
|
+
def write(self, data):
|
|
94
|
+
if not self.work_event.is_set():
|
|
95
|
+
print("Warning: work_event is not set, some data may be lost")
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
write_idx = self.idx[0]
|
|
99
|
+
|
|
100
|
+
if write_idx - self.idx[1] >= self.capacity:
|
|
101
|
+
self.idx[1] = write_idx - self.capacity + 1
|
|
102
|
+
|
|
103
|
+
offset = (write_idx % self.capacity) * self.item_size
|
|
104
|
+
|
|
105
|
+
self.buf[offset:offset + self.item_size] = data.tobytes()
|
|
106
|
+
self.idx[0] = write_idx + 1
|
|
107
|
+
|
|
108
|
+
def read(self, latest: bool = False):
|
|
109
|
+
if not self.work_event.is_set():
|
|
110
|
+
print("Warning: work_event is not set, some data may be lost")
|
|
111
|
+
return None
|
|
112
|
+
|
|
113
|
+
if latest:
|
|
114
|
+
return self.read_latest()
|
|
115
|
+
else:
|
|
116
|
+
return self.read_next()
|
|
117
|
+
|
|
118
|
+
# =========================
|
|
119
|
+
# READ LATEST(推荐)
|
|
120
|
+
# =========================
|
|
121
|
+
def read_latest(self):
|
|
122
|
+
"""
|
|
123
|
+
Always return newest frame
|
|
124
|
+
Ignore backlog
|
|
125
|
+
"""
|
|
126
|
+
write_idx = self.idx[0]
|
|
127
|
+
if write_idx == 0:
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
latest_idx = write_idx - 1
|
|
131
|
+
if latest_idx == self.last_latest_idx:
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
self.last_latest_idx = latest_idx
|
|
135
|
+
offset = (latest_idx % self.capacity) * self.item_size
|
|
136
|
+
|
|
137
|
+
raw = self.buf[offset:offset + self.item_size]
|
|
138
|
+
return self._decode(raw)
|
|
139
|
+
|
|
140
|
+
# =========================
|
|
141
|
+
# OPTIONAL: read next(FIFO)
|
|
142
|
+
# =========================
|
|
143
|
+
def read_next(self):
|
|
144
|
+
"""
|
|
145
|
+
FIFO read (not recommended for high freq)
|
|
146
|
+
"""
|
|
147
|
+
read_idx = self.idx[1]
|
|
148
|
+
write_idx = self.idx[0]
|
|
149
|
+
|
|
150
|
+
if read_idx >= write_idx:
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
offset = (read_idx % self.capacity) * self.item_size
|
|
154
|
+
raw = self.buf[offset:offset + self.item_size]
|
|
155
|
+
|
|
156
|
+
self.idx[1] = read_idx + 1
|
|
157
|
+
return self._decode(raw)
|
|
158
|
+
|
|
159
|
+
# =========================
|
|
160
|
+
# decode
|
|
161
|
+
# =========================
|
|
162
|
+
def _decode(self, raw):
|
|
163
|
+
b = raw.tobytes()
|
|
164
|
+
return np.frombuffer(b, dtype=self.dtype, count=1)[0]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def deque_helper(dq: deque, latest: bool = True) -> Any:
|
|
168
|
+
if not latest:
|
|
169
|
+
if dq:
|
|
170
|
+
return dq.popleft()
|
|
171
|
+
else:
|
|
172
|
+
return None
|
|
173
|
+
else:
|
|
174
|
+
ret = None
|
|
175
|
+
while dq:
|
|
176
|
+
ret = dq.popleft()
|
|
177
|
+
return ret
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding:utf-8 -*-
|
|
3
|
+
################################################################
|
|
4
|
+
# Copyright 2026 Dong Zhaorui. All rights reserved.
|
|
5
|
+
# Author: Dong Zhaorui 847235539@qq.com
|
|
6
|
+
# Date : 2026-04-23
|
|
7
|
+
################################################################
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
import numpy as np
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def get_env_str(key: str, default: str = "") -> str:
|
|
14
|
+
value = os.getenv(key, default)
|
|
15
|
+
if value is None:
|
|
16
|
+
print(f"Environment variable {key} is not set")
|
|
17
|
+
return default
|
|
18
|
+
return value
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_env_int(key: str, default: int = 0) -> int:
|
|
22
|
+
value_str = get_env_str(key)
|
|
23
|
+
try:
|
|
24
|
+
return int(value_str)
|
|
25
|
+
except ValueError:
|
|
26
|
+
print(f"Environment variable {key} is not a valid integer")
|
|
27
|
+
return default
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def get_env_bool(key: str) -> bool:
|
|
31
|
+
value_str = get_env_str(key)
|
|
32
|
+
return value_str.lower() in ["true", "1", "yes", "y"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_env_float(key: str, default: float = 0.0) -> float:
|
|
36
|
+
value_str = get_env_str(key)
|
|
37
|
+
try:
|
|
38
|
+
return float(value_str)
|
|
39
|
+
except ValueError:
|
|
40
|
+
print(f"Environment variable {key} is not a valid float")
|
|
41
|
+
return default
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def get_env_ndarray(key: str, default: np.ndarray = np.zeros(1)) -> np.ndarray:
|
|
45
|
+
value_str = get_env_str(key)
|
|
46
|
+
try:
|
|
47
|
+
return np.array(value_str.split(","), dtype=float)
|
|
48
|
+
except ValueError:
|
|
49
|
+
print(f"Environment variable {key} is not a valid numpy array")
|
|
50
|
+
return default
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding:utf-8 -*-
|
|
3
|
+
################################################################
|
|
4
|
+
# Copyright 2026 Dong Zhaorui. All rights reserved.
|
|
5
|
+
# Author: Dong Zhaorui 847235539@qq.com
|
|
6
|
+
# Date : 2026-03-23
|
|
7
|
+
################################################################
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def hex_rmtree(path: str) -> None:
|
|
13
|
+
if not os.path.exists(path):
|
|
14
|
+
return
|
|
15
|
+
for root, dirs, files in os.walk(path, topdown=False):
|
|
16
|
+
for f in files:
|
|
17
|
+
os.remove(os.path.join(root, f))
|
|
18
|
+
for d in dirs:
|
|
19
|
+
os.rmdir(os.path.join(root, d))
|
|
20
|
+
os.rmdir(path)
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding:utf-8 -*-
|
|
3
|
+
################################################################
|
|
4
|
+
# Copyright 2026 Dong Zhaorui. All rights reserved.
|
|
5
|
+
# Author: Dong Zhaorui 847235539@qq.com
|
|
6
|
+
# Date : 2026-02-16
|
|
7
|
+
################################################################
|
|
8
|
+
|
|
9
|
+
import os, time
|
|
10
|
+
import ctypes, ctypes.util
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SingletonMeta(type):
|
|
15
|
+
_instances = {}
|
|
16
|
+
|
|
17
|
+
def __call__(cls, *args, **kwargs):
|
|
18
|
+
if cls not in cls._instances:
|
|
19
|
+
cls._instances[cls] = super().__call__(*args, **kwargs)
|
|
20
|
+
return cls._instances[cls]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class HexTimeManager(metaclass=SingletonMeta):
|
|
24
|
+
|
|
25
|
+
class timespec(ctypes.Structure):
|
|
26
|
+
_fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)]
|
|
27
|
+
|
|
28
|
+
def __init__(self):
|
|
29
|
+
self.__use_ptp = False
|
|
30
|
+
ptp_path = os.getenv("HEX_PTP_CLOCK", None)
|
|
31
|
+
if ptp_path is not None:
|
|
32
|
+
self.__fd = os.open(ptp_path, os.O_RDONLY | os.O_CLOEXEC)
|
|
33
|
+
self.__clock_id = ((~self.__fd) << 3) | 3
|
|
34
|
+
self.__libc = ctypes.CDLL(
|
|
35
|
+
ctypes.util.find_library("c"),
|
|
36
|
+
use_errno=True,
|
|
37
|
+
)
|
|
38
|
+
self.__use_ptp = True
|
|
39
|
+
|
|
40
|
+
def __del__(self):
|
|
41
|
+
if self.__use_ptp:
|
|
42
|
+
os.close(self.__fd)
|
|
43
|
+
|
|
44
|
+
def get_now_ns(self) -> int:
|
|
45
|
+
if self.__use_ptp:
|
|
46
|
+
ts = self.timespec()
|
|
47
|
+
if self.__libc.clock_gettime(self.__clock_id,
|
|
48
|
+
ctypes.byref(ts)) != 0:
|
|
49
|
+
err = ctypes.get_errno()
|
|
50
|
+
raise OSError(err, os.strerror(err))
|
|
51
|
+
return int(ts.tv_sec * 1_000_000_000 + ts.tv_nsec)
|
|
52
|
+
else:
|
|
53
|
+
return time.perf_counter_ns()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_HEX_TIME_MANAGER = HexTimeManager()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def hex_ts_to_ns(ts: dict) -> int:
|
|
60
|
+
try:
|
|
61
|
+
return int(ts['s'] * 1_000_000_000 + ts['ns'])
|
|
62
|
+
except Exception as e:
|
|
63
|
+
print(f"hex_ts_to_ns failed: {e}")
|
|
64
|
+
return np.inf
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def ns_to_hex_ts(ns: int) -> dict:
|
|
68
|
+
return {
|
|
69
|
+
"s": int(ns // 1_000_000_000),
|
|
70
|
+
"ns": int(ns % 1_000_000_000),
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def ns_now() -> int:
|
|
75
|
+
return _HEX_TIME_MANAGER.get_now_ns()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def hex_ts_now() -> dict:
|
|
79
|
+
return ns_to_hex_ts(ns_now())
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def hex_ts_delta_ms(curr_ts, hdr_ts) -> float:
|
|
83
|
+
try:
|
|
84
|
+
return (curr_ts['s'] - hdr_ts['s']) * 1_000 + (
|
|
85
|
+
curr_ts['ns'] - hdr_ts['ns']) / 1_000_000
|
|
86
|
+
|
|
87
|
+
except Exception as e:
|
|
88
|
+
print(f"hex_ts_delta_ms failed: {e}")
|
|
89
|
+
return np.inf
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class HexRate:
|
|
93
|
+
|
|
94
|
+
def __init__(self, hz: float, spin_threshold_ns: int = 10_000):
|
|
95
|
+
if hz <= 0:
|
|
96
|
+
raise ValueError("hz must be greater than 0")
|
|
97
|
+
if spin_threshold_ns < 0:
|
|
98
|
+
raise ValueError("spin_threshold_ns must be non-negative")
|
|
99
|
+
self.__period_ns = int(1_000_000_000 / hz)
|
|
100
|
+
self.__next_ns = ns_now() + self.__period_ns
|
|
101
|
+
self.__spin_threshold_ns = spin_threshold_ns
|
|
102
|
+
|
|
103
|
+
def reset(self):
|
|
104
|
+
self.__next_ns = ns_now() + self.__period_ns
|
|
105
|
+
|
|
106
|
+
def sleep(self):
|
|
107
|
+
target_ns = self.__next_ns
|
|
108
|
+
now_ns = ns_now()
|
|
109
|
+
remain_ns = target_ns - now_ns
|
|
110
|
+
if remain_ns <= 0:
|
|
111
|
+
needed_period = (now_ns - target_ns) // self.__period_ns + 1
|
|
112
|
+
self.__next_ns += needed_period * self.__period_ns
|
|
113
|
+
return
|
|
114
|
+
|
|
115
|
+
spin_threshold = min(self.__spin_threshold_ns, self.__period_ns)
|
|
116
|
+
coarse_sleep_ns = remain_ns - spin_threshold
|
|
117
|
+
if coarse_sleep_ns > 0:
|
|
118
|
+
time.sleep(coarse_sleep_ns / 1_000_000_000.0)
|
|
119
|
+
|
|
120
|
+
while True:
|
|
121
|
+
now_ns = ns_now()
|
|
122
|
+
if now_ns >= target_ns:
|
|
123
|
+
break
|
|
124
|
+
if target_ns - now_ns > 50_000:
|
|
125
|
+
time.sleep(0)
|
|
126
|
+
|
|
127
|
+
self.__next_ns += self.__period_ns
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hex_util_runtime
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: HEXFELLOW Runtime Utilities
|
|
5
|
+
Author-email: Dong Zhaorui <joray.dong@hexfellow.com>
|
|
6
|
+
Maintainer-email: jecjune <zejun.chen@hexfellow.com>, Dong Zhaorui <joray.dong@hexfellow.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/hexfellow/hex_util_runtime
|
|
9
|
+
Project-URL: Repository, https://github.com/hexfellow/hex_util_runtime.git
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/hexfellow/hex_util_runtime/issues
|
|
11
|
+
Project-URL: Documentation, https://github.com/hexfellow/hex_util_runtime/wiki
|
|
12
|
+
Keywords: hex,util,runtime
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Classifier: Programming Language :: Python :: 3
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
22
|
+
Requires-Python: >=3.8
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: numpy>=2.2.6
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
<h1 align="center">HEXFELLOW RUNTIME UTILITIES</h1>
|
|
29
|
+
|
|
30
|
+
<p align="center">
|
|
31
|
+
<a href="https://github.com/hexfellow/hex_util_runtime/stargazers">
|
|
32
|
+
<img src="https://img.shields.io/github/stars/hexfellow/hex_util_runtime?style=flat-square&logo=github" />
|
|
33
|
+
</a>
|
|
34
|
+
<a href="https://github.com/hexfellow/hex_util_runtime/forks">
|
|
35
|
+
<img src="https://img.shields.io/github/forks/hexfellow/hex_util_runtime?style=flat-square&logo=github" />
|
|
36
|
+
</a>
|
|
37
|
+
|
|
38
|
+
<a href="https://github.com/hexfellow/hex_util_runtime/issues">
|
|
39
|
+
<img src="https://img.shields.io/github/issues/hexfellow/hex_util_runtime?style=flat-square&logo=github" />
|
|
40
|
+
</a>
|
|
41
|
+
|
|
42
|
+
<img src="https://img.shields.io/badge/python-≥3.8-blue?style=flat-square&logo=python" />
|
|
43
|
+
|
|
44
|
+
<img src="https://img.shields.io/badge/platform-Linux-orange?style=flat-square" />
|
|
45
|
+
</p>
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
# 📖 Overview
|
|
50
|
+
|
|
51
|
+
## What is `hex_util_runtime`
|
|
52
|
+
|
|
53
|
+
`hex_util_runtime` is a lightweight Python utility library providing essential runtime primitives with minimal dependencies. It is part of the HEXFELLOW ecosystem and serves as the foundational layer for time management, inter-process communication, environment configuration, and file system operations.
|
|
54
|
+
|
|
55
|
+
| Module | Primary Purpose | Key Components |
|
|
56
|
+
|--------|----------------|----------------|
|
|
57
|
+
| **time_utils** | High-precision time, PTP clock, loop rate control | `ns_now()`, `HexRate`, `HexTimeManager` |
|
|
58
|
+
| **buffer_utils** | Thread-safe variable + lock-free SPSC shared-memory ring buffer | `HexThreadingVar`, `HexShmRingBuffer`, `deque_helper` |
|
|
59
|
+
| **env_util** | Type-safe environment variable readers | `get_env_int()`, `get_env_bool()`, `get_env_ndarray()` |
|
|
60
|
+
| **file_utils** | Safe recursive directory removal | `hex_rmtree()` |
|
|
61
|
+
|
|
62
|
+
## What problem it solves
|
|
63
|
+
|
|
64
|
+
- **Unified time interface**: Abstract away the difference between system monotonic clocks and PTP hardware clocks behind a simple `ns_now()` call.
|
|
65
|
+
- **Thread-safe variable exchange**: Wrap any Python value with `HexThreadingVar` to safely read/write across threads using a mutex lock.
|
|
66
|
+
- **High-frequency inter-process streaming**: Provide a lock-free, single-producer-single-consumer shared-memory ring buffer (`HexShmRingBuffer`) optimized for 2–5 kHz+ data rates, avoiding serialization and IPC overhead.
|
|
67
|
+
- **Safe environment configuration**: Read environment variables with proper type conversion and fallback defaults, without repetitive `try/except` boilerplate.
|
|
68
|
+
- **Portable file operations**: Pure-`os` implementation of recursive directory deletion, removing the `shutil` dependency.
|
|
69
|
+
|
|
70
|
+
## Target users
|
|
71
|
+
|
|
72
|
+
- Robotics engineers who need low-latency, lock-free shared-memory communication between processes.
|
|
73
|
+
- Developers building real-time control loops with precise timing requirements.
|
|
74
|
+
- Anyone working in the HEXFELLOW ecosystem (`hex_driver_mujoco`, `hex_util_robot`, etc.) who needs runtime primitives.
|
|
75
|
+
|
|
76
|
+
## Project structure
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
hex_util_runtime/
|
|
80
|
+
├── hex_util_runtime/
|
|
81
|
+
│ ├── __init__.py # Public exports (__all__)
|
|
82
|
+
│ ├── time_utils.py # ns_now(), HexRate, HexTimeManager, hex timestamp converters
|
|
83
|
+
│ ├── buffer_utils.py # HexThreadingVar (thread-safe variable), HexShmRingBuffer (lock-free SPSC SHM ring buffer), deque_helper
|
|
84
|
+
│ ├── env_util.py # get_env_str/get_env_int/get_env_bool/get_env_float/get_env_ndarray
|
|
85
|
+
│ └── file_utils.py # hex_rmtree (safe recursive directory removal)
|
|
86
|
+
├── docs/
|
|
87
|
+
│ ├── api.md # Full API reference
|
|
88
|
+
│ └── example.md # Usage walkthroughs
|
|
89
|
+
└── pyproject.toml # Project metadata & build configuration
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
# 📦 Installation
|
|
95
|
+
|
|
96
|
+
## Requirements
|
|
97
|
+
|
|
98
|
+
- **Python** ≥ 3.8
|
|
99
|
+
- **OS**: Linux (POSIX shared memory and PTP clock support are Linux-specific)
|
|
100
|
+
- **Dependencies**:
|
|
101
|
+
- `numpy ≥ 2.2.6`
|
|
102
|
+
|
|
103
|
+
## Install from PyPI
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
pip install hex_util_runtime
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Install from Source
|
|
110
|
+
|
|
111
|
+
We use [**uv**](https://github.com/astral-sh/uv) to manage the Python environment. Please install it first.
|
|
112
|
+
|
|
113
|
+
1. Clone and install in editable mode:
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
git clone https://github.com/hexfellow/hex_util_runtime.git
|
|
117
|
+
cd hex_util_runtime
|
|
118
|
+
./venv.sh
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
2. Activate before using:
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
source .venv/bin/activate
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
# ⚡ Quick Start
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from hex_util_runtime import ns_now, HexRate, hex_ts_now
|
|
133
|
+
from hex_util_runtime import get_env_int, hex_rmtree
|
|
134
|
+
from hex_util_runtime import HexThreadingVar, HexShmRingBuffer, deque_helper
|
|
135
|
+
|
|
136
|
+
# Get current time in nanoseconds
|
|
137
|
+
print(ns_now())
|
|
138
|
+
|
|
139
|
+
# Rate-limited loop (100 Hz)
|
|
140
|
+
rate = HexRate(100)
|
|
141
|
+
for _ in range(10):
|
|
142
|
+
rate.sleep()
|
|
143
|
+
print(f"ts: {hex_ts_now()}")
|
|
144
|
+
|
|
145
|
+
# Read an integer from environment (default 0)
|
|
146
|
+
interval = get_env_int("MY_INTERVAL_MS", default=50)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
# 📑 Documentation
|
|
152
|
+
|
|
153
|
+
- [**API Reference**](docs/api.md) — Detailed documentation of all classes and functions.
|
|
154
|
+
- [**Examples**](docs/example.md) — Usage walkthroughs for each module.
|
|
155
|
+
|
|
156
|
+
---
|
|
157
|
+
|
|
158
|
+
# 📄 License
|
|
159
|
+
|
|
160
|
+
Apache License 2.0. See [LICENSE](LICENSE).
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
# 👥 Authors & Maintainers
|
|
165
|
+
|
|
166
|
+
| Role | Name | Email |
|
|
167
|
+
|------|------|-------|
|
|
168
|
+
| **Author** | Dong Zhaorui | joray.dong@hexfellow.com |
|
|
169
|
+
| **Maintainer** | jecjune (Chen Zejun) | zejun.chen@hexfellow.com |
|
|
170
|
+
| **Maintainer** | Dong Zhaorui | joray.dong@hexfellow.com |
|
|
171
|
+
|
|
172
|
+
---
|
|
173
|
+
|
|
174
|
+
# 🌟 Star History
|
|
175
|
+
|
|
176
|
+
[](https://star-history.com/#hexfellow/hex_util_runtime&Date)
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
# 👥 Contributors
|
|
181
|
+
|
|
182
|
+
<a href="https://github.com/hexfellow/hex_util_runtime/graphs/contributors">
|
|
183
|
+
<img src="https://contrib.rocks/image?repo=hexfellow/hex_util_runtime" />
|
|
184
|
+
</a>
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
hex_util_runtime/__init__.py,sha256=I2i53UGWyj5MDMoEk0uu1M1Y1B2KyOQrs5XntPxG9Cw,972
|
|
2
|
+
hex_util_runtime/buffer_utils.py,sha256=EM4yvOkWQEE9-W7xS7X7QPtVw9bQgu2RR7F0kiIc94c,4783
|
|
3
|
+
hex_util_runtime/env_util.py,sha256=HtiL_5eyx9jsjeuqWaeE_lpw54i3BDTNWzOEVYMTMvY,1446
|
|
4
|
+
hex_util_runtime/file_utils.py,sha256=Zw1R8wSHTANZBTx6v7YX8AqXM0yolrMgPydCEtqZ--c,599
|
|
5
|
+
hex_util_runtime/time_utils.py,sha256=MHsvJaH1NQvTT8OLAgnWmTrg-yGkCQ3gy7DNkvjJ7_4,3696
|
|
6
|
+
hex_util_runtime-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
7
|
+
hex_util_runtime-0.0.1.dist-info/METADATA,sha256=0yaq77I7_XgIGZpnJXiC3uxGnx_ljLXa27MJ9H9fym0,6965
|
|
8
|
+
hex_util_runtime-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
hex_util_runtime-0.0.1.dist-info/top_level.txt,sha256=wC7GUdCczLkQl8C1QbN0eSkB0Q6lLu36p2iRxl0kP_I,17
|
|
10
|
+
hex_util_runtime-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hex_util_runtime
|