Files
sunnypilot/system/manager/manager.py
Nayan 0cb0bf8028 Longitudinal: Custom ACC setpoint increments support (#889)
* Add Reverse ACC Change parameter and update cruise control logic

* lint lint lint (and lint has been summoned!)

* Add test for speed adjustment on reverse ACC button presses

* Fix formatting in cruise speed test for reverse ACC button presses

* Fix assertion in cruise speed test for reverse ACC button presses

* Enhance speed adjustment test for reverse ACC functionality

* Refactor speed adjustment test for clarity and consistency in reverse ACC behavior

* Fix metric conversion in cruise speed update for reverse ACC functionality

* custom-acc-speed-increments

* simplify

* remove unused params

* move params & add test

* lets see if this works

* minor cosmetic stuff

* clean up class names & old code

* remove unused import

* moved params to card

* stupid strings

* Add settings for developer reverse acceleration configuration

* Refactor cruise control parameters to use a dictionary for custom acceleration increments

* adjust for the default behavior

* Remove unused param

* Fuck pytest consistently failing on macos. Need to force a fail on the pipeline or I won't have confidence on the tests.

* Revert "Fuck pytest consistently failing on macos. Need to force a fail on the pipeline or I won't have confidence on the tests."

This reverts commit 05bac46a0c.

* Refactor custom acceleration increment handling to improve clarity and initialization

* Refactor AccIncrementOptionControl to accept range and per_value_change parameters for improved flexibility

* Refactor custom acceleration increment handling to improve clarity and functionality

* Adjusting tests

* Static

* no need for space changes

* no need for space changes

* no need for space changes

* Refactor constructor formatting in AccIncrementOptionControl

* Rename

* Meaningless change to test CI

* allow 1/5/10 increments for long press
move developer panel src to /offroad/settings

* update boundary condition for long press

* clamp increments of 5/10 regardless of short or long press

* update tests

* update test for long_press non-standard values

* move to cruise panel

* init

* use cereal

* update tests

* merge

* bump

* clean up

* more clean up

* no more layout warnings

* trying to resolve dev ci merge conflicts

* damn ui preview

* stack layout
enable only with oplong

* bump opendbc

* fix width

* bump tinygrad

* switch to params

* remove cereal changes

* sort params

* cleanup

* more cleanup

* lint

* rename

* split vcruise_helper

* move params to card thread
hide widget for pcm cruise

* simplify tests

* further simplify tests

* tests!!

* Revert "tests!!"

This reverts commit 85310a155e.

* move tuple from init to update_v_cruise

* lint

* temp remove tests to check

* Revert "temp remove tests to check"

This reverts commit da1c96a5db.

* handle exception

* formatting

* handle none condition

* remove from tests

* flip inheritance

* read directly

* set default

* not needed

* refactor inheritence

* rename

* already checks before invoking

* unused

* slight cleanup

* lint

* rename

* diff

* circular

* just 1 parent for now

* fix

* fix increment check with remainder

* red diff

* type hint

* update tests

* clip them

* formatting

* always check toggle visibility

* spaces are free

* hide widgets when disabled

* less

* handle more states

* private instead

* red diff says wuuuut

* fix panel click

---------

Co-authored-by: DevTekVE <devtekve@gmail.com>
Co-authored-by: Discountchubbs <159560811+Discountchubbs@users.noreply.github.com>
Co-authored-by: Jason Wen <haibin.wen3@gmail.com>
2025-06-10 22:48:46 -04:00

264 lines
8.2 KiB
Python
Executable File

#!/usr/bin/env python3
import datetime
import os
import signal
import sys
import traceback
from cereal import log
import cereal.messaging as messaging
import openpilot.system.sentry as sentry
from openpilot.common.params import Params, ParamKeyType
from openpilot.system.hardware import HARDWARE
from openpilot.system.manager.helpers import unblock_stdout, write_onroad_params, save_bootlog
from openpilot.system.manager.process import ensure_running
from openpilot.system.manager.process_config import managed_processes
from openpilot.system.athena.registration import register, UNREGISTERED_DONGLE_ID
from openpilot.common.swaglog import cloudlog, add_file_handler
from openpilot.system.version import get_build_metadata, terms_version, training_version
from openpilot.system.hardware.hw import Paths
from openpilot.sunnypilot.mapd.mapd_installer import VERSION
def manager_init() -> None:
save_bootlog()
build_metadata = get_build_metadata()
params = Params()
params.clear_all(ParamKeyType.CLEAR_ON_MANAGER_START)
params.clear_all(ParamKeyType.CLEAR_ON_ONROAD_TRANSITION)
params.clear_all(ParamKeyType.CLEAR_ON_OFFROAD_TRANSITION)
if build_metadata.release_channel:
params.clear_all(ParamKeyType.DEVELOPMENT_ONLY)
default_params: list[tuple[str, str | bytes]] = [
("CompletedTrainingVersion", "0"),
("DisengageOnAccelerator", "0"),
("GsmMetered", "1"),
("HasAcceptedTerms", "0"),
("LanguageSetting", "main_en"),
("OpenpilotEnabledToggle", "1"),
("LongitudinalPersonality", str(log.LongitudinalPersonality.standard)),
]
sunnypilot_default_params: list[tuple[str, str | bytes]] = [
("AutoLaneChangeTimer", "0"),
("AutoLaneChangeBsmDelay", "0"),
("BlindSpot", "0"),
("BlinkerMinLateralControlSpeed", "20"), # MPH or km/h
("BlinkerPauseLateralControl", "0"),
("CustomAccIncrementsEnabled", "0"),
("CustomAccLongPressIncrement", "5"),
("CustomAccShortPressIncrement", "1"),
("DeviceBootMode", "0"),
("DynamicExperimentalControl", "0"),
("HyundaiLongitudinalTuning", "0"),
("LagdToggle", "1"),
("Mads", "1"),
("MadsMainCruiseAllowed", "1"),
("MadsSteeringMode", "0"),
("MadsUnifiedEngagementMode", "1"),
("MapdVersion", f"{VERSION}"),
("MaxTimeOffroad", "1800"),
("Brightness", "0"),
("ModelManager_LastSyncTime", "0"),
("ModelManager_ModelsCache", ""),
("NeuralNetworkLateralControl", "0"),
("QuietMode", "0"),
]
# device boot mode
if params.get("DeviceBootMode") == b"1": # start in always offroad mode
params.put_bool("OffroadMode", True)
if params.get_bool("RecordFrontLock"):
params.put_bool("RecordFront", True)
# set unset params
for k, v in (default_params + sunnypilot_default_params):
if params.get(k) is None:
params.put(k, v)
# Create folders needed for msgq
try:
os.mkdir(Paths.shm_path())
except FileExistsError:
pass
except PermissionError:
print(f"WARNING: failed to make {Paths.shm_path()}")
# set params
serial = HARDWARE.get_serial()
params.put("Version", build_metadata.openpilot.version)
params.put("TermsVersion", terms_version)
params.put("TrainingVersion", training_version)
params.put("GitCommit", build_metadata.openpilot.git_commit)
params.put("GitCommitDate", build_metadata.openpilot.git_commit_date)
params.put("GitBranch", build_metadata.channel)
params.put("GitRemote", build_metadata.openpilot.git_origin)
params.put_bool("IsTestedBranch", build_metadata.tested_channel)
params.put_bool("IsReleaseBranch", build_metadata.release_channel)
params.put("HardwareSerial", serial)
# set dongle id
reg_res = register(show_spinner=True)
if reg_res:
dongle_id = reg_res
else:
raise Exception(f"Registration failed for device {serial}")
os.environ['DONGLE_ID'] = dongle_id # Needed for swaglog
os.environ['GIT_ORIGIN'] = build_metadata.openpilot.git_normalized_origin # Needed for swaglog
os.environ['GIT_BRANCH'] = build_metadata.channel # Needed for swaglog
os.environ['GIT_COMMIT'] = build_metadata.openpilot.git_commit # Needed for swaglog
if not build_metadata.openpilot.is_dirty:
os.environ['CLEAN'] = '1'
# init logging
sentry.init(sentry.SentryProject.SELFDRIVE)
cloudlog.bind_global(dongle_id=dongle_id,
version=build_metadata.openpilot.version,
origin=build_metadata.openpilot.git_normalized_origin,
branch=build_metadata.channel,
commit=build_metadata.openpilot.git_commit,
dirty=build_metadata.openpilot.is_dirty,
device=HARDWARE.get_device_type())
# preimport all processes
for p in managed_processes.values():
p.prepare()
def manager_cleanup() -> None:
# send signals to kill all procs
for p in managed_processes.values():
p.stop(block=False)
# ensure all are killed
for p in managed_processes.values():
p.stop(block=True)
cloudlog.info("everything is dead")
def manager_thread() -> None:
cloudlog.bind(daemon="manager")
cloudlog.info("manager start")
cloudlog.info({"environ": os.environ})
params = Params()
ignore: list[str] = []
if params.get("DongleId", encoding='utf8') in (None, UNREGISTERED_DONGLE_ID):
ignore += ["manage_athenad", "uploader"]
if os.getenv("NOBOARD") is not None:
ignore.append("pandad")
ignore += [x for x in os.getenv("BLOCK", "").split(",") if len(x) > 0]
sm = messaging.SubMaster(['deviceState', 'carParams'], poll='deviceState')
pm = messaging.PubMaster(['managerState'])
write_onroad_params(False, params)
ensure_running(managed_processes.values(), False, params=params, CP=sm['carParams'], not_run=ignore)
started_prev = False
while True:
sm.update(1000)
started = sm['deviceState'].started
if started and not started_prev:
params.clear_all(ParamKeyType.CLEAR_ON_ONROAD_TRANSITION)
elif not started and started_prev:
params.clear_all(ParamKeyType.CLEAR_ON_OFFROAD_TRANSITION)
# update onroad params, which drives pandad's safety setter thread
if started != started_prev:
write_onroad_params(started, params)
started_prev = started
ensure_running(managed_processes.values(), started, params=params, CP=sm['carParams'], not_run=ignore)
running = ' '.join("{}{}\u001b[0m".format("\u001b[32m" if p.proc.is_alive() else "\u001b[31m", p.name)
for p in managed_processes.values() if p.proc)
print(running)
cloudlog.debug(running)
# send managerState
msg = messaging.new_message('managerState', valid=True)
msg.managerState.processes = [p.get_process_state_msg() for p in managed_processes.values()]
pm.send('managerState', msg)
# Exit main loop when uninstall/shutdown/reboot is needed
shutdown = False
for param in ("DoUninstall", "DoShutdown", "DoReboot"):
if params.get_bool(param):
shutdown = True
params.put("LastManagerExitReason", f"{param} {datetime.datetime.now()}")
cloudlog.warning(f"Shutting down manager - {param} set")
if shutdown:
break
def main() -> None:
manager_init()
if os.getenv("PREPAREONLY") is not None:
return
# SystemExit on sigterm
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(1))
try:
manager_thread()
except Exception:
traceback.print_exc()
sentry.capture_exception()
finally:
manager_cleanup()
params = Params()
if params.get_bool("DoUninstall"):
cloudlog.warning("uninstalling")
HARDWARE.uninstall()
elif params.get_bool("DoReboot"):
cloudlog.warning("reboot")
HARDWARE.reboot()
elif params.get_bool("DoShutdown"):
cloudlog.warning("shutdown")
HARDWARE.shutdown()
if __name__ == "__main__":
from openpilot.system.ui.text import TextWindow
unblock_stdout()
try:
main()
except KeyboardInterrupt:
print("got CTRL-C, exiting")
except Exception:
add_file_handler(cloudlog)
cloudlog.exception("Manager failed to start")
try:
managed_processes['ui'].stop()
except Exception:
pass
# Show last 3 lines of traceback
error = traceback.format_exc(-3)
error = "Manager failed to start\n\n" + error
with TextWindow(error) as t:
t.wait_for_exit()
raise
# manual exit because we are forked
sys.exit(0)