From fa8babd944cd8b490fa31d7f8b2600cee849c13a Mon Sep 17 00:00:00 2001 From: Adeeb Shihadeh Date: Sun, 25 Oct 2026 14:59:14 -0700 Subject: [PATCH] Move HITL tests to UP (#39138) --- .github/labeler.yaml | 2 +- Jenkinsfile | 320 ------------------ alfred.toml | 112 ++++++ openpilot/common/hardware/usb.py | 10 + openpilot/selfdrive/modeld/helpers.py | 3 +- openpilot/selfdrive/modeld/modeld.py | 5 +- .../selfdrive/pandad/tests/test_pandad_spi.py | 24 +- openpilot/selfdrive/test/setup_device_ci.sh | 166 --------- openpilot/selfdrive/test/test_power_draw.py | 14 +- openpilot/selfdrive/ui/ui_state.py | 4 +- openpilot/system/camerad/test/test_camerad.py | 5 +- openpilot/tools/replay/can_replay.py | 28 +- tools/release/build_release.sh | 2 +- 13 files changed, 169 insertions(+), 526 deletions(-) delete mode 100644 Jenkinsfile create mode 100644 alfred.toml delete mode 100755 openpilot/selfdrive/test/setup_device_ci.sh diff --git a/.github/labeler.yaml b/.github/labeler.yaml index 2481a112ce..14d929e059 100644 --- a/.github/labeler.yaml +++ b/.github/labeler.yaml @@ -1,6 +1,6 @@ CI / testing: - changed-files: - - any-glob-to-all-files: "{.github/**,**/test_*,**/test/**,Jenkinsfile}" + - any-glob-to-all-files: "{.github/**,**/test_*,**/test/**}" car: - changed-files: diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index 5facce903f..0000000000 --- a/Jenkinsfile +++ /dev/null @@ -1,320 +0,0 @@ -def retryWithDelay(int maxRetries, int delay, Closure body) { - for (int i = 0; i < maxRetries; i++) { - try { - return body() - } catch (Exception e) { - sleep(delay) - } - } - throw Exception("Failed after ${maxRetries} retries") -} - -def device(String ip, String step_label, String cmd) { - withCredentials([file(credentialsId: 'id_rsa', variable: 'key_file')]) { - def ssh_cmd = """ -ssh -o ControlMaster=no -o ControlPath=none -o ConnectTimeout=5 -o ServerAliveInterval=5 -o ServerAliveCountMax=12 -o BatchMode=yes -o StrictHostKeyChecking=no -i ${key_file} 'comma@${ip}' exec setpriv --pdeathsig HUP /usr/bin/bash <<'END' - -set -e - -export TERM=xterm-256color - -trap 'kill 0' HUP # stop this process group on SSH disconnect - -export CI=1 -export PYTHONWARNINGS=error -export PYTHONFAULTHANDLER=1 -export COMMA_CACHE=/data/tmp/comma_download_cache -#export LOGPRINT=debug # this has gotten too spammy... -export TEST_DIR=${env.TEST_DIR} -export SOURCE_DIR=${env.SOURCE_DIR} -export GIT_BRANCH=${env.GIT_BRANCH} -export GIT_COMMIT=${env.GIT_COMMIT} -export CI_ARTIFACTS_TOKEN=${env.CI_ARTIFACTS_TOKEN} -export GITHUB_COMMENTS_TOKEN=${env.GITHUB_COMMENTS_TOKEN} -export AZURE_TOKEN='${env.AZURE_TOKEN}' -# only use 1 thread since most require real hardware that can't be shared -export PYTEST_ADDOPTS="-n0 -s" - - -export GIT_SSH_COMMAND="ssh -i /data/gitkey" - -source ~/.bash_profile -if [ -f /AGNOS ]; then - source /etc/profile - - rm -rf /tmp/tmp* - rm -rf ~/.commacache - rm -rf /dev/shm/* - rm -rf /dev/tmp/tmp* - - if ! systemctl is-active --quiet systemd-resolved; then - echo "restarting resolved" - sudo systemctl start systemd-resolved - sleep 3 - fi - - # restart aux USB - if [ -e /sys/bus/usb/drivers/hub/3-0:1.0 ]; then - echo "restarting aux usb" - echo "3-0:1.0" | sudo tee /sys/bus/usb/drivers/hub/unbind - sleep 0.5 - echo "3-0:1.0" | sudo tee /sys/bus/usb/drivers/hub/bind - fi -fi -if [ -f /data/openpilot/launch_env.sh ]; then - source /data/openpilot/launch_env.sh -fi - -export LD_LIBRARY_PATH="\$(python -c 'import ffmpeg; print(ffmpeg.LIB_DIR)'):/usr/local/lib:\${LD_LIBRARY_PATH:-}" - -ln -snf ${env.TEST_DIR} /data/pythonpath - -cd ${env.TEST_DIR} || true -time ( ${cmd} ) & -wait \$! -END""" - - sh script: ssh_cmd, label: step_label - } -} - -def deviceStage(String stageName, String deviceType, List extra_env, def steps) { - stage(stageName) { - if (currentBuild.result != null) { - return - } - - if (isReplay()) { - error("REPLAYING TESTS IS NOT ALLOWED. FIX THEM INSTEAD.") - } - - def extra = extra_env.collect { "export ${it}" }.join('\n'); - def branch = env.BRANCH_NAME ?: 'master'; - def gitDiff = sh returnStdout: true, script: 'curl -s -H "Authorization: Bearer ${GITHUB_COMMENTS_TOKEN}" https://api.github.com/repos/commaai/openpilot/compare/master...${GIT_BRANCH} | jq .files[].filename || echo "/"', label: 'Getting changes' - - lock(resource: "", label: deviceType, inversePrecedence: true, variable: 'device_ip', quantity: 1, resourceSelectStrategy: 'random') { - docker.image('ghcr.io/commaai/alpine-ssh').inside('--user=root') { - timeout(time: 35, unit: 'MINUTES') { - retry (3) { - def date = sh(script: 'date', returnStdout: true).trim(); - device(device_ip, "set time", "date -s '" + date + "'") - device(device_ip, "git checkout", extra + "\n" + readFile("openpilot/selfdrive/test/setup_device_ci.sh")) - } - steps.each { item -> - def name = item[0] - def cmd = item[1] - - def args = item[2] - def diffPaths = args.diffPaths ?: [] - def cmdTimeout = args.timeout ?: 9999 - - if (branch != "master" && !branch.contains("__jenkins_loop_") && diffPaths && !hasPathChanged(gitDiff, diffPaths)) { - println "Skipping ${name}: no changes in ${diffPaths}." - return - } else { - timeout(time: cmdTimeout, unit: 'SECONDS') { - device(device_ip, name, cmd) - } - } - } - } - } - } - } -} - -def hasPathChanged(String gitDiff, List paths) { - for (path in paths) { - if (gitDiff.contains(path)) { - return true - } - } - return false -} - -def isReplay() { - def replayClass = "org.jenkinsci.plugins.workflow.cps.replay.ReplayCause" - return currentBuild.rawBuild.getCauses().any{ cause -> cause.toString().contains(replayClass) } -} - -def setupCredentials() { - withCredentials([ - string(credentialsId: 'azure_token', variable: 'AZURE_TOKEN'), - ]) { - env.AZURE_TOKEN = "${AZURE_TOKEN}" - } - - withCredentials([ - string(credentialsId: 'ci_artifacts_pat', variable: 'CI_ARTIFACTS_TOKEN'), - ]) { - env.CI_ARTIFACTS_TOKEN = "${CI_ARTIFACTS_TOKEN}" - } - - withCredentials([ - string(credentialsId: 'post_comments_github_pat', variable: 'GITHUB_COMMENTS_TOKEN'), - ]) { - env.GITHUB_COMMENTS_TOKEN = "${GITHUB_COMMENTS_TOKEN}" - } -} - -def step(String name, String cmd, Map args = [:]) { - return [name, cmd, args] -} - -def chestnutStage(String name = "chestnut") { - deviceStage(name, "mici-chestnut-ci", ["UNSAFE=1", "CHESTNUT=1"], [ - step("build", "./openpilot/selfdrive/test/chestnut.sh"), - step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py --chestnut"), - step("onroad tests", "./openpilot/selfdrive/test/test_onroad.py TestChestnutOnroad", [timeout: 120]), - ]) -} - -node { - env.CI = "1" - env.PYTHONWARNINGS = "error" - env.TEST_DIR = "/data/openpilot" - env.SOURCE_DIR = "/data/openpilot_source/" - setupCredentials() - - env.GIT_BRANCH = checkout(scm).GIT_BRANCH - env.GIT_COMMIT = checkout(scm).GIT_COMMIT - - if (env.JOB_BASE_NAME == 'chestnut-stresstest') { - sh 'git fetch --no-tags origin nightly-chestnut' - env.GIT_COMMIT = sh(script: 'git show FETCH_HEAD:git_src_commit', returnStdout: true).trim() - if (!(env.GIT_COMMIT ==~ /[0-9a-f]{40}/)) { - error("invalid nightly-chestnut source commit") - } - def results = [] - try { - timeout(time: 12, unit: 'HOURS') { - for (int run = 1; run <= 100; run++) { - results << "run ${run}: INCOMPLETE" - try { - chestnutStage("chestnut ${run}/100") - results[run - 1] = "run ${run}: PASS" - } catch (hudson.AbortException e) { - results[run - 1] = "run ${run}: FAIL" - echo e.toString() - } - } - } - } finally { - writeFile file: 'chestnut_stress_report.txt', text: "commit: ${env.GIT_COMMIT}\ncompleted: ${results.count { !it.endsWith('INCOMPLETE') }}/100\n" + results.join('\n') + '\n' - archiveArtifacts artifacts: 'chestnut_stress_report.txt' - } - if (results.any { !it.endsWith('PASS') }) { - error("chestnut stress test failed") - } - return - } - - def excludeBranches = ['__nightly', '__nightly-chestnut', 'devel', 'devel-staging', - 'release-tizi', 'release-tizi-staging', 'release-mici', 'release-mici-staging', 'testing-closet*', 'hotfix-*'] - def excludeRegex = excludeBranches.join('|').replaceAll('\\*', '.*') - - if (env.BRANCH_NAME != 'master' && !env.BRANCH_NAME.contains('__jenkins_loop_')) { - properties([ - disableConcurrentBuilds(abortPrevious: true) - ]) - } - - try { - if (env.BRANCH_NAME == 'devel-staging') { - deviceStage("build release-tizi-staging", "tizi-needs-can", [], [ - step("build release-tizi-staging", "RELEASE_BRANCH=release-tizi-staging,release-mici-staging $SOURCE_DIR/tools/release/build_release.sh"), - ]) - } - - if (env.BRANCH_NAME == '__nightly') { - parallel ( - 'nightly': { - deviceStage("build nightly", "tizi-needs-can", [], [ - step("build nightly", "RELEASE_BRANCH=nightly $SOURCE_DIR/tools/release/build_release.sh"), - ]) - }, - 'nightly-dev': { - deviceStage("build nightly-dev", "tizi-needs-can", [], [ - step("build nightly-dev", "PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-dev $SOURCE_DIR/tools/release/build_release.sh"), - ]) - }, - ) - } - - if (env.BRANCH_NAME == '__nightly-chestnut') { - parallel ( - 'nightly-chestnut': { - deviceStage("build nightly-chestnut", "mici-chestnut-ci", ["CHESTNUT=1"], [ - step("build nightly-chestnut", "SCONSFLAGS=-j4 INCLUDE_BIG_MODEL=1 RELEASE_BRANCH=nightly-chestnut $SOURCE_DIR/tools/release/build_release.sh TestChestnutOnroad"), - ]) - }, - 'nightly-chestnut-dev': { - deviceStage("build nightly-chestnut-dev", "mici-chestnut-ci", ["CHESTNUT=1"], [ - step("build nightly-chestnut-dev", "SCONSFLAGS=-j4 INCLUDE_BIG_MODEL=1 PANDA_DEBUG_BUILD=1 RELEASE_BRANCH=nightly-chestnut-dev $SOURCE_DIR/tools/release/build_release.sh TestChestnutOnroad"), - ]) - }, - ) - } - - if (!env.BRANCH_NAME.matches(excludeRegex)) { - parallel ( - 'onroad tests': { - deviceStage("onroad", "tizi-needs-can", ["UNSAFE=1"], [ - step("build openpilot", "cd openpilot/system/manager && ./build.py"), - step("check dirty", "tools/release/check-dirty.sh"), - step("onroad tests", "./openpilot/selfdrive/test/test_onroad.py", [timeout: 60]), - ]) - }, - 'HW + Unit Tests': { - deviceStage("tizi-hardware", "tizi-common", ["UNSAFE=1"], [ - step("build", "cd openpilot/system/manager && ./build.py"), - step("test power draw", "./openpilot/selfdrive/test/test_power_draw.py"), - step("test encoder", "./openpilot/system/loggerd/tests/test_encoder.py", [diffPaths: ["openpilot/system/loggerd/"]]), - step("test manager", "./openpilot/system/manager/test/test_manager.py"), - ]) - }, - 'camerad OX03C10': { - deviceStage("OX03C10", "tizi-ox03c10", ["UNSAFE=1"], [ - step("build", "cd openpilot/system/manager && ./build.py"), - step("test pandad", "./openpilot/selfdrive/pandad/tests/test_pandad.py"), - step("test camerad", "./openpilot/system/camerad/test/test_camerad.py", [timeout: 90]), - ]) - }, - 'camerad OS04C10': { - deviceStage("OS04C10", "tici-os04c10", ["UNSAFE=1"], [ - step("build", "cd openpilot/system/manager && ./build.py"), - step("test pandad", "./openpilot/selfdrive/pandad/tests/test_pandad.py"), - step("test camerad", "./openpilot/system/camerad/test/test_camerad.py", [timeout: 90]), - ]) - }, - 'sensord': { - deviceStage("LSM + MMC", "tizi-lsmc", ["UNSAFE=1"], [ - step("build", "cd openpilot/system/manager && ./build.py"), - step("test sensord", "./openpilot/system/sensord/tests/test_sensord.py"), - ]) - }, - 'replay': { - deviceStage("model-replay", "tizi-replay", ["UNSAFE=1"], [ - step("build", "cd openpilot/system/manager && ./build.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]), - step("model replay", "openpilot/selfdrive/test/process_replay/model_replay.py", [diffPaths: ["openpilot/selfdrive/modeld/", "tinygrad_repo", "openpilot/selfdrive/test/process_replay/model_replay.py"]]), - ]) - }, - 'tizi': { - deviceStage("tizi", "tizi", ["UNSAFE=1"], [ - step("build openpilot", "cd openpilot/system/manager && ./build.py"), - step("test pandad loopback", "./openpilot/selfdrive/pandad/tests/test_pandad_loopback.py"), - step("test pandad spi", "./openpilot/selfdrive/pandad/tests/test_pandad_spi.py"), - step("test amp", "./openpilot/common/hardware/comma/tests/test_amplifier.py"), - ]) - }, - 'chestnut': { - chestnutStage() - }, - - ) - } - } catch (Exception e) { - currentBuild.result = 'FAILED' - throw e - } -} diff --git a/alfred.toml b/alfred.toml new file mode 100644 index 0000000000..c5ea8a2ca7 --- /dev/null +++ b/alfred.toml @@ -0,0 +1,112 @@ +[env] +PYTHONPATH = "/data/ci/tree/openpilot" # the tree +TERM = "xterm-256color" +PYTHONWARNINGS = "error" +PYTHONFAULTHANDLER = "1" +COMMA_CACHE = "/data/tmp/comma_download_cache" +# as launch_env.sh sets for openpilot on a device +OMP_NUM_THREADS = "1" +MKL_NUM_THREADS = "1" +NUMEXPR_NUM_THREADS = "1" +OPENBLAS_NUM_THREADS = "1" +VECLIB_MAXIMUM_THREADS = "1" +QCOM_PRIORITY = "12" + +# with the submodule package symlinks launch_chffrplus.sh makes +[steps.build] +name = "Build openpilot" +run = """ +for p in msgq_repo/msgq opendbc_repo/opendbc rednose_repo/rednose teleoprtc_repo/teleoprtc tinygrad_repo/tinygrad; do ln -sfn "$p" "${p#*/}"; done +cd openpilot/system/manager && ./build.py +""" + +# jobs run on comma fours, and on a comma 3x only where it differs, like its camera sensor +[jobs.onroad] +runs-on = "up-can" +timeout-minutes = 35 + +[[jobs.onroad.steps]] +uses = "build" + +[[jobs.onroad.steps]] +name = "Check dirty" +run = "tools/release/check-dirty.sh" + +# the UP replays the CAN until the step ends +[[jobs.onroad.steps]] +name = "Onroad tests" +run = "openpilot/tools/replay/can_replay.py --up && ./openpilot/selfdrive/test/test_onroad.py TestOnroad" +timeout-minutes = 1.5 + +[jobs.hardware] +runs-on = "up-mici" +timeout-minutes = 35 + +[[jobs.hardware.steps]] +uses = "build" + +[[jobs.hardware.steps]] +name = "Encoder" +run = "./openpilot/system/loggerd/tests/test_encoder.py" + +[[jobs.hardware.steps]] +name = "Manager" +run = "./openpilot/system/manager/test/test_manager.py" + +[[jobs.hardware.steps]] +name = "Power draw" +run = "./openpilot/selfdrive/test/test_power_draw.py" + +[jobs.replay] +runs-on = "up-mici" +timeout-minutes = 35 + +[[jobs.replay.steps]] +uses = "build" + +[[jobs.replay.steps]] +name = "Model replay" +run = "openpilot/selfdrive/test/process_replay/model_replay.py" + +[jobs.pandad] +runs-on = "up-mici" +timeout-minutes = 35 + +[[jobs.pandad.steps]] +uses = "build" + +[[jobs.pandad.steps]] +name = "Pandad" +run = "./openpilot/selfdrive/pandad/tests/test_pandad.py" + +[[jobs.pandad.steps]] +name = "Pandad loopback" +run = "./openpilot/selfdrive/pandad/tests/test_pandad_loopback.py" + +[[jobs.pandad.steps]] +name = "Pandad SPI" +run = "./openpilot/selfdrive/pandad/tests/test_pandad_spi.py" + +# TODO: back once camerad's test passes on the rack, it fails on both comma fours and the comma 3x +# [jobs.camerad] +# runs-on = ["up-mici", "up-tres"] +# timeout-minutes = 35 +# +# [[jobs.camerad.steps]] +# uses = "build" +# +# [[jobs.camerad.steps]] +# name = "Camerad" +# run = "./openpilot/system/camerad/test/test_camerad.py" +# timeout-minutes = 1.5 + +[jobs.sensord] +runs-on = "up-mici" +timeout-minutes = 35 + +[[jobs.sensord.steps]] +uses = "build" + +[[jobs.sensord.steps]] +name = "Sensord" +run = "./openpilot/system/sensord/tests/test_sensord.py" diff --git a/openpilot/common/hardware/usb.py b/openpilot/common/hardware/usb.py index 55d970a245..6658b2d4b4 100644 --- a/openpilot/common/hardware/usb.py +++ b/openpilot/common/hardware/usb.py @@ -7,6 +7,7 @@ CHESTNUT_ROM_USB_IDS = ((0x174C, 0x2464), (0x174C, 0x2463)) CHESTNUT_USB_PRODUCT = f"custom {CHESTNUT_FW_VERSION}-CLEAN" USB_DEVICES_PATH = Path("/sys/bus/usb/devices") TYPEC_CC_ORIENTATION_PATH = Path("/sys/class/power_supply/usb/typec_cc_orientation") +UDC_PATH = Path("/sys/class/udc") PRIMARY_USB_CONTROLLER = "a600000.ssusb" @@ -40,6 +41,15 @@ def cable_connected() -> bool: return read_int(TYPEC_CC_ORIENTATION_PATH) != 0 +def usb_host_connected() -> bool: + """Whether a USB host, e.g. a PC with adb or the UP in CI, is on the USB-C port, also while it has suspended this device. + A chestnut is a USB device, so then it isn't on that port.""" + try: + return any(read(p) not in (None, "not attached") for p in UDC_PATH.glob("*/state")) + except OSError: + return False + + def usb_devices() -> list[Path]: try: devices = (d for d in USB_DEVICES_PATH.glob("*") if (d / "idVendor").exists()) diff --git a/openpilot/selfdrive/modeld/helpers.py b/openpilot/selfdrive/modeld/helpers.py index 9ac772e697..6fb41cba29 100644 --- a/openpilot/selfdrive/modeld/helpers.py +++ b/openpilot/selfdrive/modeld/helpers.py @@ -40,5 +40,6 @@ def wait_for_chestnut(timeout: float = 10.) -> None: def chestnut_compiled() -> bool: path = modeld_pkl_path(chestnut=True) - return path.is_file() and all( + # the big model is only built for releases, in a dev checkout it's a git LFS pointer + return path.is_file() and path.stat().st_size > 1024 and all( (MODELS_DIR / f'big_driving_warp_{size}_tinygrad.pkl').is_file() for size in ('1344x760', '1928x1208')) diff --git a/openpilot/selfdrive/modeld/modeld.py b/openpilot/selfdrive/modeld/modeld.py index bc9407f6a0..f2b80a527c 100755 --- a/openpilot/selfdrive/modeld/modeld.py +++ b/openpilot/selfdrive/modeld/modeld.py @@ -28,7 +28,7 @@ from msgq.visionipc import VisionIpcClient, VisionBuf from opendbc.car.car_helpers import get_demo_car_params from openpilot.common.swaglog import cloudlog from openpilot.common.params import Params -from openpilot.common.hardware.usb import cable_connected +from openpilot.common.hardware.usb import cable_connected, usb_host_connected from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.realtime import config_realtime_process, DT_MDL from openpilot.common.transformations.camera import DEVICE_CAMERAS @@ -231,7 +231,8 @@ class ModelState: def main(demo=False): cloudlog.warning("modeld init") - CHESTNUT = chestnut_compiled() and (chestnut_present() or cable_connected()) + # a cable is a chestnut on its way, unless a USB host is on it + CHESTNUT = chestnut_compiled() and (chestnut_present() or (cable_connected() and not usb_host_connected())) if CHESTNUT: from tinygrad.runtime.ops_amd import AMDDevice AMDDevice.wait_timeout_ms = 3000 diff --git a/openpilot/selfdrive/pandad/tests/test_pandad_spi.py b/openpilot/selfdrive/pandad/tests/test_pandad_spi.py index 2818654282..b8dafb2f86 100755 --- a/openpilot/selfdrive/pandad/tests/test_pandad_spi.py +++ b/openpilot/selfdrive/pandad/tests/test_pandad_spi.py @@ -13,16 +13,13 @@ from openpilot.common.timeout import Timeout from openpilot.selfdrive.test.helpers import with_processes from openpilot.selfdrive.pandad.tests.test_pandad_loopback import setup_pandad, send_random_can_messages -JUNGLE_SPAM = "JUNGLE_SPAM" in os.environ - class TestBoarddSpi(OpenpilotTestCase): COMMA_HARDWARE_TEST = True @classmethod def setup_class(cls): os.environ['STARTED'] = '1' os.environ['SPI_ERR_PROB'] = '0.001' - if not JUNGLE_SPAM: - os.environ['BOARDD_LOOPBACK'] = '1' + os.environ['BOARDD_LOOPBACK'] = '1' @with_processes(['pandad']) def test_spi_corruption(self, subtests): @@ -48,7 +45,7 @@ class TestBoarddSpi(OpenpilotTestCase): test_time = int(os.getenv("TEST_TIME", "20")) for i in range(test_time + 2): # send some CAN messages, then give the last ones time to come back - if not JUNGLE_SPAM and i < test_time: + if i < test_time: sent = send_random_can_messages(sendcan, random.randrange(2, 20)) for k, v in sent.items(): sent_msgs[k].extend(list(v)) @@ -62,15 +59,6 @@ class TestBoarddSpi(OpenpilotTestCase): assert m.valid or (service == "can") if service == "can": for msg in m.can: - if JUNGLE_SPAM: - # PandaJungle.set_generated_can(True) - i = msg.address - 0x200 - assert msg.address >= 0x200 - assert msg.src == (i%3) - assert msg.dat == b"\xff"*(i%8) - total_recv_count += 1 - continue - if msg.src > 4: continue key = (msg.address, msg.dat) @@ -81,14 +69,14 @@ class TestBoarddSpi(OpenpilotTestCase): assert len(m.pandaStates) == 1 ps = m.pandaStates[0] assert ps.uptime < 1000 - assert ps.pandaType == "tres" + assert ps.pandaType in ("tres", "cuatro") assert ps.ignitionLine assert not ps.ignitionCan - assert 4000 < ps.voltage < 14000 + assert 4000 < ps.voltage < 16000 elif service == "peripheralState": ps = m.peripheralState - assert ps.pandaType == "tres" - assert 4000 < ps.voltage < 14000 + assert ps.pandaType in ("tres", "cuatro") + assert 4000 < ps.voltage < 16000 assert ps.fanSpeedRpm < 10000 time.sleep(0.5) diff --git a/openpilot/selfdrive/test/setup_device_ci.sh b/openpilot/selfdrive/test/setup_device_ci.sh deleted file mode 100755 index 0edbf43905..0000000000 --- a/openpilot/selfdrive/test/setup_device_ci.sh +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env bash - -set -e -set -x - - -if [ -z "$SOURCE_DIR" ]; then - echo "SOURCE_DIR must be set" - exit 1 -fi - -if [ -z "$GIT_COMMIT" ]; then - echo "GIT_COMMIT must be set" - exit 1 -fi - -if [ -z "$TEST_DIR" ]; then - echo "TEST_DIR must be set" - exit 1 -fi - -# prevent storage from filling up -rm -rf /data/media/0/realdata/* - -rm -rf /data/safe_staging/ || true -if [ -d /data/safe_staging/ ]; then - sudo umount /data/safe_staging/merged/ || true - rm -rf /data/safe_staging/ || true -fi - -CONTINUE_PATH="/data/continue.sh" -tee "$CONTINUE_PATH" << EOF -#!/usr/bin/env bash - -sudo abctl --set_success - -# patch sshd config -sudo mount -o rw,remount / -sudo sed -i "s,/data/params/d/GithubSshKeys,/usr/comma/setup_keys," /etc/ssh/sshd_config -sudo systemctl daemon-reload -sudo systemctl restart ssh -sudo systemctl restart NetworkManager -sudo systemctl disable ssh-param-watcher.path -sudo systemctl disable ssh-param-watcher.service -sudo mount -o ro,remount / -sudo systemctl stop power_monitor - -while true; do - if ! sudo systemctl is-active -q ssh; then - sudo systemctl start ssh - fi - sleep 5s -done - -sleep infinity -EOF -chmod +x "$CONTINUE_PATH" - -# a DUT that booted with a continue.sh that launches openpilot is still running it, which fights the tests -if pgrep -f launch_chffrplus.sh > /dev/null; then - sudo systemctl stop comma -fi - -export GIT_LFS_SKIP_SMUDGE=1 -pull_lfs() { - if [ -n "${CHESTNUT:-}" ] - then - git lfs pull --exclude='' - return - fi - - # Keep the precompiled big model as a pointer on devices without Chestnut. - LFS_EXCLUDE="openpilot/selfdrive/modeld/models/big_driving_tinygrad.pkl" - - git config --local lfs.fetchexclude "$LFS_EXCLUDE" - git lfs pull --exclude="$LFS_EXCLUDE" - if git cat-file -e "HEAD:$LFS_EXCLUDE"; then - rm -f "$LFS_EXCLUDE" - git checkout -- "$LFS_EXCLUDE" - - # `git lfs prune` retains objects referenced by HEAD, even when excluded. - # Remove this one explicitly so safe checkout doesn't rsync it either. - oid=$(git show "HEAD:$LFS_EXCLUDE" | sed -n 's/^oid sha256://p') - lfs_objects=$(git lfs env | sed -n 's/^LocalMediaDir=//p') - if [[ "$oid" =~ ^[0-9a-f]{64}$ && -n "$lfs_objects" ]]; then - rm -f "$lfs_objects/${oid:0:2}/${oid:2:2}/$oid" - fi - fi -} - -safe_checkout() { - # completely clean TEST_DIR - - cd "$SOURCE_DIR" - - # cleanup orphaned locks - find .git -type f -name "*.lock" -exec rm {} + - - git reset --hard - git fetch --no-tags --no-recurse-submodules -j4 --verbose --depth 1 origin "$GIT_COMMIT" - find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; - git reset --hard "$GIT_COMMIT" - git checkout "$GIT_COMMIT" - git clean -xdff - git submodule sync - git submodule foreach --recursive "git reset --hard && git clean -xdff" - git submodule update --init --recursive - git submodule foreach --recursive "git reset --hard && git clean -xdff" - - pull_lfs - - echo "git checkout done, t=$SECONDS" - du -hs "$SOURCE_DIR" "$SOURCE_DIR/.git" - - rsync -a --delete "$SOURCE_DIR" "$TEST_DIR" -} - -unsafe_checkout() {( set -e - # checkout directly in test dir, leave old build products - - cd "$TEST_DIR" - - # cleanup orphaned locks - find .git -type f -name "*.lock" -exec rm {} + - - git fetch --no-tags --no-recurse-submodules -j8 --verbose --depth 1 origin "$GIT_COMMIT" - git checkout --force --no-recurse-submodules "$GIT_COMMIT" - git reset --hard "$GIT_COMMIT" - git clean -dff - git submodule sync - git submodule foreach --recursive "git reset --hard && git clean -df" - git submodule update --init --recursive - git submodule foreach --recursive "git reset --hard && git clean -df" - - pull_lfs -)} - -export GIT_PACK_THREADS=8 - -# set up environment -if [ ! -d "$SOURCE_DIR" ]; then - git clone https://github.com/commaai/openpilot.git "$SOURCE_DIR" -fi - -if [ ! -z "$UNSAFE" ]; then - echo "trying unsafe checkout" - set +e - unsafe_checkout - if [[ "$?" -ne 0 ]]; then - safe_checkout - fi - set -e -else - echo "doing safe checkout" - safe_checkout -fi - -# submodule package symlinks for PYTHONPATH imports on device (same as launch_chffrplus.sh) -cd "$TEST_DIR" -ln -sfn msgq_repo/msgq msgq -ln -sfn opendbc_repo/opendbc opendbc -ln -sfn rednose_repo/rednose rednose -ln -sfn teleoprtc_repo/teleoprtc teleoprtc -ln -sfn tinygrad_repo/tinygrad tinygrad - -echo "$TEST_DIR synced with $GIT_COMMIT, t=$SECONDS" diff --git a/openpilot/selfdrive/test/test_power_draw.py b/openpilot/selfdrive/test/test_power_draw.py index 1d0be24ef0..05c2d9a29d 100755 --- a/openpilot/selfdrive/test/test_power_draw.py +++ b/openpilot/selfdrive/test/test_power_draw.py @@ -5,6 +5,7 @@ import time import unittest import numpy as np from dataclasses import dataclass +from openpilot.common.hardware import HARDWARE from openpilot.common.test import OpenpilotTestCase from openpilot.common.utils import tabulate @@ -13,12 +14,12 @@ from openpilot.cereal.services import SERVICE_LIST from opendbc.car.car_helpers import get_demo_car_params from openpilot.common.mock import mock_messages from openpilot.common.params import Params -from openpilot.common.hardware.comma.power_monitor import get_power from openpilot.system.manager.process_config import managed_processes from openpilot.system.manager.manager import manager_cleanup SAMPLE_TIME = 2 # seconds to sample power MAX_WARMUP_TIME = 30 # seconds to wait for SAMPLE_TIME consecutive valid samples +MICI = HARDWARE.get_device_type() == "mici" @dataclass class Proc: @@ -33,9 +34,10 @@ class Proc: return '+'.join(self.procs) +# how much each adds to the DUT's power, which the UP measures on its OBD-C port PROCS = [ - Proc(['camerad'], 1.65, atol=0.4, msgs=['narrowRoadCameraState', 'wideRoadCameraState', 'cabinCameraState']), - Proc(['modeld'], 1.5, atol=0.2, msgs=['modelV2']), + Proc(['camerad'], 1.0 if MICI else 1.65, atol=0.4, msgs=['narrowRoadCameraState', 'wideRoadCameraState', 'cabinCameraState']), + Proc(['modeld'], 1.15 if MICI else 1.5, atol=0.2, msgs=['modelV2']), Proc(['dmonitoringmodeld'], 0.65, atol=0.35, msgs=['driverStateV2']), Proc(['encoderd'], 0.23, msgs=[]), ] @@ -46,6 +48,8 @@ class TestPowerDraw(OpenpilotTestCase): def setup_method(self): Params().put("CarParams", get_demo_car_params().to_bytes(), block=True) + from ultimate_provisioning import UP # only on a DUT, from its UP's up run or up ssh + self.up = UP.remote() def teardown_method(self): manager_cleanup() @@ -78,7 +82,7 @@ class TestPowerDraw(OpenpilotTestCase): start_time = time.monotonic() while (time.monotonic() - start_time) < MAX_WARMUP_TIME: - power = get_power(1) + power = self.up.get_power(1) iteration_msg_counts = {} for msg,sock in socks.items(): iteration_msg_counts[msg] = len(messaging.drain_sock_raw(sock)) @@ -97,7 +101,7 @@ class TestPowerDraw(OpenpilotTestCase): @mock_messages(['deviceMotion']) def test_camera_procs(self, subtests): - baseline = get_power() + baseline = self.up.get_power() prev = baseline used = {} diff --git a/openpilot/selfdrive/ui/ui_state.py b/openpilot/selfdrive/ui/ui_state.py index bc64de5e29..9f154ee41d 100644 --- a/openpilot/selfdrive/ui/ui_state.py +++ b/openpilot/selfdrive/ui/ui_state.py @@ -12,7 +12,7 @@ from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.ui.lib.prime_state import PrimeState from openpilot.system.ui.lib.application import gui_app from openpilot.common.hardware import HARDWARE, PC -from openpilot.common.hardware.usb import cable_connected, get_usb_state, is_chestnut_usb_id +from openpilot.common.hardware.usb import cable_connected, get_usb_state, is_chestnut_usb_id, usb_host_connected from openpilot.selfdrive.modeld.helpers import chestnut_compiled from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS @@ -207,7 +207,7 @@ class UIState: self.status = UIStatus.DISENGAGED self.started_frame = self.sm.frame self.started_time = time.monotonic() - self.chestnut_present = self.sm["deviceState"].chestnutPresent or (self.chestnut_compiled and self.usb_connected) + self.chestnut_present = self.sm["deviceState"].chestnutPresent or (self.chestnut_compiled and self.usb_connected and not usb_host_connected()) for callback in self._offroad_transition_callbacks: callback() diff --git a/openpilot/system/camerad/test/test_camerad.py b/openpilot/system/camerad/test/test_camerad.py index 570f2a6780..8a6db6fcbe 100755 --- a/openpilot/system/camerad/test/test_camerad.py +++ b/openpilot/system/camerad/test/test_camerad.py @@ -30,7 +30,10 @@ def _image_stats(im): def _converged(ts, cam): measured, target = ts[cam]['measuredGreyFraction'], ts[cam]['targetGreyFraction'] - return np.abs(measured - target) < EXPOSURE_TOLERANCE * target + # in a scene too dark (or bright) to reach the target, auto exposure settles at its limit instead + ev = ts[cam]['exposureValPercent'] + saturated = ((ev > 99.9) & (measured < target)) | ((ev < 0.1) & (measured > target)) + return (np.abs(measured - target) < EXPOSURE_TOLERANCE * target) | saturated def run_and_log(procs, services, duration): diff --git a/openpilot/tools/replay/can_replay.py b/openpilot/tools/replay/can_replay.py index 0717320077..85d92ce580 100755 --- a/openpilot/tools/replay/can_replay.py +++ b/openpilot/tools/replay/can_replay.py @@ -8,7 +8,6 @@ import threading from openpilot.common.realtime import config_realtime_process, Ratekeeper, DT_CTRL from openpilot.selfdrive.pandad import can_capnp_to_list from openpilot.tools.lib.logreader import LogReader -from panda import PandaJungle # set both to cycle power or ignition PWR_ON = int(os.getenv("PWR_ON", "0")) @@ -19,19 +18,21 @@ ENABLE_IGN = IGN_ON > 0 and IGN_OFF > 0 ENABLE_PWR = PWR_ON > 0 and PWR_OFF > 0 -def send_thread(j: PandaJungle, flock): - if "FLASH" in os.environ: - with flock: - j.flash() - - j.reset() +def setup(j): for i in [0, 1, 2, 3, 0xFFFF]: j.can_clear(i) j.set_can_speed_kbps(i, 500) j.set_ignition(True) j.set_panda_power(True) - j.set_can_loopback(False) + +def send_thread(j, flock): + if "FLASH" in os.environ: + with flock: + j.flash() + j.reset() + j.set_can_loopback(False) + setup(j) rk = Ratekeeper(1 / DT_CTRL, print_delay_threshold=None) while True: # handle cycling @@ -56,6 +57,7 @@ def send_thread(j: PandaJungle, flock): def connect(): + from panda import PandaJungle config_realtime_process(3, 55) serials = {} @@ -92,6 +94,7 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description="Replay CAN messages from a route to all connected pandas and jungles in a loop.", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to replay. If not specified, a default public route will be used.") + parser.add_argument("--up", action="store_true", help="On a DUT, have its UP replay until the `up run` or `up ssh` that started this ends.") args = parser.parse_args() if args.route_or_segment_name is None: @@ -104,4 +107,11 @@ if __name__ == "__main__": if ENABLE_IGN: print(f"Cycling ignition: on for {IGN_ON}s, off for {IGN_OFF}s") - connect() + if args.up: + from ultimate_provisioning import UP + up = UP.remote() + up.set_harness_orientation(UP.HARNESS_ORIENTATION_1) + setup(up) + up.can_replay([[m for m in send if m[-1] <= 2] for send in CAN_MSGS]) + else: + connect() diff --git a/tools/release/build_release.sh b/tools/release/build_release.sh index 686c3ab8d7..97cfa8a781 100755 --- a/tools/release/build_release.sh +++ b/tools/release/build_release.sh @@ -79,7 +79,7 @@ find . -name '*.o' -delete find . -name '*.os' -delete find . -name '*.pyc' -delete find . -name '__pycache__' -delete -rm -rf .sconsign.dblite Jenkinsfile tools/release/ +rm -rf .sconsign.dblite tools/release/ rm -f openpilot/selfdrive/modeld/models/*.onnx* # Mark as prebuilt release