Skip to content

Commit bddeca6

Browse files
Reapply "params: unique default value (#35798)" (#35806)
* Reapply "params: unique default value (#35798)" This reverts commit 267acfb. * more * more * test for this * better name;
1 parent 267acfb commit bddeca6

File tree

12 files changed

+73
-55
lines changed

12 files changed

+73
-55
lines changed

common/params.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ ParamKeyType Params::getKeyType(const std::string &key) {
123123
return keys[key].type;
124124
}
125125

126-
std::string Params::getKeyDefaultValue(const std::string &key) {
126+
std::optional<std::string> Params::getKeyDefaultValue(const std::string &key) {
127127
return keys[key].default_value;
128128
}
129129

common/params.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
#include <future>
44
#include <map>
5+
#include <optional>
56
#include <string>
67
#include <tuple>
78
#include <utility>
@@ -33,7 +34,7 @@ enum ParamKeyType {
3334
struct ParamKeyAttributes {
3435
uint32_t flags;
3536
ParamKeyType type;
36-
std::string default_value = "";
37+
std::optional<std::string> default_value = std::nullopt;
3738
};
3839

3940
class Params {
@@ -48,7 +49,7 @@ class Params {
4849
bool checkKey(const std::string &key);
4950
ParamKeyFlag getKeyFlag(const std::string &key);
5051
ParamKeyType getKeyType(const std::string &key);
51-
std::string getKeyDefaultValue(const std::string &key);
52+
std::optional<std::string> getKeyDefaultValue(const std::string &key);
5253
inline std::string getParamPath(const std::string &key = {}) {
5354
return params_path + params_prefix + (key.empty() ? "" : "/" + key);
5455
}

common/params_pyx.pyx

Lines changed: 35 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import json
55
from libcpp cimport bool
66
from libcpp.string cimport string
77
from libcpp.vector cimport vector
8+
from libcpp.optional cimport optional
89

910
cdef extern from "common/params.h":
1011
cpdef enum ParamKeyFlag:
@@ -36,7 +37,7 @@ cdef extern from "common/params.h":
3637
int putBool(string, bool) nogil
3738
bool checkKey(string) nogil
3839
ParamKeyType getKeyType(string) nogil
39-
string getKeyDefaultValue(string) nogil
40+
optional[string] getKeyDefaultValue(string) nogil
4041
string getParamPath(string) nogil
4142
void clearAll(ParamKeyFlag)
4243
vector[string] allKeys()
@@ -73,40 +74,45 @@ cdef class Params:
7374
raise UnknownKeyName(key)
7475
return key
7576

76-
def get(self, key, bool block=False, default=None):
77+
def cast(self, t, value, default):
78+
if value is None:
79+
return None
80+
try:
81+
if t == STRING:
82+
return value.decode("utf-8")
83+
elif t == BOOL:
84+
return value == b"1"
85+
elif t == INT:
86+
return int(value)
87+
elif t == FLOAT:
88+
return float(value)
89+
elif t == TIME:
90+
return datetime.datetime.fromisoformat(value.decode("utf-8"))
91+
elif t == JSON:
92+
return json.loads(value)
93+
elif t == BYTES:
94+
return value
95+
else:
96+
raise TypeError()
97+
except (TypeError, ValueError):
98+
return self.cast(t, default, None)
99+
100+
def get(self, key, bool block=False, bool return_default=False):
77101
cdef string k = self.check_key(key)
78-
cdef ParamKeyType t = self.p.getKeyType(ensure_bytes(key))
102+
cdef ParamKeyType t = self.p.getKeyType(k)
79103
cdef string val
80104
with nogil:
81105
val = self.p.get(k, block)
82106

107+
default_val = self.get_default_value(k) if return_default else None
83108
if val == b"":
84109
if block:
85110
# If we got no value while running in blocked mode
86111
# it means we got an interrupt while waiting
87112
raise KeyboardInterrupt
88113
else:
89-
return default
90-
91-
try:
92-
if t == STRING:
93-
return val.decode("utf-8")
94-
elif t == BOOL:
95-
return val == b"1"
96-
elif t == INT:
97-
return int(val)
98-
elif t == FLOAT:
99-
return float(val)
100-
elif t == TIME:
101-
return datetime.datetime.fromisoformat(val.decode("utf-8"))
102-
elif t == JSON:
103-
return json.loads(val)
104-
elif t == BYTES:
105-
return val
106-
else:
107-
return default
108-
except (TypeError, ValueError):
109-
return default
114+
return self.cast(t, default_val, None)
115+
return self.cast(t, val, default_val)
110116

111117
def get_bool(self, key, bool block=False):
112118
cdef string k = self.check_key(key)
@@ -152,8 +158,12 @@ cdef class Params:
152158
cdef string key_bytes = ensure_bytes(key)
153159
return self.p.getParamPath(key_bytes).decode("utf-8")
154160

161+
def get_type(self, key):
162+
return self.p.getKeyType(self.check_key(key))
163+
155164
def all_keys(self):
156165
return self.p.allKeys()
157166

158167
def get_default_value(self, key):
159-
return self.p.getKeyDefaultValue(self.check_key(key))
168+
cdef optional[string] default = self.p.getKeyDefaultValue(self.check_key(key))
169+
return default.value() if default.has_value() else None

common/tests/test_params.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,17 @@ def test_params_all_keys(self):
110110
assert len(keys) == len(set(keys))
111111
assert b"CarParams" in keys
112112

113-
def test_params_default_init_value(self):
114-
assert self.params.get_default_value("LanguageSetting")
115-
assert self.params.get_default_value("LongitudinalPersonality")
116-
assert not self.params.get_default_value("LiveParameters")
113+
def test_params_default_value(self):
114+
self.params.remove("LanguageSetting")
115+
self.params.remove("LongitudinalPersonality")
116+
self.params.remove("LiveParameters")
117+
118+
assert self.params.get("LanguageSetting") is None
119+
assert self.params.get("LanguageSetting", return_default=False) is None
120+
assert isinstance(self.params.get("LanguageSetting", return_default=True), str)
121+
assert isinstance(self.params.get("LongitudinalPersonality", return_default=True), int)
122+
assert self.params.get("LiveParameters") is None
123+
assert self.params.get("LiveParameters", return_default=True) is None
117124

118125
def test_params_get_type(self):
119126
# json
@@ -127,18 +134,9 @@ def test_params_get_type(self):
127134
# bool
128135
self.params.put("AdbEnabled", "1")
129136
assert self.params.get("AdbEnabled")
137+
assert isinstance(self.params.get("AdbEnabled"), bool)
130138

131139
# time
132140
now = datetime.datetime.now(datetime.UTC)
133141
self.params.put("InstallDate", str(now))
134142
assert self.params.get("InstallDate") == now
135-
136-
def test_params_get_default(self):
137-
now = datetime.datetime.now(datetime.UTC)
138-
self.params.remove("InstallDate")
139-
assert self.params.get("InstallDate") is None
140-
assert self.params.get("InstallDate", default=now) == now
141-
142-
self.params.put("BootCount", "1xx1")
143-
assert self.params.get("BootCount") is None
144-
assert self.params.get("BootCount", default=1441) == 1441

selfdrive/selfdrived/selfdrived.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def __init__(self, CP=None):
109109
self.logged_comm_issue = None
110110
self.not_running_prev = None
111111
self.experimental_mode = False
112-
self.personality = self.read_personality_param()
112+
self.personality = self.params.get("LongitudinalPersonality", return_default=True)
113113
self.recalibrating_seen = False
114114
self.state_machine = StateMachine()
115115
self.rk = Ratekeeper(100, print_delay_threshold=None)
@@ -477,16 +477,13 @@ def step(self):
477477

478478
self.CS_prev = CS
479479

480-
def read_personality_param(self):
481-
return self.params.get('LongitudinalPersonality', default=log.LongitudinalPersonality.standard)
482-
483480
def params_thread(self, evt):
484481
while not evt.is_set():
485482
self.is_metric = self.params.get_bool("IsMetric")
486483
self.is_ldw_enabled = self.params.get_bool("IsLdwEnabled")
487484
self.disengage_on_accelerator = self.params.get_bool("DisengageOnAccelerator")
488485
self.experimental_mode = self.params.get_bool("ExperimentalMode") and self.CP.openpilotLongitudinalControl
489-
self.personality = self.read_personality_param()
486+
self.personality = self.params.get("LongitudinalPersonality", return_default=True)
490487
time.sleep(0.1)
491488

492489
def run(self):

selfdrive/ui/layouts/settings/device.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ def __init__(self):
4141
self._scroller = Scroller(items, line_separator=True, spacing=0)
4242

4343
def _initialize_items(self):
44-
dongle_id = self._params.get("DongleId", default="N/A")
45-
serial = self._params.get("HardwareSerial", default="N/A")
44+
dongle_id = self._params.get("DongleId") or "N/A"
45+
serial = self._params.get("HardwareSerial") or "N/A"
4646

4747
items = [
4848
text_item("Dongle ID", dongle_id),

selfdrive/ui/layouts/settings/toggles.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __init__(self):
5454
buttons=["Aggressive", "Standard", "Relaxed"],
5555
button_width=255,
5656
callback=self._set_longitudinal_personality,
57-
selected_index=self._params.get("LongitudinalPersonality", default=0),
57+
selected_index=self._params.get("LongitudinalPersonality", return_default=True),
5858
icon="speed_limit.png"
5959
),
6060
toggle_item(

selfdrive/ui/widgets/pairing_dialog.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(self):
2323

2424
def _get_pairing_url(self) -> str:
2525
try:
26-
dongle_id = self.params.get("DongleId", default="")
26+
dongle_id = self.params.get("DongleId") or ""
2727
token = Api(dongle_id).get_token()
2828
except Exception as e:
2929
cloudlog.warning(f"Failed to get pairing token: {e}")

system/athena/athenad.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -532,12 +532,12 @@ def getPublicKey() -> str | None:
532532

533533
@dispatcher.add_method
534534
def getSshAuthorizedKeys() -> str:
535-
return cast(str, Params().get("GithubSshKeys", default=""))
535+
return cast(str, Params().get("GithubSshKeys") or "")
536536

537537

538538
@dispatcher.add_method
539539
def getGithubUsername() -> str:
540-
return cast(str, Params().get("GithubUsername", default=""))
540+
return cast(str, Params().get("GithubUsername") or "")
541541

542542
@dispatcher.add_method
543543
def getSimInfo():

system/hardware/power_monitoring.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(self):
2929
self.car_voltage_instant_mV = 12e3 # Last value of peripheralState voltage
3030
self.integration_lock = threading.Lock()
3131

32-
car_battery_capacity_uWh = self.params.get("CarBatteryCapacity", default=0)
32+
car_battery_capacity_uWh = self.params.get("CarBatteryCapacity") or 0
3333

3434
# Reset capacity if it's low
3535
self.car_battery_capacity_uWh = max((CAR_BATTERY_CAPACITY_uWh / 10), car_battery_capacity_uWh)

0 commit comments

Comments
 (0)