Merge remote-tracking branch 'sunnypilot/sunnypilot/master' into py-sunnylink

# Conflicts:
#	selfdrive/ui/sunnypilot/ui_state.py
This commit is contained in:
Jason Wen
2025-11-30 00:57:09 -05:00
128 changed files with 2704 additions and 7421 deletions
@@ -6,10 +6,10 @@ env:
CI_DIR: ${{ github.workspace }}/release/ci
SCONS_CACHE_DIR: ${{ github.workspace }}/release/ci/scons_cache
PUBLIC_REPO_URL: "https://github.com/sunnypilot/sunnypilot"
# Branch configurations
STAGING_SOURCE_BRANCH: 'master'
# Runtime configuration
SOURCE_BRANCH: "${{ github.head_ref || github.ref_name }}"
@@ -75,7 +75,7 @@ jobs:
cancel="$(echo "$CONFIG" | jq -r '.cancel_publish_in_progress')";
echo "cancel_publish_in_progress=$( [ "$cancel" = "null" ] && echo "true" || echo $cancel)" >> $GITHUB_OUTPUT
echo "publish_concurrency_group=publish-${BRANCH}$( [ "$cancel" = "null" ] || [ "$cancel" = "true" ] || echo "${{ github.sha }}" )" >> $GITHUB_OUTPUT
is_stable_branch="$(echo "$CONFIG" | jq -r '.stable_branch // false')";
echo "is_stable_branch=$is_stable_branch" >> $GITHUB_OUTPUT
@@ -85,7 +85,7 @@ jobs:
fi
echo "build=$BUILD" >> $GITHUB_OUTPUT
cat $GITHUB_OUTPUT
validate_tests:
runs-on: ubuntu-24.04
needs: [ prepare_strategy ]
@@ -119,7 +119,7 @@ jobs:
needs.prepare_strategy.result == 'success' &&
(needs.validate_tests.result == 'success' || needs.validate_tests.result == 'skipped') &&
(!contains(github.event_name, 'pull_request') ||
(github.event.action == 'labeled' && github.event.label.name == 'prebuilt'))
(github.event.action == 'labeled' && github.event.label.name == 'prebuilt'))
}}
steps:
- uses: actions/checkout@v4
@@ -134,7 +134,7 @@ jobs:
with:
path: ${{env.SCONS_CACHE_DIR}}
key: scons-${{ runner.os }}-${{ runner.arch }}-${{ env.SOURCE_BRANCH }}-${{ github.sha }}
# Note: GitHub Actions enforces cache isolation between different build sources (PR builds, workflow dispatches, etc.)
# Note: GitHub Actions enforces cache isolation between different build sources (PR builds, workflow dispatches, etc.)
# for security. Only caches from the default branch are shared across all builds. This is by design and cannot be overridden.
restore-keys: |
scons-${{ runner.os }}-${{ runner.arch }}-${{ env.SOURCE_BRANCH }}
@@ -148,7 +148,7 @@ jobs:
echo "version=${{ needs.prepare_strategy.outputs.version }}" >> $GITHUB_OUTPUT
echo "extra_version_identifier=${{ needs.prepare_strategy.outputs.extra_version_identifier }}" >> $GITHUB_OUTPUT
echo "commit_sha=${{ github.sha }}" >> $GITHUB_OUTPUT
# Set up common environment
source /etc/profile;
export UV_PROJECT_ENVIRONMENT=${HOME}/venv
@@ -180,6 +180,15 @@ jobs:
./release/release_files.py | sort | uniq | rsync -rRl${RUNNER_DEBUG:+v} --files-from=- . $BUILD_DIR/
cd $BUILD_DIR
sed -i '/from .board.jungle import PandaJungle, PandaJungleDFU/s/^/#/' panda/__init__.py
echo "Building sunnypilot's modeld..."
scons -j$(nproc) cache_dir=${{env.SCONS_CACHE_DIR}} --minimal sunnypilot/modeld
echo "Building sunnypilot's modeld_v2..."
scons -j$(nproc) cache_dir=${{env.SCONS_CACHE_DIR}} --minimal sunnypilot/modeld_v2
echo "Building sunnypilot's locationd..."
scons -j2 cache_dir=${{env.SCONS_CACHE_DIR}} --minimal sunnypilot/selfdrive/locationd
echo "Building openpilot's locationd..."
scons -j$(nproc) cache_dir=${{env.SCONS_CACHE_DIR}} --minimal selfdrive/locationd
echo "Building rest of sunnypilot"
scons -j$(nproc) cache_dir=${{env.SCONS_CACHE_DIR}} --minimal
touch ${BUILD_DIR}/prebuilt
if [[ "${{ runner.debug }}" == "1" ]]; then
@@ -241,8 +250,8 @@ jobs:
if: always()
run: |
PYTHONPATH=$PYTHONPATH:${{ github.workspace }}/ ${{ github.workspace }}/scripts/manage-powersave.py --enable
publish:
concurrency:
# We do a bit of a hack here to avoid canceling the publishing job if a new commit comes in while we're publishing by adding the sha to the group name.
@@ -293,7 +302,7 @@ jobs:
echo "1. Go to: ${{ github.server_url }}/${{ github.repository }}/settings/variables/actions/AUTO_DEPLOY_PREBUILT_BRANCHES"
echo "2. Current value: ${{ vars.AUTO_DEPLOY_PREBUILT_BRANCHES }}"
echo "3. Update as needed (JSON array with no spaces)"
- name: Tag ${{ needs.prepare_strategy.outputs.environment }}
if: ${{ needs.prepare_strategy.outputs.is_stable_branch == 'true' && (github.event_name != 'push' || !startsWith(github.ref, 'refs/tags/')) }}
run: |
@@ -302,7 +311,7 @@ jobs:
git push -f origin ${TAG}
notify:
needs:
needs:
- prepare_strategy
- build
- publish
@@ -331,7 +340,7 @@ jobs:
${{ vars.DISCOURSE_GENERAL_UPDATE_NOTICE }}
EOF
)
{
echo 'content<<EOFMARKER'
echo "$MESSAGE"
+1
View File
@@ -107,6 +107,7 @@ jobs:
build_mac:
name: build macOS
if: false # temp disable since gcc-arm-embedded install is getting stuck due to checksum mismatch
runs-on: ${{ ((github.repository == 'commaai/openpilot') && ((github.event_name != 'pull_request') || (github.event.pull_request.head.repo.full_name == 'commaai/openpilot'))) && 'namespace-profile-macos-8x14' || 'macos-latest' }}
steps:
- uses: actions/checkout@v4
-10
View File
@@ -75,7 +75,6 @@ env = Environment(
"#third_party/acados/include/hpipm/include",
"#third_party/catch2/include",
"#third_party/libyuv/include",
"#third_party/snpe/include",
],
LIBPATH=[
"#common",
@@ -101,7 +100,6 @@ if arch == "larch64":
"/usr/local/lib",
"/system/vendor/lib64",
"/usr/lib/aarch64-linux-gnu",
"#third_party/snpe/larch64",
])
arch_flags = ["-D__TICI__", "-mcpu=cortex-a57", "-DQCOM2"]
env.Append(CCFLAGS=arch_flags)
@@ -125,14 +123,6 @@ else:
"/usr/local/lib",
])
if arch == "x86_64":
env.Append(LIBPATH=[
f"#third_party/snpe/{arch}"
])
env.Append(RPATH=[
Dir(f"#third_party/snpe/{arch}").abspath,
])
# Sanitizers and extra CCFLAGS from CLI
if GetOption('asan'):
env.Append(CCFLAGS=["-fsanitize=address", "-fno-omit-frame-pointer"])
+8 -28
View File
@@ -1,7 +1,5 @@
#!/usr/bin/env python3
import math
import threading
import time
from numbers import Number
from cereal import car, log
@@ -22,8 +20,6 @@ from openpilot.selfdrive.controls.lib.longcontrol import LongControl
from openpilot.selfdrive.modeld.modeld import LAT_SMOOTH_SECONDS
from openpilot.selfdrive.locationd.helpers import PoseCalibrator, Pose
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld.modeld_base import ModelStateBase
from openpilot.sunnypilot.selfdrive.controls.controlsd_ext import ControlsExt
State = log.SelfdriveState.OpenpilotState
@@ -33,7 +29,7 @@ LaneChangeDirection = log.LaneChangeDirection
ACTUATOR_FIELDS = tuple(car.CarControl.Actuators.schema.fields.keys())
class Controls(ControlsExt, ModelStateBase):
class Controls(ControlsExt):
def __init__(self) -> None:
self.params = Params()
cloudlog.info("controlsd is waiting for CarParams")
@@ -42,7 +38,6 @@ class Controls(ControlsExt, ModelStateBase):
# Initialize sunnypilot controlsd extension and base model state
ControlsExt.__init__(self, self.CP, self.params)
ModelStateBase.__init__(self)
self.CI = interfaces[self.CP.carFingerprint](self.CP, self.CP_SP)
@@ -231,30 +226,15 @@ class Controls(ControlsExt, ModelStateBase):
cc_send.carControl = CC
self.pm.send('carControl', cc_send)
def params_thread(self, evt):
while not evt.is_set():
self.get_params_sp()
if self.CP.lateralTuning.which() == 'torque':
self.lat_delay = get_lat_delay(self.params, self.sm["liveDelay"].lateralDelay)
time.sleep(0.1)
def run(self):
rk = Ratekeeper(100, print_delay_threshold=None)
e = threading.Event()
t = threading.Thread(target=self.params_thread, args=(e,))
try:
t.start()
while True:
self.update()
CC, lac_log = self.state_control()
self.publish(CC, lac_log)
self.run_ext(self.sm, self.pm)
rk.monitor_time()
finally:
e.set()
t.join()
while True:
self.update()
CC, lac_log = self.state_control()
self.publish(CC, lac_log)
self.get_params_sp(self.sm)
self.run_ext(self.sm, self.pm)
rk.monitor_time()
def main():
+1 -1
View File
@@ -227,6 +227,6 @@ class HomeLayout(Widget):
self._prev_alerts_present = alerts_present
def _get_version_text(self) -> str:
brand = "openpilot"
brand = "sunnypilot"
description = self.params.get("UpdaterCurrentDescription")
return f"{brand} {description}" if description else brand
+3
View File
@@ -10,6 +10,9 @@ from openpilot.selfdrive.ui.ui_state import device, ui_state
from openpilot.system.ui.widgets import Widget
from openpilot.selfdrive.ui.layouts.onboarding import OnboardingWindow
if gui_app.sunnypilot_ui():
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.settings import SettingsLayoutSP as SettingsLayout
class MainState(IntEnum):
HOME = 0
+4 -4
View File
@@ -109,8 +109,8 @@ class TermsPage(Widget):
self._on_accept = on_accept
self._on_decline = on_decline
self._title = Label(tr("Welcome to openpilot"), font_size=90, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT)
self._desc = Label(tr("You must accept the Terms and Conditions to use openpilot. Read the latest terms at https://comma.ai/terms before continuing."),
self._title = Label(tr("Welcome to sunnypilot"), font_size=90, font_weight=FontWeight.BOLD, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT)
self._desc = Label(tr("You must accept the Terms and Conditions to use sunnypilot. Read the latest terms at https://comma.ai/terms before continuing."),
font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT)
self._decline_btn = Button(tr("Decline"), click_callback=on_decline)
@@ -143,10 +143,10 @@ class TermsPage(Widget):
class DeclinePage(Widget):
def __init__(self, back_callback=None):
super().__init__()
self._text = Label(tr("You must accept the Terms and Conditions in order to use openpilot."),
self._text = Label(tr("You must accept the Terms and Conditions in order to use sunnypilot."),
font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT)
self._back_btn = Button(tr("Back"), click_callback=back_callback)
self._uninstall_btn = Button(tr("Decline, uninstall openpilot"), button_style=ButtonStyle.DANGER,
self._uninstall_btn = Button(tr("Decline, uninstall sunnypilot"), button_style=ButtonStyle.DANGER,
click_callback=self._on_uninstall_clicked)
def _on_uninstall_clicked(self):
+7 -5
View File
@@ -23,10 +23,11 @@ DESCRIPTIONS = {
"other than your own. A comma employee will NEVER ask you to add their GitHub username."
),
'alpha_longitudinal': tr_noop(
"<b>WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB).</b><br><br>" +
"On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. " +
"Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha. " +
"Changing this setting will restart openpilot if the car is powered on."
"<b>WARNING: sunnypilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB).</b><br><br>" +
"On this car, sunnypilot defaults to the car's built-in ACC instead of sunnypilot's longitudinal control. " +
"Enable this to switch to sunnypilot longitudinal control. " +
"Enabling Experimental mode is recommended when enabling sunnypilot longitudinal control alpha. " +
"Changing this setting will restart sunnypilot if the car is powered on."
),
}
@@ -71,7 +72,7 @@ class DeveloperLayout(Widget):
)
self._alpha_long_toggle = toggle_item(
lambda: tr("openpilot Longitudinal Control (Alpha)"),
lambda: tr("sunnypilot Longitudinal Control (Alpha)"),
description=lambda: tr(DESCRIPTIONS["alpha_longitudinal"]),
initial_state=self._params.get_bool("AlphaLongitudinalEnabled"),
callback=self._on_alpha_long_enabled,
@@ -148,6 +149,7 @@ class DeveloperLayout(Widget):
self._params.put_bool("ShowDebugInfo", state)
gui_app.set_show_touches(state)
gui_app.set_show_fps(state)
gui_app.set_show_mouse_coords(state)
def _on_enable_adb(self, state: bool):
self._params.put_bool("AdbEnabled", state)
+4 -4
View File
@@ -23,8 +23,8 @@ from openpilot.system.ui.widgets.scroller_tici import Scroller
DESCRIPTIONS = {
'pair_device': tr_noop("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer."),
'driver_camera': tr_noop("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)"),
'reset_calibration': tr_noop("openpilot requires the device to be mounted within 4° left or right and within 5° up or 9° down."),
'review_guide': tr_noop("Review the rules, features, and limitations of openpilot"),
'reset_calibration': tr_noop("sunnypilot requires the device to be mounted within 4° left or right and within 5° up or 9° down."),
'review_guide': tr_noop("Review the rules, features, and limitations of sunnypilot"),
}
@@ -162,8 +162,8 @@ class DeviceLayout(Widget):
cloudlog.exception("invalid LiveTorqueParameters")
desc += "<br><br>"
desc += tr("openpilot is continuously calibrating, resetting is rarely required. " +
"Resetting calibration will restart openpilot if the car is powered on.")
desc += tr("sunnypilot is continuously calibrating, resetting is rarely required. " +
"Resetting calibration will restart sunnypilot if the car is powered on.")
self._reset_calib_btn.set_description(desc)
+1 -1
View File
@@ -17,7 +17,7 @@ from openpilot.selfdrive.ui.lib.api_helpers import get_token
TITLE = tr_noop("Firehose Mode")
DESCRIPTION = tr_noop(
"openpilot learns to drive by watching humans, like you, drive.\n\n"
"sunnypilot learns to drive by watching humans, like you, drive.\n\n"
+ "Firehose Mode allows you to maximize your training data uploads to improve "
+ "openpilot's driving models. More data means bigger models, which means better Experimental Mode."
)
+14 -13
View File
@@ -11,26 +11,27 @@ from openpilot.selfdrive.ui.ui_state import ui_state
if gui_app.sunnypilot_ui():
from openpilot.system.ui.sunnypilot.widgets.list_view import toggle_item_sp as toggle_item
from openpilot.system.ui.sunnypilot.widgets.list_view import multiple_button_item_sp as multiple_button_item
PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants
# Description constants
DESCRIPTIONS = {
"OpenpilotEnabledToggle": tr_noop(
"Use the openpilot system for adaptive cruise control and lane keep driver assistance. " +
"Use the sunnypilot system for adaptive cruise control and lane keep driver assistance. " +
"Your attention is required at all times to use this feature."
),
"DisengageOnAccelerator": tr_noop("When enabled, pressing the accelerator pedal will disengage openpilot."),
"DisengageOnAccelerator": tr_noop("When enabled, pressing the accelerator pedal will disengage sunnypilot."),
"LongitudinalPersonality": tr_noop(
"Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. " +
"In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " +
"Standard is recommended. In aggressive mode, sunnypilot will follow lead cars closer and be more aggressive with the gas and brake. " +
"In relaxed mode sunnypilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " +
"your steering wheel distance button."
),
"IsLdwEnabled": tr_noop(
"Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line " +
"without a turn signal activated while driving over 31 mph (50 km/h)."
),
"AlwaysOnDM": tr_noop("Enable driver monitoring even when openpilot is not engaged."),
"AlwaysOnDM": tr_noop("Enable driver monitoring even when sunnypilot is not engaged."),
'RecordFront': tr_noop("Upload data from the driver facing camera and help improve the driver monitoring algorithm."),
"IsMetric": tr_noop("Display speed in km/h instead of mph."),
"RecordAudio": tr_noop("Record and store microphone audio while driving. The audio will be included in the dashcam video in comma connect."),
@@ -46,7 +47,7 @@ class TogglesLayout(Widget):
# param, title, desc, icon, needs_restart
self._toggle_defs = {
"OpenpilotEnabledToggle": (
lambda: tr("Enable openpilot"),
lambda: tr("Enable sunnypilot"),
DESCRIPTIONS["OpenpilotEnabledToggle"],
"chffr_wheel.png",
True,
@@ -99,7 +100,7 @@ class TogglesLayout(Widget):
lambda: tr("Driving Personality"),
lambda: tr(DESCRIPTIONS["LongitudinalPersonality"]),
buttons=[lambda: tr("Aggressive"), lambda: tr("Standard"), lambda: tr("Relaxed")],
button_width=255,
button_width=300,
callback=self._set_longitudinal_personality,
selected_index=self._params.get("LongitudinalPersonality", return_default=True),
icon="speed_limit.png"
@@ -125,7 +126,7 @@ class TogglesLayout(Widget):
# Make description callable for live translation
additional_desc = ""
if needs_restart and not locked:
additional_desc = tr("Changing this setting will restart openpilot if the car is powered on.")
additional_desc = tr("Changing this setting will restart sunnypilot if the car is powered on.")
toggle.set_description(lambda og_desc=toggle.description, add_desc=additional_desc: tr(og_desc) + (" " + tr(add_desc) if add_desc else ""))
# track for engaged state updates
@@ -158,10 +159,10 @@ class TogglesLayout(Widget):
ui_state.update_params()
e2e_description = tr(
"openpilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. " +
"sunnypilot defaults to driving in chill mode. Experimental mode enables alpha-level features that aren't ready for chill mode. " +
"Experimental features are listed below:<br>" +
"<h4>End-to-End Longitudinal Control</h4><br>" +
"Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. " +
"Let the driving model control the gas and brakes. sunnypilot will drive as it thinks a human would, including stopping for red lights and stop signs. " +
"Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " +
"mistakes should be expected.<br>" +
"<h4>New Driving Visualization</h4><br>" +
@@ -183,13 +184,13 @@ class TogglesLayout(Widget):
unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control.")
long_desc = unavailable + " " + tr("openpilot longitudinal control may come in a future update.")
long_desc = unavailable + " " + tr("sunnypilot longitudinal control may come in a future update.")
if ui_state.CP.alphaLongitudinalAvailable:
if self._is_release:
long_desc = unavailable + " " + tr("An alpha version of openpilot longitudinal control can be tested, along with " +
long_desc = unavailable + " " + tr("An alpha version of sunnypilot longitudinal control can be tested, along with " +
"Experimental mode, on non-release branches.")
else:
long_desc = tr("Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode.")
long_desc = tr("Enable the sunnypilot longitudinal control (alpha) toggle to allow Experimental mode.")
self._toggles["ExperimentalMode"].set_description("<b>" + long_desc + "</b><br><br>" + e2e_description)
else:
+2 -2
View File
@@ -45,7 +45,7 @@ class DeviceStatus(Widget):
self._version_text = self._get_version_text()
def _get_version_text(self) -> str:
brand = "openpilot"
brand = "sunnypilot"
description = ui_state.params.get("UpdaterCurrentDescription")
return f"{brand} {description}" if description else brand
@@ -111,7 +111,7 @@ class MiciHomeLayout(Widget):
self._cell_high_txt = gui_app.texture("icons_mici/settings/network/cell_strength_high.png", 55, 35)
self._cell_full_txt = gui_app.texture("icons_mici/settings/network/cell_strength_full.png", 55, 35)
self._openpilot_label = MiciLabel("openpilot", font_size=96, color=rl.Color(255, 255, 255, int(255 * 0.9)), font_weight=FontWeight.DISPLAY)
self._openpilot_label = MiciLabel("sunnypilot", font_size=96, color=rl.Color(255, 255, 255, int(255 * 0.9)), font_weight=FontWeight.DISPLAY)
self._version_label = MiciLabel("", font_size=36, font_weight=FontWeight.ROMAN)
self._large_version_label = MiciLabel("", font_size=64, color=rl.GRAY, font_weight=FontWeight.ROMAN)
self._date_label = MiciLabel("", font_size=36, color=rl.GRAY, font_weight=FontWeight.ROMAN)
+1 -1
View File
@@ -254,7 +254,7 @@ class MiciOffroadAlerts(Widget):
parts = new_desc.split(" / ")
if len(parts) > 3:
version, date = parts[0], parts[3]
update_alert_data.text = f"update available\n openpilot {version}, {date}. go to comma.ai/blog to read the release notes."
update_alert_data.text = f"update available\n sunnypilot {version}, {date}. go to comma.ai/blog to read the release notes."
update_alert_data.visible = True
active_count += 1
+4 -4
View File
@@ -182,7 +182,7 @@ class TrainingGuideAttentionNotice(SetupTermsPage):
def __init__(self, continue_callback):
super().__init__(continue_callback, continue_text="continue")
self._title_header = TermsHeader("driver assistance", gui_app.texture("icons_mici/setup/warning.png", 60, 60))
self._warning_label = UnifiedLabel("1. openpilot is a driver assistance system.\n\n" +
self._warning_label = UnifiedLabel("1. sunnypilot is a driver assistance system.\n\n" +
"2. You must pay attention at all times.\n\n" +
"3. You must be ready to take over at any time.\n\n" +
"4. You are fully responsible for driving the car.", 42,
@@ -239,12 +239,12 @@ class TrainingGuide(Widget):
class DeclinePage(Widget):
def __init__(self, back_callback=None):
super().__init__()
self._uninstall_slider = SmallSlider("uninstall openpilot", self._on_uninstall)
self._uninstall_slider = SmallSlider("uninstall sunnypilot", self._on_uninstall)
self._back_button = SmallButton("back")
self._back_button.set_click_callback(back_callback)
self._warning_header = TermsHeader("you must accept the\nterms to use openpilot",
self._warning_header = TermsHeader("you must accept the\nterms to use sunnypilot",
gui_app.texture("icons_mici/setup/red_warning.png", 66, 60))
def _on_uninstall(self):
@@ -282,7 +282,7 @@ class TermsPage(SetupTermsPage):
info_txt = gui_app.texture("icons_mici/setup/green_info.png", 60, 60)
self._title_header = TermsHeader("terms & conditions", info_txt)
self._terms_label = UnifiedLabel("You must accept the Terms and Conditions to use openpilot. " +
self._terms_label = UnifiedLabel("You must accept the Terms and Conditions to use sunnypilot. " +
"Read the latest terms at https://comma.ai/terms before continuing.", 36,
FontWeight.ROMAN)
+3 -3
View File
@@ -156,7 +156,7 @@ class UpdateOpenpilotBigButton(BigButton):
self._txt_update_icon = gui_app.texture("icons_mici/settings/device/update.png", 64, 64)
self._txt_reboot_icon = gui_app.texture("icons_mici/settings/device/reboot.png", 64, 64)
self._txt_up_to_date_icon = gui_app.texture("icons_mici/settings/device/up_to_date.png", 64, 64)
super().__init__("update openpilot", "", self._txt_update_icon)
super().__init__("update sunnypilot", "", self._txt_update_icon)
self._waiting_for_updater_t: float | None = None
self._hide_value_t: float | None = None
@@ -193,7 +193,7 @@ class UpdateOpenpilotBigButton(BigButton):
if value:
self.set_text("")
else:
self.set_text("update openpilot")
self.set_text("update sunnypilot")
def _update_state(self):
if ui_state.started:
@@ -294,7 +294,7 @@ class DeviceLayoutMici(NavWidget):
reset_calibration_btn = BigButton("reset calibration", "", "icons_mici/settings/device/lkas.png")
reset_calibration_btn.set_click_callback(lambda: _engaged_confirmation_callback(reset_calibration_callback, "reset"))
uninstall_openpilot_btn = BigButton("uninstall openpilot", "", "icons_mici/settings/device/uninstall.png")
uninstall_openpilot_btn = BigButton("uninstall sunnypilot", "", "icons_mici/settings/device/uninstall.png")
uninstall_openpilot_btn.set_click_callback(lambda: _engaged_confirmation_callback(uninstall_openpilot_callback, "uninstall"))
reboot_btn = BigCircleButton("icons_mici/settings/device/reboot.png", red=False)
@@ -17,7 +17,7 @@ from openpilot.system.ui.widgets import NavWidget
TITLE = tr_noop("Firehose Mode")
DESCRIPTION = tr_noop(
"openpilot learns to drive by watching humans, like you, drive.\n\n"
"sunnypilot learns to drive by watching humans, like you, drive.\n\n"
+ "Firehose Mode allows you to maximize your training data uploads to improve "
+ "openpilot's driving models. More data means bigger models, which means better Experimental Mode."
)
@@ -24,7 +24,7 @@ class TogglesLayoutMici(NavWidget):
always_on_dm_toggle = BigParamControl("always-on driver monitor", "AlwaysOnDM")
record_front = BigParamControl("record & upload driver camera", "RecordFront", toggle_callback=restart_needed_callback)
record_mic = BigParamControl("record & upload mic audio", "RecordAudio", toggle_callback=restart_needed_callback)
enable_openpilot = BigParamControl("enable openpilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback)
enable_openpilot = BigParamControl("enable sunnypilot", "OpenpilotEnabledToggle", toggle_callback=restart_needed_callback)
self._scroller = Scroller([
self._personality_toggle,
+1 -1
View File
@@ -65,7 +65,7 @@ class Alert:
# Pre-defined alert instances
ALERT_STARTUP_PENDING = Alert(
text1="openpilot Unavailable",
text1="sunnypilot Unavailable",
text2="Waiting to start",
size=AlertSize.mid,
status=AlertStatus.normal,
@@ -153,7 +153,7 @@ class AugmentedRoadView(CameraView):
self._alert_renderer = AlertRenderer()
self._driver_state_renderer = DriverStateRenderer()
self._confidence_ball = ConfidenceBall()
self._offroad_label = UnifiedLabel("start the car to\nuse openpilot", 54, FontWeight.DISPLAY,
self._offroad_label = UnifiedLabel("start the car to\nuse sunnypilot", 54, FontWeight.DISPLAY,
text_color=rl.Color(255, 255, 255, int(255 * 0.9)),
alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER,
alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE)
@@ -171,7 +171,7 @@ class AugmentedRoadView(CameraView):
if ui_state.panda_type == log.PandaState.PandaType.unknown:
self._offroad_label.set_text("system booting")
else:
self._offroad_label.set_text("start the car to\nuse openpilot")
self._offroad_label.set_text("start the car to\nuse sunnypilot")
def _handle_mouse_release(self, mouse_pos: MousePos):
# Don't trigger click callback if bookmark was triggered
+1 -1
View File
@@ -48,7 +48,7 @@ class Alert:
# Pre-defined alert instances
ALERT_STARTUP_PENDING = Alert(
text1=tr("openpilot Unavailable"),
text1=tr("sunnypilot Unavailable"),
text2=tr("Waiting to start"),
size=AlertSize.mid,
status=AlertStatus.normal,
-158
View File
@@ -1,158 +0,0 @@
/**
* Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
*
* This file is part of sunnypilot and is licensed under the MIT License.
* See the LICENSE.md file in the root directory for more details.
*/
#include "selfdrive/ui/qt/offroad/offroad_home.h"
#include "selfdrive/ui/qt/offroad/experimental_mode.h"
#include "selfdrive/ui/qt/util.h"
#include "selfdrive/ui/qt/widgets/prime.h"
// OffroadHome: the offroad home page
OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) {
QVBoxLayout* main_layout = new QVBoxLayout(this);
main_layout->setContentsMargins(40, 40, 40, 40);
// top header
header_layout = new QHBoxLayout();
header_layout->setContentsMargins(0, 0, 0, 0);
header_layout->setSpacing(16);
update_notif = new QPushButton(tr("UPDATE"));
update_notif->setVisible(false);
update_notif->setStyleSheet("background-color: #364DEF;");
QObject::connect(update_notif, &QPushButton::clicked, [=]() { center_layout->setCurrentIndex(1); });
header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignLeft);
alert_notif = new QPushButton();
alert_notif->setVisible(false);
alert_notif->setStyleSheet("background-color: #E22C2C;");
QObject::connect(alert_notif, &QPushButton::clicked, [=] { center_layout->setCurrentIndex(2); });
header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignLeft);
version = new ElidedLabel();
header_layout->addWidget(version, 0, Qt::AlignHCenter | Qt::AlignRight);
main_layout->addLayout(header_layout);
// main content
main_layout->addSpacing(25);
center_layout = new QStackedLayout();
QWidget *home_widget = new QWidget(this);
{
home_layout = new QHBoxLayout(home_widget);
home_layout->setContentsMargins(0, 0, 0, 0);
home_layout->setSpacing(30);
#ifndef SUNNYPILOT
// left: PrimeAdWidget
QStackedWidget *left_widget = new QStackedWidget(this);
QVBoxLayout *left_prime_layout = new QVBoxLayout();
left_prime_layout->setContentsMargins(0, 0, 0, 0);
QWidget *prime_user = new PrimeUserWidget();
prime_user->setStyleSheet(R"(
border-radius: 10px;
background-color: #333333;
)");
left_prime_layout->addWidget(prime_user);
left_prime_layout->addStretch();
left_widget->addWidget(new LayoutWidget(left_prime_layout));
left_widget->addWidget(new PrimeAdWidget);
left_widget->setStyleSheet("border-radius: 10px;");
connect(uiState()->prime_state, &PrimeState::changed, [left_widget]() {
left_widget->setCurrentIndex(uiState()->prime_state->isSubscribed() ? 0 : 1);
});
home_layout->addWidget(left_widget, 1);
#endif
// right: ExperimentalModeButton, SetupWidget
QWidget* right_widget = new QWidget(this);
QVBoxLayout* right_column = new QVBoxLayout(right_widget);
right_column->setContentsMargins(0, 0, 0, 0);
right_widget->setFixedWidth(750);
right_column->setSpacing(30);
ExperimentalModeButton *experimental_mode = new ExperimentalModeButton(this);
QObject::connect(experimental_mode, &ExperimentalModeButton::openSettings, this, &OffroadHome::openSettings);
right_column->addWidget(experimental_mode, 1);
SetupWidget *setup_widget = new SetupWidget;
QObject::connect(setup_widget, &SetupWidget::openSettings, this, &OffroadHome::openSettings);
right_column->addWidget(setup_widget, 1);
home_layout->addWidget(right_widget, 1);
}
center_layout->addWidget(home_widget);
// add update & alerts widgets
update_widget = new UpdateAlert();
QObject::connect(update_widget, &UpdateAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); });
center_layout->addWidget(update_widget);
alerts_widget = new OffroadAlert();
QObject::connect(alerts_widget, &OffroadAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); });
center_layout->addWidget(alerts_widget);
main_layout->addLayout(center_layout, 1);
// set up refresh timer
timer = new QTimer(this);
timer->callOnTimeout(this, &OffroadHome::refresh);
setStyleSheet(R"(
* {
color: white;
}
OffroadHome {
background-color: black;
}
OffroadHome > QPushButton {
padding: 15px 30px;
border-radius: 5px;
font-size: 40px;
font-weight: 500;
}
OffroadHome > QLabel {
font-size: 55px;
}
)");
}
void OffroadHome::showEvent(QShowEvent *event) {
refresh();
timer->start(10 * 1000);
}
void OffroadHome::hideEvent(QHideEvent *event) {
timer->stop();
}
void OffroadHome::refresh() {
version->setText(getBrand() + " " + QString::fromStdString(params.get("UpdaterCurrentDescription")));
bool updateAvailable = update_widget->refresh();
int alerts = alerts_widget->refresh();
// pop-up new notification
int idx = center_layout->currentIndex();
if (!updateAvailable && !alerts) {
idx = 0;
} else if (updateAvailable && (!update_notif->isVisible() || (!alerts && idx == 2))) {
idx = 1;
} else if (alerts && (!alert_notif->isVisible() || (!updateAvailable && idx == 1))) {
idx = 2;
}
center_layout->setCurrentIndex(idx);
update_notif->setVisible(updateAvailable);
alert_notif->setVisible(alerts);
if (alerts) {
alert_notif->setText(QString::number(alerts) + (alerts > 1 ? tr(" ALERTS") : tr(" ALERT")));
}
}
-59
View File
@@ -1,59 +0,0 @@
/**
* Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
*
* This file is part of sunnypilot and is licensed under the MIT License.
* See the LICENSE.md file in the root directory for more details.
*/
#pragma once
#include "common/params.h"
#include "selfdrive/ui/qt/body.h"
#include "selfdrive/ui/qt/widgets/offroad_alerts.h"
#ifdef SUNNYPILOT
#include "selfdrive/ui/sunnypilot/qt/widgets/controls.h"
#include "selfdrive/ui/sunnypilot/qt/onroad/onroad_home.h"
#include "selfdrive/ui/sunnypilot/qt/sidebar.h"
#include "selfdrive/ui/sunnypilot/qt/widgets/prime.h"
#define OnroadWindow OnroadWindowSP
#define LayoutWidget LayoutWidgetSP
#define Sidebar SidebarSP
#define ElidedLabel ElidedLabelSP
#define SetupWidget SetupWidgetSP
#else
#include "selfdrive/ui/qt/widgets/controls.h"
#include "selfdrive/ui/qt/onroad/onroad_home.h"
#include "selfdrive/ui/qt/sidebar.h"
#include "selfdrive/ui/qt/widgets/prime.h"
#endif
class OffroadHome : public QFrame {
Q_OBJECT
public:
explicit OffroadHome(QWidget* parent = 0);
signals:
void openSettings(int index = 0, const QString &param = "");
protected:
QHBoxLayout *home_layout;
QHBoxLayout *header_layout;
void showEvent(QShowEvent *event) override;
void refresh();
private:
void hideEvent(QHideEvent *event) override;
Params params;
QTimer* timer;
ElidedLabel* version;
QStackedLayout* center_layout;
UpdateAlert *update_widget;
OffroadAlert* alerts_widget;
QPushButton* alert_notif;
QPushButton* update_notif;
};
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class CruiseLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,12 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.selfdrive.ui.layouts.settings.device import DeviceLayout
class DeviceLayoutSP(DeviceLayout):
def __init__(self):
DeviceLayout.__init__(self)
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class DisplayLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class ModelsLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class NavigationLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class OSMLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,202 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from dataclasses import dataclass
from enum import IntEnum
import pyray as rl
from openpilot.selfdrive.ui.layouts.settings import settings as OP
from openpilot.selfdrive.ui.layouts.settings.developer import DeveloperLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.device import DeviceLayoutSP
from openpilot.selfdrive.ui.layouts.settings.firehose import FirehoseLayout
from openpilot.selfdrive.ui.layouts.settings.software import SoftwareLayout
from openpilot.selfdrive.ui.layouts.settings.toggles import TogglesLayout
from openpilot.system.ui.lib.application import gui_app, MousePos
from openpilot.system.ui.lib.multilang import tr_noop
from openpilot.system.ui.sunnypilot.lib.styles import style
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.widgets.network import NetworkUI
from openpilot.system.ui.lib.wifi_manager import WifiManager
from openpilot.system.ui.widgets import Widget
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.models import ModelsLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.sunnylink import SunnylinkLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.osm import OSMLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.trips import TripsLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.vehicle import VehicleLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.steering import SteeringLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.cruise import CruiseLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.visuals import VisualsLayout
from openpilot.selfdrive.ui.sunnypilot.layouts.settings.display import DisplayLayout
# from openpilot.selfdrive.ui.sunnypilot.layouts.settings.navigation import NavigationLayout
OP.PANEL_COLOR = rl.Color(10, 10, 10, 255)
ICON_SIZE = 70
OP.PanelType = IntEnum( # type: ignore
"PanelType",
[es.name for es in OP.PanelType] + [
"SUNNYLINK",
"MODELS",
"STEERING",
"CRUISE",
"VISUALS",
"DISPLAY",
"OSM",
"NAVIGATION",
"TRIPS",
"VEHICLE",
],
start=0,
)
@dataclass
class PanelInfo(OP.PanelInfo):
icon: str = ""
class NavButton(Widget):
def __init__(self, parent, p_type, p_info):
super().__init__()
self.parent = parent
self.panel_type = p_type
self.panel_info = p_info
def _render(self, rect):
is_selected = self.panel_type == self.parent._current_panel
text_color = OP.TEXT_SELECTED if is_selected else OP.TEXT_NORMAL
content_x = rect.x + 90
text_size = measure_text_cached(self.parent._font_medium, self.panel_info.name, 65)
# Draw background if selected
if is_selected:
self.container_rect = rl.Rectangle(
content_x - 50, rect.y, OP.SIDEBAR_WIDTH - 50, OP.NAV_BTN_HEIGHT
)
rl.draw_rectangle_rounded(self.container_rect, 0.2, 5, OP.CLOSE_BTN_COLOR)
if self.panel_info.icon:
icon_texture = gui_app.texture(self.panel_info.icon, ICON_SIZE, ICON_SIZE, keep_aspect_ratio=True)
rl.draw_texture(icon_texture, int(content_x), int(rect.y + (OP.NAV_BTN_HEIGHT - icon_texture.height) / 2),
rl.WHITE)
content_x += ICON_SIZE + 20
# Draw button text (right-aligned)
text_pos = rl.Vector2(
content_x,
rect.y + (OP.NAV_BTN_HEIGHT - text_size.y) / 2
)
rl.draw_text_ex(self.parent._font_medium, self.panel_info.name, text_pos, 55, 0, text_color)
# Store button rect for click detection
self.panel_info.button_rect = rect
class SettingsLayoutSP(OP.SettingsLayout):
def __init__(self):
OP.SettingsLayout.__init__(self)
self._nav_items: list[Widget] = []
# Create sidebar scroller
self._sidebar_scroller = Scroller([], spacing=0, line_separator=False, pad_end=False)
# Panel configuration
wifi_manager = WifiManager()
wifi_manager.set_active(False)
self._panels = {
OP.PanelType.DEVICE: PanelInfo(tr_noop("Device"), DeviceLayoutSP(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_home.png"),
OP.PanelType.NETWORK: PanelInfo(tr_noop("Network"), NetworkUI(wifi_manager), icon="icons/network.png"),
OP.PanelType.SUNNYLINK: PanelInfo(tr_noop("sunnylink"), SunnylinkLayout(), icon="icons/shell.png"),
OP.PanelType.TOGGLES: PanelInfo(tr_noop("Toggles"), TogglesLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_toggle.png"),
OP.PanelType.SOFTWARE: PanelInfo(tr_noop("Software"), SoftwareLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_software.png"),
OP.PanelType.MODELS: PanelInfo(tr_noop("Models"), ModelsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_models.png"),
OP.PanelType.STEERING: PanelInfo(tr_noop("Steering"), SteeringLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_lateral.png"),
OP.PanelType.CRUISE: PanelInfo(tr_noop("Cruise"), CruiseLayout(), icon="icons/speed_limit.png"),
OP.PanelType.VISUALS: PanelInfo(tr_noop("Visuals"), VisualsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_visuals.png"),
OP.PanelType.DISPLAY: PanelInfo(tr_noop("Display"), DisplayLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_display.png"),
OP.PanelType.OSM: PanelInfo(tr_noop("OSM"), OSMLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"),
# OP.PanelType.NAVIGATION: PanelInfo(tr_noop("Navigation"), NavigationLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_map.png"),
OP.PanelType.TRIPS: PanelInfo(tr_noop("Trips"), TripsLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_trips.png"),
OP.PanelType.VEHICLE: PanelInfo(tr_noop("Vehicle"), VehicleLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_vehicle.png"),
OP.PanelType.FIREHOSE: PanelInfo(tr_noop("Firehose"), FirehoseLayout(), icon="../../sunnypilot/selfdrive/assets/offroad/icon_firehose.png"),
OP.PanelType.DEVELOPER: PanelInfo(tr_noop("Developer"), DeveloperLayout(), icon="icons/shell.png"),
}
def _draw_sidebar(self, rect: rl.Rectangle):
rl.draw_rectangle_rec(rect, OP.SIDEBAR_COLOR)
# Close button
close_btn_rect = rl.Rectangle(
rect.x + style.ITEM_PADDING * 3, rect.y + style.ITEM_PADDING * 2, style.CLOSE_BTN_SIZE, style.CLOSE_BTN_SIZE
)
pressed = (rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT) and
rl.check_collision_point_rec(rl.get_mouse_position(), close_btn_rect))
close_color = OP.CLOSE_BTN_PRESSED if pressed else OP.CLOSE_BTN_COLOR
rl.draw_rectangle_rounded(close_btn_rect, 1.0, 20, close_color)
icon_color = rl.Color(255, 255, 255, 255) if not pressed else rl.Color(220, 220, 220, 255)
icon_dest = rl.Rectangle(
close_btn_rect.x + (close_btn_rect.width - self._close_icon.width) / 2,
close_btn_rect.y + (close_btn_rect.height - self._close_icon.height) / 2,
self._close_icon.width,
self._close_icon.height,
)
rl.draw_texture_pro(
self._close_icon,
rl.Rectangle(0, 0, self._close_icon.width, self._close_icon.height),
icon_dest,
rl.Vector2(0, 0),
0,
icon_color,
)
# Store close button rect for click detection
self._close_btn_rect = close_btn_rect
# Navigation buttons with scroller
if not self._nav_items:
for panel_type, panel_info in self._panels.items():
nav_button = NavButton(self, panel_type, panel_info)
nav_button.rect.width = rect.width - 100 # Full width minus padding
nav_button.rect.height = OP.NAV_BTN_HEIGHT
self._nav_items.append(nav_button)
self._sidebar_scroller.add_widget(nav_button)
# Draw navigation section with scroller
nav_rect = rl.Rectangle(
rect.x,
self._close_btn_rect.height + style.ITEM_PADDING * 4, # Starting Y position for nav items
rect.width,
rect.height - 300 # Remaining height after close button
)
if self._nav_items:
self._sidebar_scroller.render(nav_rect)
return
def _handle_mouse_release(self, mouse_pos: MousePos) -> bool:
# Check close button
if rl.check_collision_point_rec(mouse_pos, self._close_btn_rect):
if self._close_callback:
self._close_callback()
return True
# Check navigation buttons
for panel_type, panel_info in self._panels.items():
if rl.check_collision_point_rec(mouse_pos, panel_info.button_rect) and self._sidebar_scroller.scroll_panel.is_touch_valid():
self.set_current_panel(panel_type)
return True
return False
def show_event(self):
super().show_event()
self._panels[self._current_panel].instance.show_event()
self._sidebar_scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class SteeringLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class SunnylinkLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class TripsLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class VehicleLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
@@ -0,0 +1,30 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from openpilot.common.params import Params
from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets import Widget
class VisualsLayout(Widget):
def __init__(self):
super().__init__()
self._params = Params()
items = self._initialize_items()
self._scroller = Scroller(items, line_separator=True, spacing=0)
def _initialize_items(self):
items = [
]
return items
def _render(self, rect):
self._scroller.render(rect)
def show_event(self):
self._scroller.show_event()
+17 -21
View File
@@ -1,33 +1,29 @@
from openpilot.selfdrive.ui.ui_state import UIState
from cereal import messaging
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from cereal import messaging, custom
from openpilot.common.params import Params
from openpilot.sunnypilot.sunnylink.sunnylink_state import SunnylinkState
class UIStateSP(UIState):
_instance: 'UIStateSP | None' = None
def _initialize(self):
UIState._initialize(self)
class UIStateSP:
def __init__(self):
self.params = Params()
self.sunnylink_state = SunnylinkState()
op_services = self.sm.services
sp_services = [
self.sm_services_ext = [
"modelManagerSP", "selfdriveStateSP", "longitudinalPlanSP", "backupManagerSP",
"carControl", "gpsLocationExternal", "gpsLocation", "liveTorqueParameters",
"carStateSP", "liveParameters", "liveMapDataSP", "carParamsSP"
"gpsLocation", "liveTorqueParameters", "carStateSP", "liveMapDataSP", "carParamsSP"
]
self.sm = messaging.SubMaster(op_services + sp_services)
self.sunnylink_state = SunnylinkState()
def update(self) -> None:
UIState.update(self)
self.sunnylink_state.start()
def _update_status(self) -> None:
UIState._update_status(self)
def update_params(self) -> None:
UIState.update_params(self)
# Global instance
ui_state_sp = UIStateSP()
CP_SP_bytes = self.params.get("CarParamsSPPersistent")
if CP_SP_bytes is not None:
self.CP_SP = messaging.log_from_bytes(CP_SP_bytes, custom.CarParamsSP)
self.sunnylink_enabled = self.params.get_bool("SunnylinkEnabled")
+107 -37
View File
@@ -41,47 +41,47 @@ def put_update_params(params: Params):
params.put("UpdaterTargetBranch", BRANCH_NAME)
def setup_homescreen(click, pm: PubMaster):
def setup_homescreen(click, pm: PubMaster, scroll=None):
pass
def setup_homescreen_update_available(click, pm: PubMaster):
def setup_homescreen_update_available(click, pm: PubMaster, scroll=None):
params = Params()
params.put_bool("UpdateAvailable", True)
put_update_params(params)
setup_offroad_alert(click, pm)
def setup_settings(click, pm: PubMaster):
def setup_settings(click, pm: PubMaster, scroll=None):
click(100, 100)
def close_settings(click, pm: PubMaster):
click(240, 216)
def close_settings(click, pm: PubMaster, scroll=None):
click(140, 120)
def setup_settings_network(click, pm: PubMaster):
def setup_settings_network(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 450)
def setup_settings_network_advanced(click, pm: PubMaster):
setup_settings_network(click, pm)
def setup_settings_network_advanced(click, pm: PubMaster, scroll=None):
setup_settings_network(click, pm, scroll=scroll)
click(1880, 100)
def setup_settings_toggles(click, pm: PubMaster):
def setup_settings_toggles(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 600)
click(278, 620)
def setup_settings_software(click, pm: PubMaster):
def setup_settings_software(click, pm: PubMaster, scroll=None):
put_update_params(Params())
setup_settings(click, pm)
click(278, 720)
click(278, 730)
def setup_settings_software_download(click, pm: PubMaster):
def setup_settings_software_download(click, pm: PubMaster, scroll=None):
params = Params()
# setup_settings_software but with "DOWNLOAD" button to test long text
params.put("UpdaterState", "idle")
@@ -89,13 +89,13 @@ def setup_settings_software_download(click, pm: PubMaster):
setup_settings_software(click, pm)
def setup_settings_software_release_notes(click, pm: PubMaster):
setup_settings_software(click, pm)
def setup_settings_software_release_notes(click, pm: PubMaster, scroll=None):
setup_settings_software(click, pm, scroll=scroll)
click(588, 110) # expand description for current version
def setup_settings_software_branch_switcher(click, pm: PubMaster):
setup_settings_software(click, pm)
def setup_settings_software_branch_switcher(click, pm: PubMaster, scroll=None):
setup_settings_software(click, pm, scroll=scroll)
params = Params()
params.put("UpdaterAvailableBranches", f"master,nightly,release,{BRANCH_NAME}")
params.put("GitBranch", BRANCH_NAME) # should be on top
@@ -103,30 +103,32 @@ def setup_settings_software_branch_switcher(click, pm: PubMaster):
click(1984, 449)
def setup_settings_firehose(click, pm: PubMaster):
def setup_settings_firehose(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 845)
scroll(-1000, 278, 950)
click(278, 850)
def setup_settings_developer(click, pm: PubMaster):
def setup_settings_developer(click, pm: PubMaster, scroll=None):
CP = car.CarParams()
CP.alphaLongitudinalAvailable = True # show alpha long control toggle
Params().put("CarParamsPersistent", CP.to_bytes())
setup_settings(click, pm)
scroll(-1000, 278, 950)
click(278, 950)
def setup_keyboard(click, pm: PubMaster):
setup_settings_developer(click, pm)
def setup_keyboard(click, pm: PubMaster, scroll=None):
setup_settings_developer(click, pm, scroll=scroll)
click(1930, 470)
def setup_pair_device(click, pm: PubMaster):
def setup_pair_device(click, pm: PubMaster, scroll=None):
click(1950, 800)
def setup_offroad_alert(click, pm: PubMaster):
def setup_offroad_alert(click, pm: PubMaster, scroll=None):
put_update_params(Params())
set_offroad_alert("Offroad_TemperatureTooHigh", True, extra_text='99C')
set_offroad_alert("Offroad_ExcessiveActuation", True, extra_text='longitudinal')
@@ -137,22 +139,73 @@ def setup_offroad_alert(click, pm: PubMaster):
close_settings(click, pm)
def setup_confirmation_dialog(click, pm: PubMaster):
def setup_confirmation_dialog(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(1985, 791) # reset calibration
def setup_experimental_mode_description(click, pm: PubMaster):
def setup_experimental_mode_description(click, pm: PubMaster, scroll=None):
setup_settings_toggles(click, pm)
click(1200, 280) # expand description for experimental mode
def setup_openpilot_long_confirmation_dialog(click, pm: PubMaster):
setup_settings_developer(click, pm)
click(650, 960) # toggle openpilot longitudinal control
def setup_openpilot_long_confirmation_dialog(click, pm: PubMaster, scroll=None):
setup_settings_developer(click, pm, scroll=scroll)
click(650, 960) # toggle sunnypilot longitudinal control
def setup_onroad(click, pm: PubMaster):
def setup_settings_sunnylink(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 510)
def setup_settings_models(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 840)
def setup_settings_steering(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 950)
def setup_settings_cruise(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
click(278, 1017)
scroll(-140, 278, 950)
def setup_settings_visuals(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
scroll(-1000, 278, 950)
click(278, 330)
def setup_settings_display(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
scroll(-1000, 278, 950)
click(278, 420)
def setup_settings_osm(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
scroll(-1000, 278, 950)
click(278, 520)
def setup_settings_trips(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
scroll(-1000, 278, 950)
click(278, 630)
def setup_settings_vehicle(click, pm: PubMaster, scroll=None):
setup_settings(click, pm)
scroll(-1000, 278, 950)
click(278, 750)
def setup_onroad(click, pm: PubMaster, scroll=None):
ds = messaging.new_message('deviceState')
ds.deviceState.started = True
@@ -173,7 +226,7 @@ def setup_onroad(click, pm: PubMaster):
time.sleep(0.05)
def setup_onroad_sidebar(click, pm: PubMaster):
def setup_onroad_sidebar(click, pm: PubMaster, scroll=None):
setup_onroad(click, pm)
click(100, 100) # open sidebar
@@ -192,23 +245,23 @@ def setup_onroad_alert(click, pm: PubMaster, size: log.SelfdriveState.AlertSize,
time.sleep(0.05)
def setup_onroad_small_alert(click, pm: PubMaster):
def setup_onroad_small_alert(click, pm: PubMaster, scroll=None):
setup_onroad_alert(click, pm, AlertSize.small, "Small Alert", "This is a small alert", AlertStatus.normal)
def setup_onroad_medium_alert(click, pm: PubMaster):
def setup_onroad_medium_alert(click, pm: PubMaster, scroll=None):
setup_onroad_alert(click, pm, AlertSize.mid, "Medium Alert", "This is a medium alert", AlertStatus.userPrompt)
def setup_onroad_full_alert(click, pm: PubMaster):
def setup_onroad_full_alert(click, pm: PubMaster, scroll=None):
setup_onroad_alert(click, pm, AlertSize.full, "DISENGAGE IMMEDIATELY", "Driver Distracted", AlertStatus.critical)
def setup_onroad_full_alert_multiline(click, pm: PubMaster):
def setup_onroad_full_alert_multiline(click, pm: PubMaster, scroll=None):
setup_onroad_alert(click, pm, AlertSize.full, "Reverse\nGear", "", AlertStatus.normal)
def setup_onroad_full_alert_long_text(click, pm: PubMaster):
def setup_onroad_full_alert_long_text(click, pm: PubMaster, scroll=None):
setup_onroad_alert(click, pm, AlertSize.full, "TAKE CONTROL IMMEDIATELY", "Calibration Invalid: Remount Device & Recalibrate", AlertStatus.userPrompt)
@@ -243,6 +296,19 @@ CASES = {
"onroad_full_alert_long_text": setup_onroad_full_alert_long_text,
}
# sunnypilot cases
CASES.update({
"settings_sunnylink": setup_settings_sunnylink,
"settings_models": setup_settings_models,
"settings_steering": setup_settings_steering,
"settings_cruise": setup_settings_cruise,
"settings_visuals": setup_settings_visuals,
"settings_display": setup_settings_display,
"settings_osm": setup_settings_osm,
"settings_trips": setup_settings_trips,
"settings_vehicle": setup_settings_vehicle,
})
class TestUI:
def __init__(self):
@@ -276,11 +342,15 @@ class TestUI:
time.sleep(0.01)
pyautogui.mouseUp(self.ui.left + x, self.ui.top + y, *args, **kwargs)
def scroll(self, clicks, x, y, *args, **kwargs):
pyautogui.scroll(clicks, self.ui.left + x, self.ui.top + y, *args, **kwargs)
time.sleep(UI_DELAY)
@with_processes(["ui"])
def test_ui(self, name, setup_case):
self.setup()
time.sleep(UI_DELAY) # wait for UI to start
setup_case(self.click, self.pm)
setup_case(self.click, self.pm, self.scroll)
self.screenshot(name)
-2
View File
@@ -9,8 +9,6 @@ from openpilot.selfdrive.ui.layouts.main import MainLayout
from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout
from openpilot.selfdrive.ui.ui_state import ui_state
if gui_app.sunnypilot_ui():
from openpilot.selfdrive.ui.sunnypilot.ui_state import ui_state_sp as ui_state
def main():
cores = {5, }
+7 -2
View File
@@ -12,6 +12,8 @@ from openpilot.selfdrive.ui.lib.prime_state import PrimeState
from openpilot.system.ui.lib.application import gui_app
from openpilot.system.hardware import HARDWARE, PC
from openpilot.selfdrive.ui.sunnypilot.ui_state import UIStateSP
BACKLIGHT_OFFROAD = 65 if HARDWARE.get_device_type() == "mici" else 50
@@ -21,7 +23,7 @@ class UIStatus(Enum):
OVERRIDE = "override"
class UIState:
class UIState(UIStateSP):
_instance: 'UIState | None' = None
def __new__(cls):
@@ -31,6 +33,7 @@ class UIState:
return cls._instance
def _initialize(self):
UIStateSP.__init__(self)
self.params = Params()
self.sm = messaging.SubMaster(
[
@@ -55,7 +58,7 @@ class UIState:
"carControl",
"liveParameters",
"rawAudioData",
]
] + self.sm_services_ext
)
self.prime_state = PrimeState()
@@ -111,6 +114,7 @@ class UIState:
if time.monotonic() - self._param_update_time > 5.0:
self.update_params()
device.update()
UIStateSP.update(self)
def _update_state(self) -> None:
# Handle panda states updates
@@ -180,6 +184,7 @@ class UIState:
self.has_longitudinal_control = self.params.get_bool("AlphaLongitudinalEnabled")
else:
self.has_longitudinal_control = self.CP.openpilotLongitudinalControl
UIStateSP.update_params(self)
self._param_update_time = time.monotonic()
+1 -16
View File
@@ -1,5 +1,3 @@
import glob
Import('env', 'envCython', 'arch', 'cereal', 'messaging', 'common', 'visionipc', 'transformations')
lenv = env.Clone()
lenvCython = envCython.Clone()
@@ -23,12 +21,6 @@ thneed_src_qcom = thneed_src_common + ["thneed/thneed_qcom2.cc"]
thneed_src_pc = thneed_src_common + ["thneed/thneed_pc.cc"]
thneed_src = thneed_src_qcom if arch == "larch64" else thneed_src_pc
# SNPE except on Mac and ARM Linux
snpe_lib = []
if arch != "Darwin" and arch != "aarch64":
common_src += ['runners/snpemodel.cc']
snpe_lib += ['SNPE']
# OpenCL is a framework on Mac
if arch == "Darwin":
frameworks += ['OpenCL']
@@ -40,20 +32,13 @@ for pathdef, fn in {'TRANSFORM': 'transforms/transform.cl', 'LOADYUV': 'transfor
for xenv in (lenv, lenvCython):
xenv['CXXFLAGS'].append(f'-D{pathdef}_PATH=\\"{File(fn).abspath}\\"')
# Compile cython
snpe_rpath_qcom = "/data/pythonpath/third_party/snpe/larch64"
snpe_rpath_pc = f"{Dir('#').abspath}/third_party/snpe/x86_64-linux-clang"
snpe_rpath = lenvCython['RPATH'] + [snpe_rpath_qcom if arch == "larch64" else snpe_rpath_pc]
cython_libs = envCython["LIBS"] + libs
snpemodel_lib = lenv.Library('snpemodel', ['runners/snpemodel.cc'])
commonmodel_lib = lenv.Library('commonmodel', common_src)
lenvCython.Program('runners/runmodel_pyx.so', 'runners/runmodel_pyx.pyx', LIBS=cython_libs, FRAMEWORKS=frameworks)
lenvCython.Program('runners/snpemodel_pyx.so', 'runners/snpemodel_pyx.pyx', LIBS=[snpemodel_lib, snpe_lib, *cython_libs], FRAMEWORKS=frameworks, RPATH=snpe_rpath)
lenvCython.Program('models/commonmodel_pyx.so', 'models/commonmodel_pyx.pyx', LIBS=[commonmodel_lib, *cython_libs], FRAMEWORKS=frameworks)
if arch == "larch64":
thneed_lib = env.SharedLibrary('thneed', thneed_src, LIBS=[common, 'OpenCL', 'dl'])
thneedmodel_lib = env.Library('thneedmodel', ['runners/thneedmodel.cc'])
lenvCython.Program('runners/thneedmodel_pyx.so', 'runners/thneedmodel_pyx.pyx', LIBS=envCython["LIBS"]+[thneedmodel_lib, thneed_lib, common, 'dl', 'OpenCL'])
lenvCython.Program('runners/thneedmodel_pyx.so', 'runners/thneedmodel_pyx.pyx', LIBS=envCython["LIBS"]+[thneedmodel_lib, thneed_lib, common, 'dl', 'OpenCL'])
-5
View File
@@ -4,20 +4,15 @@ from openpilot.sunnypilot.modeld.runners.runmodel_pyx import RunModel, Runtime
assert Runtime
USE_THNEED = int(os.getenv('USE_THNEED', str(int(TICI))))
USE_SNPE = int(os.getenv('USE_SNPE', str(int(TICI))))
class ModelRunner(RunModel):
THNEED = 'THNEED'
SNPE = 'SNPE'
ONNX = 'ONNX'
def __new__(cls, paths, *args, **kwargs):
if ModelRunner.THNEED in paths and USE_THNEED:
from openpilot.sunnypilot.modeld.runners.thneedmodel_pyx import ThneedModel as Runner
runner_type = ModelRunner.THNEED
elif ModelRunner.SNPE in paths and USE_SNPE:
from openpilot.sunnypilot.modeld.runners.snpemodel_pyx import SNPEModel as Runner
runner_type = ModelRunner.SNPE
elif ModelRunner.ONNX in paths:
from openpilot.sunnypilot.modeld.runners.onnxmodel import ONNXModel as Runner
runner_type = ModelRunner.ONNX
-1
View File
@@ -1,4 +1,3 @@
#pragma once
#include "sunnypilot/modeld/runners/runmodel.h"
#include "sunnypilot/modeld/runners/snpemodel.h"
-116
View File
@@ -1,116 +0,0 @@
#pragma clang diagnostic ignored "-Wexceptions"
#include "sunnypilot/modeld/runners/snpemodel.h"
#include <cstring>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "common/util.h"
#include "common/timing.h"
void PrintErrorStringAndExit() {
std::cerr << zdl::DlSystem::getLastErrorString() << std::endl;
std::exit(EXIT_FAILURE);
}
SNPEModel::SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool _use_tf8, cl_context context) {
output = _output;
output_size = _output_size;
use_tf8 = _use_tf8;
#ifdef QCOM2
if (runtime == USE_GPU_RUNTIME) {
snpe_runtime = zdl::DlSystem::Runtime_t::GPU;
} else if (runtime == USE_DSP_RUNTIME) {
snpe_runtime = zdl::DlSystem::Runtime_t::DSP;
} else {
snpe_runtime = zdl::DlSystem::Runtime_t::CPU;
}
assert(zdl::SNPE::SNPEFactory::isRuntimeAvailable(snpe_runtime));
#endif
model_data = util::read_file(path);
assert(model_data.size() > 0);
// load model
std::unique_ptr<zdl::DlContainer::IDlContainer> container = zdl::DlContainer::IDlContainer::open((uint8_t*)model_data.data(), model_data.size());
if (!container) { PrintErrorStringAndExit(); }
LOGW("loaded model with size: %lu", model_data.size());
// create model runner
zdl::SNPE::SNPEBuilder snpe_builder(container.get());
while (!snpe) {
#ifdef QCOM2
snpe = snpe_builder.setOutputLayers({})
.setRuntimeProcessor(snpe_runtime)
.setUseUserSuppliedBuffers(true)
.setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE)
.build();
#else
snpe = snpe_builder.setOutputLayers({})
.setUseUserSuppliedBuffers(true)
.setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE)
.build();
#endif
if (!snpe) std::cerr << zdl::DlSystem::getLastErrorString() << std::endl;
}
// create output buffer
zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float;
zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory();
const auto &output_tensor_names_opt = snpe->getOutputTensorNames();
if (!output_tensor_names_opt) throw std::runtime_error("Error obtaining output tensor names");
const auto &output_tensor_names = *output_tensor_names_opt;
assert(output_tensor_names.size() == 1);
const char *output_tensor_name = output_tensor_names.at(0);
const zdl::DlSystem::TensorShape &buffer_shape = snpe->getInputOutputBufferAttributes(output_tensor_name)->getDims();
if (output_size != 0) {
assert(output_size == buffer_shape[1]);
} else {
output_size = buffer_shape[1];
}
std::vector<size_t> output_strides = {output_size * sizeof(float), sizeof(float)};
output_buffer = ub_factory.createUserBuffer(output, output_size * sizeof(float), output_strides, &ub_encoding_float);
output_map.add(output_tensor_name, output_buffer.get());
}
void SNPEModel::addInput(const std::string name, float *buffer, int size) {
const int idx = inputs.size();
const auto &input_tensor_names_opt = snpe->getInputTensorNames();
if (!input_tensor_names_opt) throw std::runtime_error("Error obtaining input tensor names");
const auto &input_tensor_names = *input_tensor_names_opt;
const char *input_tensor_name = input_tensor_names.at(idx);
const bool input_tf8 = use_tf8 && strcmp(input_tensor_name, "input_img") == 0; // TODO: This is a terrible hack, get rid of this name check both here and in onnx_runner.py
LOGW("adding index %d: %s", idx, input_tensor_name);
zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float;
zdl::DlSystem::UserBufferEncodingTf8 ub_encoding_tf8(0, 1./255); // network takes 0-1
zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory();
zdl::DlSystem::UserBufferEncoding *input_encoding = input_tf8 ? (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_tf8 : (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_float;
const auto &buffer_shape_opt = snpe->getInputDimensions(input_tensor_name);
const zdl::DlSystem::TensorShape &buffer_shape = *buffer_shape_opt;
size_t size_of_input = input_tf8 ? sizeof(uint8_t) : sizeof(float);
std::vector<size_t> strides(buffer_shape.rank());
strides[strides.size() - 1] = size_of_input;
size_t product = 1;
for (size_t i = 0; i < buffer_shape.rank(); i++) product *= buffer_shape[i];
size_t stride = strides[strides.size() - 1];
for (size_t i = buffer_shape.rank() - 1; i > 0; i--) {
stride *= buffer_shape[i];
strides[i-1] = stride;
}
auto input_buffer = ub_factory.createUserBuffer(buffer, product*size_of_input, strides, input_encoding);
input_map.add(input_tensor_name, input_buffer.get());
inputs.push_back(std::unique_ptr<SNPEModelInput>(new SNPEModelInput(name, buffer, size, std::move(input_buffer))));
}
void SNPEModel::execute() {
if (!snpe->execute(input_map, output_map)) {
PrintErrorStringAndExit();
}
}
-52
View File
@@ -1,52 +0,0 @@
#pragma once
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#include <memory>
#include <string>
#include <utility>
#include <DlContainer/IDlContainer.hpp>
#include <DlSystem/DlError.hpp>
#include <DlSystem/ITensor.hpp>
#include <DlSystem/ITensorFactory.hpp>
#include <DlSystem/IUserBuffer.hpp>
#include <DlSystem/IUserBufferFactory.hpp>
#include <SNPE/SNPE.hpp>
#include <SNPE/SNPEBuilder.hpp>
#include <SNPE/SNPEFactory.hpp>
#include "sunnypilot/modeld/runners/runmodel.h"
struct SNPEModelInput : public ModelInput {
std::unique_ptr<zdl::DlSystem::IUserBuffer> snpe_buffer;
SNPEModelInput(const std::string _name, float *_buffer, int _size, std::unique_ptr<zdl::DlSystem::IUserBuffer> _snpe_buffer) : ModelInput(_name, _buffer, _size), snpe_buffer(std::move(_snpe_buffer)) {}
void setBuffer(float *_buffer, int _size) {
ModelInput::setBuffer(_buffer, _size);
assert(snpe_buffer->setBufferAddress(_buffer) == true);
}
};
class SNPEModel : public RunModel {
public:
SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL);
void addInput(const std::string name, float *buffer, int size);
void execute();
private:
std::string model_data;
#ifdef QCOM2
zdl::DlSystem::Runtime_t snpe_runtime;
#endif
// snpe model stuff
std::unique_ptr<zdl::SNPE::SNPE> snpe;
zdl::DlSystem::UserBufferMap input_map;
zdl::DlSystem::UserBufferMap output_map;
std::unique_ptr<zdl::DlSystem::IUserBuffer> output_buffer;
bool use_tf8;
float *output;
size_t output_size;
};
-9
View File
@@ -1,9 +0,0 @@
# distutils: language = c++
from libcpp.string cimport string
from msgq.visionipc.visionipc cimport cl_context
cdef extern from "sunnypilot/modeld/runners/snpemodel.h":
cdef cppclass SNPEModel:
SNPEModel(string, float*, size_t, int, bool, cl_context)
@@ -1,17 +0,0 @@
# distutils: language = c++
# cython: c_string_encoding=ascii, language_level=3
import os
from libcpp cimport bool
from libcpp.string cimport string
from .snpemodel cimport SNPEModel as cppSNPEModel
from openpilot.sunnypilot.modeld.models.commonmodel_pyx cimport CLContext
from openpilot.sunnypilot.modeld.runners.runmodel_pyx cimport RunModel
from openpilot.sunnypilot.modeld.runners.runmodel cimport RunModel as cppRunModel
os.environ['ADSP_LIBRARY_PATH'] = "/data/pythonpath/third_party/snpe/dsp/"
cdef class SNPEModel(RunModel):
def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context):
self.model = <cppRunModel *> new cppSNPEModel(path, &output[0], len(output), runtime, use_tf8, context.context)
+1 -1
View File
@@ -116,7 +116,7 @@ class ModelCache:
class ModelFetcher:
"""Handles fetching and caching of model data from remote source"""
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-docs/refs/heads/gh-pages/docs/driving_models_v9.json"
MODEL_URL = "https://raw.githubusercontent.com/sunnypilot/sunnypilot-docs/refs/heads/gh-pages/docs/driving_models_v10.json"
def __init__(self, params: Params):
self.params = params
+2 -2
View File
@@ -19,8 +19,8 @@ from openpilot.system.hardware.hw import Paths
from pathlib import Path
# see the README.md for more details on the model selector versioning
CURRENT_SELECTOR_VERSION = 11
REQUIRED_MIN_SELECTOR_VERSION = 11
CURRENT_SELECTOR_VERSION = 12
REQUIRED_MIN_SELECTOR_VERSION = 12
USE_ONNX = os.getenv('USE_ONNX', PC)
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:a258a022f0ab90368327d899ed4fb85b47dd0e35c93508e35851d9c3184528c0
size 36382
@@ -0,0 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:8623dbc5c7dd043a91d98777cb423cfd116014ed6390af6d7d00c1f8dea3c6e8
size 1181
+16 -4
View File
@@ -4,21 +4,27 @@ Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import time
import cereal.messaging as messaging
from cereal import log, custom
from opendbc.car import structs
from openpilot.common.params import Params
from openpilot.common.swaglog import cloudlog
from openpilot.sunnypilot import PARAMS_UPDATE_PERIOD
from openpilot.sunnypilot.livedelay.helpers import get_lat_delay
from openpilot.sunnypilot.modeld.modeld_base import ModelStateBase
from openpilot.sunnypilot.selfdrive.controls.lib.blinker_pause_lateral import BlinkerPauseLateral
class ControlsExt:
class ControlsExt(ModelStateBase):
def __init__(self, CP: structs.CarParams, params: Params):
ModelStateBase.__init__(self)
self.CP = CP
self.params = params
self._param_update_time: float = 0.0
self.blinker_pause_lateral = BlinkerPauseLateral()
self.get_params_sp()
cloudlog.info("controlsd_ext is waiting for CarParamsSP")
self.CP_SP = messaging.log_from_bytes(params.get("CarParamsSP", block=True), custom.CarParamsSP)
@@ -27,8 +33,14 @@ class ControlsExt:
self.sm_services_ext = ['radarState', 'selfdriveStateSP']
self.pm_services_ext = ['carControlSP']
def get_params_sp(self) -> None:
self.blinker_pause_lateral.get_params()
def get_params_sp(self, sm: messaging.SubMaster) -> None:
if time.monotonic() - self._param_update_time > PARAMS_UPDATE_PERIOD:
self.blinker_pause_lateral.get_params()
if self.CP.lateralTuning.which() == 'torque':
self.lat_delay = get_lat_delay(self.params, sm["liveDelay"].lateralDelay)
self._param_update_time = time.monotonic()
def get_lat_active(self, sm: messaging.SubMaster) -> bool:
if self.blinker_pause_lateral.update(sm['carState']):
+3 -8
View File
@@ -3,7 +3,6 @@ import os
import random
import time
from datetime import datetime, timedelta
from pathlib import Path
import jwt
from openpilot.common.api.base import BaseApi
@@ -81,23 +80,19 @@ class SunnylinkApi(BaseApi):
if sunnylink_dongle_id not in (None, UNREGISTERED_SUNNYLINK_DONGLE_ID):
return sunnylink_dongle_id
privkey_path = Path(f"{Paths.persist_root()}/comma/id_rsa")
pubkey_path = Path(f"{Paths.persist_root()}/comma/id_rsa.pub")
jwt_algo, private_key, public_key = BaseApi.get_key_pair()
start_time = time.monotonic()
successful_registration = False
if not pubkey_path.is_file():
if not public_key:
sunnylink_dongle_id = UNREGISTERED_SUNNYLINK_DONGLE_ID
self._status_update("Public key not found, setting dongle ID to unregistered.")
else:
Params().put("LastSunnylinkPingTime", 0) # Reset the last ping time to 0 if we are trying to register
with pubkey_path.open() as f1, privkey_path.open() as f2:
public_key = f1.read()
private_key = f2.read()
backoff = 1
while True:
register_token = jwt.encode({'register': True, 'exp': datetime.utcnow() + timedelta(hours=1)}, private_key, algorithm='RS256')
register_token = jwt.encode({'register': True, 'exp': datetime.utcnow() + timedelta(hours=1)}, private_key, algorithm=jwt_algo)
try:
if verbose or time.monotonic() - start_time < timeout / 2:
self._status_update("Registering device to sunnylink...")
+25 -7
View File
@@ -1,5 +1,10 @@
#!/usr/bin/env python3
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from __future__ import annotations
import base64
@@ -32,9 +37,11 @@ LOCAL_PORT_WHITELIST = {8022}
SUNNYLINK_LOG_ATTR_NAME = "user.sunny.upload"
SUNNYLINK_RECONNECT_TIMEOUT_S = 70 # FYI changing this will also would require a change on sidebar.cc
DISALLOW_LOG_UPLOAD = threading.Event()
METADATA_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "params_metadata.json")
params = Params()
def handle_long_poll(ws: WebSocket, exit_event: threading.Event | None) -> None:
cloudlog.info("sunnylinkd.handle_long_poll started")
sm = messaging.SubMaster(['deviceState'])
@@ -180,16 +187,30 @@ def getParamsAllKeys() -> list[str]:
@dispatcher.add_method
def getParamsAllKeysV1() -> dict[str, str]:
try:
with open(METADATA_PATH) as f:
metadata = json.load(f)
except Exception:
cloudlog.exception("sunnylinkd.getParamsAllKeysV1.exception")
metadata = {}
available_keys: list[str] = [k.decode('utf-8') for k in Params().all_keys()]
params_dict: dict[str, list[dict[str, str | bool | int | None]]] = {"params": []}
params_dict: dict[str, list[dict[str, str | bool | int | object | dict | None]]] = {"params": []}
for key in available_keys:
value = get_param_as_byte(key, get_default=True)
params_dict["params"].append({
param_entry = {
"key": key,
"type": int(params.get_type(key).value),
"default_value": base64.b64encode(value).decode('utf-8') if value else None,
})
}
if key in metadata:
meta_copy = metadata[key].copy()
param_entry["_extra"] = meta_copy
params_dict["params"].append(param_entry)
return {"keys": json.dumps(params_dict.get("params", []))}
@@ -238,10 +259,7 @@ def startLocalProxy(global_end_event: threading.Event, remote_ws_uri: str, local
cloudlog.debug("athena.startLocalProxy.starting")
ws = create_connection(
remote_ws_uri,
header={"Authorization": f"Bearer {sunnylink_api.get_token()}"},
enable_multithread=True,
sslopt={"cert_reqs": ssl.CERT_NONE}
remote_ws_uri, header={"Authorization": f"Bearer {sunnylink_api.get_token()}"}, enable_multithread=True, sslopt={"cert_reqs": ssl.CERT_NONE}
)
return start_local_proxy_shim(global_end_event, local_port, ws)
File diff suppressed because it is too large Load Diff
+7 -3
View File
@@ -14,6 +14,7 @@ class RoleType(IntEnum):
SPONSOR = 1
ADMIN = 2
class SponsorTier(IntEnum):
FREE = 0
NOVICE = 1
@@ -22,6 +23,7 @@ class SponsorTier(IntEnum):
BENEFACTOR = 4
GUARDIAN = 5
class User:
device_id: str
user_id: str
@@ -36,6 +38,7 @@ class User:
self.updated_at = json_data.get("updated_at")
self.token_hash = json_data.get("token_hash")
class Role:
role_type: str
role_tier: str
@@ -44,6 +47,7 @@ class Role:
self.role_type = json_data.get("role_type")
self.role_tier = json_data.get("role_tier")
def _parse_roles(roles: str) -> list[Role]:
lst_roles = []
try:
@@ -102,7 +106,7 @@ class SunnylinkState:
users_cache = self._params.get("SunnylinkCache_Users")
if roles_cache is not None:
self._roles = _parse_roles(roles_cache)
self.sponsor_tier = self._get_highest_tier()
self.sponsor_tier = self._get_highest_tier()
if users_cache is not None:
self._users = _parse_users(users_cache)
@@ -178,8 +182,8 @@ class SunnylinkState:
def is_sponsor(self) -> bool:
with self._lock:
is_sponsor = any(role.role_type.upper() == RoleType.SPONSOR.name and role.role_tier.upper() != SponsorTier.FREE.name
for role in self._roles)
is_sponsor = any(role.role_type.upper() == RoleType.SPONSOR.name and role.role_tier.upper() != SponsorTier.FREE.name
for role in self._roles)
return is_sponsor
def is_paired(self) -> bool:
@@ -0,0 +1,86 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import json
from openpilot.sunnypilot.sunnylink.athena.sunnylinkd import getParamsAllKeysV1, METADATA_PATH
def test_get_params_all_keys_v1():
"""
Test the getParamsAllKeysV1 API endpoint.
Why:
This endpoint is used by the UI (and potentially external tools) to fetch the list of
available parameters along with their metadata (titles, descriptions, options, constraints).
We need to ensure it returns the correct structure and that the metadata from
params_metadata.json is correctly merged into the response.
Expected:
- The response should contain a "keys" field which is a JSON string of a list of parameters.
- Each parameter object should have "key", "type", "default_value", and optionally "_extra".
- The "_extra" field should contain the rich metadata (title, options, min/max, etc.) matching
the source of truth (params_metadata.json).
"""
response = getParamsAllKeysV1()
assert "keys" in response
keys_json = response["keys"]
params_list = json.loads(keys_json)
assert isinstance(params_list, list)
assert len(params_list) > 0
# Check structure of first item
first_param = params_list[0]
assert "key" in first_param
assert "type" in first_param
assert "default_value" in first_param
if "_extra" in first_param:
assert isinstance(first_param["_extra"], dict)
assert "default" not in first_param["_extra"]
assert "type" not in first_param["_extra"]
# Load the source of truth
with open(METADATA_PATH) as f:
metadata = json.load(f)
# Verify that the API response matches the metadata file for a few sample keys
# This ensures the plumbing is working without being brittle to content changes
# 1. Check a key that should have metadata
keys_with_metadata = [k for k in params_list if k["key"] in metadata]
assert len(keys_with_metadata) > 0, "No parameters found that match metadata keys"
for param in keys_with_metadata[:5]: # Check first 5 matches
key = param["key"]
expected_meta = metadata[key]
assert "_extra" in param, f"Parameter {key} should have _extra field"
actual_meta = param["_extra"]
# Verify all fields in JSON are present in the API response
for meta_key, meta_val in expected_meta.items():
assert meta_key in actual_meta, f"Missing {meta_key} in API response for {key}"
assert actual_meta[meta_key] == meta_val, f"Mismatch for {key}.{meta_key}: expected {meta_val}, got {actual_meta[meta_key]}"
# 2. Check that we are correctly serving options if they exist
params_with_options = [k for k in keys_with_metadata if "options" in k.get("_extra", {})]
if params_with_options:
param = params_with_options[0]
key = param["key"]
assert isinstance(param["_extra"]["options"], list), f"Options for {key} should be a list"
assert param["_extra"]["options"] == metadata[key]["options"]
# 3. Check that we are correctly serving numeric constraints if they exist
params_with_constraints = [k for k in keys_with_metadata if "min" in k.get("_extra", {})]
if params_with_constraints:
param = params_with_constraints[0]
key = param["key"]
assert param["_extra"]["min"] == metadata[key]["min"]
assert param["_extra"]["max"] == metadata[key]["max"]
assert param["_extra"]["step"] == metadata[key]["step"]
@@ -0,0 +1,202 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import json
import os
import pytest
from openpilot.common.params import Params
from openpilot.sunnypilot.sunnylink.athena.sunnylinkd import METADATA_PATH
def test_metadata_json_exists():
"""
Test that the params_metadata.json file exists at the expected path.
Why:
The metadata file is the source of truth for parameter descriptions, options, and constraints.
If it's missing, the UI will not be able to display rich information for parameters.
Expected:
The file should exist at sunnypilot/sunnylink/params_metadata.json.
"""
assert os.path.exists(METADATA_PATH), f"Metadata file not found at {METADATA_PATH}"
def test_metadata_json_valid():
"""
Test that the params_metadata.json file contains valid JSON.
Why:
Invalid JSON will cause the metadata loading to fail, potentially crashing the UI or
resulting in missing metadata.
Expected:
The file content should be parseable as a JSON object (dictionary).
"""
with open(METADATA_PATH) as f:
try:
data = json.load(f)
except json.JSONDecodeError:
pytest.fail("Metadata file is not valid JSON")
assert isinstance(data, dict), "Metadata root must be a dictionary"
def test_all_params_have_metadata():
"""
Test that every parameter in the codebase has a corresponding entry in params_metadata.json.
Why:
We want to ensure 100% coverage of parameter metadata. Any parameter added to the codebase
should also be documented in the metadata file.
Expected:
There should be no parameters in Params() that are missing from the metadata file.
If this fails, run 'python3 sunnypilot/sunnylink/tools/update_params_metadata.py'.
"""
params = Params()
all_keys = [k.decode('utf-8') for k in params.all_keys()]
with open(METADATA_PATH) as f:
metadata = json.load(f)
missing_keys = [key for key in all_keys if key not in metadata]
if missing_keys:
pytest.fail(
f"The following parameters are missing from metadata: {missing_keys}. "
+ "Please run 'python3 sunnypilot/sunnylink/tools/update_params_metadata.py' to update."
)
def test_metadata_keys_exist_in_params():
"""
Test that all keys in params_metadata.json actually exist in the codebase.
Why:
We want to avoid stale metadata for parameters that have been removed or renamed.
This keeps the metadata file clean and relevant.
Expected:
There should be no keys in the metadata file that are not present in Params().
This prints a warning rather than failing, as it's less critical than missing metadata.
"""
params = Params()
all_keys = {k.decode('utf-8') for k in params.all_keys()}
with open(METADATA_PATH) as f:
metadata = json.load(f)
extra_keys = [key for key in metadata.keys() if key not in all_keys]
if extra_keys:
print(f"Warning: The following keys in metadata do not exist in Params: {extra_keys}")
def test_no_default_titles():
"""
Test that no parameter has a title that is identical to its key.
Why:
The default behavior of the update script is to set the title equal to the key.
We want to force developers to provide human-readable, descriptive titles for all parameters.
Expected:
No parameter metadata should have 'title' == 'key'.
"""
with open(METADATA_PATH) as f:
metadata = json.load(f)
default_title_keys = [key for key, meta in metadata.items() if meta.get("title") == key]
if default_title_keys:
pytest.fail(
f"The following parameters have default titles (title == key): {default_title_keys}. "
+ "Please update 'params_metadata.json' with descriptive titles."
)
def test_options_structure():
"""
Test that the 'options' field in metadata follows the correct structure.
Why:
The UI expects 'options' to be a list of objects with 'value' and 'label' keys.
Incorrect structure will break the UI rendering for dropdowns/toggles.
Expected:
If 'options' is present, it must be a list of dicts, and each dict must have 'value' and 'label'.
"""
with open(METADATA_PATH) as f:
metadata = json.load(f)
for key, meta in metadata.items():
if "options" in meta:
options = meta["options"]
assert isinstance(options, list), f"Options for {key} must be a list"
for option in options:
assert isinstance(option, dict), f"Option in {key} must be a dictionary"
assert "value" in option, f"Option in {key} must have a 'value' key"
assert "label" in option, f"Option in {key} must have a 'label' key"
def test_numeric_constraints():
"""
Test that numeric parameters have valid 'min', 'max', and 'step' constraints.
Why:
The UI uses these constraints to validate user input and render sliders/steppers.
Missing or invalid constraints can lead to UI bugs or invalid parameter values.
Expected:
If any of min/max/step is present, ALL of them must be present.
They must be numbers (int/float), and min must be less than max.
"""
with open(METADATA_PATH) as f:
metadata = json.load(f)
for key, meta in metadata.items():
if "min" in meta or "max" in meta or "step" in meta:
assert "min" in meta, f"Numeric param {key} must have 'min'"
assert "max" in meta, f"Numeric param {key} must have 'max'"
assert "step" in meta, f"Numeric param {key} must have 'step'"
assert isinstance(meta["min"], (int, float)), f"Min for {key} must be number"
assert isinstance(meta["max"], (int, float)), f"Max for {key} must be number"
assert isinstance(meta["step"], (int, float)), f"Step for {key} must be number"
assert meta["min"] < meta["max"], f"Min must be less than max for {key}"
def test_known_params_metadata():
"""
Test specific known parameters to ensure they have the expected rich metadata.
Why:
This acts as a spot check to ensure that our rich metadata population logic is working correctly
and that critical parameters (like LongitudinalPersonality) have their options and constraints preserved.
Expected:
'LongitudinalPersonality' should have 3 options (Aggressive, Standard, Relaxed).
'CustomAccLongPressIncrement' should have min=1, max=10, step=1.
"""
with open(METADATA_PATH) as f:
metadata = json.load(f)
# Check an enum-like param
lp = metadata.get("LongitudinalPersonality")
assert lp is not None
assert "options" in lp
assert len(lp["options"]) == 3
assert lp["options"][0]["label"] == "Aggressive"
assert lp["options"][0]["value"] == 0
# Check a numeric param
acc_long = metadata.get("CustomAccLongPressIncrement")
assert acc_long is not None
assert acc_long["min"] == 1
assert acc_long["max"] == 10
assert acc_long["step"] == 1
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import json
import os
from openpilot.common.params import Params
METADATA_PATH = os.path.join(os.path.dirname(__file__), "../params_metadata.json")
def main():
params = Params()
all_keys = params.all_keys()
if os.path.exists(METADATA_PATH):
with open(METADATA_PATH) as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {}
else:
data = {}
# Add new keys
for key in all_keys:
key_str = key.decode("utf-8")
if key_str not in data:
print(f"Adding new key: {key_str}")
data[key_str] = {
"title": key_str,
"description": "",
}
# Remove deleted keys
# keys_to_remove = [k for k in data.keys() if k.encode("utf-8") not in all_keys]
# for k in keys_to_remove:
# print(f"Removing deleted key: {k}")
# del data[k]
# Sort keys
sorted_data = dict(sorted(data.items()))
with open(METADATA_PATH, "w") as f:
json.dump(sorted_data, f, indent=2)
f.write("\n")
print(f"Updated {METADATA_PATH}")
if __name__ == "__main__":
main()
+5
View File
@@ -227,6 +227,8 @@ class GuiApplication(GuiApplicationExt):
self._render_profiler = None
self._render_profile_start_time = None
GuiApplicationExt.__init__(self)
@property
def frame(self):
return self._frame
@@ -467,6 +469,9 @@ class GuiApplication(GuiApplicationExt):
if self._show_touches:
self._draw_touch_points()
if self._show_mouse_coords:
self._draw_mouse_coordinates(gui_app.font(FontWeight.SEMI_BOLD))
if self._grid_size > 0:
self._draw_grid()
+6 -2
View File
@@ -41,8 +41,12 @@ class GuiScrollPanel:
if DEBUG:
rl.draw_rectangle_lines(0, 0, abs(int(self._velocity_filter_y.x)), 10, rl.RED)
# Handle mouse wheel
self._offset_filter_y.x += rl.get_mouse_wheel_move() * MOUSE_WHEEL_SCROLL_SPEED
# Handle mouse wheel only when the mouse cursor is over this panel
mouse_wheel = rl.get_mouse_wheel_move()
if mouse_wheel != 0:
mouse_pos = rl.get_mouse_position()
if rl.check_collision_point_rec(mouse_pos, bounds):
self._offset_filter_y.x += mouse_wheel * MOUSE_WHEEL_SCROLL_SPEED
max_scroll_distance = max(0, content.height - bounds.height)
if self._scroll_state == ScrollState.IDLE:
+1 -1
View File
@@ -383,7 +383,7 @@ class WifiManager:
'connection': {
'type': ('s', '802-11-wireless'),
'uuid': ('s', str(uuid.uuid4())),
'id': ('s', f'openpilot connection {ssid}'),
'id': ('s', f'sunnypilot connection {ssid}'),
'autoconnect-retries': ('i', 0),
},
'802-11-wireless': {
+1 -1
View File
@@ -701,7 +701,7 @@ class Setup(Widget):
except urllib.error.HTTPError as e:
if e.code == 409:
error_msg = "Incompatible openpilot version"
error_msg = "Incompatible sunnypilot version"
self.download_failed(self.download_url, error_msg)
except Exception:
error_msg = "Invalid URL"
+25
View File
@@ -6,10 +6,35 @@ See the LICENSE.md file in the root directory for more details.
"""
import os
import pyray as rl
SHOW_MOUSE_COORDS = os.getenv("SHOW_MOUSE_COORDS") == "1"
SUNNYPILOT_UI = os.getenv("SUNNYPILOT_UI", "1") == "1"
class GuiApplicationExt:
def __init__(self):
self._show_mouse_coords = SHOW_MOUSE_COORDS
@staticmethod
def sunnypilot_ui() -> bool:
return SUNNYPILOT_UI
def _draw_mouse_coordinates(self, font):
coords_text = f"X:{int(rl.get_mouse_x())}, Y:{int(rl.get_mouse_y())}"
green_color = rl.Color(0, 159, 47, 255) # Match the green color of FPS counter
# Calculate text width to position it at the right edge; estimate width based on text length
# Each character is approximately 10-12 pixels wide at font size 20
estimated_text_width = len(coords_text) * 11
# Position text at the top right corner, 10px from the top
screen_width = self._scaled_width if self._scale != 1.0 else self._width
text_pos = rl.Vector2(screen_width - estimated_text_width - 10, 6)
# Draw the text
rl.draw_text_ex(font, coords_text, text_pos, 20, 0, green_color)
def set_show_mouse_coords(self, show: bool):
self._show_mouse_coords = show
+20 -1
View File
@@ -17,19 +17,24 @@ class Base:
ITEM_TEXT_FONT_SIZE = 50
ITEM_DESC_FONT_SIZE = 40
ITEM_DESC_V_OFFSET = 150
CLOSE_BTN_SIZE = 160
# Toggle Control
TOGGLE_HEIGHT = 120
TOGGLE_WIDTH = int(TOGGLE_HEIGHT * 1.75)
TOGGLE_BG_HEIGHT = TOGGLE_HEIGHT - 20
# Button Control
BUTTON_WIDTH = 300
BUTTON_HEIGHT = 120
@dataclass
class DefaultStyleSP(Base):
# Base Colors
BASE_BG_COLOR = rl.Color(57, 57, 57, 255) # Grey
ON_BG_COLOR = rl.Color(28, 101, 186, 255) # Blue
OFF_BG_COLOR = rl.Color(70, 70, 70, 255) # Lighter Grey
OFF_BG_COLOR = BASE_BG_COLOR
ON_HOVER_BG_COLOR = rl.Color(17, 78, 150, 255) # Dark Blue
OFF_HOVER_BG_COLOR = rl.Color(21, 21, 21, 255) # Dark gray
DISABLED_ON_BG_COLOR = rl.Color(37, 70, 107, 255) # Dull Blue
@@ -46,5 +51,19 @@ class DefaultStyleSP(Base):
TOGGLE_DISABLED_OFF_COLOR = DISABLED_OFF_BG_COLOR
TOGGLE_DISABLED_KNOB_COLOR = rl.Color(88, 88, 88, 255) # Lighter Grey
# Multi Button Control
MBC_TRANSPARENT = rl.Color(255, 255, 255, 0)
MBC_BG_CHECKED_ENABLED = rl.Color(0x69, 0x68, 0x68, 0xFF)
MBC_DISABLED = rl.Color(0xFF, 0xFF, 0xFF, 0x33)
# Option Control
OPTION_CONTROL_CONTAINER_BG = OFF_BG_COLOR
OPTION_CONTROL_BTN_ENABLED = rl.Color(88, 88, 88, 255)
OPTION_CONTROL_BTN_PRESSED = rl.Color(0x69, 0x68, 0x68, 0xFF)
OPTION_CONTROL_BTN_DISABLED = DISABLED_OFF_BG_COLOR
OPTION_CONTROL_TEXT_ENABLED = rl.WHITE
OPTION_CONTROL_TEXT_PRESSED = rl.WHITE
OPTION_CONTROL_TEXT_DISABLED = ITEM_DISABLED_TEXT_COLOR
style = DefaultStyleSP
@@ -0,0 +1,40 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import re
import unicodedata
def normalize(text: str) -> str:
return unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8').lower()
def search_from_list(query: str, items: list[str]) -> list[str]:
if not query:
return items
normalized_query = normalize(query)
search_terms = [re.sub(r'[^a-z0-9]', '', term) for term in normalized_query.split() if term.strip()]
results = []
for item in items:
normalized_item = normalize(item)
item_with_spaces = re.sub(r'[^a-z0-9\s]', ' ', normalized_item)
item_stripped = re.sub(r'[^a-z0-9]', '', normalized_item)
all_terms_match = True
for term in search_terms:
if not term:
continue
if term not in item_with_spaces and term not in item_stripped:
all_terms_match = False
break
if all_terms_match:
results.append(item)
return results
@@ -0,0 +1,41 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
from collections.abc import Callable
from openpilot.common.params import Params
from openpilot.system.ui.lib.application import gui_app
from openpilot.system.ui.lib.multilang import tr
from openpilot.system.ui.widgets import DialogResult
from openpilot.system.ui.widgets.keyboard import Keyboard
class InputDialogSP:
def __init__(self, title: str, sub_title: str | None = None, current_text: str = "", param: str | None = None,
callback: Callable[[DialogResult, str], None] | None = None,
min_text_size: int = 0, password_mode: bool = False):
self.callback = callback
self.current_text = current_text
self.keyboard = Keyboard(max_text_size=255, min_text_size=min_text_size, password_mode=password_mode)
self.param = param
self._params = Params()
self.sub_title = sub_title
self.title = title
def show(self):
self.keyboard.reset(min_text_size=self.keyboard._min_text_size)
self.keyboard.set_title(tr(self.title), *(tr(self.sub_title),) if self.sub_title else ())
self.keyboard.set_text(self.current_text)
def internal_callback(result: DialogResult):
text = self.keyboard.text if result == DialogResult.CONFIRM else ""
if result == DialogResult.CONFIRM:
if self.param:
self._params.put(self.param, text)
if self.callback:
self.callback(result, text)
gui_app.set_modal_overlay(self.keyboard, internal_callback)
+109 -13
View File
@@ -7,10 +7,13 @@ See the LICENSE.md file in the root directory for more details.
from collections.abc import Callable
import pyray as rl
from openpilot.common.params import Params
from openpilot.system.ui.lib.application import MousePos
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.sunnypilot.widgets.toggle import ToggleSP
from openpilot.system.ui.widgets.list_view import ListItem, ToggleAction, ItemAction
from openpilot.system.ui.widgets.list_view import ListItem, ToggleAction, ItemAction, MultipleButtonAction, _resolve_value
from openpilot.system.ui.sunnypilot.lib.styles import style
from openpilot.system.ui.sunnypilot.widgets.option_control import OptionControlSP, LABEL_WIDTH
class ToggleActionSP(ToggleAction):
@@ -20,11 +23,74 @@ class ToggleActionSP(ToggleAction):
self.toggle = ToggleSP(initial_state=initial_state, callback=callback, param=param)
class MultipleButtonActionSP(MultipleButtonAction):
def __init__(self, buttons: list[str | Callable[[], str]], button_width: int, selected_index: int = 0, callback: Callable = None,
param: str | None = None):
MultipleButtonAction.__init__(self, buttons, button_width, selected_index, callback)
self.param_key = param
self.params = Params()
if self.param_key:
self.selected_button = int(self.params.get(self.param_key, return_default=True))
self._anim_x: float | None = None
def _render(self, rect: rl.Rectangle):
button_y = rect.y + (rect.height - style.BUTTON_HEIGHT) / 2
total_width = len(self.buttons) * self.button_width
track_rect = rl.Rectangle(rect.x, button_y, total_width, style.BUTTON_HEIGHT)
bg_color = style.MBC_TRANSPARENT
text_color = style.ITEM_TEXT_COLOR if self.enabled else style.MBC_DISABLED
highlight_color = style.MBC_BG_CHECKED_ENABLED if self.enabled else style.MBC_DISABLED
# background
rl.draw_rectangle_rounded(track_rect, 0.2, 20, bg_color)
# border
border_color = style.MBC_BG_CHECKED_ENABLED if self.enabled else style.MBC_DISABLED
rl.draw_rectangle_rounded_lines_ex(track_rect, 0.2, 20, 2, border_color)
# highlight with animation
target_x = rect.x + self.selected_button * self.button_width
if not self._anim_x:
self._anim_x = target_x
self._anim_x += (target_x - self._anim_x) * 0.2
highlight_rect = rl.Rectangle(self._anim_x, button_y, self.button_width, style.BUTTON_HEIGHT)
rl.draw_rectangle_rounded(highlight_rect, 0.2, 20, highlight_color)
# text
for i, _text in enumerate(self.buttons):
button_x = rect.x + i * self.button_width
text = _resolve_value(_text, "")
text_size = measure_text_cached(self._font, text, 40)
text_x = button_x + (self.button_width - text_size.x) / 2
text_y = button_y + (style.BUTTON_HEIGHT - text_size.y) / 2
rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), 40, 0, text_color)
def _handle_mouse_release(self, mouse_pos: MousePos):
MultipleButtonAction._handle_mouse_release(self, mouse_pos)
if self.param_key:
self.params.put(self.param_key, self.selected_button)
class ListItemSP(ListItem):
def __init__(self, title: str | Callable[[], str] = "", icon: str | None = None, description: str | Callable[[], str] | None = None,
description_visible: bool = False, callback: Callable | None = None,
action_item: ItemAction | None = None):
action_item: ItemAction | None = None, inline: bool = True):
ListItem.__init__(self, title, icon, description, description_visible, callback, action_item)
self.inline = inline
if not self.inline:
self._rect.height += style.ITEM_BASE_HEIGHT/1.75
def get_item_height(self, font: rl.Font, max_width: int) -> float:
height = super().get_item_height(font, max_width)
if not self.inline:
height = height + style.ITEM_BASE_HEIGHT/1.75
return height
def show_description(self, show: bool):
self._set_description_visible(show)
@@ -33,6 +99,10 @@ class ListItemSP(ListItem):
if not self.action_item:
return rl.Rectangle(0, 0, 0, 0)
if not self.inline:
action_y = item_rect.y + self._text_size.y + style.ITEM_PADDING * 3
return rl.Rectangle(item_rect.x + style.ITEM_PADDING, action_y, item_rect.width - (style.ITEM_PADDING * 2), style.BUTTON_HEIGHT)
right_width = self.action_item.rect.width
if right_width == 0: # Full width action (like DualButtonAction)
return rl.Rectangle(item_rect.x + style.ITEM_PADDING, item_rect.y,
@@ -47,6 +117,13 @@ class ListItemSP(ListItem):
return rl.Rectangle(action_x, action_y, action_width, style.ITEM_BASE_HEIGHT)
def _render(self, _):
if not self.is_visible:
return
# Don't draw items that are not in parent's viewport
if (self._rect.y + self.rect.height) <= self._parent_rect.y or self._rect.y >= (self._parent_rect.y + self._parent_rect.height):
return
content_x = self._rect.x + style.ITEM_PADDING
text_x = content_x
left_action_item = isinstance(self.action_item, ToggleAction)
@@ -62,8 +139,8 @@ class ListItemSP(ListItem):
# Draw title
if self.title:
text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE)
item_y = self._rect.y + (style.ITEM_BASE_HEIGHT - text_size.y) // 2
self._text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE)
item_y = self._rect.y + (style.ITEM_BASE_HEIGHT - self._text_size.y) // 2
rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), style.ITEM_TEXT_FONT_SIZE, 0, style.ITEM_TEXT_COLOR)
# Render toggle and handle callback
@@ -74,14 +151,13 @@ class ListItemSP(ListItem):
else:
if self.title:
# Draw main text
text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE)
item_y = self._rect.y + (style.ITEM_BASE_HEIGHT - text_size.y) // 2
self._text_size = measure_text_cached(self._font, self.title, style.ITEM_TEXT_FONT_SIZE)
item_y = self._rect.y + (style.ITEM_BASE_HEIGHT - self._text_size.y) // 2 if self.inline else self._rect.y + style.ITEM_PADDING * 1.5
rl.draw_text_ex(self._font, self.title, rl.Vector2(text_x, item_y), style.ITEM_TEXT_FONT_SIZE, 0, style.ITEM_TEXT_COLOR)
# Draw right item if present
if self.action_item:
right_rect = self.get_right_item_rect(self._rect)
right_rect.y = self._rect.y
if self.action_item.render(right_rect) and self.action_item.enabled:
# Right item was clicked/activated
if self.callback:
@@ -91,12 +167,12 @@ class ListItemSP(ListItem):
if self.description_visible:
content_width = int(self._rect.width - style.ITEM_PADDING * 2)
description_height = self._html_renderer.get_total_height(content_width)
description_rect = rl.Rectangle(
self._rect.x + style.ITEM_PADDING,
self._rect.y + style.ITEM_DESC_V_OFFSET,
content_width,
description_height
)
desc_y = self._rect.y + style.ITEM_DESC_V_OFFSET
if not self.inline and self.action_item:
desc_y = self.action_item.rect.y + style.ITEM_DESC_V_OFFSET - style.ITEM_PADDING * 1.75
description_rect = rl.Rectangle(self._rect.x + style.ITEM_PADDING, desc_y, content_width, description_height)
self._html_renderer.render(description_rect)
@@ -104,3 +180,23 @@ def toggle_item_sp(title: str | Callable[[], str], description: str | Callable[[
callback: Callable | None = None, icon: str = "", enabled: bool | Callable[[], bool] = True, param: str | None = None) -> ListItemSP:
action = ToggleActionSP(initial_state=initial_state, enabled=enabled, callback=callback, param=param)
return ListItemSP(title=title, description=description, action_item=action, icon=icon, callback=callback)
def multiple_button_item_sp(title: str | Callable[[], str], description: str | Callable[[], str], buttons: list[str | Callable[[], str]],
selected_index: int = 0, button_width: int = style.BUTTON_WIDTH, callback: Callable = None,
icon: str = "", param: str | None = None, inline: bool = False) -> ListItemSP:
action = MultipleButtonActionSP(buttons, button_width, selected_index, callback=callback, param=param)
return ListItemSP(title=title, description=description, icon=icon, action_item=action, inline=inline)
def option_item_sp(title: str | Callable[[], str], param: str,
min_value: int, max_value: int, description: str | Callable[[], str] | None = None,
value_change_step: int = 1, on_value_changed: Callable[[int], None] | None = None,
enabled: bool | Callable[[], bool] = True,
icon: str = "", label_width: int = LABEL_WIDTH, value_map: dict[int, int] | None = None,
use_float_scaling: bool = False, label_callback: Callable[[int], str] | None = None) -> ListItemSP:
action = OptionControlSP(
param, min_value, max_value, value_change_step,
enabled, on_value_changed, value_map, label_width, use_float_scaling, label_callback
)
return ListItemSP(title=title, description=description, action_item=action, icon=icon)
@@ -0,0 +1,165 @@
import pyray as rl
from collections.abc import Callable
from openpilot.common.params import Params
from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.sunnypilot.lib.styles import style
from openpilot.system.ui.widgets.list_view import ItemAction
# Dimensions and styling constants
BUTTON_WIDTH = 150
BUTTON_HEIGHT = 150
LABEL_WIDTH = 350
BUTTON_SPACING = 25
VALUE_FONT_SIZE = 50
BUTTON_FONT_SIZE = 60
CONTAINER_PADDING = 20
class OptionControlSP(ItemAction):
def __init__(self, param: str, min_value: int, max_value: int,
value_change_step: int = 1, enabled: bool | Callable[[], bool] = True,
on_value_changed: Callable[[int], None] | None = None,
value_map: dict[int, int] | None = None,
label_width: int = LABEL_WIDTH,
use_float_scaling: bool = False, label_callback: Callable[[int], str] | None = None):
super().__init__(enabled=enabled)
self.params = Params()
self.param_key = param
self.min_value = min_value
self.max_value = max_value
self.value_change_step = value_change_step
self._minus_enabled = enabled
self._plus_enabled = enabled
self.on_value_changed = on_value_changed
self.value_map = value_map
self.label_width = label_width
self.use_float_scaling = use_float_scaling
self.current_value = min_value
self.label_callback = label_callback
if self.value_map:
for key in self.value_map:
if self.value_map[key] == self.params.get(self.param_key, return_default=True):
self.current_value = int(key)
break
else:
self.current_value = int(self.params.get(self.param_key, return_default=True))
# Initialize font and button styles
self._font = gui_app.font(FontWeight.MEDIUM)
# Layout rectangles for components
self.minus_btn_rect = rl.Rectangle(0, 0, 0, 0)
self.plus_btn_rect = rl.Rectangle(0, 0, 0, 0)
def get_value(self) -> int:
"""Get the current value of the control"""
return self.current_value
def set_value(self, value: int):
"""Set the control to a specific value"""
if self.min_value <= value <= self.max_value:
self.current_value = value
if self.value_map:
self.params.put(self.param_key, self.value_map[value])
else:
if self.use_float_scaling:
self.params.put(self.param_key, value / 100.0)
else:
self.params.put(self.param_key, value)
if self.on_value_changed:
self.on_value_changed(value)
def get_displayed_value(self) -> str:
"""Get the displayed value, handling value mapping if present"""
value = self.current_value
if callable(self.label_callback):
if self.value_map:
return self.label_callback(self.value_map[value])
else:
return self.label_callback(value)
if self.value_map:
# Use the value map to get the display string
if value in self.value_map:
return str(self.value_map[value]) # Return the display string
# If using float scaling, format as float
if self.use_float_scaling:
return f"{value / 100.0:.2f}"
return str(value)
def _render(self, rect: rl.Rectangle):
if self._rect.width == 0 or self._rect.height == 0 or not self.is_visible:
return
control_width = (BUTTON_WIDTH * 2) + self.label_width + (BUTTON_SPACING * 2)
total_width = control_width + (CONTAINER_PADDING * 2)
self._rect.width = total_width
start_x = self._rect.x + self._rect.width - control_width - (CONTAINER_PADDING * 2)
component_y = rect.y + (rect.height - BUTTON_HEIGHT) / 2
self.container_rect = rl.Rectangle(start_x, component_y, total_width, BUTTON_HEIGHT)
# background
rl.draw_rectangle_rounded(self.container_rect, 0.2, 20, style.OPTION_CONTROL_CONTAINER_BG)
# minus button
self.minus_btn_rect = rl.Rectangle(self.container_rect.x, component_y, BUTTON_WIDTH + CONTAINER_PADDING,
BUTTON_HEIGHT)
# label
label_x = self.container_rect.x + CONTAINER_PADDING + BUTTON_WIDTH + BUTTON_SPACING
self.label_rect = rl.Rectangle(label_x, component_y, self.label_width, BUTTON_HEIGHT)
# plus button
plus_x = label_x + self.label_width + BUTTON_SPACING
self.plus_btn_rect = rl.Rectangle(plus_x, component_y, BUTTON_WIDTH + CONTAINER_PADDING, BUTTON_HEIGHT)
self._minus_enabled = self.enabled and self.current_value > self.min_value
self._plus_enabled = self.enabled and self.current_value < self.max_value
self._render_button(self.minus_btn_rect, "-", self._minus_enabled)
self._render_value_label()
self._render_button(self.plus_btn_rect, "+", self._plus_enabled)
def _render_button(self, rect: rl.Rectangle, text: str, enabled: bool):
mouse_pos = rl.get_mouse_position()
is_pressed = (rl.check_collision_point_rec(mouse_pos, rect) and
self._touch_valid() and rl.is_mouse_button_down(rl.MouseButton.MOUSE_BUTTON_LEFT))
text_color = style.ITEM_TEXT_COLOR if enabled else style.ITEM_DISABLED_TEXT_COLOR
# highlight
if enabled and is_pressed:
rl.draw_rectangle_rounded(rect, 0.2, 20, style.OPTION_CONTROL_BTN_PRESSED)
# button text
text_size = measure_text_cached(self._font, text, BUTTON_FONT_SIZE)
text_x = rect.x + (rect.width - text_size.x) / 2
text_y = rect.y + (rect.height - text_size.y) / 2
rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), BUTTON_FONT_SIZE, 0, text_color)
def _render_value_label(self):
"""Render the current value label"""
text = self.get_displayed_value()
text_color = style.ITEM_TEXT_COLOR if self.enabled else style.ITEM_DISABLED_TEXT_COLOR
text_size = measure_text_cached(self._font, text, VALUE_FONT_SIZE)
text_x = self.label_rect.x + (self.label_rect.width - text_size.x) / 2
text_y = self.label_rect.y + (self.label_rect.height - text_size.y) / 2
rl.draw_text_ex(self._font, text, rl.Vector2(text_x, text_y), VALUE_FONT_SIZE, 0, text_color)
def _handle_mouse_release(self, mouse_pos: MousePos):
if self._minus_enabled and rl.check_collision_point_rec(mouse_pos, self.minus_btn_rect):
self.current_value -= self.value_change_step
self.current_value = max(self.min_value, self.current_value)
elif self._plus_enabled and rl.check_collision_point_rec(mouse_pos, self.plus_btn_rect):
self.current_value += self.value_change_step
self.current_value = min(self.max_value, self.current_value)
self.set_value(self.current_value)
@@ -0,0 +1,57 @@
"""
Copyright (c) 2021-, Haibin Wen, sunnypilot, and a number of other contributors.
This file is part of sunnypilot and is licensed under the MIT License.
See the LICENSE.md file in the root directory for more details.
"""
import pyray as rl
from openpilot.system.ui.lib.application import gui_app, FontWeight
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.widgets.list_view import ListItem, ItemAction
class ProgressBarAction(ItemAction):
def __init__(self, width=600):
super().__init__(width=width)
self.progress = 0.0
self.text = ""
self.show_progress = False
self.text_color = rl.GRAY
self._font = gui_app.font(FontWeight.NORMAL)
def update(self, progress, text, show_progress=False, text_color=rl.GRAY):
self.progress = progress
self.text = text
self.show_progress = show_progress
self.text_color = text_color
def _render(self, rect: rl.Rectangle):
font_size = 40
text_size = measure_text_cached(self._font, self.text, font_size)
padding = 30
bar_width = text_size.x + 2 * padding
text_x = (bar_width - text_size.x) / 2
if self.show_progress and len(parts := self.text.split(' - ', 1)) == 2:
prefix = parts[0]
max_prefix_w = measure_text_cached(self._font, "100%", font_size).x
current_prefix_w = measure_text_cached(self._font, prefix, font_size).x
bar_width = (text_size.x - current_prefix_w + max_prefix_w) + 2 * padding
text_x = padding + (max_prefix_w - current_prefix_w)
bar_height = 60
bar_rect = rl.Rectangle(rect.x + rect.width - bar_width, rect.y + (rect.height - bar_height) / 2, bar_width, bar_height)
if self.show_progress:
inner_rect = rl.Rectangle(bar_rect.x + 4, bar_rect.y + 4, bar_rect.width - 8, bar_rect.height - 8)
if inner_rect.width > 0:
fill_width = max(0, min(inner_rect.width, inner_rect.width * (self.progress / 100.0)))
rl.draw_rectangle_rounded(rl.Rectangle(inner_rect.x, inner_rect.y, fill_width, inner_rect.height), 0.2, 10, rl.Color(30, 121, 232, 255))
rl.draw_text_ex(self._font, self.text, rl.Vector2(bar_rect.x + text_x, bar_rect.y + (bar_height - text_size.y) / 2), font_size, 0, self.text_color)
def progress_item(title):
action = ProgressBarAction()
return ListItem(title=title, action_item=action)
+2
View File
@@ -16,7 +16,9 @@ from openpilot.system.ui.widgets.scroller_tici import Scroller
from openpilot.system.ui.widgets.list_view import ButtonAction, ListItem, MultipleButtonAction, ToggleAction, button_item, text_item
if gui_app.sunnypilot_ui():
from openpilot.system.ui.sunnypilot.widgets.list_view import ListItemSP as ListItem
from openpilot.system.ui.sunnypilot.widgets.list_view import ToggleActionSP as ToggleAction
from openpilot.system.ui.sunnypilot.widgets.list_view import MultipleButtonActionSP as MultipleButtonAction
# These are only used for AdvancedNetworkSettings, standalone apps just need WifiManagerUI
try:
+2 -2
View File
@@ -28,8 +28,8 @@ class LineSeparator(Widget):
self._rect.width = parent_rect.width
def _render(self, _):
rl.draw_line(int(self._rect.x), int(self._rect.y),
int(self._rect.x + self._rect.width), int(self._rect.y),
rl.draw_line(int(self._rect.x) + LINE_PADDING, int(self._rect.y),
int(self._rect.x + self._rect.width) - LINE_PADDING, int(self._rect.y),
LINE_COLOR)
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:fb3b1fd29d958e9a3a6625eac9fac9e7cd6eb40309b285ad973324761db0b4c9
size 1202792
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:161a5d0bf7347465b53ae49690a38fbacf03d606ef204147b3b148a5f59188da
size 9008016
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7e0e66c12a1eb3b5b4b2b2694831ca51e5132818f400dad789adbcc30e0e0793
size 14032
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:784f2e80fa3534cf7934c5ecbbda37db633104380f2b41d896b4721ad6006eb2
size 2420312
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:33afe465e74bbe2c409350d2ca8e86cfadf050ceb8feac75a86adc19ff1f9c48
size 26016
-3
View File
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7bee94d38195478ffdd0ce15292a2dfa7813377f4c3b7d99c270e05079d1746b
size 20828
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4e040c87072aa915c47859c8c7f74076b98c6919b83ddd5dc4bb555870d586a7
size 1813866
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:838bc58ac0094ba9593cf7c44ab6e8a94ae3dbbe176e320d9fbe86ceead53c5e
size 1817962
@@ -1,3 +0,0 @@
version https://git-lfs.github.com/spec/v1
oid sha256:77d025d59521e13e4ed012f0d9d2b684cdb858208d70426078df51219eaeb9bd
size 10098673
-84
View File
@@ -1,84 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef __IDIAGLOG_HPP_
#define __IDIAGLOG_HPP_
#include <string>
#include "DiagLog/Options.hpp"
#include "DlSystem/String.hpp"
#include "DlSystem/ZdlExportDefine.hpp"
namespace zdl
{
namespace DiagLog
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/// @brief .
///
/// Interface for controlling logging for zdl components.
class ZDL_EXPORT IDiagLog
{
public:
/// @brief .
///
/// Sets the options after initialization occurs.
///
/// @param[in] loggingOptions The options to set up diagnostic logging.
///
/// @return False if the options could not be set. Ensure logging is not started.
virtual bool setOptions(const Options& loggingOptions) = 0;
/// @brief .
///
/// Gets the curent options for the diag logger.
///
/// @return Diag log options object.
virtual Options getOptions() = 0;
/// @brief .
///
/// Allows for setting the log mask once diag logging has started
///
/// @return True if the level was set successfully, false if a failure occurred.
virtual bool setDiagLogMask(const std::string& mask) = 0;
/// @brief .
///
/// Allows for setting the log mask once diag logging has started
///
/// @return True if the level was set successfully, false if a failure occurred.
virtual bool setDiagLogMask(const zdl::DlSystem::String& mask) = 0;
/// @brief .
///
/// Enables logging for zdl components.
///
/// Logging should be started prior to the instantiation of zdl components
/// to ensure all events are captured.
///
/// @return False if diagnostic logging could not be started.
virtual bool start(void) = 0;
/// @brief Disables logging for zdl components.
virtual bool stop(void) = 0;
virtual ~IDiagLog() {};
};
} // DiagLog namespace
} // zdl namespace
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif
-79
View File
@@ -1,79 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015, 2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef __DIAGLOG_OPTIONS_HPP_
#define __DIAGLOG_OPTIONS_HPP_
#include <string>
#include "DlSystem/ZdlExportDefine.hpp"
namespace zdl
{
namespace DiagLog
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/// @brief .
///
/// Options for setting up diagnostic logging for zdl components.
class ZDL_EXPORT Options
{
public:
Options() :
DiagLogMask(""),
LogFileDirectory("diaglogs"),
LogFileName("DiagLog"),
LogFileRotateCount(20),
LogFileReplace(true)
{
// Solves the empty string problem with multiple std libs
DiagLogMask.reserve(1);
}
/// @brief .
///
/// Enables diag logging only on the specified area mask (DNN_RUNTIME=ON | OFF)
std::string DiagLogMask;
/// @brief .
///
/// The path to the directory where log files will be written.
/// The path may be relative or absolute. Relative paths are interpreted
/// from the current working directory.
/// Default value is "diaglogs"
std::string LogFileDirectory;
/// @brief .
///
//// The name used for log files. If this value is empty then BaseName will be
/// used as the default file name.
/// Default value is "DiagLog"
std::string LogFileName;
/// @brief .
///
/// The maximum number of log files to create. If set to 0 no log rotation
/// will be used and the log file name specified will be used each time, overwriting
/// any existing log file that may exist.
/// Default value is 20
uint32_t LogFileRotateCount;
/// @brief
///
/// If the log file already exists, control whether it will be replaced
/// (existing contents truncated), or appended.
/// Default value is true
bool LogFileReplace;
};
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
} // DiagLog namespace
} // zdl namespace
#endif
-191
View File
@@ -1,191 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015-2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef ZEROTH_IDNC_CONTAINER_HPP
#define ZEROTH_IDNC_CONTAINER_HPP
#include <memory>
#include <stdint.h>
#include <string>
#include <vector>
#include <set>
#include "DlSystem/ZdlExportDefine.hpp"
#include "DlSystem/String.hpp"
namespace zdl {
namespace DlContainer {
/** @addtogroup c_plus_plus_apis C++
@{ */
class IDlContainer;
class dlc_error;
/**
* The structure of a record in a DL container.
*/
struct ZDL_EXPORT DlcRecord
{
/// Name of the record.
std::string name;
/// Byte blob holding the data for the record.
std::vector<uint8_t> data;
DlcRecord();
DlcRecord( DlcRecord&& other )
: name(std::move(other.name))
, data(std::move(other.data))
{}
DlcRecord(const std::string& new_name)
: name(new_name)
, data()
{
if(name.empty())
{
name.reserve(1);
}
}
DlcRecord(const DlcRecord&) = delete;
};
// The maximum length of any record name.
extern const uint32_t RECORD_NAME_MAX_SIZE;
// The maximum size of the record payload (bytes).
extern const uint32_t RECORD_DATA_MAX_SIZE;
// The maximum number of records in an archive at one time.
extern const uint32_t ARCHIVE_MAX_RECORDS;
/**
* Represents a container for a neural network model which can
* be used to load the model into the SNPE runtime.
*/
class ZDL_EXPORT IDlContainer
{
public:
/**
* Initializes a container from a container archive file.
*
* @param[in] filename Container archive file path.
*
* @return A pointer to the initialized container
*/
static std::unique_ptr<IDlContainer>
open(const std::string &filename) noexcept;
/**
* Initializes a container from a container archive file.
*
* @param[in] filename Container archive file path.
*
* @return A pointer to the initialized container
*/
static std::unique_ptr<IDlContainer>
open(const zdl::DlSystem::String &filename) noexcept;
/**
* Initializes a container from a byte buffer.
*
* @param[in] buffer Byte buffer holding the contents of an archive
* file.
*
* @return A pointer to the initialized container
*/
static std::unique_ptr<IDlContainer>
open(const std::vector<uint8_t> &buffer) noexcept;
/**
* Initializes a container from a byte buffer.
*
* @param[in] buffer Byte buffer holding the contents of an archive
* file.
*
* @param[in] size Size of the byte buffer.
*
* @return A pointer to the initialized container
*/
static std::unique_ptr<IDlContainer>
open(const uint8_t* buffer, const size_t size) noexcept;
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
/**
* Get the record catalog for a container.
*
* @param[out] catalog Buffer that will hold the record names on
* return.
*/
virtual void getCatalog(std::set<std::string> &catalog) const = 0;
/**
* Get the record catalog for a container.
*
* @param[out] catalog Buffer that will hold the record names on
* return.
*/
virtual void getCatalog(std::set<zdl::DlSystem::String> &catalog) const = 0;
/**
* Get a record from a container by name.
*
* @param[in] name Name of the record to fetch.
* @param[out] record The passed in record will be populated with the
* record data on return. Note that the caller
* will own the data in the record and is
* responsible for freeing it if needed.
*/
virtual void getRecord(const std::string &name, DlcRecord &record) const = 0;
/**
* Get a record from a container by name.
*
* @param[in] name Name of the record to fetch.
* @param[out] record The passed in record will be populated with the
* record data on return. Note that the caller
* will own the data in the record and is
* responsible for freeing it if needed.
*/
virtual void getRecord(const zdl::DlSystem::String &name, DlcRecord &record) const = 0;
/**
* Save the container to an archive on disk. This function will save the
* container if the filename is different from the file that it was opened
* from, or if at least one record was modified since the container was
* opened.
*
* It will truncate any existing file at the target path.
*
* @param filename Container archive file path.
*
* @return indication of success/failure
*/
virtual bool save(const std::string &filename) = 0;
/**
* Save the container to an archive on disk. This function will save the
* container if the filename is different from the file that it was opened
* from, or if at least one record was modified since the container was
* opened.
*
* It will truncate any existing file at the target path.
*
* @param filename Container archive file path.
*
* @return indication of success/failure
*/
virtual bool save (const zdl::DlSystem::String &filename) = 0;
virtual ~IDlContainer() {}
};
} // ns DlContainer
} // ns zdl
#endif
-234
View File
@@ -1,234 +0,0 @@
//==============================================================================
//
// Copyright (c) 2014-2021 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#ifndef _DL_ENUMS_HPP_
#define _DL_ENUMS_HPP_
#include "DlSystem/ZdlExportDefine.hpp"
namespace zdl {
namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* Enumeration of supported target runtimes.
*/
enum class Runtime_t
{
/// Run the processing on Snapdragon CPU.
/// Data: float 32bit
/// Math: float 32bit
CPU_FLOAT32 = 0,
/// Run the processing on the Adreno GPU.
/// Data: float 16bit
/// Math: float 32bit
GPU_FLOAT32_16_HYBRID = 1,
/// Run the processing on the Hexagon DSP.
/// Data: 8bit fixed point Tensorflow style format
/// Math: 8bit fixed point Tensorflow style format
DSP_FIXED8_TF = 2,
/// Run the processing on the Adreno GPU.
/// Data: float 16bit
/// Math: float 16bit
GPU_FLOAT16 = 3,
/// Run the processing on Snapdragon AIX+HVX.
/// Data: 8bit fixed point Tensorflow style format
/// Math: 8bit fixed point Tensorflow style format
AIP_FIXED8_TF = 5,
AIP_FIXED_TF = AIP_FIXED8_TF,
/// Default legacy enum to retain backward compatibility.
/// CPU = CPU_FLOAT32
CPU = CPU_FLOAT32,
/// Default legacy enum to retain backward compatibility.
/// GPU = GPU_FLOAT32_16_HYBRID
GPU = GPU_FLOAT32_16_HYBRID,
/// Default legacy enum to retain backward compatibility.
/// DSP = DSP_FIXED8_TF
DSP = DSP_FIXED8_TF,
/// Special value indicating the property is unset.
UNSET = -1
};
/**
* Enumeration of runtime available check options.
*/
enum class RuntimeCheckOption_t
{
/// Perform standard runtime available check
DEFAULT = 0,
/// Perform standard runtime available check
NORMAL_CHECK = 0,
/// Perform basic runtime available check, may be runtime specific
BASIC_CHECK = 1,
/// Perform unsignedPD runtime available check
UNSIGNEDPD_CHECK = 2,
};
/**
* Enumeration of various performance profiles that can be requested.
*/
enum class PerformanceProfile_t
{
/// Run in a standard mode.
/// This mode will be deprecated in the future and replaced with BALANCED.
DEFAULT = 0,
/// Run in a balanced mode.
BALANCED = 0,
/// Run in high performance mode
HIGH_PERFORMANCE = 1,
/// Run in a power sensitive mode, at the expense of performance.
POWER_SAVER = 2,
/// Use system settings. SNPE makes no calls to any performance related APIs.
SYSTEM_SETTINGS = 3,
/// Run in sustained high performance mode
SUSTAINED_HIGH_PERFORMANCE = 4,
/// Run in burst mode
BURST = 5,
/// Run in lower clock than POWER_SAVER, at the expense of performance.
LOW_POWER_SAVER = 6,
/// Run in higher clock and provides better performance than POWER_SAVER.
HIGH_POWER_SAVER = 7,
/// Run in lower balanced mode
LOW_BALANCED = 8,
};
/**
* Enumeration of various profilngLevels that can be requested.
*/
enum class ProfilingLevel_t
{
/// No profiling.
/// Collects no runtime stats in the DiagLog
OFF = 0,
/// Basic profiling
/// Collects some runtime stats in the DiagLog
BASIC = 1,
/// Detailed profiling
/// Collects more runtime stats in the DiagLog, including per-layer statistics
/// Performance may be impacted
DETAILED = 2,
/// Moderate profiling
/// Collects more runtime stats in the DiagLog, no per-layer statistics
MODERATE = 3
};
/**
* Enumeration of various execution priority hints.
*/
enum class ExecutionPriorityHint_t
{
/// Normal priority
NORMAL = 0,
/// Higher than normal priority
HIGH = 1,
/// Lower priority
LOW = 2
};
/** @} */ /* end_addtogroup c_plus_plus_apis C++*/
/**
* Enumeration that lists the supported image encoding formats.
*/
enum class ImageEncoding_t
{
/// For unknown image type. Also used as a default value for ImageEncoding_t.
UNKNOWN = 0,
/// The RGB format consists of 3 bytes per pixel: one byte for
/// Red, one for Green, and one for Blue. The byte ordering is
/// endian independent and is always in RGB byte order.
RGB = 1,
/// The ARGB32 format consists of 4 bytes per pixel: one byte for
/// Red, one for Green, one for Blue, and one for the alpha channel.
/// The alpha channel is ignored. The byte ordering depends on the
/// underlying CPU. For little endian CPUs, the byte order is BGRA.
/// For big endian CPUs, the byte order is ARGB.
ARGB32 = 2,
/// The RGBA format consists of 4 bytes per pixel: one byte for
/// Red, one for Green, one for Blue, and one for the alpha channel.
/// The alpha channel is ignored. The byte ordering is endian independent
/// and is always in RGBA byte order.
RGBA = 3,
/// The GRAYSCALE format is for 8-bit grayscale.
GRAYSCALE = 4,
/// NV21 is the Android version of YUV. The Chrominance is down
/// sampled and has a subsampling ratio of 4:2:0. Note that this
/// image format has 3 channels, but the U and V channels
/// are subsampled. For every four Y pixels there is one U and one V pixel. @newpage
NV21 = 5,
/// The BGR format consists of 3 bytes per pixel: one byte for
/// Red, one for Green and one for Blue. The byte ordering is
/// endian independent and is always BGR byte order.
BGR = 6
};
/**
* Enumeration that lists the supported LogLevels that can be set by users.
*/
enum class LogLevel_t
{
/// Enumeration variable to be used by user to set logging level to FATAL.
LOG_FATAL = 0,
/// Enumeration variable to be used by user to set logging level to ERROR.
LOG_ERROR = 1,
/// Enumeration variable to be used by user to set logging level to WARN.
LOG_WARN = 2,
/// Enumeration variable to be used by user to set logging level to INFO.
LOG_INFO = 3,
/// Enumeration variable to be used by user to set logging level to VERBOSE.
LOG_VERBOSE = 4
};
typedef enum : int
{
UNSPECIFIED = 0,
FLOATING_POINT_32 = 1,
FLOATING_POINT_16 = 2,
FIXED_POINT_8 = 3,
FIXED_POINT_16 = 4
} IOBufferDataType_t;
}} // namespaces end
#endif
-259
View File
@@ -1,259 +0,0 @@
//==============================================================================
//
// Copyright (c) 2016-2021 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#ifndef _DL_ERROR_HPP_
#define _DL_ERROR_HPP_
#include <stdint.h>
#include <limits> // numeric_limits
#include "DlSystem/ZdlExportDefine.hpp"
namespace zdl {
namespace DlSystem {
// clang and arm gcc different in how ZDL_EXPORT is used with enum class
#if !defined (__clang__)
enum class ErrorCode : uint32_t ZDL_EXPORT {
#else
enum class ZDL_EXPORT ErrorCode : uint32_t {
#endif // ARM64V8A
NONE = 0,
// System config errors
SNPE_CONFIG_MISSING_PARAM = 100,
SNPE_CONFIG_INVALID_PARAM = 101,
SNPE_CONFIG_MISSING_FILE = 102,
SNPE_CONFIG_NNCONFIG_NOT_SET = 103,
SNPE_CONFIG_NNCONFIG_INVALID = 104,
SNPE_CONFIG_WRONG_INPUT_NAME = 105,
SNPE_CONFIG_INCORRECT_INPUT_DIMENSIONS = 106,
SNPE_CONFIG_DIMENSIONS_MODIFICATION_NOT_SUPPORTED = 107,
SNPE_CONFIG_BOTH_OUTPUT_LAYER_TENSOR_NAMES_SET = 108,
SNPE_CONFIG_NNCONFIG_ONLY_TENSOR_SUPPORTED = 120,
SNPE_CONFIG_NNCONFIG_ONLY_USER_BUFFER_SUPPORTED = 121,
// DlSystem errors
SNPE_DLSYSTEM_MISSING_BUFFER = 200,
SNPE_DLSYSTEM_TENSOR_CAST_FAILED = 201,
SNPE_DLSYSTEM_FIXED_POINT_PARAM_INVALID = 202,
SNPE_DLSYSTEM_SIZE_MISMATCH = 203,
SNPE_DLSYSTEM_NAME_NOT_FOUND = 204,
SNPE_DLSYSTEM_VALUE_MISMATCH = 205,
SNPE_DLSYSTEM_INSERT_FAILED = 206,
SNPE_DLSYSTEM_TENSOR_FILE_READ_FAILED = 207,
SNPE_DLSYSTEM_DIAGLOG_FAILURE = 208,
SNPE_DLSYSTEM_LAYER_NOT_SET = 209,
SNPE_DLSYSTEM_WRONG_NUMBER_INPUT_BUFFERS = 210,
SNPE_DLSYSTEM_RUNTIME_TENSOR_SHAPE_MISMATCH = 211,
SNPE_DLSYSTEM_TENSOR_MISSING = 212,
SNPE_DLSYSTEM_TENSOR_ITERATION_UNSUPPORTED = 213,
SNPE_DLSYSTEM_BUFFER_MANAGER_MISSING = 214,
SNPE_DLSYSTEM_RUNTIME_BUFFER_SOURCE_UNSUPPORTED = 215,
SNPE_DLSYSTEM_BUFFER_CAST_FAILED = 216,
SNPE_DLSYSTEM_WRONG_TRANSITION_TYPE = 217,
SNPE_DLSYSTEM_LAYER_ALREADY_REGISTERED = 218,
SNPE_DLSYSTEM_TENSOR_DIM_INVALID = 219,
SNPE_DLSYSTEM_BUFFERENCODING_UNKNOWN = 240,
SNPE_DLSYSTEM_BUFFER_INVALID_PARAM = 241,
// DlContainer errors
SNPE_DLCONTAINER_MODEL_PARSING_FAILED = 300,
SNPE_DLCONTAINER_UNKNOWN_LAYER_CODE = 301,
SNPE_DLCONTAINER_MISSING_LAYER_PARAM = 302,
SNPE_DLCONTAINER_LAYER_PARAM_NOT_SUPPORTED = 303,
SNPE_DLCONTAINER_LAYER_PARAM_INVALID = 304,
SNPE_DLCONTAINER_TENSOR_DATA_MISSING = 305,
SNPE_DLCONTAINER_MODEL_LOAD_FAILED = 306,
SNPE_DLCONTAINER_MISSING_RECORDS = 307,
SNPE_DLCONTAINER_INVALID_RECORD = 308,
SNPE_DLCONTAINER_WRITE_FAILURE = 309,
SNPE_DLCONTAINER_READ_FAILURE = 310,
SNPE_DLCONTAINER_BAD_CONTAINER = 311,
SNPE_DLCONTAINER_BAD_DNN_FORMAT_VERSION = 312,
SNPE_DLCONTAINER_UNKNOWN_AXIS_ANNOTATION = 313,
SNPE_DLCONTAINER_UNKNOWN_SHUFFLE_TYPE = 314,
SNPE_DLCONTAINER_TEMP_FILE_FAILURE = 315,
// Network errors
SNPE_NETWORK_EMPTY_NETWORK = 400,
SNPE_NETWORK_CREATION_FAILED = 401,
SNPE_NETWORK_PARTITION_FAILED = 402,
SNPE_NETWORK_NO_OUTPUT_DEFINED = 403,
SNPE_NETWORK_MISMATCH_BETWEEN_NAMES_AND_DIMS = 404,
SNPE_NETWORK_MISSING_INPUT_NAMES = 405,
SNPE_NETWORK_MISSING_OUTPUT_NAMES = 406,
SNPE_NETWORK_EXECUTION_FAILED = 407,
// Host runtime errors
SNPE_HOST_RUNTIME_TARGET_UNAVAILABLE = 500,
// CPU runtime errors
SNPE_CPU_LAYER_NOT_SUPPORTED = 600,
SNPE_CPU_LAYER_PARAM_NOT_SUPPORTED = 601,
SNPE_CPU_LAYER_PARAM_INVALID = 602,
SNPE_CPU_LAYER_PARAM_COMBINATION_INVALID = 603,
SNPE_CPU_BUFFER_NOT_FOUND = 604,
SNPE_CPU_NETWORK_NOT_SUPPORTED = 605,
SNPE_CPU_UDO_OPERATION_FAILED = 606,
// CPU fixed-point runtime errors
SNPE_CPU_FXP_LAYER_NOT_SUPPORTED = 700,
SNPE_CPU_FXP_LAYER_PARAM_NOT_SUPPORTED = 701,
SNPE_CPU_FXP_LAYER_PARAM_INVALID = 702,
// GPU runtime errors
SNPE_GPU_LAYER_NOT_SUPPORTED = 800,
SNPE_GPU_LAYER_PARAM_NOT_SUPPORTED = 801,
SNPE_GPU_LAYER_PARAM_INVALID = 802,
SNPE_GPU_LAYER_PARAM_COMBINATION_INVALID = 803,
SNPE_GPU_KERNEL_COMPILATION_FAILED = 804,
SNPE_GPU_CONTEXT_NOT_SET = 805,
SNPE_GPU_KERNEL_NOT_SET = 806,
SNPE_GPU_KERNEL_PARAM_INVALID = 807,
SNPE_GPU_OPENCL_CHECK_FAILED = 808,
SNPE_GPU_OPENCL_FUNCTION_ERROR = 809,
SNPE_GPU_BUFFER_NOT_FOUND = 810,
SNPE_GPU_TENSOR_DIM_INVALID = 811,
SNPE_GPU_MEMORY_FLAGS_INVALID = 812,
SNPE_GPU_UNEXPECTED_NUMBER_OF_IO = 813,
SNPE_GPU_LAYER_PROXY_ERROR = 814,
SNPE_GPU_BUFFER_IN_USE = 815,
SNPE_GPU_BUFFER_MODIFICATION_ERROR = 816,
SNPE_GPU_DATA_ARRANGEMENT_INVALID = 817,
SNPE_GPU_UDO_OPERATION_FAILED = 818,
// DSP runtime errors
SNPE_DSP_LAYER_NOT_SUPPORTED = 900,
SNPE_DSP_LAYER_PARAM_NOT_SUPPORTED = 901,
SNPE_DSP_LAYER_PARAM_INVALID = 902,
SNPE_DSP_LAYER_PARAM_COMBINATION_INVALID = 903,
SNPE_DSP_STUB_NOT_PRESENT = 904,
SNPE_DSP_LAYER_NAME_TRUNCATED = 905,
SNPE_DSP_LAYER_INPUT_BUFFER_NAME_TRUNCATED = 906,
SNPE_DSP_LAYER_OUTPUT_BUFFER_NAME_TRUNCATED = 907,
SNPE_DSP_RUNTIME_COMMUNICATION_ERROR = 908,
SNPE_DSP_RUNTIME_INVALID_PARAM_ERROR = 909,
SNPE_DSP_RUNTIME_SYSTEM_ERROR = 910,
SNPE_DSP_RUNTIME_CRASHED_ERROR = 911,
SNPE_DSP_BUFFER_SIZE_ERROR = 912,
SNPE_DSP_UDO_EXECUTE_ERROR = 913,
SNPE_DSP_UDO_LIB_NOT_REGISTERED_ERROR = 914,
SNPE_DSP_UDO_INVALID_QUANTIZATION_TYPE_ERROR = 915,
SNPE_DSP_RUNTIME_INVALID_RPC_DRIVER = 916,
SNPE_DSP_RUNTIME_RPC_PERMISSION_ERROR = 917,
SNPE_DSP_RUNTIME_DSP_FILE_OPEN_ERROR = 918,
// Model validataion errors
SNPE_MODEL_VALIDATION_LAYER_NOT_SUPPORTED = 1000,
SNPE_MODEL_VALIDATION_LAYER_PARAM_NOT_SUPPORTED = 1001,
SNPE_MODEL_VALIDATION_LAYER_PARAM_INVALID = 1002,
SNPE_MODEL_VALIDATION_LAYER_PARAM_MISSING = 1003,
SNPE_MODEL_VALIDATION_LAYER_PARAM_COMBINATION_INVALID = 1004,
SNPE_MODEL_VALIDATION_LAYER_ORDERING_INVALID = 1005,
SNPE_MODEL_VALIDATION_INVALID_CONSTRAINT = 1006,
SNPE_MODEL_VALIDATION_MISSING_BUFFER = 1007,
SNPE_MODEL_VALIDATION_BUFFER_REUSE_NOT_SUPPORTED = 1008,
SNPE_MODEL_VALIDATION_LAYER_COULD_NOT_BE_ASSIGNED = 1009,
SNPE_MODEL_VALIDATION_UDO_LAYER_FAILED = 1010,
// UDL errors
SNPE_UDL_LAYER_EMPTY_UDL_NETWORK = 1100,
SNPE_UDL_LAYER_PARAM_INVALID = 1101,
SNPE_UDL_LAYER_INSTANCE_MISSING = 1102,
SNPE_UDL_LAYER_SETUP_FAILED = 1103,
SNPE_UDL_EXECUTE_FAILED = 1104,
SNPE_UDL_BUNDLE_INVALID = 1105,
SNPE_UDO_REGISTRATION_FAILED = 1106,
SNPE_UDO_GET_PACKAGE_FAILED = 1107,
SNPE_UDO_GET_IMPLEMENTATION_FAILED = 1108,
// Dependent library errors
SNPE_STD_LIBRARY_ERROR = 1200,
// Unknown exception (catch (...)), Has no component attached to this
SNPE_UNKNOWN_EXCEPTION = 1210,
// Storage Errors
SNPE_STORAGE_INVALID_KERNEL_REPO = 1300,
// AIP runtime errors
SNPE_AIP_LAYER_NOT_SUPPORTED = 1400,
SNPE_AIP_LAYER_PARAM_NOT_SUPPORTED = 1401,
SNPE_AIP_LAYER_PARAM_INVALID = 1402,
SNPE_AIP_LAYER_PARAM_COMBINATION_INVALID = 1403,
SNPE_AIP_STUB_NOT_PRESENT = 1404,
SNPE_AIP_LAYER_NAME_TRUNCATED = 1405,
SNPE_AIP_LAYER_INPUT_BUFFER_NAME_TRUNCATED = 1406,
SNPE_AIP_LAYER_OUTPUT_BUFFER_NAME_TRUNCATED = 1407,
SNPE_AIP_RUNTIME_COMMUNICATION_ERROR = 1408,
SNPE_AIP_RUNTIME_INVALID_PARAM_ERROR = 1409,
SNPE_AIP_RUNTIME_SYSTEM_ERROR = 1410,
SNPE_AIP_RUNTIME_TENSOR_MISSING = 1411,
SNPE_AIP_RUNTIME_TENSOR_SHAPE_MISMATCH = 1412,
SNPE_AIP_RUNTIME_BAD_AIX_RECORD = 1413,
// DlCaching errors
SNPE_DLCACHING_INVALID_METADATA = 1500,
SNPE_DLCACHING_INVALID_INITBLOB = 1501,
// Infrastructure Errors
SNPE_INFRA_CLUSTERMGR_INSTANCE_INVALID = 1600,
SNPE_INFRA_CLUSTERMGR_EXECUTE_SYNC_FAILED = 1601,
// Memory Errors
SNPE_MEMORY_CORRUPTION_ERROR = 1700
};
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* Returns the error code of the last error encountered.
*
* @return The error code.
*
* @note The returned error code is significant only when the return
* value of the call indicated an error.
*/
ZDL_EXPORT ErrorCode getLastErrorCode();
/**
* Returns the error string of the last error encountered.
*
* @return The error string.
*
* @note The returned error string is significant only when the return
* value of the call indicated an error.
*/
ZDL_EXPORT const char* getLastErrorString();
/**
* Returns the info string of the last error encountered.
*/
ZDL_EXPORT const char* getLastInfoString();
/**
* Returns the uint32_t representation of the error code enum.
*
* @param[in] code The error code to be converted.
*
* @return uint32_t representation of the error code.
*/
ZDL_EXPORT uint32_t enumToUInt32(zdl::DlSystem::ErrorCode code);
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
} // DlSystem
} // zdl
#endif // _DL_ERROR_HPP_
-225
View File
@@ -1,225 +0,0 @@
//==============================================================================
//
// Copyright (c) 2016, 2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#ifndef _DL_SYSTEM_OPTIONAL_HPP_
#define _DL_SYSTEM_OPTIONAL_HPP_
#include <cstdio>
#include <utility>
#include <stdexcept>
#include "DlSystem/ZdlExportDefine.hpp"
namespace zdl {
namespace DlSystem {
template <typename T>
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* Class to manage a value that may or may not exist. The boolean value
* of the Optional class is true if the object contains a value and false
* if it does not contain a value.
*
* The class must be evaluated and confirmed as true (containing a value)
* before being dereferenced.
*/
class ZDL_EXPORT Optional final {
public:
enum class LIFECYCLE {
NONE = 0,
REFERENCE_OWNED = 1,
POINTER_OWNED = 2,
POINTER_NOT_OWNED = 3
};
struct ReferenceCount {
size_t count = 0;
void increment() { count++; }
size_t decrement() {
if (count > 0) {
count--;
}
return count;
}
};
using U = typename std::remove_pointer<T>::type;
/**
* The default constructor is set to not have any value, and is
* therefore evaluated as false.
*/
// Do not explicit it so we can return {}
Optional() {
m_Type = LIFECYCLE::NONE;
}
/**
* Construct an Optional class using an object.
* @param[in] Reference to an object v
* @param[out] Optional instance of object v
*/
template <typename Q = T>
Optional (const T& v, typename std::enable_if<!std::is_pointer<Q>::value>::type* = 0)
: m_Type(LIFECYCLE::REFERENCE_OWNED) {
try {
m_StoragePtr = new T(v);
} catch (...) {
m_StoragePtr = nullptr;
m_Type = LIFECYCLE::NONE;
}
}
template <typename Q = T>
Optional(U* v, LIFECYCLE type, typename std::enable_if<std::is_pointer<Q>::value>::type* = 0)
: m_Type(type) {
switch (m_Type) {
case LIFECYCLE::POINTER_OWNED:
m_StoragePtr = v;
m_Count = new ReferenceCount();
m_Count->increment();
break;
case LIFECYCLE::POINTER_NOT_OWNED:
m_StoragePtr = v;
break;
case LIFECYCLE::REFERENCE_OWNED:
throw std::bad_exception();
case LIFECYCLE::NONE:
break;
}
}
Optional(const Optional &other) : m_Type(other.m_Type), m_Count(other.m_Count) {
if (isReference()) {
m_StoragePtr = new U(*other.m_StoragePtr);
} else if (isPointer()) {
m_StoragePtr = other.m_StoragePtr;
if (isOwned()) {
m_Count->increment();
}
}
}
Optional& operator=(const Optional& other) noexcept {
Optional tmp(other);
swap(std::move(tmp));
return *this;
}
Optional(Optional&& other) noexcept {
swap(std::move(other));
}
Optional& operator=(Optional&& other) noexcept {
swap(std::move(other));
return *this;
}
~Optional() {
if (isOwned()) {
if (isReference() || (isPointer() && m_Count->decrement() == 0)) {
delete m_StoragePtr;
delete m_Count;
}
}
}
/**
* Boolean value of Optional class is only true when there exists a value.
*/
operator bool() const noexcept { return isValid(); }
bool operator!() const noexcept { return !isValid(); }
/**
* Get reference of Optional object
* @warning User must validate Optional has value before.
*/
const T& operator*() { return this->GetReference(); }
/**
* Get reference of Optional object
* @warning User must validate Optional has value before.
*/
const T& operator*() const { return this->GetReference(); }
operator T&() { return this->GetReference(); }
T operator->() {
T self = this->GetReference();
return self;
}
private:
void swap(Optional&& other) {
m_Type = other.m_Type;
m_StoragePtr = other.m_StoragePtr;
m_Count = other.m_Count;
other.m_Type = LIFECYCLE::NONE;
other.m_StoragePtr = nullptr;
other.m_Count = nullptr;
}
template <typename Q = T>
typename std::enable_if<std::is_same<U, Q>::value, const Q&>::type GetReference() const noexcept {
if (!isReference()) std::terminate();
return *static_cast<const Q*>(m_StoragePtr);
}
template <typename Q = T>
typename std::enable_if<std::is_same<U*, Q>::value, const Q&>::type GetReference() const noexcept {
if (!isPointer()) std::terminate();
return static_cast<const Q&>(m_StoragePtr);
}
template <typename Q = T>
typename std::enable_if<std::is_same<U, Q>::value, Q&>::type GetReference() noexcept {
if (!isReference()) std::terminate();
return *m_StoragePtr;
}
template <typename Q = T>
typename std::enable_if<std::is_same<U*, Q>::value, Q&>::type GetReference() noexcept {
if (!isPointer()) std::terminate();
return m_StoragePtr;
}
bool isPointer() const {
return m_Type == LIFECYCLE::POINTER_OWNED || m_Type == LIFECYCLE::POINTER_NOT_OWNED;
}
bool isOwned() const {
return m_Type == LIFECYCLE::REFERENCE_OWNED || m_Type == LIFECYCLE::POINTER_OWNED;
}
bool isReference() const {
return m_Type == LIFECYCLE::REFERENCE_OWNED;
}
bool isValid() const {
return m_Type != LIFECYCLE::NONE;
}
U* m_StoragePtr = nullptr;
LIFECYCLE m_Type;
ReferenceCount *m_Count = nullptr;
};
} // ns DlSystem
} // ns zdl
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif // _DL_SYSTEM_OPTIONAL_HPP_
-78
View File
@@ -1,78 +0,0 @@
//==============================================================================
//
// Copyright (c) 2014-2015 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#ifndef _DL_VERSION_HPP_
#define _DL_VERSION_HPP_
#include "ZdlExportDefine.hpp"
#include <stdint.h>
#include <string>
#include "DlSystem/String.hpp"
namespace zdl {
namespace DlSystem
{
class Version_t;
}}
namespace zdl { namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* A class that contains the different portions of a version number.
*/
class ZDL_EXPORT Version_t
{
public:
/// Holds the major version number. Changes in this value indicate
/// major changes that break backward compatibility.
int32_t Major;
/// Holds the minor version number. Changes in this value indicate
/// minor changes made to library that are backwards compatible
/// (such as additions to the interface).
int32_t Minor;
/// Holds the teeny version number. Changes in this value indicate
/// changes such as bug fixes and patches made to the library that
/// do not affect the interface.
int32_t Teeny;
/// This string holds information about the build version.
///
std::string Build;
static zdl::DlSystem::Version_t fromString(const std::string &stringValue);
static zdl::DlSystem::Version_t fromString(const zdl::DlSystem::String &stringValue);
/**
* @brief Returns a string in the form Major.Minor.Teeny.Build
*
* @return A formatted string holding the version information.
*/
const std::string toString() const;
/**
* @brief Returns a string in the form Major.Minor.Teeny.Build
*
* @return A formatted string holding the version information.
*/
const zdl::DlSystem::String asString() const;
};
}}
/** @} */ /* end_addtogroup c_plus_plus_apis */
#endif
-86
View File
@@ -1,86 +0,0 @@
//==============================================================================
//
// Copyright (c) 2017-2019 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#ifndef _IBUFFER_ATTRIBUTES_HPP
#define _IBUFFER_ATTRIBUTES_HPP
#include "IUserBuffer.hpp"
#include "TensorShape.hpp"
#include "ZdlExportDefine.hpp"
namespace zdl {
namespace DlSystem {
class UserBufferEncoding;
}
}
namespace zdl {
namespace DlSystem {
/**
* @brief IBufferAttributes returns a buffer's dimension and alignment
* requirements, along with info on its encoding type
*/
class ZDL_EXPORT IBufferAttributes {
public:
/**
* @brief Gets the buffer's element size, in bytes
*
* This can be used to compute the memory size required
* to back this buffer.
*
* @return Element size, in bytes
*/
virtual size_t getElementSize() const noexcept = 0;
/**
* @brief Gets the element's encoding type
*
* @return encoding type
*/
virtual zdl::DlSystem::UserBufferEncoding::ElementType_t getEncodingType() const noexcept = 0;
/**
* @brief Gets the number of elements in each dimension
*
* @return Dimension size, in terms of number of elements
*/
virtual const TensorShape getDims() const noexcept = 0;
/**
* @brief Gets the alignment requirement of each dimension
*
* Alignment per each dimension is expressed as an multiple, for
* example, if one particular dimension can accept multiples of 8,
* the alignment will be 8.
*
* @return Alignment in each dimension, in terms of multiple of
* number of elements
*/
virtual const TensorShape getAlignments() const noexcept = 0;
/**
* @brief Gets the buffer encoding returned from the network responsible
* for generating this buffer. Depending on the encoding type, this will
* be an instance of an encoding type specific derived class.
*
* @return Derived user buffer encoding object.
*/
virtual zdl::DlSystem::UserBufferEncoding* getEncoding() const noexcept = 0;
virtual ~IBufferAttributes() {}
};
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
}
}
#endif
@@ -1,127 +0,0 @@
//=============================================================================
//
// Copyright (c) 2021-2022 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP
#define DL_SYSTEM_IOBUFFER_DATATYPE_MAP_HPP
#include <cstddef>
#include <memory>
#include "DlSystem/DlEnums.hpp"
namespace DlSystem
{
// Forward declaration of IOBufferDataTypeMapImpl implementation.
class IOBufferDataTypeMapImpl;
}
namespace zdl
{
namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* The IoBufferDataTypeMap class definition
*/
class ZDL_EXPORT IOBufferDataTypeMap final
{
public:
/**
* @brief .
*
* Creates a new Buffer Data type map
*
*/
IOBufferDataTypeMap();
/**
* @brief Adds a name and the corresponding buffer data type
* to the map
*
* @param[name] name The name of the buffer
* @param[bufferDataType] buffer Data Type of the buffer
*
* @note If a buffer with the same name already exists, no new
* buffer is added.
*/
void add(const char* name, zdl::DlSystem::IOBufferDataType_t bufferDataType);
/**
* @brief Removes a buffer name from the map
*
* @param[name] name The name of the buffer
*
*/
void remove(const char* name);
/**
* @brief Returns the type of the named buffer
*
* @param[name] name The name of the buffer
*
* @return The type of the buffer, or UNSPECIFIED if the buffer does not exist
*
*/
zdl::DlSystem::IOBufferDataType_t getBufferDataType(const char* name);
/**
* @brief Returns the type of the first buffer
*
* @return The type of the first buffer, or UNSPECIFIED if the map is empty.
*
*/
zdl::DlSystem::IOBufferDataType_t getBufferDataType();
/**
* @brief Returns the size of the buffer type map.
*
* @return The size of the map
*
*/
size_t size();
/**
* @brief Checks the existence of the named buffer in the map
*
* @return True if the named buffer exists, false otherwise.
*
*/
bool find(const char* name);
/**
* @brief Resets the map
*
*/
void clear();
/**
* @brief Checks whether the map is empty
*
* @return True if the map is empty, false otherwise.
*
*/
bool empty();
/**
* @brief Destroys the map
*
*/
~IOBufferDataTypeMap();
private:
std::shared_ptr<::DlSystem::IOBufferDataTypeMapImpl> m_IOBufferDataTypeMapImpl;
};
}
}
#endif
-146
View File
@@ -1,146 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015-2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _ITENSOR_HPP_
#define _ITENSOR_HPP_
#include "ITensorItr.hpp"
#include "ITensorItrImpl.hpp"
#include "TensorShape.hpp"
#include "ZdlExportDefine.hpp"
#include <memory>
#include <ostream>
#include <cmath>
namespace zdl {
namespace DlSystem
{
class ITensor;
}}
namespace zdl { namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* Represents a tensor which holds n-dimensional data. It is important to
* understand how the tensor data is represented in memory
* relative to the tensor dimensions. Tensors store data in
* memory in row-major order (i.e. the last tensor dimension is
* the fastest varying one). For example, if you have a two
* dimensional tensor with 3 rows and 2 columns (i.e. the tensor
* dimensions are 3,2 as returned in tensor dimension vectors)
* with the following data in terms rows and columns:
*
* | 1 2 | <br/>
* | 3 4 | <br/>
* | 5 6 | <br/>
*
* This data would be stored in memory as 1,2,3,4,5,6.
*/
class ZDL_EXPORT ITensor
{
public:
typedef zdl::DlSystem::ITensorItr<false> iterator;
typedef zdl::DlSystem::ITensorItr<true> const_iterator;
virtual ~ITensor() {}
/**
* Returns a tensor iterator pointing to the beginning
* of the data in the tensor.
*
* @return A tensor iterator that points to the first data
* element in the tensor.
*/
virtual iterator begin() = 0;
/**
* Returns the const version of a tensor iterator
* pointing to the beginning of the data in the tensor.
*
* @return A tensor const iterator that points to the first data
* element in the tensor.
*/
virtual const_iterator cbegin() const = 0;
/**
* Returns a tensor iterator pointing to the end of the
* data in the tensor. This tensor should not be
* dereferenced.
*
* @return A tensor iterator that points to the end of the data
* (one past the last element) in the tensor.
*/
virtual iterator end() = 0;
/**
* Returns the const version of a tensor iterator
* pointing to the end of the data in the tensor. This
* tensor should not be dereferenced.
*
* @return A tensor const iterator that points to the end of the
* data (one past the last element) in the tensor.
*/
virtual const_iterator cend() const = 0;
/**
* @brief Gets the shape of this tensor.
*
* The last element of the vector represents the fastest varying
* dimension and the zeroth element represents the slowest
* varying dimension, etc.
*
* @return A shape class holding the tensor dimensions.
*/
virtual TensorShape getShape() const = 0;
/**
* Returns the element size of the data in the tensor
* (discounting strides). This is how big a buffer would
* need to be to hold the tensor data contiguously in
* memory.
*
* @return The size of the tensor (in elements).
*/
virtual size_t getSize() const = 0;
/**
* @brief Serializes the tensor to an output stream.
*
* @param[in] output The output stream to which to write the tensor
*
* @throw std::runtime_error If the stream is ever in a bad
* state before the tensor is fully serialized.
*/
virtual void serialize(std::ostream &output) const = 0;
friend iterator;
friend const_iterator;
virtual bool isQuantized() {return false;}
virtual float GetDelta() {return NAN;};
virtual float GetOffset() {return NAN;};
protected:
/**
* Returns the tensor iterator implementation.
*
* @return A pointer to the tensor iterator implementation.
*/
virtual std::unique_ptr<::DlSystem::ITensorItrImpl> getItrImpl() const = 0;
};
}}
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif
-92
View File
@@ -1,92 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015-2016 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _ITENSOR_FACTORY_HPP
#define _ITENSOR_FACTORY_HPP
#include "ITensor.hpp"
#include "TensorShape.hpp"
#include "ZdlExportDefine.hpp"
#include <istream>
namespace zdl {
namespace DlSystem
{
class ITensor;
class TensorShape;
}
}
namespace zdl { namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* Factory interface class to create ITensor objects.
*/
class ZDL_EXPORT ITensorFactory
{
public:
virtual ~ITensorFactory() = default;
/**
* Creates a new ITensor with uninitialized data.
*
* The strides for the tensor will match the tensor dimensions
* (i.e., the tensor data is contiguous in memory).
*
* @param[in] shape The dimensions for the tensor in which the last
* element of the vector represents the fastest varying
* dimension and the zeroth element represents the slowest
* varying, etc.
*
* @return A pointer to the created tensor or nullptr if creating failed.
*/
virtual std::unique_ptr<ITensor>
createTensor(const TensorShape &shape) noexcept = 0;
/**
* Creates a new ITensor by loading it from a file.
*
* @param[in] input The input stream from which to read the tensor
* data.
*
* @return A pointer to the created tensor or nullptr if creating failed.
*
*/
virtual std::unique_ptr<ITensor> createTensor(std::istream &input) noexcept = 0;
/**
* Create a new ITensor with specific data.
* (i.e. the tensor data is contiguous in memory). This tensor is
* primarily used to create a tensor where tensor size can't be
* computed directly from dimension. One such example is
* NV21-formatted image, or any YUV formatted image
*
* @param[in] shape The dimensions for the tensor in which the last
* element of the vector represents the fastest varying
* dimension and the zeroth element represents the slowest
* varying, etc.
*
* @param[in] data The actual data with which the Tensor object is filled.
*
* @param[in] dataSize The size of data
*
* @return A pointer to the created tensor
*/
virtual std::unique_ptr<ITensor>
createTensor(const TensorShape &shape, const unsigned char *data, size_t dataSize) noexcept = 0;
};
}}
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif
-182
View File
@@ -1,182 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _ITENSOR_ITR_HPP_
#define _ITENSOR_ITR_HPP_
#include "ZdlExportDefine.hpp"
#include "ITensorItrImpl.hpp"
#include <memory>
#include <iterator>
#include <iostream>
namespace zdl {
namespace DlSystem
{
template<bool IS_CONST> class ITensorItr;
class ITensor;
void ZDL_EXPORT fill(ITensorItr<false> first, ITensorItr<false> end, float val);
template<class InItr, class OutItr> OutItr ZDL_EXPORT copy(InItr first, InItr last, OutItr result)
{
return std::copy(first, last, result);
}
}}
namespace DlSystem
{
class ITensorItrImpl;
}
namespace zdl { namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* A bidirectional iterator (with limited random access
* capabilities) for the zdl::DlSystem::ITensor class.
*
* This is a standard bidrectional iterator and is compatible
* with standard algorithm functions that operate on bidirectional
* access iterators (e.g., std::copy, std::fill, etc.). It uses a
* template parameter to create const and non-const iterators
* from the same code. Iterators are easiest to declare via the
* typedefs iterator and const_iterator in the ITensor class
* (e.g., zdl::DlSystem::ITensor::iterator).
*
* Note that if the tensor the iterator is traversing was
* created with nondefault (i.e., nontrivial) strides, the
* iterator will obey the strides when traversing the tensor
* data.
*
* Also note that nontrivial strides dramatically affect the
* performance of the iterator (on the order of 20x slower).
*/
template<bool IS_CONST=true>
class ZDL_EXPORT ITensorItr : public std::iterator<std::bidirectional_iterator_tag, float>
{
public:
typedef typename std::conditional<IS_CONST, const float&, float&>::type VALUE_REF;
ITensorItr() = delete;
virtual ~ITensorItr() {}
ITensorItr(std::unique_ptr<::DlSystem::ITensorItrImpl> impl,
bool isTrivial = false,
float* data = nullptr)
: m_Impl(impl->clone())
, m_IsTrivial(isTrivial)
, m_Data(data)
, m_DataStart(data) {}
ITensorItr(const ITensorItr<IS_CONST>& itr)
: m_Impl(itr.m_Impl->clone()),
m_IsTrivial(itr.m_IsTrivial),
m_Data(itr.m_Data),
m_DataStart(itr.m_DataStart) {}
zdl::DlSystem::ITensorItr<IS_CONST>& operator=(const ITensorItr<IS_CONST>& other)
{
if (this == &other) return *this;
m_Impl = std::move(other.m_Impl->clone());
m_IsTrivial = other.m_IsTrivial;
m_Data = other.m_Data;
m_DataStart = other.m_DataStart;
return *this;
}
inline zdl::DlSystem::ITensorItr<IS_CONST>& operator++()
{
if (m_IsTrivial) m_Data++; else m_Impl->increment();
return *this;
}
inline zdl::DlSystem::ITensorItr<IS_CONST> operator++(int)
{
ITensorItr tmp(*this);
operator++();
return tmp;
}
inline zdl::DlSystem::ITensorItr<IS_CONST>& operator--()
{
if (m_IsTrivial) m_Data--; else m_Impl->decrement();
return *this;
}
inline zdl::DlSystem::ITensorItr<IS_CONST> operator--(int)
{
ITensorItr tmp(*this);
operator--();
return tmp;
}
inline zdl::DlSystem::ITensorItr<IS_CONST>& operator+=(int rhs)
{
if (m_IsTrivial) m_Data += rhs; else m_Impl->increment(rhs);
return *this;
}
inline friend zdl::DlSystem::ITensorItr<IS_CONST> operator+(zdl::DlSystem::ITensorItr<IS_CONST> lhs, int rhs)
{ lhs += rhs; return lhs; }
inline zdl::DlSystem::ITensorItr<IS_CONST>& operator-=(int rhs)
{
if (m_IsTrivial) m_Data -= rhs; else m_Impl->decrement(rhs);
return *this;
}
inline friend zdl::DlSystem::ITensorItr<IS_CONST> operator-(zdl::DlSystem::ITensorItr<IS_CONST> lhs, int rhs)
{ lhs -= rhs; return lhs; }
inline size_t operator-(const zdl::DlSystem::ITensorItr<IS_CONST>& rhs)
{
if (m_IsTrivial) return (m_Data - m_DataStart) - (rhs.m_Data - rhs.m_DataStart);
return m_Impl->getPosition() - rhs.m_Impl->getPosition();
}
inline friend bool operator<(const ITensorItr<IS_CONST>& lhs, const ITensorItr<IS_CONST>& rhs)
{
if (lhs.m_IsTrivial) return lhs.m_Data < rhs.m_Data;
return lhs.m_Impl->dataPointer() < rhs.m_Impl->dataPointer();
}
inline friend bool operator>(const ITensorItr<IS_CONST>& lhs, const ITensorItr<IS_CONST>& rhs)
{ return rhs < lhs; }
inline friend bool operator<=(const ITensorItr<IS_CONST>& lhs, const ITensorItr<IS_CONST>& rhs)
{ return !(lhs > rhs); }
inline friend bool operator>=(const ITensorItr<IS_CONST>& lhs, const ITensorItr<IS_CONST>& rhs)
{ return !(lhs < rhs); }
inline bool operator==(const ITensorItr<IS_CONST>& rhs) const
{
if (m_IsTrivial) return m_Data == rhs.m_Data;
return m_Impl->dataPointer() == rhs.m_Impl->dataPointer();
}
inline bool operator!=(const ITensorItr<IS_CONST>& rhs) const
{ return !operator==(rhs); }
inline VALUE_REF operator[](size_t idx)
{
if (m_IsTrivial) return *(m_DataStart + idx);
return m_Impl->getReferenceAt(idx);
}
inline VALUE_REF operator*()
{ if (m_IsTrivial) return *m_Data; else return m_Impl->getReference(); }
inline VALUE_REF operator->()
{ return *(*this); }
inline float* dataPointer() const
{ if (m_IsTrivial) return m_Data; else return m_Impl->dataPointer(); }
protected:
std::unique_ptr<::DlSystem::ITensorItrImpl> m_Impl;
bool m_IsTrivial = false;
float* m_Data = nullptr;
float* m_DataStart = nullptr;
};
}}
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif
-42
View File
@@ -1,42 +0,0 @@
//=============================================================================
//
// Copyright (c) 2015-2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _ITENSOR_ITR_IMPL_HPP_
#define _ITENSOR_ITR_IMPL_HPP_
#include "ZdlExportDefine.hpp"
#include <memory>
#include <iterator>
namespace DlSystem
{
class ITensorItrImpl;
}
class ZDL_EXPORT DlSystem::ITensorItrImpl
{
public:
ITensorItrImpl() {}
virtual ~ITensorItrImpl() {}
virtual float getValue() const = 0;
virtual float& getReference() = 0;
virtual float& getReferenceAt(size_t idx) = 0;
virtual float* dataPointer() const = 0;
virtual void increment(int incVal = 1) = 0;
virtual void decrement(int decVal = 1) = 0;
virtual size_t getPosition() = 0;
virtual std::unique_ptr<DlSystem::ITensorItrImpl> clone() = 0;
private:
ITensorItrImpl& operator=(const ITensorItrImpl& other) = delete;
ITensorItrImpl(const ITensorItrImpl& other) = delete;
};
#endif
-105
View File
@@ -1,105 +0,0 @@
//=============================================================================
//
// Copyright (c) 2016-2021 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _DL_SYSTEM_IUDL_HPP_
#define _DL_SYSTEM_IUDL_HPP_
#include "ZdlExportDefine.hpp"
namespace zdl {
namespace DlSystem {
/**
* NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
*
* @brief .
*
* Base class user concrete UDL implementation.
*
* All functions are marked as:
*
* - virtual
* - noexcept
*
* User should make sure no exceptions are propagated outside of
* their module. Errors can be communicated via return values.
*/
class ZDL_EXPORT IUDL {
public:
/**
* NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
*
* @brief .
*
* Destructor
*/
virtual ~IUDL() = default;
/**
* NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
*
* @brief Sets up the user's environment.
* This is called by the SNPE framework to allow the user the
* opportunity to setup anything which is needed for running
* user defined layers.
*
* @param cookie User provided opaque data returned by the SNPE
* runtime
*
* @param insz How many elements in input size array
* @param indim Pointer to a buffer that holds input dimension
* array
* @param indimsz Input dimension size array of the buffer
* 'indim'. Corresponds to indim
*
* @param outsz How many elements in output size array
* @param outdim Pointer to a buffer that holds output
* dimension array
* @param outdimsz Output dimension size of the buffer 'oudim'.
* Corresponds to indim
*
* @return true on success, false otherwise
*/
virtual bool setup(void *cookie,
size_t insz, const size_t **indim, const size_t *indimsz,
size_t outsz, const size_t **outdim, const size_t *outdimsz) = 0;
/**
* NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
*
* @brief Close the instance. Invoked by the SNPE
* framework to allow the user the opportunity to release any resources
* allocated during setup.
*
* @param cookie - User provided opaque data returned by the SNPE runtime
*/
virtual void close(void *cookie) noexcept = 0;
/**
* NOTE: DEPRECATED, MAY BE REMOVED IN THE FUTURE.
*
* @brief Execute the user defined layer
*
* @param cookie User provided opaque data returned by the SNPE
* runtime
*
* @param input Const pointer to a float buffer that contains
* the input
*
* @param output Float pointer to a buffer that would hold
* the user defined layer's output. This buffer
* is allocated and owned by SNPE runtime.
*/
virtual bool execute(void *cookie, const float **input, float **output) = 0;
};
} // ns DlSystem
} // ns zdl
#endif // _DL_SYSTEM_IUDL_HPP_
-358
View File
@@ -1,358 +0,0 @@
//==============================================================================
//
// Copyright (c) 2017-2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//==============================================================================
#ifndef _IUSER_BUFFER_HPP
#define _IUSER_BUFFER_HPP
#include "TensorShape.hpp"
#include "ZdlExportDefine.hpp"
#include <math.h>
namespace zdl {
namespace DlSystem {
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* A base class buffer encoding type
*/
class ZDL_EXPORT UserBufferEncoding {
public:
/**
* @brief .
*
* An enum class of all supported element types in a IUserBuffer
*/
enum class ElementType_t
{
/// Unknown element type.
UNKNOWN = 0,
/// Each element is presented by float.
FLOAT = 1,
/// Each element is presented by an unsigned int.
UNSIGNED8BIT = 2,
/// Each element is presented by an 8-bit quantized value.
TF8 = 10,
/// Each element is presented by an 16-bit quantized value.
TF16 = 11
};
/**
* @brief Retrieves the size of the element, in bytes.
*
* @return Size of the element, in bytes.
*/
virtual size_t getElementSize() const noexcept = 0;
/**
* @brief Retrieves the element type
*
* @return Element type
*/
ElementType_t getElementType() const noexcept {return m_ElementType;};
virtual ~UserBufferEncoding() {}
protected:
UserBufferEncoding(ElementType_t elementType) : m_ElementType(elementType) {};
private:
const ElementType_t m_ElementType;
};
/**
* @brief .
*
* A base class buffer source type
*
* @note User buffer from CPU support all kinds of runtimes;
* User buffer from GLBUFFER support only GPU runtime.
*/
class ZDL_EXPORT UserBufferSource {
public:
enum class SourceType_t
{
/// Unknown buffer source type.
UNKNOWN = 0,
/// The network inputs are from CPU buffer.
CPU = 1,
/// The network inputs are from OpenGL buffer.
GLBUFFER = 2
};
/**
* @brief Retrieves the source type
*
* @return Source type
*/
SourceType_t getSourceType() const noexcept {return m_SourceType;};
protected:
UserBufferSource(SourceType_t sourceType): m_SourceType(sourceType) {};
private:
const SourceType_t m_SourceType;
};
/**
* @brief .
*
* An source type where input data is delivered from OpenGL buffer
*/
class ZDL_EXPORT UserBufferSourceGLBuffer : public UserBufferSource{
public:
UserBufferSourceGLBuffer() : UserBufferSource(SourceType_t::GLBUFFER) {};
};
/**
* @brief .
*
* An encoding type where each element is represented by an unsigned int
*/
class ZDL_EXPORT UserBufferEncodingUnsigned8Bit : public UserBufferEncoding {
public:
UserBufferEncodingUnsigned8Bit() : UserBufferEncoding(ElementType_t::UNSIGNED8BIT) {};
size_t getElementSize() const noexcept override;
protected:
UserBufferEncodingUnsigned8Bit(ElementType_t elementType) : UserBufferEncoding(elementType) {};
};
/**
* @brief .
*
* An encoding type where each element is represented by a float
*/
class ZDL_EXPORT UserBufferEncodingFloat : public UserBufferEncoding {
public:
UserBufferEncodingFloat() : UserBufferEncoding(ElementType_t::FLOAT) {};
size_t getElementSize() const noexcept override;
};
/**
* @brief .
*
* An encoding type where each element is represented by tf8, which is an
* 8-bit quantizd value, which has an exact representation of 0.0
*/
class ZDL_EXPORT UserBufferEncodingTfN : public UserBufferEncoding {
public:
UserBufferEncodingTfN() = delete;
UserBufferEncodingTfN(uint64_t stepFor0, float stepSize, uint8_t bWidth=8):
UserBufferEncoding(getTypeFromWidth(bWidth)),
bitWidth(bWidth),
m_StepExactly0(stepFor0),
m_QuantizedStepSize(stepSize){};
UserBufferEncodingTfN(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncoding(ubEncoding.getElementType()){
const zdl::DlSystem::UserBufferEncodingTfN* ubEncodingTfN
= dynamic_cast <const zdl::DlSystem::UserBufferEncodingTfN*> (&ubEncoding);
if (ubEncodingTfN) {
m_StepExactly0 = ubEncodingTfN->getStepExactly0();
m_QuantizedStepSize = ubEncodingTfN->getQuantizedStepSize();
bitWidth = ubEncodingTfN->bitWidth;
}
}
size_t getElementSize() const noexcept override;
/**
* @brief Sets the step value that represents 0
*
* @param[in] stepExactly0 The step value that represents 0
*
*/
void setStepExactly0(uint64_t stepExactly0) {
m_StepExactly0 = stepExactly0;
}
/**
* @brief Sets the float value that each step represents
*
* @param[in] quantizedStepSize The float value of each step size
*
*/
void setQuantizedStepSize(const float quantizedStepSize) {
m_QuantizedStepSize = quantizedStepSize;
}
/**
* @brief Retrieves the step that represents 0.0
*
* @return Step value
*/
uint64_t getStepExactly0() const {
return m_StepExactly0;
}
/**
* Calculates the minimum floating point value that
* can be represented with this encoding.
*
* @return Minimum representable floating point value
*/
float getMin() const {
return static_cast<float>(m_QuantizedStepSize * (0 - (double)m_StepExactly0));
}
/**
* Calculates the maximum floating point value that
* can be represented with this encoding.
*
* @return Maximum representable floating point value
*/
float getMax() const{
return static_cast<float>(m_QuantizedStepSize * (pow(2,bitWidth)-1 - (double)m_StepExactly0));
};
/**
* @brief Retrieves the step size
*
* @return Step size
*/
float getQuantizedStepSize() const {
return m_QuantizedStepSize;
}
ElementType_t getTypeFromWidth(uint8_t width);
uint8_t bitWidth;
protected:
uint64_t m_StepExactly0;
float m_QuantizedStepSize;
};
class ZDL_EXPORT UserBufferEncodingTf8 : public UserBufferEncodingTfN {
public:
UserBufferEncodingTf8() = delete;
UserBufferEncodingTf8(unsigned char stepFor0, float stepSize) :
UserBufferEncodingTfN(stepFor0, stepSize) {};
UserBufferEncodingTf8(const zdl::DlSystem::UserBufferEncoding &ubEncoding) : UserBufferEncodingTfN(ubEncoding){}
/**
* @brief Sets the step value that represents 0
*
* @param[in] stepExactly0 The step value that represents 0
*
*/
void setStepExactly0(const unsigned char stepExactly0) {
UserBufferEncodingTfN::m_StepExactly0 = stepExactly0;
}
/**
* @brief Retrieves the step that represents 0.0
*
* @return Step value
*/
unsigned char getStepExactly0() const {
return UserBufferEncodingTfN::m_StepExactly0;
}
};
/**
* @brief UserBuffer contains a pointer and info on how to walk it and interpret its content.
*/
class ZDL_EXPORT IUserBuffer {
public:
virtual ~IUserBuffer() = default;
/**
* @brief Retrieves the total number of bytes between elements in each dimension if
* the buffer were to be interpreted as a multi-dimensional array.
*
* @return Number of bytes between elements in each dimension.
* e.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would
* return strides of [24, 8, 4].
*/
virtual const TensorShape& getStrides() const = 0;
/**
* @brief Retrieves the size of the buffer, in bytes.
*
* @return Size of the underlying buffer, in bytes.
*/
virtual size_t getSize() const = 0;
/**
* @brief Retrieves the size of the inference data in the buffer, in bytes.
*
* The inference results from a dynamic-sized model may not be exactly the same size
* as the UserBuffer provided to SNPE. This function can be used to get the amount
* of output inference data, which may be less or greater than the size of the UserBuffer.
*
* If the inference results fit in the UserBuffer, getOutputSize() would be less than
* or equal to getSize(). But if the inference results were more than the capacity of
* the provided UserBuffer, the results would be truncated to fit the UserBuffer. But,
* getOutputSize() would be greater than getSize(), which indicates a bigger buffer
* needs to be provided to SNPE to hold all of the inference results.
*
* @return Size required for the buffer to hold all inference results, which can be less
* or more than the size of the buffer, in bytes.
*/
virtual size_t getOutputSize() const = 0;
/**
* @brief Changes the underlying memory that backs the UserBuffer.
*
* This can be used to avoid creating multiple UserBuffer objects
* when the only thing that differs is the memory location.
*
* @param[in] buffer Pointer to the memory location
*
* @return Whether the set succeeds.
*/
virtual bool setBufferAddress(void *buffer) noexcept = 0;
/**
* @brief Gets a const reference to the data encoding object of
* the underlying buffer
*
* This is necessary when the UserBuffer is filled by SNPE with
* data types such as TF8, where the caller needs to know the quantization
* parameters in order to interpret the data properly
*
* @return A read-only encoding object
*/
virtual const UserBufferEncoding& getEncoding() const noexcept = 0;
/**
* @brief Gets a reference to the data encoding object of
* the underlying buffer
*
* This is necessary when the UserBuffer is re-used, and the encoding
* parameters can change. For example, each input can be quantized with
* different step sizes.
*
* @return Data encoding meta-data
*/
virtual UserBufferEncoding& getEncoding() noexcept = 0;
};
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
}
}
#endif
@@ -1,81 +0,0 @@
//=============================================================================
//
// Copyright (c) 2017 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _IUSERBUFFER_FACTORY_HPP
#define _IUSERBUFFER_FACTORY_HPP
#include "IUserBuffer.hpp"
#include "TensorShape.hpp"
#include "ZdlExportDefine.hpp"
#include "DlEnums.hpp"
namespace zdl {
namespace DlSystem {
class IUserBuffer;
class TensorShape;
}
}
namespace zdl {
namespace DlSystem {
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* Factory interface class to create IUserBuffer objects.
*/
class ZDL_EXPORT IUserBufferFactory {
public:
virtual ~IUserBufferFactory() = default;
/**
* @brief Creates a UserBuffer
*
* @param[in] buffer Pointer to the buffer that the caller supplies
*
* @param[in] bufSize Buffer size, in bytes
*
* @param[in] strides Total number of bytes between elements in each dimension.
* E.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would have strides of [24, 8, 4].
*
* @param[in] userBufferEncoding Reference to an UserBufferEncoding object
*
* @note Caller has to ensure that memory pointed to by buffer stays accessible
* for the lifetime of the object created
*/
virtual std::unique_ptr<IUserBuffer>
createUserBuffer(void *buffer, size_t bufSize, const zdl::DlSystem::TensorShape &strides, zdl::DlSystem::UserBufferEncoding* userBufferEncoding) noexcept = 0;
/**
* @brief Creates a UserBuffer
*
* @param[in] buffer Pointer to the buffer that the caller supplies
*
* @param[in] bufSize Buffer size, in bytes
*
* @param[in] strides Total number of bytes between elements in each dimension.
* E.g. A tightly packed tensor of floats with dimensions [4, 3, 2] would have strides of [24, 8, 4].
*
* @param[in] userBufferEncoding Reference to an UserBufferEncoding object
*
* @param[in] userBufferSource Reference to an UserBufferSource object
*
* @note Caller has to ensure that memory pointed to by buffer stays accessible
* for the lifetime of the object created
*/
virtual std::unique_ptr<IUserBuffer>
createUserBuffer(void *buffer, size_t bufSize, const zdl::DlSystem::TensorShape &strides, zdl::DlSystem::UserBufferEncoding* userBufferEncoding, zdl::DlSystem::UserBufferSource* userBufferSource) noexcept = 0;
};
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
}
}
#endif
-230
View File
@@ -1,230 +0,0 @@
//=============================================================================
//
// Copyright (c) 2017-2018,2021 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef _DL_SYSTEM_PLATFORM_CONFIG_HPP_
#define _DL_SYSTEM_PLATFORM_CONFIG_HPP_
#include "DlSystem/ZdlExportDefine.hpp"
#include <string>
namespace zdl{
namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* A structure OpenGL configuration
*
* @note When certain OpenGL context and display are provided to UserGLConfig for using
* GPU buffer as input directly, the user MUST ensure the particular OpenGL
* context and display remain vaild throughout the execution of neural network models.
*/
struct ZDL_EXPORT UserGLConfig
{
/// Holds user EGL context.
///
void* userGLContext = nullptr;
/// Holds user EGL display.
void* userGLDisplay = nullptr;
};
/**
* @brief .
*
* A structure Gpu configuration
*/
struct ZDL_EXPORT UserGpuConfig{
/// Holds user OpenGL configuration.
///
UserGLConfig userGLConfig;
};
/**
* @brief .
*
* A class user platform configuration
*/
class ZDL_EXPORT PlatformConfig
{
public:
/**
* @brief .
*
* An enum class of all supported platform types
*/
enum class PlatformType_t
{
/// Unknown platform type.
UNKNOWN = 0,
/// Snapdragon CPU.
CPU = 1,
/// Adreno GPU.
GPU = 2,
/// Hexagon DSP.
DSP = 3
};
/**
* @brief .
*
* A union class user platform configuration information
*/
union PlatformConfigInfo
{
/// Holds user GPU Configuration.
///
UserGpuConfig userGpuConfig;
PlatformConfigInfo(){};
};
PlatformConfig() : m_PlatformType(PlatformType_t::UNKNOWN),
m_PlatformOptions("") {};
/**
* @brief Retrieves the platform type
*
* @return Platform type
*/
PlatformType_t getPlatformType() const {return m_PlatformType;};
/**
* @brief Indicates whther the plaform configuration is valid.
*
* @return True if the platform configuration is valid; false otherwise.
*/
bool isValid() const {return (PlatformType_t::UNKNOWN != m_PlatformType);};
/**
* @brief Retrieves the Gpu configuration
*
* @param[out] userGpuConfig The passed in userGpuConfig populated with the Gpu configuration on return.
*
* @return True if Gpu configuration was retrieved; false otherwise.
*/
bool getUserGpuConfig(UserGpuConfig& userGpuConfig) const
{
if(m_PlatformType == PlatformType_t::GPU)
{
userGpuConfig = m_PlatformConfigInfo.userGpuConfig;
return true;
}
else
{
return false;
}
}
/**
* @brief Sets the Gpu configuration
*
* @param[in] userGpuConfig Gpu Configuration
*
* @return True if Gpu configuration was successfully set; false otherwise.
*/
bool setUserGpuConfig(UserGpuConfig& userGpuConfig)
{
if((userGpuConfig.userGLConfig.userGLContext != nullptr) && (userGpuConfig.userGLConfig.userGLDisplay != nullptr))
{
switch (m_PlatformType)
{
case PlatformType_t::GPU:
m_PlatformConfigInfo.userGpuConfig = userGpuConfig;
return true;
case PlatformType_t::UNKNOWN:
m_PlatformType = PlatformType_t::GPU;
m_PlatformConfigInfo.userGpuConfig = userGpuConfig;
return true;
default:
return false;
}
}
else
return false;
}
/**
* @brief Sets the platform options
*
* @param[in] options Options as a string in the form of "keyword:options"
*
* @return True if options are pass validation; otherwise false. If false, the options are not updated.
*/
bool setPlatformOptions(std::string options) {
std::string oldOptions = m_PlatformOptions;
m_PlatformOptions = options;
if (isOptionsValid()) {
return true;
} else {
m_PlatformOptions = oldOptions;
return false;
}
}
/**
* @brief Indicates whther the plaform configuration is valid.
*
* @return True if the platform configuration is valid; false otherwise.
*/
bool isOptionsValid() const;
/**
* @brief Gets the platform options
*
* @return Options as a string
*/
std::string getPlatformOptions() const { return m_PlatformOptions; }
/**
* @brief Sets the platform options
*
* @param[in] optionName Name of platform options"
* @param[in] value Value of specified optionName
*
* @return If true, add "optionName:value" to platform options if optionName don't exist, otherwise update the
* value of specified optionName.
* If false, the platform options will not be changed.
*/
bool setPlatformOptionValue(const std::string& optionName, const std::string& value);
/**
* @brief Removes the platform options
*
* @param[in] optionName Name of platform options"
* @param[in] value Value of specified optionName
*
* @return If true, removed "optionName:value" to platform options if optionName don't exist, do nothing.
* If false, the platform options will not be changed.
*/
bool removePlatformOptionValue(const std::string& optionName, const std::string& value);
static void SetIsUserGLBuffer(bool isUserGLBuffer);
static bool GetIsUserGLBuffer();
private:
PlatformType_t m_PlatformType;
PlatformConfigInfo m_PlatformConfigInfo;
std::string m_PlatformOptions;
static bool m_IsUserGLBuffer;
};
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
}} //namespace end
#endif
-154
View File
@@ -1,154 +0,0 @@
//=============================================================================
//
// Copyright (c) 2019 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#include "ZdlExportDefine.hpp"
#include "DlSystem/DlEnums.hpp"
#include "DlSystem/StringList.hpp"
#include <cstddef>
#include <memory>
#ifndef DL_SYSTEM_RUNTIME_LIST_HPP
#define DL_SYSTEM_RUNTIME_LIST_HPP
namespace DlSystem
{
// Forward declaration of Runtime List implementation.
class RuntimeListImpl;
}
namespace zdl
{
namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* A class representing list of runtimes
*/
class ZDL_EXPORT RuntimeList final
{
public:
/**
* @brief .
*
* Creates a new runtime list
*
*/
RuntimeList();
/**
* @brief .
*
* copy constructor.
* @param[in] other object to copy.
*/
RuntimeList(const RuntimeList& other);
/**
* @brief .
*
* constructor with single Runtime_t object
* @param[in] Runtime_t object
*/
RuntimeList(const zdl::DlSystem::Runtime_t& runtime);
/**
* @brief .
*
* assignment operator.
*/
RuntimeList& operator=(const RuntimeList& other);
/**
* @brief .
*
* subscript operator.
*/
Runtime_t& operator[](size_t index);
/**
* @brief Adds runtime to the end of the runtime list
* order of precedence is former followed by latter entry
*
* @param[in] runtime to add
*
* Ruturns false If the runtime already exists
*/
bool add(const zdl::DlSystem::Runtime_t& runtime);
/**
* @brief Removes the runtime from the list
*
* @param[in] runtime to be removed
*
* @note If the runtime is not found, nothing is done.
*/
void remove(const zdl::DlSystem::Runtime_t runtime) noexcept;
/**
* @brief Returns the number of runtimes in the list
*/
size_t size() const noexcept;
/**
* @brief Returns true if the list is empty
*/
bool empty() const noexcept;
/**
* @brief .
*
* Removes all runtime from the list
*/
void clear() noexcept;
/**
* @brief .
*
* Returns a StringList of names from the runtime list in
* order of precedence
*/
zdl::DlSystem::StringList getRuntimeListNames() const;
/**
* @brief .
*
* @param[in] runtime string
* Returns a Runtime enum corresponding to the in param string
*
*/
static zdl::DlSystem::Runtime_t stringToRuntime(const char* runtimeStr);
/**
* @brief .
*
* @param[in] runtime
* Returns a string corresponding to the in param runtime enum
*
*/
static const char* runtimeToString(const zdl::DlSystem::Runtime_t runtime);
~RuntimeList();
private:
void deepCopy(const RuntimeList &other);
std::unique_ptr<::DlSystem::RuntimeListImpl> m_RuntimeListImpl;
};
} // DlSystem namespace
} // zdl namespace
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif // DL_SYSTEM_RUNTIME_LIST_HPP
-104
View File
@@ -1,104 +0,0 @@
//=============================================================================
//
// Copyright (c) 2017, 2020 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#ifndef PLATFORM_STANDARD_STRING_HPP
#define PLATFORM_STANDARD_STRING_HPP
#include <cstdio>
#include <string>
#include <ostream>
#include "DlSystem/ZdlExportDefine.hpp"
namespace zdl
{
namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* Class for wrapping char * as a really stripped down std::string replacement.
*/
class ZDL_EXPORT String final
{
public:
String() = delete;
/**
* Construct a string from std::string reference.
* @param str Reference to a std::string
*/
explicit String(const std::string& str);
/**
* Construct a string from char* reference.
* @param a char*
*/
explicit String(const char* str);
/**
* move constructor.
*/
String(String&& other) noexcept;
/**
* copy constructor.
*/
String(const String& other) = delete;
/**
* assignment operator.
*/
String& operator=(const String&) = delete;
/**
* move assignment operator.
*/
String& operator=(String&&) = delete;
/**
* class comparators
*/
bool operator<(const String& rhs) const noexcept;
bool operator>(const String& rhs) const noexcept;
bool operator<=(const String& rhs) const noexcept;
bool operator>=(const String& rhs) const noexcept;
bool operator==(const String& rhs) const noexcept;
bool operator!=(const String& rhs) const noexcept;
/**
* class comparators against std::string
*/
bool operator<(const std::string& rhs) const noexcept;
bool operator>(const std::string& rhs) const noexcept;
bool operator<=(const std::string& rhs) const noexcept;
bool operator>=(const std::string& rhs) const noexcept;
bool operator==(const std::string& rhs) const noexcept;
bool operator!=(const std::string& rhs) const noexcept;
const char* c_str() const noexcept;
~String();
private:
char* m_string;
};
/**
* overloaded << operator
*/
ZDL_EXPORT std::ostream& operator<<(std::ostream& os, const String& str) noexcept;
} // DlSystem namespace
} // zdl namespace
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif // PLATFORM_STANDARD_STRING_HPP
-107
View File
@@ -1,107 +0,0 @@
//=============================================================================
//
// Copyright (c) 2016 Qualcomm Technologies, Inc.
// All Rights Reserved.
// Confidential and Proprietary - Qualcomm Technologies, Inc.
//
//=============================================================================
#include <cstdio>
#include "ZdlExportDefine.hpp"
#ifndef DL_SYSTEM_STRINGLIST_HPP
#define DL_SYSTEM_STRINGLIST_HPP
namespace zdl
{
namespace DlSystem
{
/** @addtogroup c_plus_plus_apis C++
@{ */
/**
* @brief .
*
* Class for holding an order list of null-terminated ASCII strings.
*/
class ZDL_EXPORT StringList final
{
public:
StringList() {}
/**
* Construct a string list with some pre-allocated memory.
* @warning Contents of the list will be uninitialized
* @param[in] length Number of elements for which to pre-allocate space.
*/
explicit StringList(size_t length);
/**
* Append a string to the list.
* @param[in] str Null-terminated ASCII string to append to the list.
*/
void append(const char* str);
/**
* Returns the string at the indicated position,
* or an empty string if the positions is greater than the size
* of the list.
* @param[in] idx Position in the list of the desired string
*/
const char* at(size_t idx) const noexcept;
/**
* Pointer to the first string in the list.
* Can be used to iterate through the list.
*/
const char** begin() const noexcept;
/**
* Pointer to one after the last string in the list.
* Can be used to iterate through the list.
*/
const char** end() const noexcept;
/**
* Return the number of valid string pointers held by this list.
*/
size_t size() const noexcept;
/**
* assignment operator.
*/
StringList& operator=(const StringList&) noexcept;
/**
* copy constructor.
* @param[in] other object to copy.
*/
StringList(const StringList& other);
/**
* move constructor.
* @param[in] other object to move.
*/
StringList(StringList&& other) noexcept;
~StringList();
private:
void copy(const StringList& other);
void resize(size_t length);
void clear();
static const char* s_Empty;
const char** m_Strings = nullptr;
const char** m_End = nullptr;
size_t m_Size = 0;
};
} // DlSystem namespace
} // zdl namespace
/** @} */ /* end_addtogroup c_plus_plus_apis C++ */
#endif // DL_SYSTEM_STRINGLIST_HPP

Some files were not shown because too many files have changed in this diff Show More