sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/ripemd.py
# Copyright (c) 2022 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module for RIPEMD algorithm.""" # Imports from typing import Union from Crypto.Hash import RIPEMD160 from ..misc import AlgoUtils class Ripemd160: """ RIPEMD160 class. It computes digests using RIPEMD160 algorithm. """ @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ return RIPEMD160.new(AlgoUtils.Encode(data)).digest() @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return RIPEMD160.digest_size
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/crypto/ripemd.py", "license": "MIT License", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/scrypt.py
# Copyright (c) 2022 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module for Scrypt algorithm.""" # Imports from typing import Union from Crypto.Protocol.KDF import scrypt from ..misc import AlgoUtils class Scrypt: """ Scrypt class. It derives key using Scrypt algorithm. """ @staticmethod def DeriveKey(password: Union[bytes, str], # pylint: disable=too-many-arguments salt: Union[bytes, str], key_len: int, n: int, r: int, p: int) -> bytes: """ Derive a key. Args: password (str or bytes): Password salt (str or bytes) : Salt key_len (int) : Length of the derived key n (int) : CPU/Memory cost parameter r (int) : Block size parameter p (int) : Parallelization parameter Returns: bytes: Computed result """ # Type for password and salt should be Union[bytes, str] in pycryptodome, but it's only str # So, we ignore the mypy warning return scrypt(AlgoUtils.Encode(password), # type: ignore [arg-type, return-value] AlgoUtils.Encode(salt), # type: ignore [arg-type] key_len=key_len, N=n, r=r, p=p)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/crypto/scrypt.py", "license": "MIT License", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/sha2.py
# Copyright (c) 2022 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module for SHA-2 algorithms.""" # Imports import hashlib from typing import Any, Union from Crypto.Hash import SHA512 from ..misc import AlgoUtils HASHLIB_USE_SHA512_256: bool = "sha512_256" in hashlib.algorithms_available class Sha256: """ SHA256 class. It computes digests using SHA256 algorithm. """ handle: Any def __init__(self) -> None: """Construct class.""" self.handle = hashlib.sha256() def Update(self, data_bytes: bytes) -> None: """ Update digest. Args: data_bytes (bytes): Data bytes """ self.handle.update(data_bytes) def Digest(self) -> bytes: """ Get the computed digest. Returns: bytes: Computed digest """ return self.handle.digest() @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ return hashlib.sha256(AlgoUtils.Encode(data)).digest() @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return hashlib.sha256().digest_size class DoubleSha256: """ Double SHA256 class. It computes digests using SHA256 algorithm twice. """ @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ return Sha256.QuickDigest(Sha256.QuickDigest(data)) @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return Sha256.DigestSize() class Sha512: """ SHA512 class. It computes digests using SHA512 algorithm. """ @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ return hashlib.sha512(AlgoUtils.Encode(data)).digest() @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return hashlib.sha512().digest_size class Sha512_256: # noqa: N801 """ SHA512/256 class. It computes digests using SHA512/256 algorithm. """ @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ if HASHLIB_USE_SHA512_256: return hashlib.new("sha512_256", AlgoUtils.Encode(data)).digest() # Use Cryptodome if not implemented in hashlib return SHA512.new(AlgoUtils.Encode(data), truncate="256").digest() @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return (hashlib.new("sha512_256").digest_size if HASHLIB_USE_SHA512_256 else SHA512.new(truncate="256").digest_size)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/crypto/sha2.py", "license": "MIT License", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/crypto/sha3.py
# Copyright (c) 2022 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module for SHA-3 algorithms.""" # Imports import hashlib from typing import Union from Crypto.Hash import SHA3_256, keccak from ..misc import AlgoUtils HASHLIB_USE_SHA3_256: bool = "sha3_256" in hashlib.algorithms_available class Kekkak256: """ Kekkak-256 class. It computes digests using Kekkak-256 algorithm. """ @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ return keccak.new(data=AlgoUtils.Encode(data), digest_bits=256).digest() @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return (hashlib.new("sha3_256").digest_size if HASHLIB_USE_SHA3_256 else keccak.new(digest_bits=256).digest_size) class Sha3_256: # noqa: N801 """ SHA3-256 class. It computes digests using SHA3-256 algorithm. """ @staticmethod def QuickDigest(data: Union[bytes, str]) -> bytes: """ Compute the digest (quick version). Args: data (str or bytes): Data Returns: bytes: Computed digest """ if HASHLIB_USE_SHA3_256: return hashlib.new("sha3_256", AlgoUtils.Encode(data)).digest() # Use Cryptodome if not implemented in hashlib return SHA3_256.new(AlgoUtils.Encode(data)).digest() @staticmethod def DigestSize() -> int: """ Get the digest size in bytes. Returns: int: Digest size in bytes """ return (hashlib.new("sha3_256").digest_size if HASHLIB_USE_SHA3_256 else SHA3_256.digest_size)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/crypto/sha3.py", "license": "MIT License", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/algo.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with some algorithm utility functions.""" # Imports from bisect import bisect_left from typing import Any, List, Union class AlgoUtils: """Class container for algorithm utility functions.""" @staticmethod def BinarySearch(arr: List, elem: Any) -> int: """ Binary search algorithm simply implemented by using the bisect library. Args: arr (list): list of elements elem (any): element to be searched Returns: int: First index of the element, -1 if not found """ invalid_idx = -1 i = bisect_left(arr, elem) if i != len(arr) and arr[i] == elem: return i return invalid_idx @staticmethod def Decode(data: Union[bytes, str], encoding: str = "utf-8") -> str: """ Decode from bytes. Args: data (str or bytes): Data encoding (str) : Encoding type Returns: str: String encoded to bytes Raises: TypeError: If the data is neither string nor bytes """ if isinstance(data, str): return data if isinstance(data, bytes): return data.decode(encoding) raise TypeError("Invalid data type") @staticmethod def Encode(data: Union[bytes, str], encoding: str = "utf-8") -> bytes: """ Encode to bytes. Args: data (str or bytes): Data encoding (str) : Encoding type Returns: bytes: String encoded to bytes Raises: TypeError: If the data is neither string nor bytes """ if isinstance(data, str): return data.encode(encoding) if isinstance(data, bytes): return data raise TypeError("Invalid data type") @staticmethod def IsStringMixed(data_str: str) -> bool: """ Get if the specified string is in mixed case. Args: data_str (str): string Returns: bool: True if mixed case, false otherwise """ return any(c.islower() for c in data_str) and any(c.isupper() for c in data_str)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/algo.py", "license": "MIT License", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/base32.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with helper class for Base32.""" # Imports import base64 import binascii from typing import Optional, Union from .algo import AlgoUtils class Base32Const: """Class container for Base32 constants.""" # Alphabet ALPHABET: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" # Padding character PADDING_CHAR: str = "=" class _Base32Utils: """ Base32 utility class. It provides some helper methods for decoding/encoding Base32 format. """ @staticmethod def AddPadding(data: str) -> str: """ Add padding to an encoded Base32 string. Used if the string was encoded with Base32Encoder.EncodeNoPadding Args: data (str): Data Returns: str: Padded string """ last_block_width = len(data) % 8 if last_block_width != 0: data += (8 - last_block_width) * Base32Const.PADDING_CHAR return data @staticmethod def TranslateAlphabet(data: str, from_alphabet: str, to_alphabet: str) -> str: """ Translate the standard Base32 alphabet to a custom one. Args: data (str) : Data from_alphabet (str): Starting alphabet string to_alphabet (str) : Final alphabet string Returns: str: String with translated alphabet """ return data.translate(str.maketrans(from_alphabet, to_alphabet)) class Base32Decoder: """ Base32 decoder class. It provides methods for decoding to Base32 format. """ @staticmethod def Decode(data: str, custom_alphabet: Optional[str] = None) -> bytes: """ Decode from Base32. Args: data (str) : Data custom_alphabet (str, optional): Custom alphabet string Returns: bytes: Decoded bytes Raises: ValueError: If the Base32 string is not valid """ try: data_dec = _Base32Utils.AddPadding(data) if custom_alphabet is not None: data_dec = _Base32Utils.TranslateAlphabet(data_dec, custom_alphabet, Base32Const.ALPHABET) return base64.b32decode(data_dec) except binascii.Error as ex: raise ValueError("Invalid Base32 string") from ex class Base32Encoder: """ Base32 encoder class. It provides methods for encoding to Base32 format. """ @staticmethod def Encode(data: Union[bytes, str], custom_alphabet: Optional[str] = None) -> str: """ Encode to Base32. Args: data (str or bytes) : Data custom_alphabet (str, optional): Custom alphabet string Returns: str: Encoded string """ b32_enc = AlgoUtils.Decode(base64.b32encode(AlgoUtils.Encode(data))) if custom_alphabet is not None: b32_enc = _Base32Utils.TranslateAlphabet(b32_enc, Base32Const.ALPHABET, custom_alphabet) return b32_enc @staticmethod def EncodeNoPadding(data: Union[bytes, str], custom_alphabet: Optional[str] = None) -> str: """ Encode to Base32 by removing the final padding. Args: data (str or bytes) : Data custom_alphabet (str, optional): Custom alphabet string Returns: str: Encoded string """ return Base32Encoder.Encode(data, custom_alphabet).rstrip(Base32Const.PADDING_CHAR)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/base32.py", "license": "MIT License", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/bit.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with some bits utility functions.""" class BitUtils: """Class container for bit utility functions.""" @staticmethod def IsBitSet(value: int, bit_num: int) -> bool: """ Get if the specified bit is set. Args: value (int) : Value bit_num (int): Bit number to check Returns: bool: True if bit is set, false otherwise """ return (value & (1 << bit_num)) != 0 @staticmethod def AreBitsSet(value: int, bit_mask: int) -> bool: """ Get if the specified bits are set. Args: value (int) : Value bit_mask (int): Bit mask to check Returns: bool: True if bit is set, false otherwise """ return (value & bit_mask) != 0 @staticmethod def SetBit(value: int, bit_num: int) -> int: """ Set the specified bit. Args: value (int) : Value bit_num (int): Bit number to set Returns: int: Value with the specified bit set """ return value | (1 << bit_num) @staticmethod def SetBits(value: int, bit_mask: int) -> int: """ Set the specified bits. Args: value (int) : Value bit_mask (int): Bit mask to set Returns: int: Value with the specified bit set """ return value | bit_mask @staticmethod def ResetBit(value: int, bit_num: int) -> int: """ Reset the specified bit. Args: value (int) : Value bit_num (int): Bit number to reset Returns: int: Value with the specified bit reset """ return value & ~(1 << bit_num) @staticmethod def ResetBits(value: int, bit_mask: int) -> int: """ Reset the specified bits. Args: value (int) : Value bit_mask (int): Bit mask to reset Returns: int: Value with the specified bit reset """ return value & ~bit_mask
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/bit.py", "license": "MIT License", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/bytes.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with some bytes utility functions.""" # Imports import binascii from typing import List, Union from .algo import AlgoUtils from .integer import IntegerUtils from ..typing import Literal class BytesUtils: """Class container for bytes utility functions.""" @staticmethod def Reverse(data_bytes: bytes) -> bytes: """ Reverse the specified bytes. Args: data_bytes (bytes): Data bytes Returns: bytes: Original bytes in the reverse order """ tmp = bytearray(data_bytes) tmp.reverse() return bytes(tmp) @staticmethod def Xor(data_bytes_1: bytes, data_bytes_2: bytes) -> bytes: """ XOR the specified bytes. Args: data_bytes_1 (bytes): Data bytes 1 data_bytes_2 (bytes): Data bytes 2 Returns: bytes: XORed bytes """ return bytes( [b1 ^ b2 for b1, b2 in zip(data_bytes_1, data_bytes_2)] ) @staticmethod def AddNoCarry(data_bytes_1: bytes, data_bytes_2: bytes) -> bytes: """ Add the specified bytes (byte-by-byte, no carry). Args: data_bytes_1 (bytes): Data bytes 1 data_bytes_2 (bytes): Data bytes 2 Returns: bytes: XORed bytes """ return bytes( [(b1 + b2) & 0xFF for b1, b2 in zip(data_bytes_1, data_bytes_2)] ) @staticmethod def MultiplyScalarNoCarry(data_bytes: bytes, scalar: int) -> bytes: """ Multiply the specified bytes with the specified scalar (byte-by-byte, no carry). Args: data_bytes (bytes): Data bytes scalar (int) : Scalar Returns: bytes: XORed bytes """ return bytes( [(b * scalar) & 0xFF for b in data_bytes] ) @staticmethod def ToBinaryStr(data_bytes: bytes, zero_pad_bit_len: int = 0) -> str: """ Convert the specified bytes to a binary string. Args: data_bytes (bytes) : Data bytes zero_pad_bit_len (int, optional): Zero pad length in bits, 0 if not specified Returns: str: Binary string """ return IntegerUtils.ToBinaryStr(BytesUtils.ToInteger(data_bytes), zero_pad_bit_len) @staticmethod def ToInteger(data_bytes: bytes, endianness: Literal["little", "big"] = "big", signed: bool = False) -> int: """ Convert the specified bytes to integer. Args: data_bytes (bytes) : Data bytes endianness ("big" or "little", optional): Endianness (default: big) signed (bool, optional) : True if signed, false otherwise (default: false) Returns: int: Integer representation """ return int.from_bytes(data_bytes, byteorder=endianness, signed=signed) @staticmethod def FromBinaryStr(data: Union[bytes, str], zero_pad_byte_len: int = 0) -> bytes: """ Convert the specified binary string to bytes. Args: data (str or bytes) : Data zero_pad_byte_len (int, optional): Zero pad length in bytes, 0 if not specified Returns: bytes: Bytes representation """ return binascii.unhexlify(hex(IntegerUtils.FromBinaryStr(data))[2:].zfill(zero_pad_byte_len)) @staticmethod def ToHexString(data_bytes: bytes, encoding: str = "utf-8") -> str: """ Convert bytes to hex string. Args: data_bytes (bytes) : Data bytes encoding (str, optional): Encoding type, utf-8 by default Returns: str: Bytes converted to hex string """ return AlgoUtils.Decode(binascii.hexlify(data_bytes), encoding) @staticmethod def FromHexString(data: Union[bytes, str]) -> bytes: """ Convert hex string to bytes. Args: data (str or bytes): Data bytes Returns bytes: Hex string converted to bytes """ return binascii.unhexlify(AlgoUtils.Encode(data)) @staticmethod def FromList(data_list: List[int]) -> bytes: """ Convert the specified list of integers to bytes. Args: data_list (list[int]): List of integers Returns: bytes: Bytes representation """ return bytes(data_list) @staticmethod def ToList(data_bytes: bytes) -> List[int]: """ Convert the specified bytes to a list of integers. Args: data_bytes (bytes): Data bytes Returns: list[int]: List of integers """ return list(data_bytes)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/bytes.py", "license": "MIT License", "lines": 162, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/data_bytes.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with helper class for data bytes.""" # Imports from typing import Iterator from .bytes import BytesUtils from ..typing import Literal class DataBytes: """ Data bytes class. It allows to get bytes in different formats. """ m_data_bytes: bytes def __init__(self, data_bytes: bytes) -> None: """ Construct class. Args: data_bytes (bytes): Data bytes """ self.m_data_bytes = data_bytes def Length(self) -> int: """ Get length in bytes. Returns: int: Length in bytes """ return len(self.m_data_bytes) def Size(self) -> int: """ Get length in bytes (same of Length()). Returns: int: Length in bytes """ return self.Length() def ToBytes(self) -> bytes: """ Get data bytes. Returns: bytes: Data bytes """ return self.m_data_bytes def ToHex(self) -> str: """ Get data bytes in hex format. Returns: str: Data bytes in hex format """ return BytesUtils.ToHexString(self.m_data_bytes) def ToInt(self, endianness: Literal["little", "big"] = "big") -> int: """ Get data bytes as an integer. Args: endianness ("big" or "little", optional): Endianness (default: big) Returns: int: Data bytes as an integer """ return BytesUtils.ToInteger(self.m_data_bytes, endianness) def __len__(self) -> int: """ Get length in bytes. Returns: int: Length in bytes """ return self.Length() def __bytes__(self) -> bytes: """ Get data bytes. Returns: bytes: Data bytes """ return self.ToBytes() def __int__(self) -> int: """ Get data bytes as integer. Returns: bytes: Data bytes as integer """ return self.ToInt() def __repr__(self) -> str: """ Get data bytes representation. Returns: str: Data bytes representation """ return self.ToHex() def __getitem__(self, idx: int) -> int: """ Get the element with the specified index. Args: idx (int): Index Returns: int: Element Raises: IndexError: If the index is not valid """ return self.m_data_bytes[idx] def __iter__(self) -> Iterator[int]: """ Get the iterator to the current element. Returns: Iterator object: Iterator to the current element """ yield from self.m_data_bytes def __eq__(self, other: object) -> bool: """ Equality operator. Args: other (bytes, str, int or DataBytes object): Other object to compare Returns: bool: True if equal false otherwise Raises: TypeError: If the other object is not of the correct type """ if not isinstance(other, (bytes, int, str, DataBytes)): raise TypeError(f"Invalid type for checking equality ({type(other)})") if isinstance(other, bytes): return other == bytes(self) if isinstance(other, int): return other == int(self) if isinstance(other, str): return other == str(self) return bytes(other) == bytes(self)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/data_bytes.py", "license": "MIT License", "lines": 143, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/integer.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with some integer utility functions.""" # Imports from typing import Optional, Union from .algo import AlgoUtils from ..typing import Literal class IntegerUtils: """Class container for integer utility functions.""" @staticmethod def GetBytesNumber(data_int: int) -> int: """ Get the number of bytes of the specified integer. Args: data_int (int): Data integer Returns: int: Number of bytes """ return ((data_int.bit_length() if data_int > 0 else 1) + 7) // 8 @staticmethod def ToBytes(data_int: int, bytes_num: Optional[int] = None, endianness: Literal["little", "big"] = "big", signed: bool = False) -> bytes: """ Convert integer to bytes. Args: data_int (int) : Data integer bytes_num (int, optional) : Number of bytes, automatic if None endianness ("big" or "little", optional): Endianness (default: big) signed (bool, optional) : True if signed, false otherwise (default: false) Returns: bytes: Bytes representation """ # In case gmpy is used if data_int.__class__.__name__ == "mpz": data_int = int(data_int) bytes_num = bytes_num or IntegerUtils.GetBytesNumber(data_int) return data_int.to_bytes(bytes_num, byteorder=endianness, signed=signed) @staticmethod def FromBinaryStr(data: Union[bytes, str]) -> int: """ Convert the specified binary string to integer. Args: data (str or bytes): Data Returns: int: Integer representation """ return int(AlgoUtils.Encode(data), 2) @staticmethod def ToBinaryStr(data_int: int, zero_pad_bit_len: int = 0) -> str: """ Convert the specified integer to a binary string. Args: data_int (int) : Data integer zero_pad_bit_len (int, optional): Zero pad length in bits, 0 if not specified Returns: str: Binary string """ return bin(data_int)[2:].zfill(zero_pad_bit_len)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/integer.py", "license": "MIT License", "lines": 78, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/misc/string.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with some string utility functions.""" # Imports import unicodedata class StringUtils: """Class container for string utility functions.""" @staticmethod def NormalizeNfc(data_str: str) -> str: """ Normalize string using NFC. Args: data_str (str): Input string Returns: str: Normalized string """ return unicodedata.normalize("NFC", data_str) @staticmethod def NormalizeNfkd(data_str: str) -> str: """ Normalize string using NFKD. Args: data_str (str): Input string Returns: str: Normalized string """ return unicodedata.normalize("NFKD", data_str)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/misc/string.py", "license": "MIT License", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/utils/typing/literal.py
# Copyright (c) 2022 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module with Literal type definition.""" try: from typing import Literal # pylint: disable=unused-import except ImportError: # Literal not supported by Python 3.7 from typing_extensions import Literal # type: ignore # noqa: F401
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/utils/typing/literal.py", "license": "MIT License", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/bip/wif/wif.py
# Copyright (c) 2021 Emanuele Bellocchia # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Module for WIF encoding/decoding.""" # Imports from typing import Tuple, Union from ..addr import P2PKHPubKeyModes from ..base58 import Base58Decoder, Base58Encoder from ..coin_conf import CoinsConf from ..ecc import IPrivateKey, Secp256k1PrivateKey from ..utils.misc import BytesUtils # Alias for P2PKHPubKeyModes WifPubKeyModes = P2PKHPubKeyModes class WifConst: """Class container for WIF constants.""" # Suffix to be added if the private key correspond to a compressed public key COMPR_PUB_KEY_SUFFIX: bytes = b"\x01" class WifEncoder: """ WIF encoder class. It provides methods for encoding to WIF format. """ @staticmethod def Encode(priv_key: Union[bytes, IPrivateKey], net_ver: bytes = CoinsConf.BitcoinMainNet.ParamByKey("wif_net_ver"), pub_key_mode: WifPubKeyModes = WifPubKeyModes.COMPRESSED) -> str: """ Encode key bytes into a WIF string. Args: priv_key (bytes or IPrivateKey) : Private key bytes or object net_ver (bytes, optional) : Net version (Bitcoin main net by default) pub_key_mode (WifPubKeyModes, optional): Specify if the private key corresponds to a compressed public key Returns: str: WIF encoded string Raises: TypeError: If pub_key_mode is not a WifPubKeyModes enum or the private key is not a valid Secp256k1PrivateKey ValueError: If the key is not valid """ if not isinstance(pub_key_mode, WifPubKeyModes): raise TypeError("Public key mode is not an enumerative of WifPubKeyModes") # Convert to private key to check if bytes are valid if isinstance(priv_key, bytes): priv_key = Secp256k1PrivateKey.FromBytes(priv_key) elif not isinstance(priv_key, Secp256k1PrivateKey): raise TypeError("A secp256k1 private key is required") priv_key = priv_key.Raw().ToBytes() # Add suffix if correspond to a compressed public key if pub_key_mode == WifPubKeyModes.COMPRESSED: priv_key += WifConst.COMPR_PUB_KEY_SUFFIX # Add net address version priv_key = net_ver + priv_key # Encode key return Base58Encoder.CheckEncode(priv_key) class WifDecoder: """ WIF encoder class. It provides methods for encoding to WIF format. """ @staticmethod def Decode(wif_str: str, net_ver: bytes = CoinsConf.BitcoinMainNet.ParamByKey("wif_net_ver")) -> Tuple[bytes, WifPubKeyModes]: """ Decode key bytes from a WIF string. Args: wif_str (str) : WIF string net_ver (bytes, optional): Net version (Bitcoin main net by default) Returns: tuple[bytes, WifPubKeyModes]: Key bytes (index 0), public key mode (index 1) Raises: Base58ChecksumError: If the base58 checksum is not valid ValueError: If the resulting key is not valid """ # Decode string priv_key_bytes = Base58Decoder.CheckDecode(wif_str) # Check net version if priv_key_bytes[0] != ord(net_ver): raise ValueError( f"Invalid net version (expected 0x{ord(net_ver):02X}, got 0x{priv_key_bytes[0]:02X})" ) # Remove net version priv_key_bytes = priv_key_bytes[1:] # Remove suffix if correspond to a compressed public key if Secp256k1PrivateKey.IsValidBytes(priv_key_bytes[:-1]): # Check the compressed public key suffix if priv_key_bytes[-1] != ord(WifConst.COMPR_PUB_KEY_SUFFIX): raise ValueError( f"Invalid compressed public key suffix (expected 0x{ord(WifConst.COMPR_PUB_KEY_SUFFIX):02X}, " f"got 0x{priv_key_bytes[-1]:02X})" ) # Remove it priv_key_bytes = priv_key_bytes[:-1] pub_key_mode = WifPubKeyModes.COMPRESSED else: if not Secp256k1PrivateKey.IsValidBytes(priv_key_bytes): raise ValueError(f"Invalid decoded key ({BytesUtils.ToHexString(priv_key_bytes)})") pub_key_mode = WifPubKeyModes.UNCOMPRESSED return priv_key_bytes, pub_key_mode
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/bip/wif/wif.py", "license": "MIT License", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:python/ccxt/static_dependencies/dydx_v4_client/registry.py
from google.protobuf.json_format import ParseDict from google.protobuf.any_pb2 import Any from .dydxprotocol.sending.transfer_pb2 import ( MsgDepositToSubaccount, MsgWithdrawFromSubaccount, ) from .dydxprotocol.sending.tx_pb2 import MsgCreateTransfer from .dydxprotocol.clob.tx_pb2 import ( MsgPlaceOrder, MsgCancelOrder, MsgBatchCancel, ) from .dydxprotocol.accountplus.tx_pb2 import TxExtension from .cosmos.crypto.secp256k1.keys_pb2 import PubKey registry = { '/dydxprotocol.clob.MsgPlaceOrder': MsgPlaceOrder, '/dydxprotocol.clob.MsgCancelOrder': MsgCancelOrder, '/dydxprotocol.clob.MsgBatchCancel': MsgBatchCancel, '/dydxprotocol.sending.MsgCreateTransfer': MsgCreateTransfer, '/dydxprotocol.sending.MsgWithdrawFromSubaccount': MsgWithdrawFromSubaccount, '/dydxprotocol.sending.MsgDepositToSubaccount': MsgDepositToSubaccount, '/dydxprotocol.accountplus.TxExtension': TxExtension, '/cosmos.crypto.secp256k1.PubKey': PubKey, } def encode_as_any(encodeObject): typeUrl = encodeObject['typeUrl'] value = encodeObject['value'] t = registry[typeUrl] message = ParseDict(value, t()) packed = Any( type_url=typeUrl, value=message.SerializeToString() ) return packed
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/dydx_v4_client/registry.py", "license": "MIT License", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
ccxt/ccxt:python/ccxt/static_dependencies/mnemonic/mnemonic.py
# # Copyright (c) 2013 Pavol Rusnak # Copyright (c) 2017 mruddy # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is furnished to do # so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # from __future__ import annotations import hashlib import hmac import itertools import os import secrets import typing as t import unicodedata PBKDF2_ROUNDS = 2048 class ConfigurationError(Exception): pass # Refactored code segments from <https://github.com/keis/base58> def b58encode(v: bytes) -> str: alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" p, acc = 1, 0 for c in reversed(v): acc += p * c p = p << 8 string = "" while acc: acc, idx = divmod(acc, 58) string = alphabet[idx : idx + 1] + string return string class Mnemonic(object): def __init__(self, language: str = "english", wordlist: list[str] | None = None): self.radix = 2048 self.language = language if wordlist is None: d = os.path.join(os.path.dirname(__file__), f"wordlist/{language}.txt") if os.path.exists(d) and os.path.isfile(d): with open(d, "r", encoding="utf-8") as f: wordlist = [w.strip() for w in f.readlines()] else: raise ConfigurationError("Language not detected") if len(wordlist) != self.radix: raise ConfigurationError(f"Wordlist must contain {self.radix} words.") self.wordlist = wordlist # Japanese must be joined by ideographic space self.delimiter = "\u3000" if language == "japanese" else " " @classmethod def list_languages(cls) -> list[str]: return [ f.split(".")[0] for f in os.listdir(os.path.join(os.path.dirname(__file__), "wordlist")) if f.endswith(".txt") ] @staticmethod def normalize_string(txt: t.AnyStr) -> str: if isinstance(txt, bytes): utxt = txt.decode("utf8") elif isinstance(txt, str): utxt = txt else: raise TypeError("String value expected") return unicodedata.normalize("NFKD", utxt) @classmethod def detect_language(cls, code: str) -> str: """Scan the Mnemonic until the language becomes unambiguous, including as abbreviation prefixes. Unfortunately, there are valid words that are ambiguous between languages, which are complete words in one language and are prefixes in another: english: abandon ... about french: abandon ... aboutir If prefixes remain ambiguous, require exactly one language where word(s) match exactly. """ code = cls.normalize_string(code) possible = set(cls(lang) for lang in cls.list_languages()) words = set(code.split()) for word in words: # possible languages have candidate(s) starting with the word/prefix possible = set( p for p in possible if any(c.startswith(word) for c in p.wordlist) ) if not possible: raise ConfigurationError(f"Language unrecognized for {word!r}") if len(possible) == 1: return possible.pop().language # Multiple languages match: A prefix in many, but an exact match in one determines language. complete = set() for word in words: exact = set(p for p in possible if word in p.wordlist) if len(exact) == 1: complete.update(exact) if len(complete) == 1: return complete.pop().language raise ConfigurationError( f"Language ambiguous between {', '.join(p.language for p in possible)}" ) def generate(self, strength: int = 128) -> str: """ Create a new mnemonic using a random generated number as entropy. As defined in BIP39, the entropy must be a multiple of 32 bits, and its size must be between 128 and 256 bits. Therefore the possible values for `strength` are 128, 160, 192, 224 and 256. If not provided, the default entropy length will be set to 128 bits. The return is a list of words that encodes the generated entropy. :param strength: Number of bytes used as entropy :type strength: int :return: A randomly generated mnemonic :rtype: str """ if strength not in [128, 160, 192, 224, 256]: raise ValueError( "Invalid strength value. Allowed values are [128, 160, 192, 224, 256]." ) return self.to_mnemonic(secrets.token_bytes(strength // 8)) # Adapted from <http://tinyurl.com/oxmn476> def to_entropy(self, words: list[str] | str) -> bytearray: if not isinstance(words, list): words = words.split(" ") if len(words) not in [12, 15, 18, 21, 24]: raise ValueError( "Number of words must be one of the following: [12, 15, 18, 21, 24], but it is not (%d)." % len(words) ) # Look up all the words in the list and construct the # concatenation of the original entropy and the checksum. concatLenBits = len(words) * 11 concatBits = [False] * concatLenBits wordindex = 0 for word in words: # Find the words index in the wordlist ndx = self.wordlist.index(self.normalize_string(word)) if ndx < 0: raise LookupError('Unable to find "%s" in word list.' % word) # Set the next 11 bits to the value of the index. for ii in range(11): concatBits[(wordindex * 11) + ii] = (ndx & (1 << (10 - ii))) != 0 wordindex += 1 checksumLengthBits = concatLenBits // 33 entropyLengthBits = concatLenBits - checksumLengthBits # Extract original entropy as bytes. entropy = bytearray(entropyLengthBits // 8) for ii in range(len(entropy)): for jj in range(8): if concatBits[(ii * 8) + jj]: entropy[ii] |= 1 << (7 - jj) # Take the digest of the entropy. hashBytes = hashlib.sha256(entropy).digest() hashBits = list( itertools.chain.from_iterable( [c & (1 << (7 - i)) != 0 for i in range(8)] for c in hashBytes ) ) # Check all the checksum bits. for i in range(checksumLengthBits): if concatBits[entropyLengthBits + i] != hashBits[i]: raise ValueError("Failed checksum.") return entropy def to_mnemonic(self, data: bytes) -> str: if len(data) not in [16, 20, 24, 28, 32]: raise ValueError( f"Data length should be one of the following: [16, 20, 24, 28, 32], but it is not {len(data)}." ) h = hashlib.sha256(data).hexdigest() b = ( bin(int.from_bytes(data, byteorder="big"))[2:].zfill(len(data) * 8) + bin(int(h, 16))[2:].zfill(256)[: len(data) * 8 // 32] ) result = [] for i in range(len(b) // 11): idx = int(b[i * 11 : (i + 1) * 11], 2) result.append(self.wordlist[idx]) return self.delimiter.join(result) def check(self, mnemonic: str) -> bool: mnemonic_list = self.normalize_string(mnemonic).split(" ") # list of valid mnemonic lengths if len(mnemonic_list) not in [12, 15, 18, 21, 24]: return False try: idx = map( lambda x: bin(self.wordlist.index(x))[2:].zfill(11), mnemonic_list ) b = "".join(idx) except ValueError: return False l = len(b) # noqa: E741 d = b[: l // 33 * 32] h = b[-l // 33 :] nd = int(d, 2).to_bytes(l // 33 * 4, byteorder="big") nh = bin(int(hashlib.sha256(nd).hexdigest(), 16))[2:].zfill(256)[: l // 33] return h == nh def expand_word(self, prefix: str) -> str: if prefix in self.wordlist: return prefix else: matches = [word for word in self.wordlist if word.startswith(prefix)] if len(matches) == 1: # matched exactly one word in the wordlist return matches[0] else: # exact match not found. # this is not a validation routine, just return the input return prefix def expand(self, mnemonic: str) -> str: return " ".join(map(self.expand_word, mnemonic.split(" "))) @classmethod def to_seed(cls, mnemonic: str, passphrase: str = "") -> bytes: mnemonic = cls.normalize_string(mnemonic) passphrase = cls.normalize_string(passphrase) passphrase = "mnemonic" + passphrase mnemonic_bytes = mnemonic.encode("utf-8") passphrase_bytes = passphrase.encode("utf-8") stretched = hashlib.pbkdf2_hmac( "sha512", mnemonic_bytes, passphrase_bytes, PBKDF2_ROUNDS ) return stretched[:64] @staticmethod def to_hd_master_key(seed: bytes, testnet: bool = False) -> str: if len(seed) != 64: raise ValueError("Provided seed should have length of 64") # Compute HMAC-SHA512 of seed seed = hmac.new(b"Bitcoin seed", seed, digestmod=hashlib.sha512).digest() # Serialization format can be found at: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format xprv = b"\x04\x88\xad\xe4" # Version for private mainnet if testnet: xprv = b"\x04\x35\x83\x94" # Version for private testnet xprv += b"\x00" * 9 # Depth, parent fingerprint, and child number xprv += seed[32:] # Chain code xprv += b"\x00" + seed[:32] # Master key # Double hash using SHA256 hashed_xprv = hashlib.sha256(xprv).digest() hashed_xprv = hashlib.sha256(hashed_xprv).digest() # Append 4 bytes of checksum xprv += hashed_xprv[:4] # Return base58 return b58encode(xprv)
{ "repo_id": "ccxt/ccxt", "file_path": "python/ccxt/static_dependencies/mnemonic/mnemonic.py", "license": "MIT License", "lines": 245, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
ccxt/ccxt:examples/py/set_markets_from_exchange.py
# -*- coding: utf-8 -*- import asyncio import os import sys root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async_support as ccxt # noqa: E402 import psutil # noqa: E402 def get_memory_usage(): """Get current memory usage in MB""" process = psutil.Process() memory_info = process.memory_info() return memory_info.rss / 1024 / 1024 # Convert to MB async def test(): print(f"Initial memory usage: {get_memory_usage():.2f} MB") binance = ccxt.binance({}) print(f"Memory usage after creating binance: {get_memory_usage():.2f} MB") await binance.load_markets() print(f"Memory usage after loading markets: {get_memory_usage():.2f} MB") binance2 = ccxt.binance({}) print(f"Memory usage after creating binance2: {get_memory_usage():.2f} MB") binance2.set_markets_from_exchange(binance) print(f"Memory usage after setting markets from exchange: {get_memory_usage():.2f} MB") print (f"binance2.symbols loaded: {len(binance2.symbols)}") await binance.close() await binance2.close() print(f"Final memory usage after closing: {get_memory_usage():.2f} MB") asyncio.run(test())
{ "repo_id": "ccxt/ccxt", "file_path": "examples/py/set_markets_from_exchange.py", "license": "MIT License", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
ccxt/ccxt:examples/py/ws_test_load.py
import asyncio import os import sys import psutil import time from collections import defaultdict from datetime import datetime sys.path.append('./python') import ccxt.pro as ccxt class PerformanceMetrics: def __init__(self): self.message_count = defaultdict(int) self.error_count = defaultdict(int) self.start_time = time.time() self.process = psutil.Process() self.last_print_time = time.time() self.print_interval = 5 # Print metrics every 5 seconds def increment_message_count(self, symbol): self.message_count[symbol] += 1 def increment_error_count(self, symbol): self.error_count[symbol] += 1 def get_metrics(self): current_time = time.time() elapsed = current_time - self.start_time # Calculate messages per second total_messages = sum(self.message_count.values()) total_errors = sum(self.error_count.values()) messages_per_second = total_messages / elapsed if elapsed > 0 else 0 # Get system metrics memory_info = self.process.memory_info() cpu_percent = self.process.cpu_percent() return { 'elapsed_time': elapsed, 'total_messages': total_messages, 'total_errors': total_errors, 'messages_per_second': messages_per_second, 'memory_usage_mb': memory_info.rss / (1024 * 1024), # Convert to MB 'cpu_percent': cpu_percent, 'symbols_subscribed': len(self.message_count) } def should_print_metrics(self): current_time = time.time() if current_time - self.last_print_time >= self.print_interval: self.last_print_time = current_time return True return False async def watch_orderbook(binance, symbol, metrics): while True: try: await binance.watch_order_book(symbol) metrics.increment_message_count(symbol) if metrics.should_print_metrics(): current_metrics = metrics.get_metrics() print(f"\nPerformance Metrics at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:") print(f"Symbols subscribed: {current_metrics['symbols_subscribed']}") print(f"Messages per second: {current_metrics['messages_per_second']:.2f}") print(f"Total messages: {current_metrics['total_messages']}") print(f"Total errors: {current_metrics['total_errors']}") print(f"Memory usage: {current_metrics['memory_usage_mb']:.2f} MB") print(f"CPU usage: {current_metrics['cpu_percent']:.1f}%") print(f"Elapsed time: {current_metrics['elapsed_time']:.1f} seconds") print("-" * 50) except Exception as e: print(f"Error in {symbol}: {str(e)}") metrics.increment_error_count(symbol) await asyncio.sleep(1) # Wait before retrying async def main(): binance = ccxt.binance({}) await binance.load_markets() symbols = binance.symbols metrics = PerformanceMetrics() print(f"Starting to monitor {len(symbols)} symbols...") tasks = [] for symbol in symbols[:500]: await asyncio.sleep(0.1) task = asyncio.create_task(watch_orderbook(binance, symbol, metrics)) tasks.append(task) await asyncio.gather(*tasks) if __name__ == '__main__': asyncio.run(main()) # Results Using asyncio 3.12^ # Performance Metrics at 2025-05-18 20:24:04: # Symbols subscribed: 100 # Messages per second: 358.01 # Total messages: 174240 # Memory usage: 73.94 MB # CPU usage: 6.6% # Elapsed time: 486.7 seconds # Results using current version using asyncio 3.10 # Performance Metrics at 2025-05-18 20:41:31: # Symbols subscribed: 100 # Messages per second: 297.41 # Total messages: 119353 # Memory usage: 79.78 MB # CPU usage: 7.5% # Elapsed time: 401.3 seconds
{ "repo_id": "ccxt/ccxt", "file_path": "examples/py/ws_test_load.py", "license": "MIT License", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:tools/lib/file_downloader.py
#!/usr/bin/env python3 """ CLI tool for downloading files and querying the comma API. Called by C++ replay/cabana via subprocess. Subcommands: route-files <route> - Get route file URLs as JSON download <url> - Download URL to local cache, print local path devices - List user's devices as JSON device-routes <did> - List routes for a device as JSON """ import argparse import hashlib import json import os import sys import tempfile import shutil from openpilot.system.hardware.hw import Paths from openpilot.tools.lib.api import CommaApi, UnauthorizedError, APIError from openpilot.tools.lib.auth_config import get_token from openpilot.tools.lib.url_file import URLFile def api_call(func): """Run an API call, outputting JSON result or error to stdout.""" try: result = func(CommaApi(get_token())) json.dump(result, sys.stdout) except UnauthorizedError: json.dump({"error": "unauthorized"}, sys.stdout) except APIError as e: error = "not_found" if getattr(e, 'status_code', 0) == 404 else str(e) json.dump({"error": error}, sys.stdout) except Exception as e: json.dump({"error": str(e)}, sys.stdout) sys.stdout.write("\n") sys.stdout.flush() def cache_file_path(url): url_without_query = url.split("?")[0] return os.path.join(Paths.download_cache_root(), hashlib.sha256(url_without_query.encode()).hexdigest()) def cmd_route_files(args): api_call(lambda api: api.get(f"v1/route/{args.route}/files")) def cmd_download(args): url = args.url use_cache = not args.no_cache if use_cache: local_path = cache_file_path(url) if os.path.exists(local_path): sys.stdout.write(local_path + "\n") sys.stdout.flush() return try: uf = URLFile(url, cache=False) total = uf.get_length() if total <= 0: sys.stderr.write("ERROR:File not found or empty\n") sys.stderr.flush() sys.exit(1) os.makedirs(Paths.download_cache_root(), exist_ok=True) tmp_fd, tmp_path = tempfile.mkstemp(dir=Paths.download_cache_root()) try: downloaded = 0 chunk_size = 1024 * 1024 with os.fdopen(tmp_fd, 'wb') as f: while downloaded < total: data = uf.read(min(chunk_size, total - downloaded)) f.write(data) downloaded += len(data) sys.stderr.write(f"PROGRESS:{downloaded}:{total}\n") sys.stderr.flush() if use_cache: shutil.move(tmp_path, local_path) sys.stdout.write(local_path + "\n") else: sys.stdout.write(tmp_path + "\n") except Exception: try: os.unlink(tmp_path) except OSError: pass raise except Exception as e: sys.stderr.write(f"ERROR:{e}\n") sys.stderr.flush() sys.exit(1) sys.stdout.flush() def cmd_devices(args): api_call(lambda api: api.get("v1/me/devices/")) def cmd_device_routes(args): def fetch(api): if args.preserved: return api.get(f"v1/devices/{args.dongle_id}/routes/preserved") params = {} if args.start is not None: params['start'] = args.start if args.end is not None: params['end'] = args.end return api.get(f"v1/devices/{args.dongle_id}/routes_segments", params=params) api_call(fetch) def main(): parser = argparse.ArgumentParser(description="File downloader CLI for openpilot tools") subparsers = parser.add_subparsers(dest="command", required=True) p_rf = subparsers.add_parser("route-files") p_rf.add_argument("route") p_rf.set_defaults(func=cmd_route_files) p_dl = subparsers.add_parser("download") p_dl.add_argument("url") p_dl.add_argument("--no-cache", action="store_true") p_dl.set_defaults(func=cmd_download) p_dev = subparsers.add_parser("devices") p_dev.set_defaults(func=cmd_devices) p_dr = subparsers.add_parser("device-routes") p_dr.add_argument("dongle_id") p_dr.add_argument("--start", type=int, default=None) p_dr.add_argument("--end", type=int, default=None) p_dr.add_argument("--preserved", action="store_true") p_dr.set_defaults(func=cmd_device_routes) args = parser.parse_args() args.func(args) if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "tools/lib/file_downloader.py", "license": "MIT License", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/lib/tests/test_handle_state_change.py
"""Tests for WifiManager._handle_state_change. Tests the state machine in isolation by constructing a WifiManager with mocked DBus, then calling _handle_state_change directly with NM state transitions. """ import pytest from jeepney.low_level import MessageType from pytest_mock import MockerFixture from openpilot.system.ui.lib.networkmanager import NMDeviceState, NMDeviceStateReason from openpilot.system.ui.lib.wifi_manager import WifiManager, WifiState, ConnectStatus def _make_wm(mocker: MockerFixture, connections=None): """Create a WifiManager with only the fields _handle_state_change touches.""" mocker.patch.object(WifiManager, '_initialize') wm = WifiManager.__new__(WifiManager) wm._exit = True # prevent stop() from doing anything in __del__ wm._conn_monitor = mocker.MagicMock() wm._connections = dict(connections or {}) wm._wifi_state = WifiState() wm._user_epoch = 0 wm._callback_queue = [] wm._need_auth = [] wm._activated = [] wm._update_networks = mocker.MagicMock() wm._update_active_connection_info = mocker.MagicMock() wm._get_active_wifi_connection = mocker.MagicMock(return_value=(None, None)) return wm def fire(wm: WifiManager, new_state: int, prev_state: int = NMDeviceState.UNKNOWN, reason: int = NMDeviceStateReason.NONE) -> None: """Feed a state change into the handler.""" wm._handle_state_change(new_state, prev_state, reason) def fire_wpa_connect(wm: WifiManager) -> None: """WPA handshake then IP negotiation through ACTIVATED, as seen on device.""" fire(wm, NMDeviceState.NEED_AUTH) fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) fire(wm, NMDeviceState.CONFIG) fire(wm, NMDeviceState.IP_CONFIG) fire(wm, NMDeviceState.IP_CHECK) fire(wm, NMDeviceState.SECONDARIES) fire(wm, NMDeviceState.ACTIVATED) # --------------------------------------------------------------------------- # Basic transitions # --------------------------------------------------------------------------- class TestDisconnected: def test_generic_disconnect_clears_state(self, mocker): wm = _make_wm(mocker) wm._wifi_state = WifiState(ssid="Net", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.UNKNOWN) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED wm._update_networks.assert_not_called() def test_new_activation_is_noop(self, mocker): """NEW_ACTIVATION means NM is about to connect to another network — don't clear.""" wm = _make_wm(mocker) wm._wifi_state = WifiState(ssid="OldNet", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NEW_ACTIVATION) assert wm._wifi_state.ssid == "OldNet" assert wm._wifi_state.status == ConnectStatus.CONNECTED def test_connection_removed_keeps_other_connecting(self, mocker): """Forget A while connecting to B: CONNECTION_REMOVED for A must not clear B.""" wm = _make_wm(mocker, connections={"B": "/path/B"}) wm._set_connecting("B") fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING def test_connection_removed_clears_when_forgotten(self, mocker): """Forget A: A is no longer in _connections, so state should clear.""" wm = _make_wm(mocker, connections={}) wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED class TestDeactivating: def test_deactivating_noop_for_non_connection_removed(self, mocker): """DEACTIVATING with non-CONNECTION_REMOVED reason is a no-op.""" wm = _make_wm(mocker) wm._wifi_state = WifiState(ssid="Net", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.USER_REQUESTED) assert wm._wifi_state.ssid == "Net" assert wm._wifi_state.status == ConnectStatus.CONNECTED @pytest.mark.parametrize("status, expected_clears", [ (ConnectStatus.CONNECTED, True), (ConnectStatus.CONNECTING, False), ]) def test_deactivating_connection_removed(self, mocker, status, expected_clears): """DEACTIVATING(CONNECTION_REMOVED) clears CONNECTED but preserves CONNECTING. CONNECTED: forgetting the current network. The forgotten callback fires between DEACTIVATING and DISCONNECTED — must clear here so the UI doesn't flash "connected" after the eager _network_forgetting flag resets. CONNECTING: forget A while connecting to B. DEACTIVATING fires for A's removal, but B's CONNECTING state must be preserved. """ wm = _make_wm(mocker, connections={"B": "/path/B"}) wm._wifi_state = WifiState(ssid="B" if status == ConnectStatus.CONNECTING else "A", status=status) fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) if expected_clears: assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED else: assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING class TestPrepareConfig: def test_user_initiated_skips_dbus_lookup(self, mocker): """User called _set_connecting('B') — PREPARE must not overwrite via DBus. Reproduced on device: rapidly tap A then B. PREPARE's DBus lookup returns A's stale conn_path, overwriting ssid to A for 1-2 frames. UI shows the "connecting" indicator briefly jump to the wrong network row then back. """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) wm._set_connecting("B") wm._get_active_wifi_connection.return_value = ("/path/A", {}) fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING wm._get_active_wifi_connection.assert_not_called() @pytest.mark.parametrize("state", [NMDeviceState.PREPARE, NMDeviceState.CONFIG]) def test_auto_connect_looks_up_ssid(self, mocker, state): """Auto-connection (ssid=None): PREPARE and CONFIG must look up ssid from NM.""" wm = _make_wm(mocker, connections={"AutoNet": "/path/auto"}) wm._get_active_wifi_connection.return_value = ("/path/auto", {}) fire(wm, state) assert wm._wifi_state.ssid == "AutoNet" assert wm._wifi_state.status == ConnectStatus.CONNECTING def test_auto_connect_dbus_fails(self, mocker): """Auto-connection but DBus returns None: ssid stays None, status CONNECTING.""" wm = _make_wm(mocker) fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.CONNECTING def test_auto_connect_conn_path_not_in_connections(self, mocker): """DBus returns a conn_path that doesn't match any known connection.""" wm = _make_wm(mocker, connections={"Other": "/path/other"}) wm._get_active_wifi_connection.return_value = ("/path/unknown", {}) fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.CONNECTING class TestNeedAuth: def test_wrong_password_fires_callback(self, mocker): """NEED_AUTH+SUPPLICANT_DISCONNECT from CONFIG = real wrong password.""" wm = _make_wm(mocker) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("SecNet") fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) assert wm._wifi_state.status == ConnectStatus.DISCONNECTED assert len(wm._callback_queue) == 1 wm.process_callbacks() cb.assert_called_once_with("SecNet") def test_failed_no_secrets_fires_callback(self, mocker): """FAILED+NO_SECRETS = wrong password (weak/gone network). Confirmed on device: also fires when a hotspot turns off during connection. NM can't complete the WPA handshake (AP vanished) and reports NO_SECRETS rather than SSID_NOT_FOUND. The need_auth callback fires, so the UI shows "wrong password" — a false positive, but same signal path. Real device sequence (new connection, hotspot turned off immediately): PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG → NEED_AUTH(CONFIG, NONE) → FAILED(NEED_AUTH, NO_SECRETS) → DISCONNECTED(FAILED, NONE) """ wm = _make_wm(mocker) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("WeakNet") fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NO_SECRETS) assert wm._wifi_state.status == ConnectStatus.DISCONNECTED assert len(wm._callback_queue) == 1 wm.process_callbacks() cb.assert_called_once_with("WeakNet") def test_need_auth_then_failed_no_double_fire(self, mocker): """Real device sends NEED_AUTH(SUPPLICANT_DISCONNECT) then FAILED(NO_SECRETS) back-to-back. The first clears ssid, so the second must not fire a duplicate callback. Real device sequence: NEED_AUTH(CONFIG, SUPPLICANT_DISCONNECT) → FAILED(NEED_AUTH, NO_SECRETS) """ wm = _make_wm(mocker) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("BadPass") fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) assert len(wm._callback_queue) == 1 fire(wm, NMDeviceState.FAILED, prev_state=NMDeviceState.NEED_AUTH, reason=NMDeviceStateReason.NO_SECRETS) assert len(wm._callback_queue) == 1 # no duplicate wm.process_callbacks() cb.assert_called_once_with("BadPass") def test_no_ssid_no_callback(self, mocker): """If ssid is None when NEED_AUTH fires, no callback enqueued.""" wm = _make_wm(mocker) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) fire(wm, NMDeviceState.NEED_AUTH, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) assert len(wm._callback_queue) == 0 def test_interrupted_auth_ignored(self, mocker): """Switching A->B: NEED_AUTH from A (prev=DISCONNECTED) must not fire callback. Reproduced on device: rapidly switching between two saved networks can trigger a rare false "wrong password" dialog for the previous network, even though both have correct passwords. The stale NEED_AUTH has prev_state=DISCONNECTED (not CONFIG). """ wm = _make_wm(mocker) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("A") wm._set_connecting("B") fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING assert len(wm._callback_queue) == 0 class TestPassthroughStates: """NEED_AUTH (generic), IP_CONFIG, IP_CHECK, SECONDARIES, FAILED (generic) are no-ops.""" @pytest.mark.parametrize("state", [ NMDeviceState.NEED_AUTH, NMDeviceState.IP_CONFIG, NMDeviceState.IP_CHECK, NMDeviceState.SECONDARIES, NMDeviceState.FAILED, ]) def test_passthrough_is_noop(self, mocker, state): wm = _make_wm(mocker) wm._set_connecting("Net") fire(wm, state, reason=NMDeviceStateReason.NONE) assert wm._wifi_state.ssid == "Net" assert wm._wifi_state.status == ConnectStatus.CONNECTING assert len(wm._callback_queue) == 0 class TestActivated: def test_sets_connected(self, mocker): """ACTIVATED sets status to CONNECTED and fires callback.""" wm = _make_wm(mocker, connections={"MyNet": "/path/mynet"}) cb = mocker.MagicMock() wm.add_callbacks(activated=cb) wm._set_connecting("MyNet") wm._get_active_wifi_connection.return_value = ("/path/mynet", {}) fire(wm, NMDeviceState.ACTIVATED) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "MyNet" assert len(wm._callback_queue) == 1 wm.process_callbacks() cb.assert_called_once() def test_conn_path_none_still_connected(self, mocker): """ACTIVATED but DBus returns None: status CONNECTED, ssid unchanged.""" wm = _make_wm(mocker) wm._set_connecting("MyNet") fire(wm, NMDeviceState.ACTIVATED) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "MyNet" def test_activated_side_effects(self, mocker): """ACTIVATED persists the volatile connection to disk and updates active connection info.""" wm = _make_wm(mocker, connections={"Net": "/path/net"}) wm._set_connecting("Net") wm._get_active_wifi_connection.return_value = ("/path/net", {}) fire(wm, NMDeviceState.ACTIVATED) wm._conn_monitor.send_and_get_reply.assert_called_once() wm._update_active_connection_info.assert_called_once() wm._update_networks.assert_not_called() # --------------------------------------------------------------------------- # Thread races: _set_connecting on main thread vs _handle_state_change on monitor thread. # Uses side_effect on the DBus mock to simulate _set_connecting running mid-handler. # The epoch counter detects that a user action occurred during the slow DBus call # and discards the stale update. # --------------------------------------------------------------------------- # The deterministic fixes (skip DBus lookup when ssid already set, prev_state guard # on NEED_AUTH, DEACTIVATING clears CONNECTED on CONNECTION_REMOVED, CONNECTION_REMOVED # guard) shrink these race windows significantly. The epoch counter closes the # remaining gaps. class TestThreadRaces: def test_prepare_race_user_tap_during_dbus(self, mocker): """User taps B while PREPARE's DBus call is in flight for auto-connect. Monitor thread reads wifi_state (ssid=None), starts DBus call. Main thread: _set_connecting("B"). Monitor thread writes back stale ssid from DBus. """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) def user_taps_b_during_dbus(*args, **kwargs): wm._set_connecting("B") return ("/path/A", {}) wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING def test_activated_race_user_tap_during_dbus(self, mocker): """User taps B right as A finishes connecting (ACTIVATED handler running). Monitor thread reads wifi_state (A, CONNECTING), starts DBus call. Main thread: _set_connecting("B"). Monitor thread writes (A, CONNECTED), losing B. """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) wm._set_connecting("A") def user_taps_b_during_dbus(*args, **kwargs): wm._set_connecting("B") return ("/path/A", {}) wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus fire(wm, NMDeviceState.ACTIVATED) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING def test_init_wifi_state_race_user_tap_during_dbus(self, mocker): """User taps B while _init_wifi_state's DBus calls are in flight. _init_wifi_state runs from set_active(True) or worker error paths. It does 2 DBus calls (device State property + _get_active_wifi_connection) then unconditionally writes _wifi_state. If the user taps a network during those calls, _set_connecting("B") is overwritten with stale NM ground truth. """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) wm._wifi_device = "/dev/wifi0" wm._router_main = mocker.MagicMock() state_reply = mocker.MagicMock() state_reply.body = [('u', NMDeviceState.ACTIVATED)] wm._router_main.send_and_get_reply.return_value = state_reply def user_taps_b_during_dbus(*args, **kwargs): wm._set_connecting("B") return ("/path/A", {}) wm._get_active_wifi_connection.side_effect = user_taps_b_during_dbus wm._init_wifi_state() assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING # --------------------------------------------------------------------------- # Full sequences (NM signal order from real devices) # --------------------------------------------------------------------------- class TestFullSequences: def test_normal_connect(self, mocker): """User connects to saved network: full happy path. Real device sequence (switching from another connected network): DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED """ wm = _make_wm(mocker, connections={"Home": "/path/home"}) wm._get_active_wifi_connection.return_value = ("/path/home", {}) wm._set_connecting("Home") fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) fire(wm, NMDeviceState.CONFIG) assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.IP_CONFIG) fire(wm, NMDeviceState.IP_CHECK) fire(wm, NMDeviceState.SECONDARIES) fire(wm, NMDeviceState.ACTIVATED) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "Home" def test_wrong_password_then_retry(self, mocker): """Wrong password → NEED_AUTH → FAILED → NM auto-reconnects to saved network. Confirmed on device: wrong password for Shane's iPhone, NM auto-connected to unifi. Real device sequence (switching from a connected network): DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) ← WPA handshake → PREPARE(NEED_AUTH, NONE) → CONFIG → NEED_AUTH(CONFIG, SUPPLICANT_DISCONNECT) ← wrong password → FAILED(NEED_AUTH, NO_SECRETS) ← NM gives up → DISCONNECTED(FAILED, NONE) → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED ← auto-reconnect to other saved network """ wm = _make_wm(mocker, connections={"Sec": "/path/sec"}) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("Sec") fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) fire(wm, NMDeviceState.CONFIG) fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.CONFIG, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) assert wm._wifi_state.status == ConnectStatus.DISCONNECTED assert len(wm._callback_queue) == 1 # FAILED(NO_SECRETS) follows but ssid is already cleared — no double-fire fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NO_SECRETS) assert len(wm._callback_queue) == 1 fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.FAILED) # Retry wm._callback_queue.clear() wm._set_connecting("Sec") wm._get_active_wifi_connection.return_value = ("/path/sec", {}) fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED def test_switch_saved_networks(self, mocker): """Switch from A to B (both saved): NM signal sequence from real device. Real device sequence: DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) wm._get_active_wifi_connection.return_value = ("/path/B", {}) wm._set_connecting("B") fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, reason=NMDeviceStateReason.NEW_ACTIVATION) fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.NEW_ACTIVATION) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "B" def test_rapid_switch_no_false_wrong_password(self, mocker): """Switch A→B quickly: A's interrupted NEED_AUTH must NOT show wrong password. NOTE: The late NEED_AUTH(DISCONNECTED, SUPPLICANT_DISCONNECT) is common when rapidly switching between networks with wrong/new passwords. Less common when switching between saved networks with correct passwords. Not guaranteed — some switches skip it and go straight from DISCONNECTED to PREPARE. The prev_state is consistently DISCONNECTED for stale signals, so the prev_state guard reliably distinguishes them. Worst-case signal sequence this protects against: DEACTIVATING(NEW_ACTIVATION) → DISCONNECTED(NEW_ACTIVATION) → NEED_AUTH(DISCONNECTED, SUPPLICANT_DISCONNECT) ← A's stale auth failure → PREPARE → CONFIG → ... → ACTIVATED ← B connects """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) wm._get_active_wifi_connection.return_value = ("/path/B", {}) wm._set_connecting("B") fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, reason=NMDeviceStateReason.NEW_ACTIVATION) fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.NEW_ACTIVATION) fire(wm, NMDeviceState.NEED_AUTH, prev_state=NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.SUPPLICANT_DISCONNECT) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING assert len(wm._callback_queue) == 0 fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED def test_forget_while_connecting(self, mocker): """Forget the network we're currently connecting to (not yet ACTIVATED). Confirmed on device: connected to unifi, tapped Shane's iPhone, then forgot Shane's iPhone while at CONFIG. NM auto-connected to unifi afterward. Real device sequence (switching then forgetting mid-connection): DEACTIVATING(ACTIVATED, NEW_ACTIVATION) → DISCONNECTED(DEACTIVATING, NEW_ACTIVATION) → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG → DEACTIVATING(CONFIG, CONNECTION_REMOVED) ← forget at CONFIG → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) → PREPARE → CONFIG → ... → ACTIVATED ← NM auto-connects to other saved network Note: DEACTIVATING fires from CONFIG (not ACTIVATED). wifi_state.status is CONNECTING, so the DEACTIVATING handler is a no-op. DISCONNECTED clears state (ssid removed from _connections by ConnectionRemoved), then PREPARE recovers via DBus lookup for the auto-connect. """ wm = _make_wm(mocker, connections={"A": "/path/A", "Other": "/path/other"}) wm._get_active_wifi_connection.return_value = ("/path/other", {}) wm._set_connecting("A") fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) assert wm._wifi_state.ssid == "A" assert wm._wifi_state.status == ConnectStatus.CONNECTING # User forgets A: ConnectionRemoved processed first, then state changes del wm._connections["A"] fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.CONFIG, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid == "A" assert wm._wifi_state.status == ConnectStatus.CONNECTING # DEACTIVATING preserves CONNECTING fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED # NM auto-connects to another saved network fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid == "Other" assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "Other" def test_forget_connected_network(self, mocker): """Forget the currently connected network (not switching to another). Real device sequence: DEACTIVATING(ACTIVATED, CONNECTION_REMOVED) → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) ConnectionRemoved signal may or may not have been processed before state changes. Either way, state must clear — we're forgetting what we're connected to, not switching. """ wm = _make_wm(mocker, connections={"A": "/path/A"}) wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED # DISCONNECTED follows — harmless since state is already cleared fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED def test_forget_A_connect_B(self, mocker): """Forget A while connecting to B: full signal sequence. Real device sequence: DEACTIVATING(ACTIVATED, CONNECTION_REMOVED) → DISCONNECTED(DEACTIVATING, CONNECTION_REMOVED) → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH, NONE) → CONFIG → IP_CONFIG → IP_CHECK → SECONDARIES → ACTIVATED Signal order: 1. User: _set_connecting("B"), forget("A") removes A from _connections 2. NewConnection for B arrives → _connections["B"] = ... 3. DEACTIVATING(CONNECTION_REMOVED) — no-op 4. DISCONNECTED(CONNECTION_REMOVED) — B is in _connections, must not clear 5. PREPARE → CONFIG → NEED_AUTH → PREPARE → CONFIG → ... → ACTIVATED """ wm = _make_wm(mocker, connections={"A": "/path/A"}) wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) wm._set_connecting("B") del wm._connections["A"] wm._connections["B"] = "/path/B" fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING wm._get_active_wifi_connection.return_value = ("/path/B", {}) fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "B" def test_forget_A_connect_B_late_new_connection(self, mocker): """Forget A, connect B: NewConnection for B arrives AFTER DISCONNECTED. This is the worst-case race: B isn't in _connections when DISCONNECTED fires, so the guard can't protect it and state clears. PREPARE must recover by doing the DBus lookup (ssid is None at that point). Signal order: 1. User: _set_connecting("B"), forget("A") removes A from _connections 2. DEACTIVATING(CONNECTION_REMOVED) — B NOT in _connections, should be no-op 3. DISCONNECTED(CONNECTION_REMOVED) — B STILL NOT in _connections, clears state 4. NewConnection for B arrives late → _connections["B"] = ... 5. PREPARE (ssid=None, so DBus lookup recovers) → CONFIG → ACTIVATED """ wm = _make_wm(mocker, connections={"A": "/path/A"}) wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) wm._set_connecting("B") del wm._connections["A"] fire(wm, NMDeviceState.DEACTIVATING, prev_state=NMDeviceState.ACTIVATED, reason=NMDeviceStateReason.CONNECTION_REMOVED) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.CONNECTION_REMOVED) # B not in _connections yet, so state clears — this is the known edge case assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED # NewConnection arrives late wm._connections["B"] = "/path/B" wm._get_active_wifi_connection.return_value = ("/path/B", {}) # PREPARE recovers: ssid is None so it looks up from DBus fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid == "B" assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "B" def test_auto_connect(self, mocker): """NM auto-connects (no user action, ssid starts None).""" wm = _make_wm(mocker, connections={"AutoNet": "/path/auto"}) wm._get_active_wifi_connection.return_value = ("/path/auto", {}) fire(wm, NMDeviceState.PREPARE) assert wm._wifi_state.ssid == "AutoNet" assert wm._wifi_state.status == ConnectStatus.CONNECTING fire(wm, NMDeviceState.CONFIG) fire_wpa_connect(wm) assert wm._wifi_state.status == ConnectStatus.CONNECTED assert wm._wifi_state.ssid == "AutoNet" def test_network_lost_during_connection(self, mocker): """Hotspot turned off while connecting (before ACTIVATED). Confirmed on device: started new connection to Shane's iPhone, immediately turned off the hotspot. NM can't complete WPA handshake and reports FAILED(NO_SECRETS) — same signal as wrong password (false positive). Real device sequence: PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG → NEED_AUTH(CONFIG, NONE) → FAILED(NEED_AUTH, NO_SECRETS) → DISCONNECTED(FAILED, NONE) Note: no DEACTIVATING, no SUPPLICANT_DISCONNECT. The NEED_AUTH(CONFIG, NONE) is the normal WPA handshake (not an error). NM gives up with NO_SECRETS because the AP vanished mid-handshake. """ wm = _make_wm(mocker, connections={"Hotspot": "/path/hs"}) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("Hotspot") fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire(wm, NMDeviceState.NEED_AUTH) # WPA handshake (reason=NONE) fire(wm, NMDeviceState.PREPARE, prev_state=NMDeviceState.NEED_AUTH) fire(wm, NMDeviceState.CONFIG) assert wm._wifi_state.status == ConnectStatus.CONNECTING # Second NEED_AUTH(CONFIG, NONE) — NM retries handshake, AP vanishing fire(wm, NMDeviceState.NEED_AUTH) assert wm._wifi_state.status == ConnectStatus.CONNECTING # NM gives up — reports NO_SECRETS (same as wrong password) fire(wm, NMDeviceState.FAILED, prev_state=NMDeviceState.NEED_AUTH, reason=NMDeviceStateReason.NO_SECRETS) assert wm._wifi_state.status == ConnectStatus.DISCONNECTED assert len(wm._callback_queue) == 1 fire(wm, NMDeviceState.DISCONNECTED, prev_state=NMDeviceState.FAILED) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED wm.process_callbacks() cb.assert_called_once_with("Hotspot") @pytest.mark.xfail(reason="TODO: FAILED(SSID_NOT_FOUND) should emit error for UI") def test_ssid_not_found(self, mocker): """Network drops off while connected — hotspot turned off. NM docs: SSID_NOT_FOUND (53) = "The WiFi network could not be found" Confirmed on device: connected to Shane's iPhone, then turned off the hotspot. No DEACTIVATING fires — NM goes straight from ACTIVATED to FAILED(SSID_NOT_FOUND). NM retries connecting (PREPARE → CONFIG → ... → FAILED(CONFIG, SSID_NOT_FOUND)) before finally giving up with DISCONNECTED. NOTE: turning off a hotspot during initial connection (before ACTIVATED) typically produces FAILED(NO_SECRETS) instead of SSID_NOT_FOUND (see test_failed_no_secrets). Real device sequence (hotspot turned off while connected): FAILED(ACTIVATED, SSID_NOT_FOUND) → DISCONNECTED(FAILED, NONE) → PREPARE → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG → NEED_AUTH(CONFIG, NONE) → PREPARE(NEED_AUTH) → CONFIG → FAILED(CONFIG, SSID_NOT_FOUND) → DISCONNECTED(FAILED, NONE) The UI error callback mechanism is intentionally deferred — for now just clear state. """ wm = _make_wm(mocker, connections={"GoneNet": "/path/gone"}) cb = mocker.MagicMock() wm.add_callbacks(need_auth=cb) wm._set_connecting("GoneNet") fire(wm, NMDeviceState.PREPARE) fire(wm, NMDeviceState.CONFIG) fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.SSID_NOT_FOUND) assert wm._wifi_state.status == ConnectStatus.DISCONNECTED assert wm._wifi_state.ssid is None def test_failed_then_disconnected_clears_state(self, mocker): """After FAILED, NM always transitions to DISCONNECTED to clean up. NM docs: FAILED (120) = "failed to connect, cleaning up the connection request" Full sequence: ... → FAILED(reason) → DISCONNECTED(NONE) """ wm = _make_wm(mocker) wm._set_connecting("Net") fire(wm, NMDeviceState.FAILED, reason=NMDeviceStateReason.NONE) assert wm._wifi_state.status == ConnectStatus.CONNECTING # FAILED(NONE) is a no-op fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.NONE) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED def test_user_requested_disconnect(self, mocker): """User explicitly disconnects from the network. NM docs: USER_REQUESTED (39) = "Device disconnected by user or client" Expected sequence: DEACTIVATING(USER_REQUESTED) → DISCONNECTED(USER_REQUESTED) """ wm = _make_wm(mocker) wm._wifi_state = WifiState(ssid="MyNet", status=ConnectStatus.CONNECTED) fire(wm, NMDeviceState.DEACTIVATING, reason=NMDeviceStateReason.USER_REQUESTED) fire(wm, NMDeviceState.DISCONNECTED, reason=NMDeviceStateReason.USER_REQUESTED) assert wm._wifi_state.ssid is None assert wm._wifi_state.status == ConnectStatus.DISCONNECTED # --------------------------------------------------------------------------- # Worker error recovery: DBus errors in activate/connect re-sync with NM # --------------------------------------------------------------------------- # Verified on device: when ActivateConnection returns UnknownConnection error, # NM emits no state signals. The worker error path is the only recovery point. class TestWorkerErrorRecovery: """Worker threads re-sync with NM via _init_wifi_state on DBus errors, preserving actual NM state instead of blindly clearing to DISCONNECTED.""" def _mock_init_restores(self, wm, mocker, ssid, status): """Replace _init_wifi_state with a mock that simulates NM reporting the given state.""" mock = mocker.MagicMock( side_effect=lambda: setattr(wm, '_wifi_state', WifiState(ssid=ssid, status=status)) ) wm._init_wifi_state = mock return mock def test_activate_dbus_error_resyncs(self, mocker): """ActivateConnection returns DBus error while A is connected. NM rejects the request — no state signals emitted. Worker must re-read NM state to discover A is still connected, not clear to DISCONNECTED. """ wm = _make_wm(mocker, connections={"A": "/path/A", "B": "/path/B"}) wm._wifi_device = "/dev/wifi0" wm._nm = mocker.MagicMock() wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) wm._router_main = mocker.MagicMock() error_reply = mocker.MagicMock() error_reply.header.message_type = MessageType.error wm._router_main.send_and_get_reply.return_value = error_reply mock_init = self._mock_init_restores(wm, mocker, "A", ConnectStatus.CONNECTED) wm.activate_connection("B", block=True) mock_init.assert_called_once() assert wm._wifi_state.ssid == "A" assert wm._wifi_state.status == ConnectStatus.CONNECTED def test_connect_to_network_dbus_error_resyncs(self, mocker): """AddAndActivateConnection2 returns DBus error while A is connected.""" wm = _make_wm(mocker, connections={"A": "/path/A"}) wm._wifi_device = "/dev/wifi0" wm._nm = mocker.MagicMock() wm._wifi_state = WifiState(ssid="A", status=ConnectStatus.CONNECTED) wm._router_main = mocker.MagicMock() wm._forgotten = [] error_reply = mocker.MagicMock() error_reply.header.message_type = MessageType.error wm._router_main.send_and_get_reply.return_value = error_reply mock_init = self._mock_init_restores(wm, mocker, "A", ConnectStatus.CONNECTED) # Run worker thread synchronously workers = [] mocker.patch('openpilot.system.ui.lib.wifi_manager.threading.Thread', side_effect=lambda target, **kw: type('T', (), {'start': lambda self: workers.append(target)})()) wm.connect_to_network("B", "password123") workers[-1]() mock_init.assert_called_once() assert wm._wifi_state.ssid == "A" assert wm._wifi_state.status == ConnectStatus.CONNECTED
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/lib/tests/test_handle_state_change.py", "license": "MIT License", "lines": 702, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/ui/translations/potools.py
"""Pure Python tools for managing .po translation files. Replaces GNU gettext CLI tools (xgettext, msginit, msgmerge) with Python implementations for extracting, creating, and updating .po files. """ import ast import os import re from dataclasses import dataclass, field from datetime import UTC, datetime from pathlib import Path @dataclass class POEntry: msgid: str = "" msgstr: str = "" msgid_plural: str = "" msgstr_plural: dict[int, str] = field(default_factory=dict) comments: list[str] = field(default_factory=list) source_refs: list[str] = field(default_factory=list) flags: list[str] = field(default_factory=list) @property def is_plural(self) -> bool: return bool(self.msgid_plural) # ──── PO file parsing ──── def _parse_quoted(s: str) -> str: """Parse a PO-format quoted string, handling escape sequences.""" s = s.strip() if not (s.startswith('"') and s.endswith('"')): raise ValueError(f"Expected quoted string: {s!r}") s = s[1:-1] result = [] i = 0 while i < len(s): if s[i] == '\\' and i + 1 < len(s): c = s[i + 1] if c == 'n': result.append('\n') elif c == 't': result.append('\t') elif c == '"': result.append('"') elif c == '\\': result.append('\\') else: result.append(s[i:i + 2]) i += 2 else: result.append(s[i]) i += 1 return ''.join(result) def parse_po(path: str | Path) -> tuple[POEntry | None, list[POEntry]]: """Parse a .po/.pot file. Returns (header_entry, entries).""" with open(path, encoding='utf-8') as f: lines = f.readlines() entries: list[POEntry] = [] header: POEntry | None = None cur: POEntry | None = None cur_field: str | None = None plural_idx = 0 def finish(): nonlocal cur, header if cur is None: return if cur.msgid == "" and cur.msgstr: header = cur elif cur.msgid != "" or cur.is_plural: entries.append(cur) cur = None for raw in lines: line = raw.rstrip('\n') stripped = line.strip() if not stripped: finish() cur_field = None continue # Skip obsolete entries if stripped.startswith('#~'): continue if stripped.startswith('#'): if cur is None: cur = POEntry() if stripped.startswith('#:'): cur.source_refs.append(stripped[2:].strip()) elif stripped.startswith('#,'): cur.flags.extend(f.strip() for f in stripped[2:].split(',') if f.strip()) else: cur.comments.append(line) continue if stripped.startswith('msgid_plural '): if cur is None: cur = POEntry() cur.msgid_plural = _parse_quoted(stripped[len('msgid_plural '):]) cur_field = 'msgid_plural' continue if stripped.startswith('msgid '): if cur is None: cur = POEntry() cur.msgid = _parse_quoted(stripped[len('msgid '):]) cur_field = 'msgid' continue m = re.match(r'msgstr\[(\d+)]\s+(.*)', stripped) if m: plural_idx = int(m.group(1)) cur.msgstr_plural[plural_idx] = _parse_quoted(m.group(2)) cur_field = 'msgstr_plural' continue if stripped.startswith('msgstr '): cur.msgstr = _parse_quoted(stripped[len('msgstr '):]) cur_field = 'msgstr' continue if stripped.startswith('"'): val = _parse_quoted(stripped) if cur_field == 'msgid': cur.msgid += val elif cur_field == 'msgid_plural': cur.msgid_plural += val elif cur_field == 'msgstr': cur.msgstr += val elif cur_field == 'msgstr_plural': cur.msgstr_plural[plural_idx] += val finish() return header, entries # ──── PO file writing ──── def _quote(s: str) -> str: """Quote a string for .po file output.""" s = s.replace('\\', '\\\\').replace('"', '\\"').replace('\t', '\\t') if '\n' in s and s != '\n': parts = s.split('\n') lines = ['""'] for i, part in enumerate(parts): text = part + ('\\n' if i < len(parts) - 1 else '') if text: lines.append(f'"{text}"') return '\n'.join(lines) return f'"{s}"'.replace('\n', '\\n') def write_po(path: str | Path, header: POEntry | None, entries: list[POEntry]) -> None: """Write a .po/.pot file.""" with open(path, 'w', encoding='utf-8') as f: if header: for c in header.comments: f.write(c + '\n') if header.flags: f.write('#, ' + ', '.join(header.flags) + '\n') f.write(f'msgid {_quote("")}\n') f.write(f'msgstr {_quote(header.msgstr)}\n\n') for entry in entries: for c in entry.comments: f.write(c + '\n') for ref in entry.source_refs: f.write(f'#: {ref}\n') if entry.flags: f.write('#, ' + ', '.join(entry.flags) + '\n') f.write(f'msgid {_quote(entry.msgid)}\n') if entry.is_plural: f.write(f'msgid_plural {_quote(entry.msgid_plural)}\n') for idx in sorted(entry.msgstr_plural): f.write(f'msgstr[{idx}] {_quote(entry.msgstr_plural[idx])}\n') else: f.write(f'msgstr {_quote(entry.msgstr)}\n') f.write('\n') # ──── String extraction (replaces xgettext) ──── def extract_strings(files: list[str], basedir: str) -> list[POEntry]: """Extract tr/trn/tr_noop calls from Python source files.""" seen: dict[str, POEntry] = {} for filepath in files: full = os.path.join(basedir, filepath) with open(full, encoding='utf-8') as f: source = f.read() try: tree = ast.parse(source, filename=filepath) except SyntaxError: continue for node in ast.walk(tree): if not isinstance(node, ast.Call): continue func = node.func if isinstance(func, ast.Name): name = func.id elif isinstance(func, ast.Attribute): name = func.attr else: continue if name not in ('tr', 'trn', 'tr_noop'): continue ref = f'{filepath}:{node.lineno}' is_flagged = name in ('tr', 'trn') if name in ('tr', 'tr_noop'): if not node.args or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str): continue msgid = node.args[0].value if msgid in seen: if ref not in seen[msgid].source_refs: seen[msgid].source_refs.append(ref) else: flags = ['python-format'] if is_flagged else [] seen[msgid] = POEntry(msgid=msgid, source_refs=[ref], flags=flags) elif name == 'trn': if len(node.args) < 2: continue a1, a2 = node.args[0], node.args[1] if not (isinstance(a1, ast.Constant) and isinstance(a1.value, str)): continue if not (isinstance(a2, ast.Constant) and isinstance(a2.value, str)): continue msgid, msgid_plural = a1.value, a2.value if msgid in seen: if ref not in seen[msgid].source_refs: seen[msgid].source_refs.append(ref) else: flags = ['python-format'] if is_flagged else [] seen[msgid] = POEntry( msgid=msgid, msgid_plural=msgid_plural, source_refs=[ref], flags=flags, msgstr_plural={0: '', 1: ''}, ) return list(seen.values()) # ──── POT generation ──── def generate_pot(entries: list[POEntry], pot_path: str | Path) -> None: """Generate a .pot template file from extracted entries.""" now = datetime.now(UTC).strftime('%Y-%m-%d %H:%M%z') header = POEntry( comments=[ '# SOME DESCRIPTIVE TITLE.', "# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER", '# This file is distributed under the same license as the PACKAGE package.', '# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.', '#', ], flags=['fuzzy'], msgstr='Project-Id-Version: PACKAGE VERSION\n' + 'Report-Msgid-Bugs-To: \n' + f'POT-Creation-Date: {now}\n' + 'PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n' + 'Last-Translator: FULL NAME <EMAIL@ADDRESS>\n' + 'Language-Team: LANGUAGE <LL@li.org>\n' + 'Language: \n' + 'MIME-Version: 1.0\n' + 'Content-Type: text/plain; charset=UTF-8\n' + 'Content-Transfer-Encoding: 8bit\n' + 'Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n', ) write_po(pot_path, header, entries) # ──── PO init (replaces msginit) ──── PLURAL_FORMS: dict[str, str] = { 'en': 'nplurals=2; plural=(n != 1);', 'de': 'nplurals=2; plural=(n != 1);', 'fr': 'nplurals=2; plural=(n > 1);', 'es': 'nplurals=2; plural=(n != 1);', 'pt-BR': 'nplurals=2; plural=(n > 1);', 'tr': 'nplurals=2; plural=(n != 1);', 'uk': 'nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : 2);', 'th': 'nplurals=1; plural=0;', 'zh-CHT': 'nplurals=1; plural=0;', 'zh-CHS': 'nplurals=1; plural=0;', 'ko': 'nplurals=1; plural=0;', 'ja': 'nplurals=1; plural=0;', } def init_po(pot_path: str | Path, po_path: str | Path, language: str) -> None: """Create a new .po file from a .pot template (replaces msginit).""" _, entries = parse_po(pot_path) plural_forms = PLURAL_FORMS.get(language, 'nplurals=2; plural=(n != 1);') now = datetime.now(UTC).strftime('%Y-%m-%d %H:%M%z') header = POEntry( comments=[ f'# {language} translations for PACKAGE package.', "# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER", '# This file is distributed under the same license as the PACKAGE package.', '# Automatically generated.', '#', ], msgstr='Project-Id-Version: PACKAGE VERSION\n' + 'Report-Msgid-Bugs-To: \n' + f'POT-Creation-Date: {now}\n' + f'PO-Revision-Date: {now}\n' + 'Last-Translator: Automatically generated\n' + 'Language-Team: none\n' + f'Language: {language}\n' + 'MIME-Version: 1.0\n' + 'Content-Type: text/plain; charset=UTF-8\n' + 'Content-Transfer-Encoding: 8bit\n' + f'Plural-Forms: {plural_forms}\n', ) nplurals = int(re.search(r'nplurals=(\d+)', plural_forms).group(1)) for e in entries: if e.is_plural: e.msgstr_plural = dict.fromkeys(range(nplurals), '') write_po(po_path, header, entries) # ──── PO merge (replaces msgmerge) ──── def merge_po(po_path: str | Path, pot_path: str | Path) -> None: """Update a .po file with entries from a .pot template (replaces msgmerge --update).""" po_header, po_entries = parse_po(po_path) _, pot_entries = parse_po(pot_path) existing = {e.msgid: e for e in po_entries} merged = [] for pot_e in pot_entries: if pot_e.msgid in existing: old = existing[pot_e.msgid] old.source_refs = pot_e.source_refs old.flags = pot_e.flags old.comments = pot_e.comments if pot_e.is_plural: old.msgid_plural = pot_e.msgid_plural merged.append(old) else: merged.append(pot_e) merged.sort(key=lambda e: e.msgid) write_po(po_path, po_header, merged)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/translations/potools.py", "license": "MIT License", "lines": 306, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:common/file_chunker.py
import math import os from pathlib import Path CHUNK_SIZE = 45 * 1024 * 1024 # 45MB, under GitHub's 50MB limit def get_chunk_name(name, idx, num_chunks): return f"{name}.chunk{idx+1:02d}of{num_chunks:02d}" def get_manifest_path(name): return f"{name}.chunkmanifest" def get_chunk_paths(path, file_size): num_chunks = math.ceil(file_size / CHUNK_SIZE) return [get_manifest_path(path)] + [get_chunk_name(path, i, num_chunks) for i in range(num_chunks)] def chunk_file(path, targets): manifest_path, *chunk_paths = targets with open(path, 'rb') as f: data = f.read() actual_num_chunks = max(1, math.ceil(len(data) / CHUNK_SIZE)) assert len(chunk_paths) >= actual_num_chunks, f"Allowed {len(chunk_paths)} chunks but needs at least {actual_num_chunks}, for path {path}" for i, chunk_path in enumerate(chunk_paths): with open(chunk_path, 'wb') as f: f.write(data[i * CHUNK_SIZE:(i + 1) * CHUNK_SIZE]) Path(manifest_path).write_text(str(len(chunk_paths))) os.remove(path) def read_file_chunked(path): manifest_path = get_manifest_path(path) if os.path.isfile(manifest_path): num_chunks = int(Path(manifest_path).read_text().strip()) return b''.join(Path(get_chunk_name(path, i, num_chunks)).read_bytes() for i in range(num_chunks)) if os.path.isfile(path): return Path(path).read_bytes() raise FileNotFoundError(path)
{ "repo_id": "commaai/openpilot", "file_path": "common/file_chunker.py", "license": "MIT License", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ui/widgets/icon_widget.py
import pyray as rl from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.widgets import Widget class IconWidget(Widget): def __init__(self, image_path: str, size: tuple[int, int], opacity: float = 1.0): super().__init__() self._texture = gui_app.texture(image_path, size[0], size[1]) self._opacity = opacity self.set_rect(rl.Rectangle(0, 0, float(size[0]), float(size[1]))) self.set_enabled(False) def _render(self, _) -> None: color = rl.Color(255, 255, 255, int(self._opacity * 255)) rl.draw_texture_ex(self._texture, rl.Vector2(self._rect.x, self._rect.y), 0.0, 1.0, color)
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/icon_widget.py", "license": "MIT License", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ui/widgets/layouts.py
from enum import IntFlag from openpilot.system.ui.widgets import Widget class Alignment(IntFlag): LEFT = 0 # TODO: implement # H_CENTER = 2 # RIGHT = 4 TOP = 8 V_CENTER = 16 BOTTOM = 32 class HBoxLayout(Widget): """ A Widget that lays out child Widgets horizontally. """ def __init__(self, widgets: list[Widget] | None = None, spacing: int = 0, alignment: Alignment = Alignment.LEFT | Alignment.V_CENTER): super().__init__() self._widgets: list[Widget] = [] self._spacing = spacing self._alignment = alignment if widgets is not None: for widget in widgets: self.add_widget(widget) @property def widgets(self) -> list[Widget]: return self._widgets def add_widget(self, widget: Widget) -> None: self._widgets.append(widget) def _render(self, _): visible_widgets = [w for w in self._widgets if w.is_visible] cur_offset_x = 0 for idx, widget in enumerate(visible_widgets): spacing = self._spacing if (idx > 0) else 0 x = self._rect.x + cur_offset_x + spacing cur_offset_x += widget.rect.width + spacing if self._alignment & Alignment.TOP: y = self._rect.y elif self._alignment & Alignment.BOTTOM: y = self._rect.y + self._rect.height - widget.rect.height else: # center y = self._rect.y + (self._rect.height - widget.rect.height) / 2 # Update widget position and render widget.set_position(round(x), round(y)) widget.set_parent_rect(self._rect) widget.render()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/layouts.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ui/widgets/nav_widget.py
from __future__ import annotations import abc import pyray as rl from collections.abc import Callable from openpilot.system.ui.widgets import Widget from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter from openpilot.system.ui.lib.application import gui_app, MousePos, MouseEvent SWIPE_AWAY_THRESHOLD = 80 # px to dismiss after releasing START_DISMISSING_THRESHOLD = 40 # px to start dismissing while dragging BLOCK_SWIPE_AWAY_THRESHOLD = 60 # px horizontal movement to block swipe away NAV_BAR_MARGIN = 6 NAV_BAR_WIDTH = 205 NAV_BAR_HEIGHT = 8 DISMISS_PUSH_OFFSET = NAV_BAR_MARGIN + NAV_BAR_HEIGHT + 50 # px extra to push down when dismissing DISMISS_ANIMATION_RC = 0.2 # slightly slower for non-user triggered dismiss animation class NavBar(Widget): FADE_AFTER_SECONDS = 2.0 def __init__(self): super().__init__() self.set_rect(rl.Rectangle(0, 0, NAV_BAR_WIDTH, NAV_BAR_HEIGHT)) self._alpha = 1.0 self._alpha_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) self._fade_time = 0.0 def set_alpha(self, alpha: float) -> None: self._alpha = alpha self._fade_time = rl.get_time() def show_event(self): super().show_event() self._alpha = 1.0 self._alpha_filter.x = 1.0 self._fade_time = rl.get_time() def _render(self, _): if rl.get_time() - self._fade_time > self.FADE_AFTER_SECONDS: self._alpha = 0.0 alpha = self._alpha_filter.update(self._alpha) # white bar with black border rl.draw_rectangle_rounded(self._rect, 1.0, 6, rl.Color(255, 255, 255, int(255 * 0.9 * alpha))) rl.draw_rectangle_rounded_lines_ex(self._rect, 1.0, 6, 2, rl.Color(0, 0, 0, int(255 * 0.3 * alpha))) class NavWidget(Widget, abc.ABC): """ A full screen widget that supports back navigation by swiping down from the top. """ BACK_TOUCH_AREA_PERCENTAGE = 0.65 def __init__(self): super().__init__() # State self._drag_start_pos: MousePos | None = None # cleared after certain amount of horizontal movement self._dragging_down = False # swiped down enough to trigger dismissing on release self._playing_dismiss_animation = False # released and animating away self._y_pos_filter = BounceFilter(0.0, 0.1, 1 / gui_app.target_fps, bounce=1) self._back_callback: Callable[[], None] | None = None # persistent callback for any back navigation self._dismiss_callback: Callable[[], None] | None = None # transient callback for programmatic dismiss # TODO: move this state into NavBar self._nav_bar = NavBar() self._nav_bar_show_time = 0.0 self._nav_bar_y_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) def _back_enabled(self) -> bool: # Children can override this to block swipe away, like when not at # the top of a vertical scroll panel to prevent erroneous swipes return True def set_back_callback(self, callback: Callable[[], None]) -> None: self._back_callback = callback def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: super()._handle_mouse_event(mouse_event) # Don't let touch events change filter state during dismiss animation if self._playing_dismiss_animation: return if mouse_event.left_pressed: # user is able to swipe away if starting near top of screen self._y_pos_filter.update_alpha(0.04) in_dismiss_area = mouse_event.pos.y < self._rect.height * self.BACK_TOUCH_AREA_PERCENTAGE if in_dismiss_area and self._back_enabled(): self._drag_start_pos = mouse_event.pos elif mouse_event.left_down: if self._drag_start_pos is not None: # block swiping away if too much horizontal or upward movement # block (lock-in) threshold is higher than start dismissing horizontal_movement = abs(mouse_event.pos.x - self._drag_start_pos.x) > BLOCK_SWIPE_AWAY_THRESHOLD upward_movement = mouse_event.pos.y - self._drag_start_pos.y < -BLOCK_SWIPE_AWAY_THRESHOLD if not (horizontal_movement or upward_movement): # no blocking movement, check if we should start dismissing if mouse_event.pos.y - self._drag_start_pos.y > START_DISMISSING_THRESHOLD: self._dragging_down = True else: if not self._dragging_down: self._drag_start_pos = None elif mouse_event.left_released: # reset rc for either slide up or down animation self._y_pos_filter.update_alpha(0.1) # if far enough, trigger back navigation callback if self._drag_start_pos is not None: if mouse_event.pos.y - self._drag_start_pos.y > SWIPE_AWAY_THRESHOLD: self._playing_dismiss_animation = True self._drag_start_pos = None self._dragging_down = False def _update_state(self): super()._update_state() new_y = 0.0 if self._dragging_down: self._nav_bar.set_alpha(1.0) # FIXME: disabling this widget on new push_widget still causes this widget to track mouse events without mouse down if not self.enabled: self._drag_start_pos = None if self._drag_start_pos is not None: last_mouse_event = gui_app.last_mouse_event # push entire widget as user drags it away new_y = max(last_mouse_event.pos.y - self._drag_start_pos.y, 0) if new_y < SWIPE_AWAY_THRESHOLD: new_y /= 2 # resistance until mouse release would dismiss widget if self._playing_dismiss_animation: new_y = self._rect.height + DISMISS_PUSH_OFFSET new_y = round(self._y_pos_filter.update(new_y)) if abs(new_y) < 1 and self._y_pos_filter.velocity.x == 0.0: new_y = self._y_pos_filter.x = 0.0 if new_y > self._rect.height + DISMISS_PUSH_OFFSET - 10: gui_app.pop_widget() if self._back_callback is not None: self._back_callback() if self._dismiss_callback is not None: self._dismiss_callback() self._dismiss_callback = None self._playing_dismiss_animation = False self._drag_start_pos = None self._dragging_down = False self.set_position(self._rect.x, new_y) def _layout(self): # Dim whatever is behind this widget, fading with position (runs after _update_state so position is correct) overlay_alpha = int(200 * max(0.0, min(1.0, 1.0 - self._rect.y / self._rect.height))) if self._rect.height > 0 else 0 rl.draw_rectangle(0, 0, int(self._rect.width), int(self._rect.height), rl.Color(0, 0, 0, overlay_alpha)) bounce_height = 20 rl.draw_rectangle(int(self._rect.x), int(self._rect.y), int(self._rect.width), int(self._rect.height + bounce_height), rl.BLACK) def render(self, rect: rl.Rectangle | None = None) -> bool | int | None: ret = super().render(rect) bar_x = self._rect.x + (self._rect.width - self._nav_bar.rect.width) / 2 nav_bar_delayed = rl.get_time() - self._nav_bar_show_time < 0.4 # User dragging or dismissing, nav bar follows NavWidget if self._drag_start_pos is not None or self._playing_dismiss_animation: self._nav_bar_y_filter.x = NAV_BAR_MARGIN + self._y_pos_filter.x # Waiting to show elif nav_bar_delayed: self._nav_bar_y_filter.x = -NAV_BAR_MARGIN - NAV_BAR_HEIGHT # Animate back to top else: self._nav_bar_y_filter.update(NAV_BAR_MARGIN) self._nav_bar.set_position(bar_x, round(self._nav_bar_y_filter.x)) self._nav_bar.render() return ret @property def is_dismissing(self) -> bool: return self._dragging_down or self._playing_dismiss_animation def dismiss(self, callback: Callable[[], None] | None = None): """Programmatically trigger the dismiss animation. Calls pop_widget when done, then callback.""" if not self._playing_dismiss_animation: self._playing_dismiss_animation = True self._y_pos_filter.update_alpha(DISMISS_ANIMATION_RC) self._dismiss_callback = callback def show_event(self): super().show_event() self._nav_bar.show_event() # Reset state self._drag_start_pos = None self._dragging_down = False self._playing_dismiss_animation = False self._dismiss_callback = None # Start NavWidget off-screen, no matter how tall it is self._y_pos_filter.update_alpha(0.1) self._y_pos_filter.x = gui_app.height self._nav_bar_y_filter.x = -NAV_BAR_MARGIN - NAV_BAR_HEIGHT self._nav_bar_show_time = rl.get_time()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/nav_widget.py", "license": "MIT License", "lines": 169, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:common/parameterized.py
import sys import pytest import inspect class parameterized: @staticmethod def expand(cases): cases = list(cases) if not cases: return lambda func: pytest.mark.skip("no parameterized cases")(func) def decorator(func): params = [p for p in inspect.signature(func).parameters if p != 'self'] normalized = [c if isinstance(c, tuple) else (c,) for c in cases] # Infer arg count from first case so extra params (e.g. from @given) are left untouched expand_params = params[: len(normalized[0])] if len(expand_params) == 1: return pytest.mark.parametrize(expand_params[0], [c[0] for c in normalized])(func) return pytest.mark.parametrize(', '.join(expand_params), normalized)(func) return decorator def parameterized_class(attrs, input_list=None): if isinstance(attrs, list) and (not attrs or isinstance(attrs[0], dict)): params_list = attrs else: assert input_list is not None attr_names = (attrs,) if isinstance(attrs, str) else tuple(attrs) params_list = [dict(zip(attr_names, v if isinstance(v, (tuple, list)) else (v,), strict=False)) for v in input_list] def decorator(cls): globs = sys._getframe(1).f_globals for i, params in enumerate(params_list): name = f"{cls.__name__}_{i}" new_cls = type(name, (cls,), dict(params)) new_cls.__module__ = cls.__module__ new_cls.__test__ = True # override inherited False so pytest collects this subclass globs[name] = new_cls # Don't collect the un-parametrised base, but return it so outer decorators # (e.g. @pytest.mark.skip) land on it and propagate to subclasses via MRO. cls.__test__ = False return cls return decorator
{ "repo_id": "commaai/openpilot", "file_path": "common/parameterized.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/tests/test_widget_leaks.py
import pyray as rl rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) import gc import weakref import pytest from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.widgets import Widget # mici dialogs from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide as MiciTrainingGuide, OnboardingWindow as MiciOnboardingWindow from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import DriverCameraDialog as MiciDriverCameraDialog from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog as MiciPairingDialog from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialogV2, BigInputDialog from openpilot.selfdrive.ui.mici.layouts.settings.device import MiciFccModal # tici dialogs from openpilot.selfdrive.ui.onroad.driver_camera_dialog import DriverCameraDialog as TiciDriverCameraDialog from openpilot.selfdrive.ui.layouts.onboarding import OnboardingWindow as TiciOnboardingWindow from openpilot.selfdrive.ui.widgets.pairing_dialog import PairingDialog as TiciPairingDialog from openpilot.system.ui.widgets.confirm_dialog import ConfirmDialog from openpilot.system.ui.widgets.option_dialog import MultiOptionDialog from openpilot.system.ui.widgets.html_render import HtmlModal from openpilot.system.ui.widgets.keyboard import Keyboard # FIXME: known small leaks not worth worrying about at the moment KNOWN_LEAKS = { "openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog.DriverCameraView", "openpilot.selfdrive.ui.mici.layouts.onboarding.TermsPage", "openpilot.selfdrive.ui.mici.layouts.onboarding.TrainingGuide", "openpilot.selfdrive.ui.mici.layouts.onboarding.DeclinePage", "openpilot.selfdrive.ui.mici.layouts.onboarding.OnboardingWindow", "openpilot.selfdrive.ui.onroad.driver_state.DriverStateRenderer", "openpilot.selfdrive.ui.onroad.driver_camera_dialog.DriverCameraDialog", "openpilot.selfdrive.ui.layouts.onboarding.TermsPage", "openpilot.selfdrive.ui.layouts.onboarding.DeclinePage", "openpilot.selfdrive.ui.layouts.onboarding.OnboardingWindow", "openpilot.system.ui.widgets.confirm_dialog.ConfirmDialog", "openpilot.system.ui.widgets.label.Label", "openpilot.system.ui.widgets.button.Button", "openpilot.system.ui.widgets.html_render.HtmlRenderer", "openpilot.system.ui.widgets.nav_widget.NavBar", "openpilot.selfdrive.ui.mici.layouts.settings.device.MiciFccModal", "openpilot.system.ui.widgets.inputbox.InputBox", "openpilot.system.ui.widgets.scroller_tici.Scroller", "openpilot.system.ui.widgets.label.UnifiedLabel", "openpilot.system.ui.widgets.mici_keyboard.MiciKeyboard", "openpilot.selfdrive.ui.mici.widgets.dialog.BigConfirmationDialogV2", "openpilot.system.ui.widgets.keyboard.Keyboard", "openpilot.system.ui.widgets.slider.BigSlider", "openpilot.selfdrive.ui.mici.widgets.dialog.BigInputDialog", "openpilot.system.ui.widgets.option_dialog.MultiOptionDialog", } def get_child_widgets(widget: Widget) -> list[Widget]: children = [] for val in widget.__dict__.values(): items = val if isinstance(val, (list, tuple)) else (val,) children.extend(w for w in items if isinstance(w, Widget)) return children @pytest.mark.skip(reason="segfaults") def test_dialogs_do_not_leak(): gui_app.init_window("ref-test") leaked_widgets = set() for ctor in ( # mici MiciDriverCameraDialog, MiciTrainingGuide, MiciOnboardingWindow, MiciPairingDialog, lambda: BigDialog("test", "test"), lambda: BigConfirmationDialogV2("test", "icons_mici/settings/network/new/trash.png"), lambda: BigInputDialog("test"), lambda: MiciFccModal(text="test"), # tici TiciDriverCameraDialog, TiciOnboardingWindow, TiciPairingDialog, Keyboard, lambda: ConfirmDialog("test", "ok"), lambda: MultiOptionDialog("test", ["a", "b"]), lambda: HtmlModal(text="test"), ): widget = ctor() all_refs = [weakref.ref(w) for w in get_child_widgets(widget) + [widget]] del widget for ref in all_refs: if ref() is not None: obj = ref() name = f"{type(obj).__module__}.{type(obj).__qualname__}" leaked_widgets.add(name) print(f"\n=== Widget {name} alive after del") print(" Referrers:") for r in gc.get_referrers(obj): if r is obj: continue if hasattr(r, '__self__') and r.__self__ is not obj: print(f" bound method: {type(r.__self__).__qualname__}.{r.__name__}") elif hasattr(r, '__func__'): print(f" method: {r.__name__}") else: print(f" {type(r).__module__}.{type(r).__qualname__}") del obj gui_app.close() unexpected = leaked_widgets - KNOWN_LEAKS assert not unexpected, f"New leaked widgets: {unexpected}" fixed = KNOWN_LEAKS - leaked_widgets assert not fixed, f"These leaks are fixed, remove from KNOWN_LEAKS: {fixed}" if __name__ == "__main__": test_dialogs_do_not_leak()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/tests/test_widget_leaks.py", "license": "MIT License", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:system/hardware/tici/lpa.py
# SGP.22 v2.3: https://www.gsma.com/solutions-and-impact/technologies/esim/wp-content/uploads/2021/07/SGP.22-v2.3.pdf import atexit import base64 import math import os import serial import sys from collections.abc import Generator from openpilot.system.hardware.base import LPABase, Profile DEFAULT_DEVICE = "/dev/ttyUSB2" DEFAULT_BAUD = 9600 DEFAULT_TIMEOUT = 5.0 # https://euicc-manual.osmocom.org/docs/lpa/applet-id/ ISDR_AID = "A0000005591010FFFFFFFF8900000100" MM = "org.freedesktop.ModemManager1" MM_MODEM = MM + ".Modem" ES10X_MSS = 120 DEBUG = os.environ.get("DEBUG") == "1" # TLV Tags TAG_ICCID = 0x5A TAG_PROFILE_INFO_LIST = 0xBF2D STATE_LABELS = {0: "disabled", 1: "enabled", 255: "unknown"} ICON_LABELS = {0: "jpeg", 1: "png", 255: "unknown"} CLASS_LABELS = {0: "test", 1: "provisioning", 2: "operational", 255: "unknown"} def b64e(data: bytes) -> str: return base64.b64encode(data).decode("ascii") class AtClient: def __init__(self, device: str, baud: int, timeout: float, debug: bool) -> None: self.debug = debug self.channel: str | None = None self._timeout = timeout self._serial: serial.Serial | None = None try: self._serial = serial.Serial(device, baudrate=baud, timeout=timeout) self._serial.reset_input_buffer() except (serial.SerialException, PermissionError, OSError): pass def close(self) -> None: try: if self.channel: self.query(f"AT+CCHC={self.channel}") self.channel = None finally: if self._serial: self._serial.close() def _send(self, cmd: str) -> None: if self.debug: print(f"SER >> {cmd}", file=sys.stderr) self._serial.write((cmd + "\r").encode("ascii")) def _expect(self) -> list[str]: lines: list[str] = [] while True: raw = self._serial.readline() if not raw: raise TimeoutError("AT command timed out") line = raw.decode(errors="ignore").strip() if not line: continue if self.debug: print(f"SER << {line}", file=sys.stderr) if line == "OK": return lines if line == "ERROR" or line.startswith("+CME ERROR"): raise RuntimeError(f"AT command failed: {line}") lines.append(line) def _get_modem(self): import dbus bus = dbus.SystemBus() mm = bus.get_object(MM, '/org/freedesktop/ModemManager1') objects = mm.GetManagedObjects(dbus_interface="org.freedesktop.DBus.ObjectManager", timeout=self._timeout) modem_path = list(objects.keys())[0] return bus.get_object(MM, modem_path) def _dbus_query(self, cmd: str) -> list[str]: if self.debug: print(f"DBUS >> {cmd}", file=sys.stderr) try: result = str(self._get_modem().Command(cmd, math.ceil(self._timeout), dbus_interface=MM_MODEM, timeout=self._timeout)) except Exception as e: raise RuntimeError(f"AT command failed: {e}") from e lines = [line.strip() for line in result.splitlines() if line.strip()] if self.debug: for line in lines: print(f"DBUS << {line}", file=sys.stderr) return lines def query(self, cmd: str) -> list[str]: if self._serial: self._send(cmd) return self._expect() return self._dbus_query(cmd) def open_isdr(self) -> None: # close any stale logical channel from a previous crashed session try: self.query("AT+CCHC=1") except RuntimeError: pass for line in self.query(f'AT+CCHO="{ISDR_AID}"'): if line.startswith("+CCHO:") and (ch := line.split(":", 1)[1].strip()): self.channel = ch return raise RuntimeError("Failed to open ISD-R application") def send_apdu(self, apdu: bytes) -> tuple[bytes, int, int]: if not self.channel: raise RuntimeError("Logical channel is not open") hex_payload = apdu.hex().upper() for line in self.query(f'AT+CGLA={self.channel},{len(hex_payload)},"{hex_payload}"'): if line.startswith("+CGLA:"): parts = line.split(":", 1)[1].split(",", 1) if len(parts) == 2: data = bytes.fromhex(parts[1].strip().strip('"')) if len(data) >= 2: return data[:-2], data[-2], data[-1] raise RuntimeError("Missing +CGLA response") # --- TLV utilities --- def iter_tlv(data: bytes, with_positions: bool = False) -> Generator: idx, length = 0, len(data) while idx < length: start_pos = idx tag = data[idx] idx += 1 if tag & 0x1F == 0x1F: # Multi-byte tag tag_value = tag while idx < length: next_byte = data[idx] idx += 1 tag_value = (tag_value << 8) | next_byte if not (next_byte & 0x80): break else: tag_value = tag if idx >= length: break size = data[idx] idx += 1 if size & 0x80: # Multi-byte length num_bytes = size & 0x7F if idx + num_bytes > length: break size = int.from_bytes(data[idx : idx + num_bytes], "big") idx += num_bytes if idx + size > length: break value = data[idx : idx + size] idx += size yield (tag_value, value, start_pos, idx) if with_positions else (tag_value, value) def find_tag(data: bytes, target: int) -> bytes | None: return next((v for t, v in iter_tlv(data) if t == target), None) def tbcd_to_string(raw: bytes) -> str: return "".join(str(n) for b in raw for n in (b & 0x0F, b >> 4) if n <= 9) # Profile field decoders: TLV tag -> (field_name, decoder) _PROFILE_FIELDS = { TAG_ICCID: ("iccid", tbcd_to_string), 0x4F: ("isdpAid", lambda v: v.hex().upper()), 0x9F70: ("profileState", lambda v: STATE_LABELS.get(v[0], "unknown")), 0x90: ("profileNickname", lambda v: v.decode("utf-8", errors="ignore") or None), 0x91: ("serviceProviderName", lambda v: v.decode("utf-8", errors="ignore") or None), 0x92: ("profileName", lambda v: v.decode("utf-8", errors="ignore") or None), 0x93: ("iconType", lambda v: ICON_LABELS.get(v[0], "unknown")), 0x94: ("icon", b64e), 0x95: ("profileClass", lambda v: CLASS_LABELS.get(v[0], "unknown")), } def _decode_profile_fields(data: bytes) -> dict: """Parse known profile metadata TLV fields into a dict.""" result = {} for tag, value in iter_tlv(data): if (field := _PROFILE_FIELDS.get(tag)): result[field[0]] = field[1](value) return result # --- ES10x command transport --- def es10x_command(client: AtClient, data: bytes) -> bytes: response = bytearray() sequence = 0 offset = 0 while offset < len(data): chunk = data[offset : offset + ES10X_MSS] offset += len(chunk) is_last = offset == len(data) apdu = bytes([0x80, 0xE2, 0x91 if is_last else 0x11, sequence & 0xFF, len(chunk)]) + chunk segment, sw1, sw2 = client.send_apdu(apdu) response.extend(segment) while True: if sw1 == 0x61: # More data available segment, sw1, sw2 = client.send_apdu(bytes([0x80, 0xC0, 0x00, 0x00, sw2 or 0])) response.extend(segment) continue if (sw1 & 0xF0) == 0x90: break raise RuntimeError(f"APDU failed with SW={sw1:02X}{sw2:02X}") sequence += 1 return bytes(response) # --- Profile operations --- def decode_profiles(blob: bytes) -> list[dict]: root = find_tag(blob, TAG_PROFILE_INFO_LIST) if root is None: raise RuntimeError("Missing ProfileInfoList") list_ok = find_tag(root, 0xA0) if list_ok is None: return [] defaults = {name: None for name, _ in _PROFILE_FIELDS.values()} return [{**defaults, **_decode_profile_fields(value)} for tag, value in iter_tlv(list_ok) if tag == 0xE3] def list_profiles(client: AtClient) -> list[dict]: return decode_profiles(es10x_command(client, TAG_PROFILE_INFO_LIST.to_bytes(2, "big") + b"\x00")) class TiciLPA(LPABase): _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): if hasattr(self, '_client'): return self._client = AtClient(DEFAULT_DEVICE, DEFAULT_BAUD, DEFAULT_TIMEOUT, debug=DEBUG) self._client.open_isdr() atexit.register(self._client.close) def list_profiles(self) -> list[Profile]: return [ Profile( iccid=p.get("iccid", ""), nickname=p.get("profileNickname") or "", enabled=p.get("profileState") == "enabled", provider=p.get("serviceProviderName") or "", ) for p in list_profiles(self._client) ] def get_active_profile(self) -> Profile | None: return None def delete_profile(self, iccid: str) -> None: return None def download_profile(self, qr: str, nickname: str | None = None) -> None: return None def nickname_profile(self, iccid: str, nickname: str) -> None: return None def switch_profile(self, iccid: str) -> None: return None
{ "repo_id": "commaai/openpilot", "file_path": "system/hardware/tici/lpa.py", "license": "MIT License", "lines": 233, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:tools/longitudinal_maneuvers/maneuver_helpers.py
from enum import IntEnum class Axis(IntEnum): TIME = 0 EGO_POSITION = 1 LEAD_DISTANCE= 2 EGO_V = 3 LEAD_V = 4 EGO_A = 5 D_REL = 6 axis_labels = {Axis.TIME: 'Time (s)', Axis.EGO_POSITION: 'Ego position (m)', Axis.LEAD_DISTANCE: 'Lead absolute position (m)', Axis.EGO_V: 'Ego Velocity (m/s)', Axis.LEAD_V: 'Lead Velocity (m/s)', Axis.EGO_A: 'Ego acceleration (m/s^2)', Axis.D_REL: 'Lead distance (m)'}
{ "repo_id": "commaai/openpilot", "file_path": "tools/longitudinal_maneuvers/maneuver_helpers.py", "license": "MIT License", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/tests/diff/replay_script.py
from __future__ import annotations from typing import TYPE_CHECKING from collections.abc import Callable from dataclasses import dataclass from cereal import car, log, messaging from cereal.messaging import PubMaster from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params from openpilot.selfdrive.selfdrived.alertmanager import set_offroad_alert from openpilot.selfdrive.ui.tests.diff.replay import FPS, LayoutVariant from openpilot.system.updated.updated import parse_release_notes WAIT = int(FPS * 0.5) # Default frames to wait after events AlertSize = log.SelfdriveState.AlertSize AlertStatus = log.SelfdriveState.AlertStatus BRANCH_NAME = "this-is-a-really-super-mega-ultra-max-extreme-ultimate-long-branch-name" @dataclass class ScriptEvent: if TYPE_CHECKING: # Only import for type checking to avoid excluding the application code from coverage from openpilot.system.ui.lib.application import MouseEvent setup: Callable | None = None # Setup function to run prior to adding mouse events mouse_events: list[MouseEvent] | None = None # Mouse events to send to the application on this event's frame send_fn: Callable | None = None # When set, the main loop uses this as the new persistent sender ScriptEntry = tuple[int, ScriptEvent] # (frame, event) class Script: def __init__(self, fps: int) -> None: self.fps = fps self.frame = 0 self.entries: list[ScriptEntry] = [] def get_frame_time(self) -> float: return self.frame / self.fps def add(self, event: ScriptEvent, before: int = 0, after: int = 0) -> None: """Add event to the script, optionally with the given number of frames to wait before or after the event.""" self.frame += before self.entries.append((self.frame, event)) self.frame += after def end(self) -> None: """Add a final empty event to mark the end of the script.""" self.add(ScriptEvent()) # Without this, it will just end on the last event without waiting for any specified delay after it def wait(self, frames: int) -> None: """Add a delay for the given number of frames followed by an empty event.""" self.add(ScriptEvent(), before=frames) def setup(self, fn: Callable, wait_after: int = WAIT) -> None: """Add a setup function to be called immediately followed by a delay of the given number of frames.""" self.add(ScriptEvent(setup=fn), after=wait_after) def set_send(self, fn: Callable, wait_after: int = WAIT) -> None: """Set a new persistent send function to be called every frame.""" self.add(ScriptEvent(send_fn=fn), after=wait_after) # TODO: Also add more complex gestures, like swipe or drag def click(self, x: int, y: int, wait_after: int = WAIT, wait_between: int = 2) -> None: """Add a click event to the script for the given position and specify frames to wait between mouse events or after the click.""" # NOTE: By default we wait a couple frames between mouse events so pressed states will be rendered from openpilot.system.ui.lib.application import MouseEvent, MousePos # TODO: Add support for long press (left_down=True) mouse_down = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=True, left_released=False, left_down=False, t=self.get_frame_time()) self.add(ScriptEvent(mouse_events=[mouse_down]), after=wait_between) mouse_up = MouseEvent(pos=MousePos(x, y), slot=0, left_pressed=False, left_released=True, left_down=False, t=self.get_frame_time()) self.add(ScriptEvent(mouse_events=[mouse_up]), after=wait_after) # --- Setup functions --- def put_update_params(params: Params | None = None) -> None: if params is None: params = Params() params.put("UpdaterCurrentReleaseNotes", parse_release_notes(BASEDIR)) params.put("UpdaterNewReleaseNotes", parse_release_notes(BASEDIR)) params.put("UpdaterTargetBranch", BRANCH_NAME) def setup_offroad_alerts() -> None: put_update_params(Params()) set_offroad_alert("Offroad_TemperatureTooHigh", True, extra_text='99C') set_offroad_alert("Offroad_ExcessiveActuation", True, extra_text='longitudinal') set_offroad_alert("Offroad_IsTakingSnapshot", True) def setup_update_available() -> None: params = Params() params.put_bool("UpdateAvailable", True) params.put("UpdaterNewDescription", f"0.10.2 / {BRANCH_NAME} / 0a1b2c3 / Jan 01") put_update_params(params) def setup_developer_params() -> None: CP = car.CarParams() CP.alphaLongitudinalAvailable = True Params().put("CarParamsPersistent", CP.to_bytes()) # --- Send functions --- def send_onroad(pm: PubMaster) -> None: ds = messaging.new_message('deviceState') ds.deviceState.started = True ds.deviceState.networkType = log.DeviceState.NetworkType.wifi ps = messaging.new_message('pandaStates', 1) ps.pandaStates[0].pandaType = log.PandaState.PandaType.dos ps.pandaStates[0].ignitionLine = True pm.send('deviceState', ds) pm.send('pandaStates', ps) def make_network_state_setup(pm: PubMaster, network_type) -> Callable: def _send() -> None: ds = messaging.new_message('deviceState') ds.deviceState.networkType = network_type pm.send('deviceState', ds) return _send def make_alert_setup(pm: PubMaster, size, text1, text2, status) -> Callable: def _send() -> None: send_onroad(pm) alert = messaging.new_message('selfdriveState') ss = alert.selfdriveState ss.alertSize = size ss.alertText1 = text1 ss.alertText2 = text2 ss.alertStatus = status pm.send('selfdriveState', alert) return _send # --- Script builders --- def build_mici_script(pm: PubMaster, main_layout, script: Script) -> None: """Build the replay script for the mici layout.""" from openpilot.system.ui.lib.application import gui_app center = (gui_app.width // 2, gui_app.height // 2) # TODO: Explore more script.wait(FPS) script.click(*center, FPS) # Open settings script.click(*center, FPS) # Open toggles script.end() def build_tizi_script(pm: PubMaster, main_layout, script: Script) -> None: """Build the replay script for the tizi layout.""" def make_home_refresh_setup(fn: Callable) -> Callable: """Return setup function that calls the given function to modify state and forces an immediate refresh on the home layout.""" from openpilot.selfdrive.ui.layouts.main import MainState def setup(): fn() main_layout._layouts[MainState.HOME].last_refresh = 0 return setup # TODO: Better way of organizing the events # === Homescreen === script.set_send(make_network_state_setup(pm, log.DeviceState.NetworkType.wifi)) # === Offroad Alerts (auto-transitions via HomeLayout refresh) === script.setup(make_home_refresh_setup(setup_offroad_alerts)) # === Update Available (auto-transitions via HomeLayout refresh) === script.setup(make_home_refresh_setup(setup_update_available)) # === Settings - Device (click sidebar settings button) === script.click(150, 90) script.click(1985, 790) # reset calibration confirmation script.click(650, 750) # cancel # === Settings - Network === script.click(278, 450) script.click(1880, 100) # advanced network settings script.click(630, 80) # back # === Settings - Toggles === script.click(278, 600) script.click(1200, 280) # experimental mode description # === Settings - Software === script.setup(put_update_params, wait_after=0) script.click(278, 720) # === Settings - Firehose === script.click(278, 845) # === Settings - Developer (set CarParamsPersistent first) === script.setup(setup_developer_params, wait_after=0) script.click(278, 950) script.click(2000, 960) # toggle alpha long script.click(1500, 875) # confirm # === Keyboard modal (SSH keys button in developer panel) === script.click(1930, 470) # click SSH keys script.click(1930, 115) # click cancel on keyboard # === Close settings === script.click(250, 160) # === Onroad === script.set_send(lambda: send_onroad(pm)) script.click(1000, 500) # click onroad to toggle sidebar # === Onroad alerts === # Small alert (normal) script.set_send(make_alert_setup(pm, AlertSize.small, "Small Alert", "This is a small alert", AlertStatus.normal)) # Medium alert (userPrompt) script.set_send(make_alert_setup(pm, AlertSize.mid, "Medium Alert", "This is a medium alert", AlertStatus.userPrompt)) # Full alert (critical) script.set_send(make_alert_setup(pm, AlertSize.full, "DISENGAGE IMMEDIATELY", "Driver Distracted", AlertStatus.critical)) # Full alert multiline script.set_send(make_alert_setup(pm, AlertSize.full, "Reverse\nGear", "", AlertStatus.normal)) # Full alert long text script.set_send(make_alert_setup(pm, AlertSize.full, "TAKE CONTROL IMMEDIATELY", "Calibration Invalid: Remount Device & Recalibrate", AlertStatus.userPrompt)) # End script.end() def build_script(pm: PubMaster, main_layout, variant: LayoutVariant) -> list[ScriptEntry]: """Build the replay script for the appropriate layout variant and return list of script entries.""" print(f"Building {variant} replay script...") script = Script(FPS) builder = build_tizi_script if variant == 'tizi' else build_mici_script builder(pm, main_layout, script) print(f"Built replay script with {len(script.entries)} events and {script.frame} frames ({script.get_frame_time():.2f} seconds)") return script.entries
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/tests/diff/replay_script.py", "license": "MIT License", "lines": 182, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/modeld/compile_warp.py
#!/usr/bin/env python3 import time import pickle import numpy as np from pathlib import Path from tinygrad.tensor import Tensor from tinygrad.helpers import Context from tinygrad.device import Device from tinygrad.engine.jit import TinyJit from openpilot.system.camerad.cameras.nv12_info import get_nv12_info from openpilot.common.transformations.model import MEDMODEL_INPUT_SIZE, DM_INPUT_SIZE from openpilot.common.transformations.camera import _ar_ox_fisheye, _os_fisheye MODELS_DIR = Path(__file__).parent / 'models' CAMERA_CONFIGS = [ (_ar_ox_fisheye.width, _ar_ox_fisheye.height), # tici: 1928x1208 (_os_fisheye.width, _os_fisheye.height), # mici: 1344x760 ] UV_SCALE_MATRIX = np.array([[0.5, 0, 0], [0, 0.5, 0], [0, 0, 1]], dtype=np.float32) UV_SCALE_MATRIX_INV = np.linalg.inv(UV_SCALE_MATRIX) IMG_BUFFER_SHAPE = (30, MEDMODEL_INPUT_SIZE[1] // 2, MEDMODEL_INPUT_SIZE[0] // 2) def warp_pkl_path(w, h): return MODELS_DIR / f'warp_{w}x{h}_tinygrad.pkl' def dm_warp_pkl_path(w, h): return MODELS_DIR / f'dm_warp_{w}x{h}_tinygrad.pkl' def warp_perspective_tinygrad(src_flat, M_inv, dst_shape, src_shape, stride_pad): w_dst, h_dst = dst_shape h_src, w_src = src_shape x = Tensor.arange(w_dst).reshape(1, w_dst).expand(h_dst, w_dst).reshape(-1) y = Tensor.arange(h_dst).reshape(h_dst, 1).expand(h_dst, w_dst).reshape(-1) # inline 3x3 matmul as elementwise to avoid reduce op (enables fusion with gather) src_x = M_inv[0, 0] * x + M_inv[0, 1] * y + M_inv[0, 2] src_y = M_inv[1, 0] * x + M_inv[1, 1] * y + M_inv[1, 2] src_w = M_inv[2, 0] * x + M_inv[2, 1] * y + M_inv[2, 2] src_x = src_x / src_w src_y = src_y / src_w x_nn_clipped = Tensor.round(src_x).clip(0, w_src - 1).cast('int') y_nn_clipped = Tensor.round(src_y).clip(0, h_src - 1).cast('int') idx = y_nn_clipped * (w_src + stride_pad) + x_nn_clipped return src_flat[idx] def frames_to_tensor(frames, model_w, model_h): H = (frames.shape[0] * 2) // 3 W = frames.shape[1] in_img1 = Tensor.cat(frames[0:H:2, 0::2], frames[1:H:2, 0::2], frames[0:H:2, 1::2], frames[1:H:2, 1::2], frames[H:H+H//4].reshape((H//2, W//2)), frames[H+H//4:H+H//2].reshape((H//2, W//2)), dim=0).reshape((6, H//2, W//2)) return in_img1 def make_frame_prepare(cam_w, cam_h, model_w, model_h): stride, y_height, uv_height, _ = get_nv12_info(cam_w, cam_h) uv_offset = stride * y_height stride_pad = stride - cam_w def frame_prepare_tinygrad(input_frame, M_inv): # UV_SCALE @ M_inv @ UV_SCALE_INV simplifies to elementwise scaling M_inv_uv = M_inv * Tensor([[1.0, 1.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 1.0]]) # deinterleave NV12 UV plane (UVUV... -> separate U, V) uv = input_frame[uv_offset:uv_offset + uv_height * stride].reshape(uv_height, stride) with Context(SPLIT_REDUCEOP=0): y = warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, (model_w, model_h), (cam_h, cam_w), stride_pad).realize() u = warp_perspective_tinygrad(uv[:cam_h//2, :cam_w:2].flatten(), M_inv_uv, (model_w//2, model_h//2), (cam_h//2, cam_w//2), 0).realize() v = warp_perspective_tinygrad(uv[:cam_h//2, 1:cam_w:2].flatten(), M_inv_uv, (model_w//2, model_h//2), (cam_h//2, cam_w//2), 0).realize() yuv = y.cat(u).cat(v).reshape((model_h * 3 // 2, model_w)) tensor = frames_to_tensor(yuv, model_w, model_h) return tensor return frame_prepare_tinygrad def make_update_img_input(frame_prepare, model_w, model_h): def update_img_input_tinygrad(tensor, frame, M_inv): M_inv = M_inv.to(Device.DEFAULT) new_img = frame_prepare(frame, M_inv) full_buffer = tensor[6:].cat(new_img, dim=0).contiguous() return full_buffer, Tensor.cat(full_buffer[:6], full_buffer[-6:], dim=0).contiguous().reshape(1, 12, model_h//2, model_w//2) return update_img_input_tinygrad def make_update_both_imgs(frame_prepare, model_w, model_h): update_img = make_update_img_input(frame_prepare, model_w, model_h) def update_both_imgs_tinygrad(calib_img_buffer, new_img, M_inv, calib_big_img_buffer, new_big_img, M_inv_big): calib_img_buffer, calib_img_pair = update_img(calib_img_buffer, new_img, M_inv) calib_big_img_buffer, calib_big_img_pair = update_img(calib_big_img_buffer, new_big_img, M_inv_big) return calib_img_buffer, calib_img_pair, calib_big_img_buffer, calib_big_img_pair return update_both_imgs_tinygrad def make_warp_dm(cam_w, cam_h, dm_w, dm_h): stride, y_height, _, _ = get_nv12_info(cam_w, cam_h) stride_pad = stride - cam_w def warp_dm(input_frame, M_inv): M_inv = M_inv.to(Device.DEFAULT) result = warp_perspective_tinygrad(input_frame[:cam_h*stride], M_inv, (dm_w, dm_h), (cam_h, cam_w), stride_pad).reshape(-1, dm_h * dm_w) return result return warp_dm def compile_modeld_warp(cam_w, cam_h): model_w, model_h = MEDMODEL_INPUT_SIZE _, _, _, yuv_size = get_nv12_info(cam_w, cam_h) print(f"Compiling modeld warp for {cam_w}x{cam_h}...") frame_prepare = make_frame_prepare(cam_w, cam_h, model_w, model_h) update_both_imgs = make_update_both_imgs(frame_prepare, model_w, model_h) update_img_jit = TinyJit(update_both_imgs, prune=True) full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize() big_full_buffer = Tensor.zeros(IMG_BUFFER_SHAPE, dtype='uint8').contiguous().realize() full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8) big_full_buffer_np = np.zeros(IMG_BUFFER_SHAPE, dtype=np.uint8) for i in range(10): new_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8) img_inputs = [full_buffer, Tensor.from_blob(new_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(), Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')] new_big_frame_np = (32 * np.random.randn(yuv_size).astype(np.float32) + 128).clip(0, 255).astype(np.uint8) big_img_inputs = [big_full_buffer, Tensor.from_blob(new_big_frame_np.ctypes.data, (yuv_size,), dtype='uint8').realize(), Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')] inputs = img_inputs + big_img_inputs Device.default.synchronize() inputs_np = [x.numpy() for x in inputs] inputs_np[0] = full_buffer_np inputs_np[3] = big_full_buffer_np st = time.perf_counter() out = update_img_jit(*inputs) full_buffer = out[0].contiguous().realize().clone() big_full_buffer = out[2].contiguous().realize().clone() mt = time.perf_counter() Device.default.synchronize() et = time.perf_counter() print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") pkl_path = warp_pkl_path(cam_w, cam_h) with open(pkl_path, "wb") as f: pickle.dump(update_img_jit, f) print(f" Saved to {pkl_path}") jit = pickle.load(open(pkl_path, "rb")) jit(*inputs) def compile_dm_warp(cam_w, cam_h): dm_w, dm_h = DM_INPUT_SIZE _, _, _, yuv_size = get_nv12_info(cam_w, cam_h) print(f"Compiling DM warp for {cam_w}x{cam_h}...") warp_dm = make_warp_dm(cam_w, cam_h, dm_w, dm_h) warp_dm_jit = TinyJit(warp_dm, prune=True) for i in range(10): inputs = [Tensor.from_blob((32 * Tensor.randn(yuv_size,) + 128).cast(dtype='uint8').realize().numpy().ctypes.data, (yuv_size,), dtype='uint8'), Tensor(Tensor.randn(3, 3).mul(8).realize().numpy(), device='NPY')] Device.default.synchronize() st = time.perf_counter() warp_dm_jit(*inputs) mt = time.perf_counter() Device.default.synchronize() et = time.perf_counter() print(f" [{i+1}/10] enqueue {(mt-st)*1e3:6.2f} ms -- total {(et-st)*1e3:6.2f} ms") pkl_path = dm_warp_pkl_path(cam_w, cam_h) with open(pkl_path, "wb") as f: pickle.dump(warp_dm_jit, f) print(f" Saved to {pkl_path}") def run_and_save_pickle(): for cam_w, cam_h in CAMERA_CONFIGS: compile_modeld_warp(cam_w, cam_h) compile_dm_warp(cam_w, cam_h) if __name__ == "__main__": run_and_save_pickle()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/modeld/compile_warp.py", "license": "MIT License", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/debug/mem_usage.py
#!/usr/bin/env python3 import argparse import os from collections import defaultdict import numpy as np from openpilot.common.utils import tabulate from openpilot.tools.lib.logreader import LogReader DEMO_ROUTE = "5beb9b58bd12b691/0000010a--a51155e496" MB = 1024 * 1024 TABULATE_OPTS = dict(tablefmt="simple_grid", stralign="center", numalign="center") def _get_procs(): from openpilot.selfdrive.test.test_onroad import PROCS return PROCS def is_openpilot_proc(name): if any(p in name for p in _get_procs()): return True # catch openpilot processes not in PROCS (athenad, manager, etc.) return 'openpilot' in name or name.startswith(('selfdrive.', 'system.')) def get_proc_name(proc): if len(proc.cmdline) > 0: return list(proc.cmdline)[0] return proc.name def pct(val_mb, total_mb): return val_mb / total_mb * 100 if total_mb else 0 def has_pss(proc_logs): """Check if logs contain PSS data (new field, not in old logs).""" try: for proc in proc_logs[-1].procLog.procs: if proc.memPss > 0: return True except AttributeError: pass return False def print_summary(proc_logs, device_states): mem = proc_logs[-1].procLog.mem total = mem.total / MB used = (mem.total - mem.available) / MB cached = mem.cached / MB shared = mem.shared / MB buffers = mem.buffers / MB lines = [ f" Total: {total:.0f} MB", f" Used (total-avail): {used:.0f} MB ({pct(used, total):.0f}%)", f" Cached: {cached:.0f} MB ({pct(cached, total):.0f}%) Buffers: {buffers:.0f} MB ({pct(buffers, total):.0f}%)", f" Shared/MSGQ: {shared:.0f} MB ({pct(shared, total):.0f}%)", ] if device_states: mem_pcts = [m.deviceState.memoryUsagePercent for m in device_states] lines.append(f" deviceState memory: {np.min(mem_pcts)}-{np.max(mem_pcts)}% (avg {np.mean(mem_pcts):.0f}%)") print("\n-- Memory Summary --") print("\n".join(lines)) return total def collect_per_process_mem(proc_logs, use_pss): """Collect per-process memory samples. Returns {name: {metric: [values_per_sample_in_MB]}}.""" by_proc = defaultdict(lambda: defaultdict(list)) for msg in proc_logs: sample = defaultdict(lambda: defaultdict(float)) for proc in msg.procLog.procs: name = get_proc_name(proc) sample[name]['rss'] += proc.memRss / MB if use_pss: sample[name]['pss'] += proc.memPss / MB sample[name]['pss_anon'] += proc.memPssAnon / MB sample[name]['pss_shmem'] += proc.memPssShmem / MB for name, metrics in sample.items(): for metric, val in metrics.items(): by_proc[name][metric].append(val) return by_proc def _has_pss_detail(by_proc) -> bool: """Check if any process has non-zero pss_anon/pss_shmem (unavailable on some kernels).""" return any(sum(v.get('pss_anon', [])) > 0 or sum(v.get('pss_shmem', [])) > 0 for v in by_proc.values()) def process_table_rows(by_proc, total_mb, use_pss, show_detail): """Build table rows. Returns (rows, total_row).""" mem_key = 'pss' if use_pss else 'rss' rows = [] for name in sorted(by_proc, key=lambda n: np.mean(by_proc[n][mem_key]), reverse=True): m = by_proc[name] vals = m[mem_key] avg = round(np.mean(vals)) row = [name, f"{avg} MB", f"{round(np.max(vals))} MB", f"{round(pct(avg, total_mb), 1)}%"] if show_detail: row.append(f"{round(np.mean(m['pss_anon']))} MB") row.append(f"{round(np.mean(m['pss_shmem']))} MB") rows.append(row) # Total row total_row = None if by_proc: max_samples = max(len(v[mem_key]) for v in by_proc.values()) totals = [] for i in range(max_samples): s = sum(v[mem_key][i] for v in by_proc.values() if i < len(v[mem_key])) totals.append(s) avg_total = round(np.mean(totals)) total_row = ["TOTAL", f"{avg_total} MB", f"{round(np.max(totals))} MB", f"{round(pct(avg_total, total_mb), 1)}%"] if show_detail: total_row.append(f"{round(sum(np.mean(v['pss_anon']) for v in by_proc.values()))} MB") total_row.append(f"{round(sum(np.mean(v['pss_shmem']) for v in by_proc.values()))} MB") return rows, total_row def print_process_tables(op_procs, other_procs, total_mb, use_pss): all_procs = {**op_procs, **other_procs} show_detail = use_pss and _has_pss_detail(all_procs) header = ["process", "avg", "max", "%"] if show_detail: header += ["anon", "shmem"] op_rows, op_total = process_table_rows(op_procs, total_mb, use_pss, show_detail) # filter other: >5MB avg and not bare interpreter paths (test infra noise) other_filtered = {n: v for n, v in other_procs.items() if np.mean(v['pss' if use_pss else 'rss']) > 5.0 and os.path.basename(n.split()[0]) not in ('python', 'python3')} other_rows, other_total = process_table_rows(other_filtered, total_mb, use_pss, show_detail) rows = op_rows if op_total: rows.append(op_total) if other_rows: sep_width = len(header) rows.append([""] * sep_width) rows.extend(other_rows) if other_total: other_total[0] = "TOTAL (other)" rows.append(other_total) metric = "PSS (no shared double-count)" if use_pss else "RSS (includes shared, overcounts)" print(f"\n-- Per-Process Memory: {metric} --") print(tabulate(rows, header, **TABULATE_OPTS)) def print_memory_accounting(proc_logs, op_procs, other_procs, total_mb, use_pss): last = proc_logs[-1].procLog.mem used = (last.total - last.available) / MB shared = last.shared / MB cached_buf = (last.buffers + last.cached) / MB - shared # shared (MSGQ) is in Cached; separate it msgq = shared mem_key = 'pss' if use_pss else 'rss' op_total = sum(v[mem_key][-1] for v in op_procs.values()) if op_procs else 0 other_total = sum(v[mem_key][-1] for v in other_procs.values()) if other_procs else 0 proc_sum = op_total + other_total remainder = used - (cached_buf + msgq) - proc_sum if not use_pss: # RSS double-counts shared; add back once to partially correct remainder += shared header = ["", "MB", "%", ""] label = "PSS" if use_pss else "RSS*" rows = [ ["Used (total - avail)", f"{used:.0f}", f"{pct(used, total_mb):.1f}", "memory in use by the system"], [" Cached + Buffers", f"{cached_buf:.0f}", f"{pct(cached_buf, total_mb):.1f}", "pagecache + fs metadata, reclaimable"], [" MSGQ (shared)", f"{msgq:.0f}", f"{pct(msgq, total_mb):.1f}", "/dev/shm tmpfs, also in process PSS"], [f" openpilot {label}", f"{op_total:.0f}", f"{pct(op_total, total_mb):.1f}", "sum of openpilot process memory"], [f" other {label}", f"{other_total:.0f}", f"{pct(other_total, total_mb):.1f}", "sum of non-openpilot process memory"], [" kernel/ION/GPU", f"{remainder:.0f}", f"{pct(remainder, total_mb):.1f}", "slab, ION/DMA-BUF, GPU, page tables"], ] note = "" if use_pss else " (*RSS overcounts shared mem)" print(f"\n-- Memory Accounting (last sample){note} --") print(tabulate(rows, header, tablefmt="simple_grid", stralign="right")) def print_report(proc_logs, device_states=None): """Print full memory analysis report. Can be called from tests or CLI.""" if not proc_logs: print("No procLog messages found") return print(f"{len(proc_logs)} procLog samples, {len(device_states or [])} deviceState samples") use_pss = has_pss(proc_logs) if not use_pss: print(" (no PSS data — re-record with updated proclogd for accurate numbers)") total_mb = print_summary(proc_logs, device_states or []) by_proc = collect_per_process_mem(proc_logs, use_pss) op_procs = {n: v for n, v in by_proc.items() if is_openpilot_proc(n)} other_procs = {n: v for n, v in by_proc.items() if not is_openpilot_proc(n)} print_process_tables(op_procs, other_procs, total_mb, use_pss) print_memory_accounting(proc_logs, op_procs, other_procs, total_mb, use_pss) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Analyze memory usage from route logs") parser.add_argument("route", nargs="?", default=None, help="route ID or local rlog path") parser.add_argument("--demo", action="store_true", help=f"use demo route ({DEMO_ROUTE})") args = parser.parse_args() if args.demo: route = DEMO_ROUTE elif args.route: route = args.route else: parser.error("provide a route or use --demo") print(f"Reading logs from: {route}") proc_logs = [] device_states = [] for msg in LogReader(route): if msg.which() == 'procLog': proc_logs.append(msg) elif msg.which() == 'deviceState': device_states.append(msg) print_report(proc_logs, device_states)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/debug/mem_usage.py", "license": "MIT License", "lines": 185, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ubloxd/binary_struct.py
""" Binary struct parsing DSL. Defines a declarative schema for binary messages using dataclasses and type annotations. """ import struct from enum import Enum from dataclasses import dataclass, is_dataclass from typing import Annotated, Any, TypeVar, get_args, get_origin class FieldType: """Base class for field type descriptors.""" @dataclass(frozen=True) class IntType(FieldType): bits: int signed: bool big_endian: bool = False @dataclass(frozen=True) class FloatType(FieldType): bits: int @dataclass(frozen=True) class BitsType(FieldType): bits: int @dataclass(frozen=True) class BytesType(FieldType): size: int @dataclass(frozen=True) class ArrayType(FieldType): element_type: Any count_field: str @dataclass(frozen=True) class SwitchType(FieldType): selector: str cases: dict[Any, Any] default: Any = None @dataclass(frozen=True) class EnumType(FieldType): base_type: FieldType enum_cls: type[Enum] @dataclass(frozen=True) class ConstType(FieldType): base_type: FieldType expected: Any @dataclass(frozen=True) class SubstreamType(FieldType): length_field: str element_type: Any # Common types - little endian u8 = IntType(8, False) u16 = IntType(16, False) u32 = IntType(32, False) s8 = IntType(8, True) s16 = IntType(16, True) s32 = IntType(32, True) f32 = FloatType(32) f64 = FloatType(64) # Big endian variants u16be = IntType(16, False, big_endian=True) u32be = IntType(32, False, big_endian=True) s16be = IntType(16, True, big_endian=True) s32be = IntType(32, True, big_endian=True) def bits(n: int) -> BitsType: """Create a bit-level field type.""" return BitsType(n) def bytes_field(size: int) -> BytesType: """Create a fixed-size bytes field.""" return BytesType(size) def array(element_type: Any, count_field: str) -> ArrayType: """Create an array/repeated field.""" return ArrayType(element_type, count_field) def switch(selector: str, cases: dict[Any, Any], default: Any = None) -> SwitchType: """Create a switch-on field.""" return SwitchType(selector, cases, default) def enum(base_type: Any, enum_cls: type[Enum]) -> EnumType: """Create an enum-wrapped field.""" field_type = _field_type_from_spec(base_type) if field_type is None: raise TypeError(f"Unsupported field type: {base_type!r}") return EnumType(field_type, enum_cls) def const(base_type: Any, expected: Any) -> ConstType: """Create a constant-value field.""" field_type = _field_type_from_spec(base_type) if field_type is None: raise TypeError(f"Unsupported field type: {base_type!r}") return ConstType(field_type, expected) def substream(length_field: str, element_type: Any) -> SubstreamType: """Parse a fixed-length substream using an inner schema.""" return SubstreamType(length_field, element_type) class BinaryReader: def __init__(self, data: bytes): self.data = data self.pos = 0 self.bit_pos = 0 # 0-7, position within current byte def _require(self, n: int) -> None: if self.pos + n > len(self.data): raise EOFError("Unexpected end of data") def _read_struct(self, fmt: str): self._align_to_byte() size = struct.calcsize(fmt) self._require(size) value = struct.unpack_from(fmt, self.data, self.pos)[0] self.pos += size return value def read_bytes(self, n: int) -> bytes: self._align_to_byte() self._require(n) result = self.data[self.pos : self.pos + n] self.pos += n return result def read_bits_int_be(self, n: int) -> int: result = 0 bits_remaining = n while bits_remaining > 0: if self.pos >= len(self.data): raise EOFError("Unexpected end of data while reading bits") bits_in_byte = 8 - self.bit_pos bits_to_read = min(bits_remaining, bits_in_byte) byte_val = self.data[self.pos] shift = bits_in_byte - bits_to_read mask = (1 << bits_to_read) - 1 extracted = (byte_val >> shift) & mask result = (result << bits_to_read) | extracted self.bit_pos += bits_to_read bits_remaining -= bits_to_read if self.bit_pos >= 8: self.bit_pos = 0 self.pos += 1 return result def _align_to_byte(self) -> None: if self.bit_pos > 0: self.bit_pos = 0 self.pos += 1 T = TypeVar('T', bound='BinaryStruct') class BinaryStruct: """Base class for binary struct definitions.""" def __init_subclass__(cls, **kwargs) -> None: super().__init_subclass__(**kwargs) if cls is BinaryStruct: return if not is_dataclass(cls): dataclass(init=False)(cls) fields = list(getattr(cls, '__annotations__', {}).items()) cls.__binary_fields__ = fields @classmethod def _read(inner_cls, reader: BinaryReader): obj = inner_cls.__new__(inner_cls) for name, spec in inner_cls.__binary_fields__: value = _parse_field(spec, reader, obj) setattr(obj, name, value) return obj cls._read = _read @classmethod def from_bytes(cls: type[T], data: bytes) -> T: """Parse struct from bytes.""" reader = BinaryReader(data) return cls._read(reader) @classmethod def _read(cls: type[T], reader: BinaryReader) -> T: """Override in subclasses to implement parsing.""" raise NotImplementedError def _resolve_path(obj: Any, path: str) -> Any: cur = obj for part in path.split('.'): cur = getattr(cur, part) return cur def _unwrap_annotated(spec: Any) -> tuple[Any, ...]: if get_origin(spec) is Annotated: return get_args(spec)[1:] return () def _field_type_from_spec(spec: Any) -> FieldType | None: if isinstance(spec, FieldType): return spec for item in _unwrap_annotated(spec): if isinstance(item, FieldType): return item return None def _int_format(field_type: IntType) -> str: if field_type.bits == 8: return 'b' if field_type.signed else 'B' endian = '>' if field_type.big_endian else '<' if field_type.bits == 16: code = 'h' if field_type.signed else 'H' elif field_type.bits == 32: code = 'i' if field_type.signed else 'I' else: raise ValueError(f"Unsupported integer size: {field_type.bits}") return f"{endian}{code}" def _float_format(field_type: FloatType) -> str: if field_type.bits == 32: return '<f' if field_type.bits == 64: return '<d' raise ValueError(f"Unsupported float size: {field_type.bits}") def _parse_field(spec: Any, reader: BinaryReader, obj: Any) -> Any: field_type = _field_type_from_spec(spec) if field_type is not None: spec = field_type if isinstance(spec, ConstType): value = _parse_field(spec.base_type, reader, obj) if value != spec.expected: raise ValueError(f"Invalid constant: expected {spec.expected!r}, got {value!r}") return value if isinstance(spec, EnumType): raw = _parse_field(spec.base_type, reader, obj) try: return spec.enum_cls(raw) except ValueError: return raw if isinstance(spec, SwitchType): key = _resolve_path(obj, spec.selector) target = spec.cases.get(key, spec.default) if target is None: return None return _parse_field(target, reader, obj) if isinstance(spec, ArrayType): count = _resolve_path(obj, spec.count_field) return [_parse_field(spec.element_type, reader, obj) for _ in range(int(count))] if isinstance(spec, SubstreamType): length = _resolve_path(obj, spec.length_field) data = reader.read_bytes(int(length)) sub_reader = BinaryReader(data) return _parse_field(spec.element_type, sub_reader, obj) if isinstance(spec, IntType): return reader._read_struct(_int_format(spec)) if isinstance(spec, FloatType): return reader._read_struct(_float_format(spec)) if isinstance(spec, BitsType): value = reader.read_bits_int_be(spec.bits) return bool(value) if spec.bits == 1 else value if isinstance(spec, BytesType): return reader.read_bytes(spec.size) if isinstance(spec, type) and issubclass(spec, BinaryStruct): return spec._read(reader) raise TypeError(f"Unsupported field spec: {spec!r}")
{ "repo_id": "commaai/openpilot", "file_path": "system/ubloxd/binary_struct.py", "license": "MIT License", "lines": 233, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ubloxd/glonass.py
""" Parses GLONASS navigation strings per GLONASS ICD specification. http://gauss.gge.unb.ca/GLONASS.ICD.pdf https://www.unavco.org/help/glossary/docs/ICD_GLONASS_4.0_(1998)_en.pdf """ from typing import Annotated from openpilot.system.ubloxd import binary_struct as bs class Glonass(bs.BinaryStruct): class String1(bs.BinaryStruct): not_used: Annotated[int, bs.bits(2)] p1: Annotated[int, bs.bits(2)] t_k: Annotated[int, bs.bits(12)] x_vel_sign: Annotated[bool, bs.bits(1)] x_vel_value: Annotated[int, bs.bits(23)] x_accel_sign: Annotated[bool, bs.bits(1)] x_accel_value: Annotated[int, bs.bits(4)] x_sign: Annotated[bool, bs.bits(1)] x_value: Annotated[int, bs.bits(26)] @property def x_vel(self) -> int: """Computed x_vel from sign-magnitude representation.""" return (self.x_vel_value * -1) if self.x_vel_sign else self.x_vel_value @property def x_accel(self) -> int: """Computed x_accel from sign-magnitude representation.""" return (self.x_accel_value * -1) if self.x_accel_sign else self.x_accel_value @property def x(self) -> int: """Computed x from sign-magnitude representation.""" return (self.x_value * -1) if self.x_sign else self.x_value class String2(bs.BinaryStruct): b_n: Annotated[int, bs.bits(3)] p2: Annotated[bool, bs.bits(1)] t_b: Annotated[int, bs.bits(7)] not_used: Annotated[int, bs.bits(5)] y_vel_sign: Annotated[bool, bs.bits(1)] y_vel_value: Annotated[int, bs.bits(23)] y_accel_sign: Annotated[bool, bs.bits(1)] y_accel_value: Annotated[int, bs.bits(4)] y_sign: Annotated[bool, bs.bits(1)] y_value: Annotated[int, bs.bits(26)] @property def y_vel(self) -> int: """Computed y_vel from sign-magnitude representation.""" return (self.y_vel_value * -1) if self.y_vel_sign else self.y_vel_value @property def y_accel(self) -> int: """Computed y_accel from sign-magnitude representation.""" return (self.y_accel_value * -1) if self.y_accel_sign else self.y_accel_value @property def y(self) -> int: """Computed y from sign-magnitude representation.""" return (self.y_value * -1) if self.y_sign else self.y_value class String3(bs.BinaryStruct): p3: Annotated[bool, bs.bits(1)] gamma_n_sign: Annotated[bool, bs.bits(1)] gamma_n_value: Annotated[int, bs.bits(10)] not_used: Annotated[bool, bs.bits(1)] p: Annotated[int, bs.bits(2)] l_n: Annotated[bool, bs.bits(1)] z_vel_sign: Annotated[bool, bs.bits(1)] z_vel_value: Annotated[int, bs.bits(23)] z_accel_sign: Annotated[bool, bs.bits(1)] z_accel_value: Annotated[int, bs.bits(4)] z_sign: Annotated[bool, bs.bits(1)] z_value: Annotated[int, bs.bits(26)] @property def gamma_n(self) -> int: """Computed gamma_n from sign-magnitude representation.""" return (self.gamma_n_value * -1) if self.gamma_n_sign else self.gamma_n_value @property def z_vel(self) -> int: """Computed z_vel from sign-magnitude representation.""" return (self.z_vel_value * -1) if self.z_vel_sign else self.z_vel_value @property def z_accel(self) -> int: """Computed z_accel from sign-magnitude representation.""" return (self.z_accel_value * -1) if self.z_accel_sign else self.z_accel_value @property def z(self) -> int: """Computed z from sign-magnitude representation.""" return (self.z_value * -1) if self.z_sign else self.z_value class String4(bs.BinaryStruct): tau_n_sign: Annotated[bool, bs.bits(1)] tau_n_value: Annotated[int, bs.bits(21)] delta_tau_n_sign: Annotated[bool, bs.bits(1)] delta_tau_n_value: Annotated[int, bs.bits(4)] e_n: Annotated[int, bs.bits(5)] not_used_1: Annotated[int, bs.bits(14)] p4: Annotated[bool, bs.bits(1)] f_t: Annotated[int, bs.bits(4)] not_used_2: Annotated[int, bs.bits(3)] n_t: Annotated[int, bs.bits(11)] n: Annotated[int, bs.bits(5)] m: Annotated[int, bs.bits(2)] @property def tau_n(self) -> int: """Computed tau_n from sign-magnitude representation.""" return (self.tau_n_value * -1) if self.tau_n_sign else self.tau_n_value @property def delta_tau_n(self) -> int: """Computed delta_tau_n from sign-magnitude representation.""" return (self.delta_tau_n_value * -1) if self.delta_tau_n_sign else self.delta_tau_n_value class String5(bs.BinaryStruct): n_a: Annotated[int, bs.bits(11)] tau_c: Annotated[int, bs.bits(32)] not_used: Annotated[bool, bs.bits(1)] n_4: Annotated[int, bs.bits(5)] tau_gps: Annotated[int, bs.bits(22)] l_n: Annotated[bool, bs.bits(1)] class StringNonImmediate(bs.BinaryStruct): data_1: Annotated[int, bs.bits(64)] data_2: Annotated[int, bs.bits(8)] idle_chip: Annotated[bool, bs.bits(1)] string_number: Annotated[int, bs.bits(4)] data: Annotated[ object, bs.switch( 'string_number', { 1: String1, 2: String2, 3: String3, 4: String4, 5: String5, }, default=StringNonImmediate, ), ] hamming_code: Annotated[int, bs.bits(8)] pad_1: Annotated[int, bs.bits(11)] superframe_number: Annotated[int, bs.bits(16)] pad_2: Annotated[int, bs.bits(8)] frame_number: Annotated[int, bs.bits(8)]
{ "repo_id": "commaai/openpilot", "file_path": "system/ubloxd/glonass.py", "license": "MIT License", "lines": 134, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ubloxd/gps.py
""" Parses GPS navigation subframes per IS-GPS-200E specification. https://www.gps.gov/technical/icwg/IS-GPS-200E.pdf """ from typing import Annotated from openpilot.system.ubloxd import binary_struct as bs class Gps(bs.BinaryStruct): class Tlm(bs.BinaryStruct): preamble: Annotated[bytes, bs.const(bs.bytes_field(1), b"\x8b")] tlm: Annotated[int, bs.bits(14)] integrity_status: Annotated[bool, bs.bits(1)] reserved: Annotated[bool, bs.bits(1)] class How(bs.BinaryStruct): tow_count: Annotated[int, bs.bits(17)] alert: Annotated[bool, bs.bits(1)] anti_spoof: Annotated[bool, bs.bits(1)] subframe_id: Annotated[int, bs.bits(3)] reserved: Annotated[int, bs.bits(2)] class Subframe1(bs.BinaryStruct): week_no: Annotated[int, bs.bits(10)] code: Annotated[int, bs.bits(2)] sv_accuracy: Annotated[int, bs.bits(4)] sv_health: Annotated[int, bs.bits(6)] iodc_msb: Annotated[int, bs.bits(2)] l2_p_data_flag: Annotated[bool, bs.bits(1)] reserved1: Annotated[int, bs.bits(23)] reserved2: Annotated[int, bs.bits(24)] reserved3: Annotated[int, bs.bits(24)] reserved4: Annotated[int, bs.bits(16)] t_gd: Annotated[int, bs.s8] iodc_lsb: Annotated[int, bs.u8] t_oc: Annotated[int, bs.u16be] af_2: Annotated[int, bs.s8] af_1: Annotated[int, bs.s16be] af_0_sign: Annotated[bool, bs.bits(1)] af_0_value: Annotated[int, bs.bits(21)] reserved5: Annotated[int, bs.bits(2)] @property def af_0(self) -> int: """Computed af_0 from sign-magnitude representation.""" return (self.af_0_value - (1 << 21)) if self.af_0_sign else self.af_0_value class Subframe2(bs.BinaryStruct): iode: Annotated[int, bs.u8] c_rs: Annotated[int, bs.s16be] delta_n: Annotated[int, bs.s16be] m_0: Annotated[int, bs.s32be] c_uc: Annotated[int, bs.s16be] e: Annotated[int, bs.s32be] c_us: Annotated[int, bs.s16be] sqrt_a: Annotated[int, bs.u32be] t_oe: Annotated[int, bs.u16be] fit_interval_flag: Annotated[bool, bs.bits(1)] aoda: Annotated[int, bs.bits(5)] reserved: Annotated[int, bs.bits(2)] class Subframe3(bs.BinaryStruct): c_ic: Annotated[int, bs.s16be] omega_0: Annotated[int, bs.s32be] c_is: Annotated[int, bs.s16be] i_0: Annotated[int, bs.s32be] c_rc: Annotated[int, bs.s16be] omega: Annotated[int, bs.s32be] omega_dot_sign: Annotated[bool, bs.bits(1)] omega_dot_value: Annotated[int, bs.bits(23)] iode: Annotated[int, bs.u8] idot_sign: Annotated[bool, bs.bits(1)] idot_value: Annotated[int, bs.bits(13)] reserved: Annotated[int, bs.bits(2)] @property def omega_dot(self) -> int: """Computed omega_dot from sign-magnitude representation.""" return (self.omega_dot_value - (1 << 23)) if self.omega_dot_sign else self.omega_dot_value @property def idot(self) -> int: """Computed idot from sign-magnitude representation.""" return (self.idot_value - (1 << 13)) if self.idot_sign else self.idot_value class Subframe4(bs.BinaryStruct): class IonosphereData(bs.BinaryStruct): a0: Annotated[int, bs.s8] a1: Annotated[int, bs.s8] a2: Annotated[int, bs.s8] a3: Annotated[int, bs.s8] b0: Annotated[int, bs.s8] b1: Annotated[int, bs.s8] b2: Annotated[int, bs.s8] b3: Annotated[int, bs.s8] data_id: Annotated[int, bs.bits(2)] page_id: Annotated[int, bs.bits(6)] body: Annotated[object, bs.switch('page_id', {56: IonosphereData})] tlm: Tlm how: How body: Annotated[ object, bs.switch( 'how.subframe_id', { 1: Subframe1, 2: Subframe2, 3: Subframe3, 4: Subframe4, }, ), ]
{ "repo_id": "commaai/openpilot", "file_path": "system/ubloxd/gps.py", "license": "MIT License", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ubloxd/ubx.py
""" UBX protocol parser """ from enum import IntEnum from typing import Annotated from openpilot.system.ubloxd import binary_struct as bs class GnssType(IntEnum): gps = 0 sbas = 1 galileo = 2 beidou = 3 imes = 4 qzss = 5 glonass = 6 class Ubx(bs.BinaryStruct): GnssType = GnssType class RxmRawx(bs.BinaryStruct): class Measurement(bs.BinaryStruct): pr_mes: Annotated[float, bs.f64] cp_mes: Annotated[float, bs.f64] do_mes: Annotated[float, bs.f32] gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] sv_id: Annotated[int, bs.u8] reserved2: Annotated[bytes, bs.bytes_field(1)] freq_id: Annotated[int, bs.u8] lock_time: Annotated[int, bs.u16] cno: Annotated[int, bs.u8] pr_stdev: Annotated[int, bs.u8] cp_stdev: Annotated[int, bs.u8] do_stdev: Annotated[int, bs.u8] trk_stat: Annotated[int, bs.u8] reserved3: Annotated[bytes, bs.bytes_field(1)] rcv_tow: Annotated[float, bs.f64] week: Annotated[int, bs.u16] leap_s: Annotated[int, bs.s8] num_meas: Annotated[int, bs.u8] rec_stat: Annotated[int, bs.u8] reserved1: Annotated[bytes, bs.bytes_field(3)] meas: Annotated[list[Measurement], bs.array(Measurement, count_field='num_meas')] class RxmSfrbx(bs.BinaryStruct): gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] sv_id: Annotated[int, bs.u8] reserved1: Annotated[bytes, bs.bytes_field(1)] freq_id: Annotated[int, bs.u8] num_words: Annotated[int, bs.u8] reserved2: Annotated[bytes, bs.bytes_field(1)] version: Annotated[int, bs.u8] reserved3: Annotated[bytes, bs.bytes_field(1)] body: Annotated[list[int], bs.array(bs.u32, count_field='num_words')] class NavSat(bs.BinaryStruct): class Nav(bs.BinaryStruct): gnss_id: Annotated[GnssType | int, bs.enum(bs.u8, GnssType)] sv_id: Annotated[int, bs.u8] cno: Annotated[int, bs.u8] elev: Annotated[int, bs.s8] azim: Annotated[int, bs.s16] pr_res: Annotated[int, bs.s16] flags: Annotated[int, bs.u32] itow: Annotated[int, bs.u32] version: Annotated[int, bs.u8] num_svs: Annotated[int, bs.u8] reserved: Annotated[bytes, bs.bytes_field(2)] svs: Annotated[list[Nav], bs.array(Nav, count_field='num_svs')] class NavPvt(bs.BinaryStruct): i_tow: Annotated[int, bs.u32] year: Annotated[int, bs.u16] month: Annotated[int, bs.u8] day: Annotated[int, bs.u8] hour: Annotated[int, bs.u8] min: Annotated[int, bs.u8] sec: Annotated[int, bs.u8] valid: Annotated[int, bs.u8] t_acc: Annotated[int, bs.u32] nano: Annotated[int, bs.s32] fix_type: Annotated[int, bs.u8] flags: Annotated[int, bs.u8] flags2: Annotated[int, bs.u8] num_sv: Annotated[int, bs.u8] lon: Annotated[int, bs.s32] lat: Annotated[int, bs.s32] height: Annotated[int, bs.s32] h_msl: Annotated[int, bs.s32] h_acc: Annotated[int, bs.u32] v_acc: Annotated[int, bs.u32] vel_n: Annotated[int, bs.s32] vel_e: Annotated[int, bs.s32] vel_d: Annotated[int, bs.s32] g_speed: Annotated[int, bs.s32] head_mot: Annotated[int, bs.s32] s_acc: Annotated[int, bs.s32] head_acc: Annotated[int, bs.u32] p_dop: Annotated[int, bs.u16] flags3: Annotated[int, bs.u8] reserved1: Annotated[bytes, bs.bytes_field(5)] head_veh: Annotated[int, bs.s32] mag_dec: Annotated[int, bs.s16] mag_acc: Annotated[int, bs.u16] class MonHw2(bs.BinaryStruct): class ConfigSource(IntEnum): flash = 102 otp = 111 config_pins = 112 rom = 113 ofs_i: Annotated[int, bs.s8] mag_i: Annotated[int, bs.u8] ofs_q: Annotated[int, bs.s8] mag_q: Annotated[int, bs.u8] cfg_source: Annotated[ConfigSource | int, bs.enum(bs.u8, ConfigSource)] reserved1: Annotated[bytes, bs.bytes_field(3)] low_lev_cfg: Annotated[int, bs.u32] reserved2: Annotated[bytes, bs.bytes_field(8)] post_status: Annotated[int, bs.u32] reserved3: Annotated[bytes, bs.bytes_field(4)] class MonHw(bs.BinaryStruct): class AntennaStatus(IntEnum): init = 0 dontknow = 1 ok = 2 short = 3 open = 4 class AntennaPower(IntEnum): false = 0 true = 1 dontknow = 2 pin_sel: Annotated[int, bs.u32] pin_bank: Annotated[int, bs.u32] pin_dir: Annotated[int, bs.u32] pin_val: Annotated[int, bs.u32] noise_per_ms: Annotated[int, bs.u16] agc_cnt: Annotated[int, bs.u16] a_status: Annotated[AntennaStatus | int, bs.enum(bs.u8, AntennaStatus)] a_power: Annotated[AntennaPower | int, bs.enum(bs.u8, AntennaPower)] flags: Annotated[int, bs.u8] reserved1: Annotated[bytes, bs.bytes_field(1)] used_mask: Annotated[int, bs.u32] vp: Annotated[bytes, bs.bytes_field(17)] jam_ind: Annotated[int, bs.u8] reserved2: Annotated[bytes, bs.bytes_field(2)] pin_irq: Annotated[int, bs.u32] pull_h: Annotated[int, bs.u32] pull_l: Annotated[int, bs.u32] magic: Annotated[bytes, bs.const(bs.bytes_field(2), b"\xb5\x62")] msg_type: Annotated[int, bs.u16be] length: Annotated[int, bs.u16] body: Annotated[ object, bs.substream( 'length', bs.switch( 'msg_type', { 0x0107: NavPvt, 0x0213: RxmSfrbx, 0x0215: RxmRawx, 0x0A09: MonHw, 0x0A0B: MonHw2, 0x0135: NavSat, }, ), ), ] checksum: Annotated[int, bs.u16]
{ "repo_id": "commaai/openpilot", "file_path": "system/ubloxd/ubx.py", "license": "MIT License", "lines": 162, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:common/i2c.py
import os import fcntl import ctypes # I2C constants from /usr/include/linux/i2c-dev.h I2C_SLAVE = 0x0703 I2C_SLAVE_FORCE = 0x0706 I2C_SMBUS = 0x0720 # SMBus transfer types I2C_SMBUS_READ = 1 I2C_SMBUS_WRITE = 0 I2C_SMBUS_BYTE_DATA = 2 I2C_SMBUS_I2C_BLOCK_DATA = 8 I2C_SMBUS_BLOCK_MAX = 32 class _I2cSmbusData(ctypes.Union): _fields_ = [ ("byte", ctypes.c_uint8), ("word", ctypes.c_uint16), ("block", ctypes.c_uint8 * (I2C_SMBUS_BLOCK_MAX + 2)), ] class _I2cSmbusIoctlData(ctypes.Structure): _fields_ = [ ("read_write", ctypes.c_uint8), ("command", ctypes.c_uint8), ("size", ctypes.c_uint32), ("data", ctypes.POINTER(_I2cSmbusData)), ] class SMBus: def __init__(self, bus: int): self._fd = os.open(f'/dev/i2c-{bus}', os.O_RDWR) def __enter__(self) -> 'SMBus': return self def __exit__(self, *args) -> None: self.close() def close(self) -> None: if hasattr(self, '_fd') and self._fd >= 0: os.close(self._fd) self._fd = -1 def _set_address(self, addr: int, force: bool = False) -> None: ioctl_arg = I2C_SLAVE_FORCE if force else I2C_SLAVE fcntl.ioctl(self._fd, ioctl_arg, addr) def _smbus_access(self, read_write: int, command: int, size: int, data: _I2cSmbusData) -> None: ioctl_data = _I2cSmbusIoctlData(read_write, command, size, ctypes.pointer(data)) fcntl.ioctl(self._fd, I2C_SMBUS, ioctl_data) def read_byte_data(self, addr: int, register: int, force: bool = False) -> int: self._set_address(addr, force) data = _I2cSmbusData() self._smbus_access(I2C_SMBUS_READ, register, I2C_SMBUS_BYTE_DATA, data) return int(data.byte) def write_byte_data(self, addr: int, register: int, value: int, force: bool = False) -> None: self._set_address(addr, force) data = _I2cSmbusData() data.byte = value & 0xFF self._smbus_access(I2C_SMBUS_WRITE, register, I2C_SMBUS_BYTE_DATA, data) def read_i2c_block_data(self, addr: int, register: int, length: int, force: bool = False) -> list[int]: self._set_address(addr, force) if not (0 <= length <= I2C_SMBUS_BLOCK_MAX): raise ValueError(f"length must be 0..{I2C_SMBUS_BLOCK_MAX}") data = _I2cSmbusData() data.block[0] = length self._smbus_access(I2C_SMBUS_READ, register, I2C_SMBUS_I2C_BLOCK_DATA, data) read_len = int(data.block[0]) or length read_len = min(read_len, length) return [int(b) for b in data.block[1 : read_len + 1]]
{ "repo_id": "commaai/openpilot", "file_path": "common/i2c.py", "license": "MIT License", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py
import io import sys import markdown import numpy as np import matplotlib.pyplot as plt from openpilot.common.realtime import DT_MDL from openpilot.selfdrive.controls.tests.test_following_distance import desired_follow_distance from openpilot.tools.longitudinal_maneuvers.maneuver_helpers import Axis, axis_labels from openpilot.selfdrive.test.longitudinal_maneuvers.maneuver import Maneuver def get_html_from_results(results, labels, AXIS): fig, ax = plt.subplots(figsize=(16, 8)) for idx, key in enumerate(results.keys()): ax.plot(results[key][:, Axis.TIME], results[key][:, AXIS], label=labels[idx]) ax.set_xlabel(axis_labels[Axis.TIME]) ax.set_ylabel(axis_labels[AXIS]) ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', borderaxespad=0) ax.grid(True, linestyle='--', alpha=0.7) ax.text(-0.075, 0.5, '.', transform=ax.transAxes, color='none') fig_buffer = io.StringIO() fig.savefig(fig_buffer, format='svg', bbox_inches='tight') plt.close(fig) return fig_buffer.getvalue() + '<br/>' def generate_mpc_tuning_report(): htmls = [] results = {} name = 'Resuming behind lead' labels = [] for lead_accel in np.linspace(1.0, 4.0, 4): man = Maneuver( '', duration=11, initial_speed=0.0, lead_relevancy=True, initial_distance_lead=desired_follow_distance(0.0, 0.0), speed_lead_values=[0.0, 10 * lead_accel], cruise_values=[100, 100], prob_lead_values=[1.0, 1.0], breakpoints=[1., 11], ) valid, results[lead_accel] = man.evaluate() labels.append(f'{lead_accel} m/s^2 lead acceleration') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) results = {} name = 'Approaching stopped car from 140m' labels = [] for speed in np.arange(0,45,5): man = Maneuver( name, duration=30., initial_speed=float(speed), lead_relevancy=True, initial_distance_lead=140., speed_lead_values=[0.0, 0.], breakpoints=[0., 30.], ) valid, results[speed] = man.evaluate() labels.append(f'{speed} m/s approach speed') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) results = {} name = 'Following 5s (triangular) oscillating lead' labels = [] speed = np.int64(10) for oscil in np.arange(0, 10, 1): man = Maneuver( '', duration=30., initial_speed=float(speed), lead_relevancy=True, initial_distance_lead=desired_follow_distance(speed, speed), speed_lead_values=[speed, speed, speed - oscil, speed + oscil, speed - oscil, speed + oscil, speed - oscil], breakpoints=[0.,2., 5, 8, 15, 18, 25.], ) valid, results[oscil] = man.evaluate() labels.append(f'{oscil} m/s oscillation size') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) results = {} name = 'Following 5s (sinusoidal) oscillating lead' labels = [] speed = np.int64(10) duration = float(30) f_osc = 1. / 5 for oscil in np.arange(0, 10, 1): bps = DT_MDL * np.arange(int(duration / DT_MDL)) lead_speeds = speed + oscil * np.sin(2 * np.pi * f_osc * bps) man = Maneuver( '', duration=duration, initial_speed=float(speed), lead_relevancy=True, initial_distance_lead=desired_follow_distance(speed, speed), speed_lead_values=lead_speeds, breakpoints=bps, ) valid, results[oscil] = man.evaluate() labels.append(f'{oscil} m/s oscillation size') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) results = {} name = 'Speed profile when converging to steady state lead at 30m/s' labels = [] for distance in np.arange(20, 140, 10): man = Maneuver( '', duration=50, initial_speed=30.0, lead_relevancy=True, initial_distance_lead=distance, speed_lead_values=[30.0], breakpoints=[0.], ) valid, results[distance] = man.evaluate() labels.append(f'{distance} m initial distance') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) results = {} name = 'Speed profile when converging to steady state lead at 20m/s' labels = [] for distance in np.arange(20, 140, 10): man = Maneuver( '', duration=50, initial_speed=20.0, lead_relevancy=True, initial_distance_lead=distance, speed_lead_values=[20.0], breakpoints=[0.], ) valid, results[distance] = man.evaluate() labels.append(f'{distance} m initial distance') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) results = {} name = 'Following car at 30m/s that comes to a stop' labels = [] for stop_time in np.arange(4, 14, 1): man = Maneuver( '', duration=30, initial_speed=30.0, cruise_values=[30.0, 30.0, 30.0], lead_relevancy=True, initial_distance_lead=60.0, speed_lead_values=[30.0, 30.0, 0.0], breakpoints=[0., 5., 5 + stop_time], ) valid, results[stop_time] = man.evaluate() labels.append(f'{stop_time} seconds stop time') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) results = {} name = 'Response to cut-in at half follow distance' labels = [] for speed in np.arange(0, 40, 5): man = Maneuver( '', duration=20, initial_speed=float(speed), cruise_values=[speed, speed, speed], lead_relevancy=True, initial_distance_lead=desired_follow_distance(speed, speed)/2, speed_lead_values=[speed, speed, speed], prob_lead_values=[0.0, 0.0, 1.0], breakpoints=[0., 5.0, 5.01], ) valid, results[speed] = man.evaluate() labels.append(f'{speed} m/s speed') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) htmls.append(get_html_from_results(results, labels, Axis.D_REL)) results = {} name = 'Follow a lead that accelerates at 2m/s^2 until steady state speed' labels = [] for speed in np.arange(0, 40, 5): man = Maneuver( '', duration=60, initial_speed=0.0, lead_relevancy=True, initial_distance_lead=desired_follow_distance(0.0, 0.0), speed_lead_values=[0.0, 0.0, speed], prob_lead_values=[1.0, 1.0, 1.0], breakpoints=[0., 1.0, speed/2], ) valid, results[speed] = man.evaluate() labels.append(f'{speed} m/s speed') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) results = {} name = 'From stop to cruise' labels = [] for speed in np.arange(0, 40, 5): man = Maneuver( '', duration=50, initial_speed=0.0, lead_relevancy=True, initial_distance_lead=desired_follow_distance(0.0, 0.0), speed_lead_values=[0.0, 0.0], cruise_values=[0.0, speed], prob_lead_values=[0.0, 0.0], breakpoints=[1., 1.01], ) valid, results[speed] = man.evaluate() labels.append(f'{speed} m/s speed') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) results = {} name = 'From cruise to min' labels = [] for speed in np.arange(10, 40, 5): man = Maneuver( '', duration=50, initial_speed=float(speed), lead_relevancy=True, initial_distance_lead=desired_follow_distance(0.0, 0.0), speed_lead_values=[0.0, 0.0], cruise_values=[speed, 10.0], prob_lead_values=[0.0, 0.0], breakpoints=[1., 1.01], ) valid, results[speed] = man.evaluate() labels.append(f'{speed} m/s speed') htmls.append(markdown.markdown('# ' + name)) htmls.append(get_html_from_results(results, labels, Axis.EGO_V)) htmls.append(get_html_from_results(results, labels, Axis.EGO_A)) return htmls if __name__ == '__main__': htmls = generate_mpc_tuning_report() if len(sys.argv) < 2: file_name = 'long_mpc_tune_report.html' else: file_name = sys.argv[1] with open(file_name, 'w') as f: f.write(markdown.markdown('# MPC longitudinal tuning report')) for html in htmls: f.write(html)
{ "repo_id": "commaai/openpilot", "file_path": "tools/longitudinal_maneuvers/mpc_longitudinal_tuning_report.py", "license": "MIT License", "lines": 251, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/pandad/pandad_api_impl.py
import time from cereal import log NO_TRAVERSAL_LIMIT = 2**64 - 1 # Cache schema fields for faster access (avoids string lookup on each field access) _cached_reader_fields = None # (address_field, dat_field, src_field) for reading _cached_writer_fields = None # (address_field, dat_field, src_field) for writing def _get_reader_fields(schema): """Get cached schema field objects for reading.""" global _cached_reader_fields if _cached_reader_fields is None: fields = schema.fields _cached_reader_fields = (fields['address'], fields['dat'], fields['src']) return _cached_reader_fields def _get_writer_fields(schema): """Get cached schema field objects for writing.""" global _cached_writer_fields if _cached_writer_fields is None: fields = schema.fields _cached_writer_fields = (fields['address'], fields['dat'], fields['src']) return _cached_writer_fields def can_list_to_can_capnp(can_msgs, msgtype='can', valid=True): """Convert list of CAN messages to Cap'n Proto serialized bytes. Args: can_msgs: List of tuples [(address, data_bytes, src), ...] msgtype: 'can' or 'sendcan' valid: Whether the event is valid Returns: Cap'n Proto serialized bytes """ global _cached_writer_fields dat = log.Event.new_message(valid=valid, logMonoTime=int(time.monotonic() * 1e9)) can_data = dat.init(msgtype, len(can_msgs)) # Cache schema fields on first call if _cached_writer_fields is None and len(can_msgs) > 0: _cached_writer_fields = _get_writer_fields(can_data[0].schema) if _cached_writer_fields is not None: addr_f, dat_f, src_f = _cached_writer_fields for i, msg in enumerate(can_msgs): f = can_data[i] f._set_by_field(addr_f, msg[0]) f._set_by_field(dat_f, msg[1]) f._set_by_field(src_f, msg[2]) return dat.to_bytes() def can_capnp_to_list(strings, msgtype='can'): """Convert Cap'n Proto serialized bytes to list of CAN messages. Args: strings: Tuple/list of serialized Cap'n Proto bytes msgtype: 'can' or 'sendcan' Returns: List of tuples [(nanos, [(address, data, src), ...]), ...] """ global _cached_reader_fields result = [] for s in strings: with log.Event.from_bytes(s, traversal_limit_in_words=NO_TRAVERSAL_LIMIT) as event: frames = getattr(event, msgtype) # Cache schema fields on first frame for faster access if _cached_reader_fields is None and len(frames) > 0: _cached_reader_fields = _get_reader_fields(frames[0].schema) if _cached_reader_fields is not None: addr_f, dat_f, src_f = _cached_reader_fields frame_list = [(f._get_by_field(addr_f), f._get_by_field(dat_f), f._get_by_field(src_f)) for f in frames] else: frame_list = [] result.append((event.logMonoTime, frame_list)) return result
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/pandad/pandad_api_impl.py", "license": "MIT License", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:scripts/ci_results.py
#!/usr/bin/env python3 """Fetch CI results from GitHub Actions and Jenkins.""" import argparse import json import subprocess import time import urllib.error import urllib.request from datetime import datetime JENKINS_URL = "https://jenkins.comma.life" DEFAULT_TIMEOUT = 1800 # 30 minutes POLL_INTERVAL = 30 # seconds LOG_TAIL_LINES = 10 # lines of log to include for failed jobs def get_git_info(): branch = subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"], text=True).strip() commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() return branch, commit def get_github_actions_status(commit_sha): result = subprocess.run( ["gh", "run", "list", "--commit", commit_sha, "--workflow", "tests.yaml", "--json", "databaseId,status,conclusion"], capture_output=True, text=True, check=True ) runs = json.loads(result.stdout) if not runs: return None, None run_id = runs[0]["databaseId"] result = subprocess.run( ["gh", "run", "view", str(run_id), "--json", "jobs"], capture_output=True, text=True, check=True ) data = json.loads(result.stdout) jobs = {job["name"]: {"status": job["status"], "conclusion": job["conclusion"], "duration": format_duration(job) if job["conclusion"] not in ("skipped", None) and job.get("startedAt") else "", "id": job["databaseId"]} for job in data.get("jobs", [])} return jobs, run_id def get_github_job_log(run_id, job_id): result = subprocess.run( ["gh", "run", "view", str(run_id), "--job", str(job_id), "--log-failed"], capture_output=True, text=True ) lines = result.stdout.strip().split('\n') return '\n'.join(lines[-LOG_TAIL_LINES:]) if len(lines) > LOG_TAIL_LINES else result.stdout.strip() def format_duration(job): start = datetime.fromisoformat(job["startedAt"].replace("Z", "+00:00")) end = datetime.fromisoformat(job["completedAt"].replace("Z", "+00:00")) secs = int((end - start).total_seconds()) return f"{secs // 60}m {secs % 60}s" def get_jenkins_status(branch, commit_sha): base_url = f"{JENKINS_URL}/job/openpilot/job/{branch}" try: # Get list of recent builds with urllib.request.urlopen(f"{base_url}/api/json?tree=builds[number,url]", timeout=10) as resp: builds = json.loads(resp.read().decode()).get("builds", []) # Find build matching commit for build in builds[:20]: # check last 20 builds with urllib.request.urlopen(f"{build['url']}api/json", timeout=10) as resp: data = json.loads(resp.read().decode()) for action in data.get("actions", []): if action.get("_class") == "hudson.plugins.git.util.BuildData": build_sha = action.get("lastBuiltRevision", {}).get("SHA1", "") if build_sha.startswith(commit_sha) or commit_sha.startswith(build_sha): # Get stages info stages = [] try: with urllib.request.urlopen(f"{build['url']}wfapi/describe", timeout=10) as resp2: wf_data = json.loads(resp2.read().decode()) stages = [{"name": s["name"], "status": s["status"]} for s in wf_data.get("stages", [])] except urllib.error.HTTPError: pass return { "number": data["number"], "in_progress": data.get("inProgress", False), "result": data.get("result"), "url": data.get("url", ""), "stages": stages, } return None # no build found for this commit except urllib.error.HTTPError: return None # branch doesn't exist on Jenkins def get_jenkins_log(build_url): url = f"{build_url}consoleText" with urllib.request.urlopen(url, timeout=30) as resp: text = resp.read().decode(errors='replace') lines = text.strip().split('\n') return '\n'.join(lines[-LOG_TAIL_LINES:]) if len(lines) > LOG_TAIL_LINES else text.strip() def is_complete(gh_status, jenkins_status): gh_done = gh_status is None or all(j["status"] == "completed" for j in gh_status.values()) jenkins_done = jenkins_status is None or not jenkins_status.get("in_progress", True) return gh_done and jenkins_done def status_icon(status, conclusion=None): if status == "completed": return ":white_check_mark:" if conclusion == "success" else ":x:" return ":hourglass:" if status == "in_progress" else ":grey_question:" def format_markdown(gh_status, gh_run_id, jenkins_status, commit_sha, branch): lines = ["# CI Results", "", f"**Branch**: {branch}", f"**Commit**: {commit_sha[:7]}", f"**Generated**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ""] lines.extend(["## GitHub Actions", "", "| Job | Status | Duration |", "|-----|--------|----------|"]) failed_gh_jobs = [] if gh_status: for job_name, job in gh_status.items(): icon = status_icon(job["status"], job.get("conclusion")) conclusion = job.get("conclusion") or job["status"] lines.append(f"| {job_name} | {icon} {conclusion} | {job.get('duration', '')} |") if job.get("conclusion") == "failure": failed_gh_jobs.append((job_name, job.get("id"))) else: lines.append("| - | No workflow runs found | |") lines.extend(["", "## Jenkins", "", "| Stage | Status |", "|-------|--------|"]) failed_jenkins_stages = [] if jenkins_status: stages = jenkins_status.get("stages", []) if stages: for stage in stages: icon = ":white_check_mark:" if stage["status"] == "SUCCESS" else ( ":x:" if stage["status"] == "FAILED" else ":hourglass:") lines.append(f"| {stage['name']} | {icon} {stage['status'].lower()} |") if stage["status"] == "FAILED": failed_jenkins_stages.append(stage["name"]) # Show overall build status if still in progress if jenkins_status["in_progress"]: lines.append("| (build in progress) | :hourglass: in_progress |") else: icon = ":hourglass:" if jenkins_status["in_progress"] else ( ":white_check_mark:" if jenkins_status["result"] == "SUCCESS" else ":x:") status = "in progress" if jenkins_status["in_progress"] else (jenkins_status["result"] or "unknown") lines.append(f"| #{jenkins_status['number']} | {icon} {status.lower()} |") if jenkins_status.get("url"): lines.append(f"\n[View build]({jenkins_status['url']})") else: lines.append("| - | No builds found for branch |") if failed_gh_jobs or failed_jenkins_stages: lines.extend(["", "## Failure Logs", ""]) for job_name, job_id in failed_gh_jobs: lines.append(f"### GitHub Actions: {job_name}") log = get_github_job_log(gh_run_id, job_id) lines.extend(["", "```", log, "```", ""]) for stage_name in failed_jenkins_stages: lines.append(f"### Jenkins: {stage_name}") log = get_jenkins_log(jenkins_status["url"]) lines.extend(["", "```", log, "```", ""]) return "\n".join(lines) + "\n" def main(): parser = argparse.ArgumentParser(description="Fetch CI results from GitHub Actions and Jenkins") parser.add_argument("--wait", action="store_true", help="Wait for CI to complete") parser.add_argument("--timeout", type=int, default=DEFAULT_TIMEOUT, help="Timeout in seconds (default: 1800)") parser.add_argument("-o", "--output", default="ci_results.md", help="Output file (default: ci_results.md)") parser.add_argument("--branch", help="Branch to check (default: current branch)") parser.add_argument("--commit", help="Commit SHA to check (default: HEAD)") args = parser.parse_args() branch, commit = get_git_info() branch = args.branch or branch commit = args.commit or commit print(f"Fetching CI results for {branch} @ {commit[:7]}") start_time = time.monotonic() while True: gh_status, gh_run_id = get_github_actions_status(commit) jenkins_status = get_jenkins_status(branch, commit) if branch != "HEAD" else None if not args.wait or is_complete(gh_status, jenkins_status): break elapsed = time.monotonic() - start_time if elapsed >= args.timeout: print(f"Timeout after {int(elapsed)}s") break print(f"CI still running, waiting {POLL_INTERVAL}s... ({int(elapsed)}s elapsed)") time.sleep(POLL_INTERVAL) content = format_markdown(gh_status, gh_run_id, jenkins_status, commit, branch) with open(args.output, "w") as f: f.write(content) print(f"Results written to {args.output}") if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "scripts/ci_results.py", "license": "MIT License", "lines": 174, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/controls/tests/test_latcontrol_torque_buffer.py
from openpilot.common.parameterized import parameterized from cereal import car, log from opendbc.car.car_helpers import interfaces from opendbc.car.toyota.values import CAR as TOYOTA from opendbc.car.vehicle_model import VehicleModel from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.controls.lib.latcontrol_torque import LatControlTorque, LAT_ACCEL_REQUEST_BUFFER_SECONDS def get_controller(car_name): CarInterface = interfaces[car_name] CP = CarInterface.get_non_essential_params(car_name) CI = CarInterface(CP) VM = VehicleModel(CP) controller = LatControlTorque(CP.as_reader(), CI, DT_CTRL) return controller, VM class TestLatControlTorqueBuffer: @parameterized.expand([(TOYOTA.TOYOTA_COROLLA_TSS2,)]) def test_request_buffer_consistency(self, car_name): buffer_steps = int(LAT_ACCEL_REQUEST_BUFFER_SECONDS / DT_CTRL) controller, VM = get_controller(car_name) CS = car.CarState.new_message() CS.vEgo = 30 CS.steeringPressed = False params = log.LiveParametersData.new_message() for _ in range(buffer_steps): controller.update(True, CS, VM, params, False, 0.001, False, 0.2) assert all(val != 0 for val in controller.lat_accel_request_buffer) for _ in range(buffer_steps): controller.update(False, CS, VM, params, False, 0.0, False, 0.2) assert all(val == 0 for val in controller.lat_accel_request_buffer)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/controls/tests/test_latcontrol_torque_buffer.py", "license": "MIT License", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:system/camerad/cameras/nv12_info.py
# Python version of system/camerad/cameras/nv12_info.h # Calculations from third_party/linux/include/msm_media_info.h (VENUS_BUFFER_SIZE) def align(val: int, alignment: int) -> int: return ((val + alignment - 1) // alignment) * alignment def get_nv12_info(width: int, height: int) -> tuple[int, int, int, int]: """Returns (stride, y_height, uv_height, buffer_size) for NV12 frame dimensions.""" stride = align(width, 128) y_height = align(height, 32) uv_height = align(height // 2, 16) # VENUS_BUFFER_SIZE for NV12 y_plane = stride * y_height uv_plane = stride * uv_height + 4096 size = y_plane + uv_plane + max(16 * 1024, 8 * stride) size = align(size, 4096) size += align(width, 512) * 512 # kernel padding for non-aligned frames size = align(size, 4096) return stride, y_height, uv_height, size
{ "repo_id": "commaai/openpilot", "file_path": "system/camerad/cameras/nv12_info.py", "license": "MIT License", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:common/transformations/transformations.py
import numpy as np # Constants a = 6378137.0 b = 6356752.3142 esq = 6.69437999014e-3 e1sq = 6.73949674228e-3 def geodetic2ecef_single(g): """ Convert geodetic coordinates (latitude, longitude, altitude) to ECEF. """ try: if len(g) != 3: raise ValueError("Geodetic must be size 3") except TypeError: raise ValueError("Geodetic must be a sequence of length 3") from None lat, lon, alt = g lat = np.radians(lat) lon = np.radians(lon) xi = np.sqrt(1.0 - esq * np.sin(lat)**2) x = (a / xi + alt) * np.cos(lat) * np.cos(lon) y = (a / xi + alt) * np.cos(lat) * np.sin(lon) z = (a / xi * (1.0 - esq) + alt) * np.sin(lat) return np.array([x, y, z]) def ecef2geodetic_single(e): """ Convert ECEF to geodetic coordinates using Ferrari's solution. """ x, y, z = e r = np.sqrt(x**2 + y**2) Esq = a**2 - b**2 F = 54 * b**2 * z**2 G = r**2 + (1 - esq) * z**2 - esq * Esq C = (esq**2 * F * r**2) / (G**3) S = np.cbrt(1 + C + np.sqrt(C**2 + 2 * C)) P = F / (3 * (S + 1 / S + 1)**2 * G**2) Q = np.sqrt(1 + 2 * esq**2 * P) r_0 = -(P * esq * r) / (1 + Q) + np.sqrt(0.5 * a**2 * (1 + 1.0 / Q) - P * (1 - esq) * z**2 / (Q * (1 + Q)) - 0.5 * P * r**2) U = np.sqrt((r - esq * r_0)**2 + z**2) V = np.sqrt((r - esq * r_0)**2 + (1 - esq) * z**2) Z_0 = b**2 * z / (a * V) h = U * (1 - b**2 / (a * V)) lat = np.arctan((z + e1sq * Z_0) / r) lon = np.arctan2(y, x) return np.array([np.degrees(lat), np.degrees(lon), h]) def euler2quat_single(euler): """ Convert Euler angles (roll, pitch, yaw) to a quaternion. Rotation order: Z-Y-X (yaw, pitch, roll). """ phi, theta, psi = euler c_phi, s_phi = np.cos(phi / 2), np.sin(phi / 2) c_theta, s_theta = np.cos(theta / 2), np.sin(theta / 2) c_psi, s_psi = np.cos(psi / 2), np.sin(psi / 2) w = c_phi * c_theta * c_psi + s_phi * s_theta * s_psi x = s_phi * c_theta * c_psi - c_phi * s_theta * s_psi y = c_phi * s_theta * c_psi + s_phi * c_theta * s_psi z = c_phi * c_theta * s_psi - s_phi * s_theta * c_psi if w < 0: return np.array([-w, -x, -y, -z]) return np.array([w, x, y, z]) def quat2euler_single(q): """ Convert a quaternion to Euler angles (roll, pitch, yaw). """ w, x, y, z = q gamma = np.arctan2(2 * (w * x + y * z), 1 - 2 * (x**2 + y**2)) sin_arg = 2 * (w * y - z * x) sin_arg = np.clip(sin_arg, -1.0, 1.0) theta = np.arcsin(sin_arg) psi = np.arctan2(2 * (w * z + x * y), 1 - 2 * (y**2 + z**2)) return np.array([gamma, theta, psi]) def quat2rot_single(q): """ Convert a quaternion to a 3x3 rotation matrix. """ w, x, y, z = q xx, yy, zz = x * x, y * y, z * z xy, xz, yz = x * y, x * z, y * z wx, wy, wz = w * x, w * y, w * z mat = np.array([ [1 - 2 * (yy + zz), 2 * (xy - wz), 2 * (xz + wy)], [2 * (xy + wz), 1 - 2 * (xx + zz), 2 * (yz - wx)], [2 * (xz - wy), 2 * (yz + wx), 1 - 2 * (xx + yy)] ]) return mat def rot2quat_single(rot): """ Convert a 3x3 rotation matrix to a quaternion. """ trace = np.trace(rot) if trace > 0: s = 0.5 / np.sqrt(trace + 1.0) w = 0.25 / s x = (rot[2, 1] - rot[1, 2]) * s y = (rot[0, 2] - rot[2, 0]) * s z = (rot[1, 0] - rot[0, 1]) * s else: if rot[0, 0] > rot[1, 1] and rot[0, 0] > rot[2, 2]: s = 2.0 * np.sqrt(1.0 + rot[0, 0] - rot[1, 1] - rot[2, 2]) w = (rot[2, 1] - rot[1, 2]) / s x = 0.25 * s y = (rot[0, 1] + rot[1, 0]) / s z = (rot[0, 2] + rot[2, 0]) / s elif rot[1, 1] > rot[2, 2]: s = 2.0 * np.sqrt(1.0 + rot[1, 1] - rot[0, 0] - rot[2, 2]) w = (rot[0, 2] - rot[2, 0]) / s x = (rot[0, 1] + rot[1, 0]) / s y = 0.25 * s z = (rot[1, 2] + rot[2, 1]) / s else: s = 2.0 * np.sqrt(1.0 + rot[2, 2] - rot[0, 0] - rot[1, 1]) w = (rot[1, 0] - rot[0, 1]) / s x = (rot[0, 2] + rot[2, 0]) / s y = (rot[1, 2] + rot[2, 1]) / s z = 0.25 * s if w < 0: return np.array([-w, -x, -y, -z]) return np.array([w, x, y, z]) def euler2rot_single(euler): """ Convert Euler angles (roll, pitch, yaw) to a 3x3 rotation matrix. Rotation order: Z-Y-X (yaw, pitch, roll). """ phi, theta, psi = euler cx, sx = np.cos(phi), np.sin(phi) cy, sy = np.cos(theta), np.sin(theta) cz, sz = np.cos(psi), np.sin(psi) Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]]) Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]]) Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]]) return Rz @ Ry @ Rx def rot2euler_single(rot): """ Convert a 3x3 rotation matrix to Euler angles (roll, pitch, yaw). """ return quat2euler_single(rot2quat_single(rot)) def rot_matrix(roll, pitch, yaw): """ Create a 3x3 rotation matrix from roll, pitch, and yaw angles. """ return euler2rot_single([roll, pitch, yaw]) def axis_angle_to_rot(axis, angle): """ Convert an axis-angle representation to a 3x3 rotation matrix. """ c = np.cos(angle / 2) s = np.sin(angle / 2) q = np.array([c, s*axis[0], s*axis[1], s*axis[2]]) return quat2rot_single(q) class LocalCoord: """ A class to handle conversions between ECEF and local NED coordinates. """ def __init__(self, geodetic=None, ecef=None): """ Initialize LocalCoord with either geodetic or ECEF coordinates. """ if geodetic is not None: self.init_ecef = geodetic2ecef_single(geodetic) lat, lon, _ = geodetic elif ecef is not None: self.init_ecef = np.array(ecef) lat, lon, _ = ecef2geodetic_single(ecef) else: raise ValueError("Must provide geodetic or ecef") lat = np.radians(lat) lon = np.radians(lon) self.ned2ecef_matrix = np.array([ [-np.sin(lat) * np.cos(lon), -np.sin(lon), -np.cos(lat) * np.cos(lon)], [-np.sin(lat) * np.sin(lon), np.cos(lon), -np.cos(lat) * np.sin(lon)], [np.cos(lat), 0, -np.sin(lat)] ]) self.ecef2ned_matrix = self.ned2ecef_matrix.T @classmethod def from_geodetic(cls, geodetic): """ Create a LocalCoord instance from geodetic coordinates. """ return cls(geodetic=geodetic) @classmethod def from_ecef(cls, ecef): """ Create a LocalCoord instance from ECEF coordinates. """ return cls(ecef=ecef) def ecef2ned_single(self, ecef): """ Convert a single ECEF point to NED coordinates relative to the origin. """ return self.ecef2ned_matrix @ (ecef - self.init_ecef) def ned2ecef_single(self, ned): """ Convert a single NED point to ECEF coordinates. """ return self.ned2ecef_matrix @ ned + self.init_ecef def geodetic2ned_single(self, geodetic): """ Convert a single geodetic point to NED coordinates. """ ecef = geodetic2ecef_single(geodetic) return self.ecef2ned_single(ecef) def ned2geodetic_single(self, ned): """ Convert a single NED point to geodetic coordinates. """ ecef = self.ned2ecef_single(ned) return ecef2geodetic_single(ecef) @property def ned_from_ecef_matrix(self): """ Returns the rotation matrix from ECEF to NED coordinates. """ return self.ecef2ned_matrix @property def ecef_from_ned_matrix(self): """ Returns the rotation matrix from NED to ECEF coordinates. """ return self.ned2ecef_matrix def ecef_euler_from_ned_single(ecef_init, ned_pose): """ Convert NED Euler angles (roll, pitch, yaw) at a given ECEF origin to equivalent ECEF Euler angles. """ converter = LocalCoord(ecef=ecef_init) zero = np.array(ecef_init) x0 = converter.ned2ecef_single([1, 0, 0]) - zero y0 = converter.ned2ecef_single([0, 1, 0]) - zero z0 = converter.ned2ecef_single([0, 0, 1]) - zero phi, theta, psi = ned_pose x1 = axis_angle_to_rot(z0, psi) @ x0 y1 = axis_angle_to_rot(z0, psi) @ y0 z1 = axis_angle_to_rot(z0, psi) @ z0 x2 = axis_angle_to_rot(y1, theta) @ x1 y2 = axis_angle_to_rot(y1, theta) @ y1 z2 = axis_angle_to_rot(y1, theta) @ z1 x3 = axis_angle_to_rot(x2, phi) @ x2 y3 = axis_angle_to_rot(x2, phi) @ y2 x0 = np.array([1.0, 0, 0]) y0 = np.array([0, 1.0, 0]) z0 = np.array([0, 0, 1.0]) psi_out = np.arctan2(np.dot(x3, y0), np.dot(x3, x0)) theta_out = np.arctan2(-np.dot(x3, z0), np.sqrt(np.dot(x3, x0)**2 + np.dot(x3, y0)**2)) y2 = axis_angle_to_rot(z0, psi_out) @ y0 z2 = axis_angle_to_rot(y2, theta_out) @ z0 phi_out = np.arctan2(np.dot(y3, z2), np.dot(y3, y2)) return np.array([phi_out, theta_out, psi_out]) def ned_euler_from_ecef_single(ecef_init, ecef_pose): """ Convert ECEF Euler angles (roll, pitch, yaw) at a given ECEF origin to equivalent NED Euler angles. """ converter = LocalCoord(ecef=ecef_init) x0 = np.array([1.0, 0, 0]) y0 = np.array([0, 1.0, 0]) z0 = np.array([0, 0, 1.0]) phi, theta, psi = ecef_pose x1 = axis_angle_to_rot(z0, psi) @ x0 y1 = axis_angle_to_rot(z0, psi) @ y0 z1 = axis_angle_to_rot(z0, psi) @ z0 x2 = axis_angle_to_rot(y1, theta) @ x1 y2 = axis_angle_to_rot(y1, theta) @ y1 z2 = axis_angle_to_rot(y1, theta) @ z1 x3 = axis_angle_to_rot(x2, phi) @ x2 y3 = axis_angle_to_rot(x2, phi) @ y2 zero = np.array(ecef_init) x0 = converter.ned2ecef_single([1, 0, 0]) - zero y0 = converter.ned2ecef_single([0, 1, 0]) - zero z0 = converter.ned2ecef_single([0, 0, 1]) - zero psi_out = np.arctan2(np.dot(x3, y0), np.dot(x3, x0)) theta_out = np.arctan2(-np.dot(x3, z0), np.sqrt(np.dot(x3, x0)**2 + np.dot(x3, y0)**2)) y2 = axis_angle_to_rot(z0, psi_out) @ y0 z2 = axis_angle_to_rot(y2, theta_out) @ z0 phi_out = np.arctan2(np.dot(y3, z2), np.dot(y3, y2)) return np.array([phi_out, theta_out, psi_out])
{ "repo_id": "commaai/openpilot", "file_path": "common/transformations/transformations.py", "license": "MIT License", "lines": 275, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/debug/analyze-msg-size.py
#!/usr/bin/env python3 import argparse from tqdm import tqdm from cereal.services import SERVICE_LIST, QueueSize from openpilot.tools.lib.logreader import LogReader if __name__ == "__main__": parser = argparse.ArgumentParser(description="Analyze message sizes from a log route") parser.add_argument("route", nargs="?", default="98395b7c5b27882e/000000a8--f87e7cd255", help="Log route to analyze (default: 98395b7c5b27882e/000000a8--f87e7cd255)") args = parser.parse_args() lr = LogReader(args.route) szs = {} for msg in tqdm(lr): sz = len(msg.as_builder().to_bytes()) msg_type = msg.which() if msg_type not in szs: szs[msg_type] = {'min': sz, 'max': sz, 'sum': sz, 'count': 1} else: szs[msg_type]['min'] = min(szs[msg_type]['min'], sz) szs[msg_type]['max'] = max(szs[msg_type]['max'], sz) szs[msg_type]['sum'] += sz szs[msg_type]['count'] += 1 print() print(f"{'Service':<36} {'Min (KB)':>12} {'Max (KB)':>12} {'Avg (KB)':>12} {'KB/min':>12} {'KB/sec':>12} {'Minutes in 10MB':>18} {'Seconds in Queue':>18}") print("-" * 132) def sort_key(x): k, v = x avg = v['sum'] / v['count'] freq = SERVICE_LIST.get(k, None) freq_val = freq.frequency if freq else 0.0 kb_per_min = (avg * freq_val * 60) / 1024 if freq_val > 0 else 0.0 return kb_per_min total_kb_per_min = 0.0 RINGBUFFER_SIZE_KB = 10 * 1024 # 10MB old default for k, v in sorted(szs.items(), key=sort_key, reverse=True): avg = v['sum'] / v['count'] service = SERVICE_LIST.get(k, None) freq_val = service.frequency if service else 0.0 queue_size_kb = (service.queue_size / 1024) if service else 250 # default to SMALL kb_per_min = (avg * freq_val * 60) / 1024 if freq_val > 0 else 0.0 kb_per_sec = kb_per_min / 60 minutes_in_buffer = RINGBUFFER_SIZE_KB / kb_per_min if kb_per_min > 0 else float('inf') seconds_in_queue = (queue_size_kb / kb_per_sec) if kb_per_sec > 0 else float('inf') total_kb_per_min += kb_per_min min_str = f"{minutes_in_buffer:.2f}" if minutes_in_buffer != float('inf') else "inf" sec_queue_str = f"{seconds_in_queue:.2f}" if seconds_in_queue != float('inf') else "inf" print(f"{k:<36} {v['min']/1024:>12.2f} {v['max']/1024:>12.2f} {avg/1024:>12.2f} {kb_per_min:>12.2f} {kb_per_sec:>12.2f} {min_str:>18} {sec_queue_str:>18}") # Summary section print() print(f"Total usage: {total_kb_per_min / 1024:.2f} MB/min") # Calculate memory usage: old (10MB for all) vs new (from services.py) OLD_SIZE = 10 * 1024 * 1024 # 10MB was the old default old_total = len(SERVICE_LIST) * OLD_SIZE new_total = sum(s.queue_size for s in SERVICE_LIST.values()) # Count by queue size size_counts = {QueueSize.BIG: 0, QueueSize.MEDIUM: 0, QueueSize.SMALL: 0} for s in SERVICE_LIST.values(): size_counts[s.queue_size] += 1 savings_pct = (1 - new_total / old_total) * 100 print() print(f"{'Queue Size Comparison':<40}") print("-" * 60) print(f"{'Old (10MB default):':<30} {old_total / 1024 / 1024:>10.2f} MB") print(f"{'New (from services.py):':<30} {new_total / 1024 / 1024:>10.2f} MB") print(f"{'Savings:':<30} {savings_pct:>10.1f}%") print() print(f"{'Breakdown:':<30}") print(f" BIG (10MB): {size_counts[QueueSize.BIG]:>3} services") print(f" MEDIUM (2MB): {size_counts[QueueSize.MEDIUM]:>3} services") print(f" SMALL (250KB): {size_counts[QueueSize.SMALL]:>3} services")
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/debug/analyze-msg-size.py", "license": "MIT License", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/tests/diff/diff.py
#!/usr/bin/env python3 import os import sys import subprocess import webbrowser import argparse from pathlib import Path from openpilot.common.basedir import BASEDIR DIFF_OUT_DIR = Path(BASEDIR) / "selfdrive" / "ui" / "tests" / "diff" / "report" HTML_TEMPLATE_PATH = Path(__file__).with_name("diff_template.html") def extract_framehashes(video_path): cmd = ['ffmpeg', '-i', video_path, '-map', '0:v:0', '-vsync', '0', '-f', 'framehash', '-hash', 'md5', '-'] result = subprocess.run(cmd, capture_output=True, text=True, check=True) hashes = [] for line in result.stdout.splitlines(): if not line or line.startswith('#'): continue parts = line.split(',') if len(parts) < 4: continue hashes.append(parts[-1].strip()) return hashes def create_diff_video(video1, video2, output_path): """Create a diff video using ffmpeg blend filter with difference mode.""" print("Creating diff video...") cmd = ['ffmpeg', '-i', video1, '-i', video2, '-filter_complex', '[0:v]blend=all_mode=difference', '-vsync', '0', '-y', output_path] subprocess.run(cmd, capture_output=True, check=True) def find_differences(video1, video2) -> tuple[list[int], tuple[int, int]]: print(f"Hashing frames from {video1}...") hashes1 = extract_framehashes(video1) print(f"Hashing frames from {video2}...") hashes2 = extract_framehashes(video2) print(f"Comparing {len(hashes1)} frames...") different_frames = [] for i, (h1, h2) in enumerate(zip(hashes1, hashes2, strict=False)): if h1 != h2: different_frames.append(i) return different_frames, (len(hashes1), len(hashes2)) def generate_html_report(videos: tuple[str, str], basedir: str, different_frames: list[int], frame_counts: tuple[int, int], diff_video_name): chunks = [] if different_frames: current_chunk = [different_frames[0]] for i in range(1, len(different_frames)): if different_frames[i] == different_frames[i - 1] + 1: current_chunk.append(different_frames[i]) else: chunks.append(current_chunk) current_chunk = [different_frames[i]] chunks.append(current_chunk) total_frames = max(frame_counts) frame_delta = frame_counts[1] - frame_counts[0] different_total = len(different_frames) + abs(frame_delta) result_text = ( f"✅ Videos are identical! ({total_frames} frames)" if different_total == 0 else f"❌ Found {different_total} different frames out of {total_frames} total ({different_total / total_frames * 100:.1f}%)." + (f" Video {'2' if frame_delta > 0 else '1'} is longer by {abs(frame_delta)} frames." if frame_delta != 0 else "") ) # Load HTML template and replace placeholders html = HTML_TEMPLATE_PATH.read_text() placeholders = { "VIDEO1_SRC": os.path.join(basedir, os.path.basename(videos[0])), "VIDEO2_SRC": os.path.join(basedir, os.path.basename(videos[1])), "DIFF_SRC": os.path.join(basedir, diff_video_name), "RESULT_TEXT": result_text, } for key, value in placeholders.items(): html = html.replace(f"${key}", value) return html def main(): parser = argparse.ArgumentParser(description='Compare two videos and generate HTML diff report') parser.add_argument('video1', help='First video file') parser.add_argument('video2', help='Second video file') parser.add_argument('output', nargs='?', default='diff.html', help='Output HTML file (default: diff.html)') parser.add_argument("--basedir", type=str, help="Base directory for output", default="") parser.add_argument('--no-open', action='store_true', help='Do not open HTML report in browser') args = parser.parse_args() if not args.output.lower().endswith('.html'): args.output += '.html' os.makedirs(DIFF_OUT_DIR, exist_ok=True) print("=" * 60) print("VIDEO DIFF - HTML REPORT") print("=" * 60) print(f"Video 1: {args.video1}") print(f"Video 2: {args.video2}") print(f"Output: {args.output}") print() # Create diff video with name derived from output HTML diff_video_name = Path(args.output).stem + '.mp4' diff_video_path = str(DIFF_OUT_DIR / diff_video_name) create_diff_video(args.video1, args.video2, diff_video_path) different_frames, frame_counts = find_differences(args.video1, args.video2) if different_frames is None: sys.exit(1) print() print("Generating HTML report...") html = generate_html_report((args.video1, args.video2), args.basedir, different_frames, frame_counts, diff_video_name) with open(DIFF_OUT_DIR / args.output, 'w') as f: f.write(html) # Open in browser by default if not args.no_open: print(f"Opening {args.output} in browser...") webbrowser.open(f'file://{os.path.abspath(DIFF_OUT_DIR / args.output)}') extra_frames = abs(frame_counts[0] - frame_counts[1]) return 0 if (len(different_frames) + extra_frames) == 0 else 1 if __name__ == "__main__": sys.exit(main())
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/tests/diff/diff.py", "license": "MIT License", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/ui/tests/diff/replay.py
#!/usr/bin/env python3 import os import argparse import coverage import pyray as rl from typing import Literal from collections.abc import Callable from cereal.messaging import PubMaster from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix from openpilot.selfdrive.ui.tests.diff.diff import DIFF_OUT_DIR from openpilot.system.version import terms_version, training_version LayoutVariant = Literal["mici", "tizi"] FPS = 60 HEADLESS = os.getenv("WINDOWED", "0") != "1" def setup_state(): params = Params() params.put("HasAcceptedTerms", terms_version) params.put("CompletedTrainingVersion", training_version) params.put("DongleId", "test123456789") # Combined description for layouts that still use it (BIG home, settings/software) params.put("UpdaterCurrentDescription", "0.10.1 / test-branch / abc1234 / Nov 30") # Params for mici home params.put("Version", "0.10.1") params.put("GitBranch", "test-branch") params.put("GitCommit", "abc12340ff9131237ba23a1d0fbd8edf9c80e87") params.put("GitCommitDate", "'1732924800 2024-11-30 00:00:00 +0000'") def run_replay(variant: LayoutVariant) -> None: if HEADLESS: rl.set_config_flags(rl.ConfigFlags.FLAG_WINDOW_HIDDEN) os.environ["OFFSCREEN"] = "1" # Run UI without FPS limit (set before importing gui_app) setup_state() os.makedirs(DIFF_OUT_DIR, exist_ok=True) from openpilot.selfdrive.ui.ui_state import ui_state # Import within OpenpilotPrefix context so param values are setup correctly from openpilot.system.ui.lib.application import gui_app # Import here for accurate coverage from openpilot.selfdrive.ui.tests.diff.replay_script import build_script gui_app.init_window("ui diff test", fps=FPS) # Dynamically import main layout based on variant if variant == "mici": from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout as MainLayout else: from openpilot.selfdrive.ui.layouts.main import MainLayout main_layout = MainLayout() pm = PubMaster(["deviceState", "pandaStates", "driverStateV2", "selfdriveState"]) script = build_script(pm, main_layout, variant) script_index = 0 send_fn: Callable | None = None frame = 0 # Override raylib timing functions to return deterministic values based on frame count instead of real time rl.get_frame_time = lambda: 1.0 / FPS rl.get_time = lambda: frame / FPS # Main loop to replay events and render frames for _ in gui_app.render(): # Handle all events for the current frame while script_index < len(script) and script[script_index][0] == frame: _, event = script[script_index] # Call setup function, if any if event.setup: event.setup() # Send mouse events to the application if event.mouse_events: with gui_app._mouse._lock: gui_app._mouse._events.extend(event.mouse_events) # Update persistent send function if event.send_fn is not None: send_fn = event.send_fn # Move to next script event script_index += 1 # Keep sending cereal messages for persistent states (onroad, alerts) if send_fn: send_fn() ui_state.update() frame += 1 if script_index >= len(script): break gui_app.close() print(f"Total frames: {frame}") print(f"Video saved to: {os.environ['RECORD_OUTPUT']}") def main(): parser = argparse.ArgumentParser() parser.add_argument('--big', action='store_true', help='Use big UI layout (tizi/tici) instead of mici layout') args = parser.parse_args() variant: LayoutVariant = 'tizi' if args.big else 'mici' if args.big: os.environ["BIG"] = "1" os.environ["RECORD"] = "1" os.environ["RECORD_QUALITY"] = "0" # Use CRF 0 ("lossless" encode) for deterministic output across different machines os.environ["RECORD_OUTPUT"] = os.path.join(DIFF_OUT_DIR, os.environ.get("RECORD_OUTPUT", f"{variant}_ui_replay.mp4")) print(f"Running {variant} UI replay...") with OpenpilotPrefix(): sources = ["openpilot.system.ui"] if variant == "mici": sources.append("openpilot.selfdrive.ui.mici") omit = ["**/*tizi*", "**/*tici*"] # exclude files containing "tizi" or "tici" else: sources.extend(["openpilot.selfdrive.ui.layouts", "openpilot.selfdrive.ui.onroad", "openpilot.selfdrive.ui.widgets"]) omit = ["**/*mici*"] # exclude files containing "mici" cov = coverage.Coverage(source=sources, omit=omit) with cov.collect(): run_replay(variant) cov.save() cov.report() directory = os.path.join(DIFF_OUT_DIR, f"htmlcov-{variant}") cov.html_report(directory=directory) print(f"HTML report: {directory}/index.html") if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/tests/diff/replay.py", "license": "MIT License", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/assets/sounds/make_beeps.py
import numpy as np from scipy.io import wavfile sr = 48000 max_int16 = 2**15 - 1 def harmonic_beep(freq, duration_seconds): n_total = int(sr * duration_seconds) signal = np.sin(2 * np.pi * freq * np.arange(n_total) / sr) x = np.arange(n_total) exp_scale = np.exp(-x/5.5e3) return max_int16 * signal * exp_scale engage_beep = harmonic_beep(1661.219, 0.5) wavfile.write("engage.wav", sr, engage_beep.astype(np.int16)) disengage_beep = harmonic_beep(1318.51, 0.5) wavfile.write("disengage.wav", sr, disengage_beep.astype(np.int16))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/assets/sounds/make_beeps.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/mici/layouts/home.py
import datetime import time from cereal import log import pyray as rl from collections.abc import Callable from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.layouts import HBoxLayout from openpilot.system.ui.widgets.icon_widget import IconWidget from openpilot.system.ui.widgets.label import MiciLabel, UnifiedLabel from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.system.version import RELEASE_BRANCHES HEAD_BUTTON_FONT_SIZE = 40 HOME_PADDING = 8 NetworkType = log.DeviceState.NetworkType NETWORK_TYPES = { NetworkType.none: "Offline", NetworkType.wifi: "WiFi", NetworkType.cell2G: "2G", NetworkType.cell3G: "3G", NetworkType.cell4G: "LTE", NetworkType.cell5G: "5G", NetworkType.ethernet: "Ethernet", } class NetworkIcon(Widget): def __init__(self): super().__init__() self.set_rect(rl.Rectangle(0, 0, 54, 44)) # max size of all icons self._net_type = NetworkType.none self._net_strength = 0 self._wifi_slash_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_slash.png", 50, 44) self._wifi_none_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_none.png", 50, 37) self._wifi_low_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_low.png", 50, 37) self._wifi_medium_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_medium.png", 50, 37) self._wifi_full_txt = gui_app.texture("icons_mici/settings/network/wifi_strength_full.png", 50, 37) self._cell_none_txt = gui_app.texture("icons_mici/settings/network/cell_strength_none.png", 54, 36) self._cell_low_txt = gui_app.texture("icons_mici/settings/network/cell_strength_low.png", 54, 36) self._cell_medium_txt = gui_app.texture("icons_mici/settings/network/cell_strength_medium.png", 54, 36) self._cell_high_txt = gui_app.texture("icons_mici/settings/network/cell_strength_high.png", 54, 36) self._cell_full_txt = gui_app.texture("icons_mici/settings/network/cell_strength_full.png", 54, 36) def _update_state(self): device_state = ui_state.sm['deviceState'] self._net_type = device_state.networkType strength = device_state.networkStrength self._net_strength = max(0, min(5, strength.raw + 1)) if strength.raw > 0 else 0 def _render(self, _): if self._net_type == NetworkType.wifi: # There is no 1 draw_net_txt = {0: self._wifi_none_txt, 2: self._wifi_low_txt, 3: self._wifi_medium_txt, 4: self._wifi_full_txt, 5: self._wifi_full_txt}.get(self._net_strength, self._wifi_low_txt) elif self._net_type in (NetworkType.cell2G, NetworkType.cell3G, NetworkType.cell4G, NetworkType.cell5G): draw_net_txt = {0: self._cell_none_txt, 2: self._cell_low_txt, 3: self._cell_medium_txt, 4: self._cell_high_txt, 5: self._cell_full_txt}.get(self._net_strength, self._cell_none_txt) else: draw_net_txt = self._wifi_slash_txt draw_x = self._rect.x + (self._rect.width - draw_net_txt.width) / 2 draw_y = self._rect.y + (self._rect.height - draw_net_txt.height) / 2 if draw_net_txt == self._wifi_slash_txt: # Offset by difference in height between slashless and slash icons to make center align match draw_y -= (self._wifi_slash_txt.height - self._wifi_none_txt.height) / 2 rl.draw_texture(draw_net_txt, int(draw_x), int(draw_y), rl.Color(255, 255, 255, int(255 * 0.9))) class MiciHomeLayout(Widget): def __init__(self): super().__init__() self._on_settings_click: Callable | None = None self._last_refresh = 0 self._mouse_down_t: None | float = None self._did_long_press = False self._is_pressed_prev = False self._version_text = None self._experimental_mode = False self._experimental_icon = IconWidget("icons_mici/experimental_mode.png", (48, 48)) self._mic_icon = IconWidget("icons_mici/microphone.png", (32, 46)) self._status_bar_layout = HBoxLayout([ IconWidget("icons_mici/settings.png", (48, 48), opacity=0.9), NetworkIcon(), self._experimental_icon, self._mic_icon, ], spacing=18) self._openpilot_label = MiciLabel("openpilot", 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) self._branch_label = UnifiedLabel("", font_size=36, text_color=rl.GRAY, font_weight=FontWeight.ROMAN, scroll=True) self._version_commit_label = MiciLabel("", font_size=36, color=rl.GRAY, font_weight=FontWeight.ROMAN) def show_event(self): self._version_text = self._get_version_text() self._update_params() def _update_params(self): self._experimental_mode = ui_state.params.get_bool("ExperimentalMode") def _update_state(self): if self.is_pressed and not self._is_pressed_prev: self._mouse_down_t = time.monotonic() elif not self.is_pressed and self._is_pressed_prev: self._mouse_down_t = None self._did_long_press = False self._is_pressed_prev = self.is_pressed if self._mouse_down_t is not None: if time.monotonic() - self._mouse_down_t > 0.5: # long gating for experimental mode - only allow toggle if longitudinal control is available if ui_state.has_longitudinal_control: self._experimental_mode = not self._experimental_mode ui_state.params.put("ExperimentalMode", self._experimental_mode) self._mouse_down_t = None self._did_long_press = True if rl.get_time() - self._last_refresh > 5.0: # Update version text self._version_text = self._get_version_text() self._last_refresh = rl.get_time() self._update_params() def set_callbacks(self, on_settings: Callable | None = None): self._on_settings_click = on_settings def _handle_mouse_release(self, mouse_pos: MousePos): if not self._did_long_press: if self._on_settings_click: self._on_settings_click() self._did_long_press = False def _get_version_text(self) -> tuple[str, str, str, str] | None: version = ui_state.params.get("Version") branch = ui_state.params.get("GitBranch") commit = ui_state.params.get("GitCommit") if not all((version, branch, commit)): return None commit_date_raw = ui_state.params.get("GitCommitDate") try: # GitCommitDate format from get_commit_date(): '%ct %ci' e.g. "'1708012345 2024-02-15 ...'" unix_ts = int(commit_date_raw.strip("'").split()[0]) date_str = datetime.datetime.fromtimestamp(unix_ts).strftime("%b %d") except (ValueError, IndexError, TypeError, AttributeError): date_str = "" return version, branch, commit[:7], date_str def _render(self, _): # TODO: why is there extra space here to get it to be flush? text_pos = rl.Vector2(self.rect.x - 2 + HOME_PADDING, self.rect.y - 16) self._openpilot_label.set_position(text_pos.x, text_pos.y) self._openpilot_label.render() if self._version_text is not None: # release branch release_branch = self._version_text[1] in RELEASE_BRANCHES version_pos = rl.Rectangle(text_pos.x, text_pos.y + self._openpilot_label.font_size + 16, 100, 44) self._version_label.set_text(self._version_text[0]) self._version_label.set_position(version_pos.x, version_pos.y) self._version_label.render() self._date_label.set_text(" " + self._version_text[3]) self._date_label.set_position(version_pos.x + self._version_label.rect.width + 10, version_pos.y) self._date_label.render() self._branch_label.set_max_width(gui_app.width - self._version_label.rect.width - self._date_label.rect.width - 32) self._branch_label.set_text(" " + ("release" if release_branch else self._version_text[1])) self._branch_label.set_position(version_pos.x + self._version_label.rect.width + self._date_label.rect.width + 20, version_pos.y) self._branch_label.render() if not release_branch: # 2nd line self._version_commit_label.set_text(self._version_text[2]) self._version_commit_label.set_position(version_pos.x, version_pos.y + self._date_label.font_size + 7) self._version_commit_label.render() # ***** Center-aligned bottom section icons ***** self._experimental_icon.set_visible(self._experimental_mode) self._mic_icon.set_visible(ui_state.recording_audio) footer_rect = rl.Rectangle(self.rect.x + HOME_PADDING, self.rect.y + self.rect.height - 48, self.rect.width - HOME_PADDING, 48) self._status_bar_layout.render(footer_rect)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/home.py", "license": "MIT License", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/layouts/main.py
import pyray as rl import cereal.messaging as messaging from openpilot.selfdrive.ui.mici.layouts.home import MiciHomeLayout from openpilot.selfdrive.ui.mici.layouts.settings.settings import SettingsLayout from openpilot.selfdrive.ui.mici.layouts.offroad_alerts import MiciOffroadAlerts from openpilot.selfdrive.ui.mici.onroad.augmented_road_view import AugmentedRoadView from openpilot.selfdrive.ui.ui_state import device, ui_state from openpilot.selfdrive.ui.mici.layouts.onboarding import OnboardingWindow from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.scroller import Scroller from openpilot.system.ui.lib.application import gui_app ONROAD_DELAY = 2.5 # seconds class MiciMainLayout(Scroller): def __init__(self): super().__init__(snap_items=True, spacing=0, pad=0, scroll_indicator=False, edge_shadows=False) self._pm = messaging.PubMaster(['bookmarkButton']) self._prev_onroad = False self._prev_standstill = False self._onroad_time_delay: float | None = None self._setup = False # Initialize widgets self._home_layout = MiciHomeLayout() self._alerts_layout = MiciOffroadAlerts() self._settings_layout = SettingsLayout() self._onroad_layout = AugmentedRoadView(bookmark_callback=self._on_bookmark_clicked) # Initialize widget rects for widget in (self._home_layout, self._settings_layout, self._alerts_layout, self._onroad_layout): # TODO: set parent rect and use it if never passed rect from render (like in Scroller) widget.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) self._scroller.add_widgets([ self._alerts_layout, self._home_layout, self._onroad_layout, ]) self._scroller.set_reset_scroll_at_show(False) # Disable scrolling when onroad is interacting with bookmark self._scroller.set_scrolling_enabled(lambda: not self._onroad_layout.is_swiping_left()) # Set callbacks self._setup_callbacks() gui_app.add_nav_stack_tick(self._handle_transitions) gui_app.push_widget(self) # Start onboarding if terms or training not completed, make sure to push after self self._onboarding_window = OnboardingWindow() if not self._onboarding_window.completed: gui_app.push_widget(self._onboarding_window) def _setup_callbacks(self): self._home_layout.set_callbacks(on_settings=lambda: gui_app.push_widget(self._settings_layout)) self._onroad_layout.set_click_callback(lambda: self._scroll_to(self._home_layout)) device.add_interactive_timeout_callback(self._on_interactive_timeout) def _scroll_to(self, layout: Widget): layout_x = int(layout.rect.x) self._scroller.scroll_to(layout_x, smooth=True) def _render(self, _): if not self._setup: if self._alerts_layout.active_alerts() > 0: self._scroller.scroll_to(self._alerts_layout.rect.x) else: self._scroller.scroll_to(self._rect.width) self._setup = True # Render super()._render(self._rect) def _handle_transitions(self): # Don't pop if onboarding if gui_app.get_active_widget() == self._onboarding_window: return if ui_state.started != self._prev_onroad: self._prev_onroad = ui_state.started # onroad: after delay, pop nav stack and scroll to onroad # offroad: immediately scroll to home, but don't pop nav stack (can stay in settings) if ui_state.started: self._onroad_time_delay = rl.get_time() else: self._scroll_to(self._home_layout) # FIXME: these two pops can interrupt user interacting in the settings if self._onroad_time_delay is not None and rl.get_time() - self._onroad_time_delay >= ONROAD_DELAY: gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) self._onroad_time_delay = None # When car leaves standstill, pop nav stack and scroll to onroad CS = ui_state.sm["carState"] if not CS.standstill and self._prev_standstill: gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) self._prev_standstill = CS.standstill def _on_interactive_timeout(self): # Don't pop if onboarding if gui_app.get_active_widget() == self._onboarding_window: return if ui_state.started: # Don't pop if at standstill if not ui_state.sm["carState"].standstill: gui_app.pop_widgets_to(self, lambda: self._scroll_to(self._onroad_layout)) else: # Screen turns off on timeout offroad, so pop immediately without animation gui_app.pop_widgets_to(self, instant=True) self._scroll_to(self._home_layout) def _on_bookmark_clicked(self): user_bookmark = messaging.new_message('bookmarkButton') user_bookmark.valid = True self._pm.send('bookmarkButton', user_bookmark)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/main.py", "license": "MIT License", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/layouts/offroad_alerts.py
import pyray as rl import re import time from dataclasses import dataclass from enum import IntEnum from openpilot.common.params import Params from openpilot.selfdrive.selfdrived.alertmanager import OFFROAD_ALERTS from openpilot.system.hardware import HARDWARE from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.label import UnifiedLabel from openpilot.system.ui.widgets.scroller import Scroller from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.lib.multilang import tr REFRESH_INTERVAL = 5.0 # seconds class AlertSize(IntEnum): SMALL = 0 MEDIUM = 1 BIG = 2 @dataclass class AlertData: key: str text: str severity: int visible: bool = False class AlertItem(Widget): # TODO: click should always go somewhere: home or specific settings pane """Individual alert item widget with background image and text.""" ALERT_WIDTH = 520 ALERT_HEIGHT_SMALL = 212 ALERT_HEIGHT_MED = 240 ALERT_HEIGHT_BIG = 324 ALERT_PADDING = 28 ICON_SIZE = 64 ICON_MARGIN = 12 TEXT_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) TITLE_BODY_SPACING = 24 def __init__(self, alert_data: AlertData): super().__init__() self.alert_data = alert_data # Load background textures self._bg_small = gui_app.texture("icons_mici/offroad_alerts/small_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_SMALL) self._bg_small_pressed = gui_app.texture("icons_mici/offroad_alerts/small_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_SMALL) self._bg_medium = gui_app.texture("icons_mici/offroad_alerts/medium_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_MED) self._bg_medium_pressed = gui_app.texture("icons_mici/offroad_alerts/medium_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_MED) self._bg_big = gui_app.texture("icons_mici/offroad_alerts/big_alert.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_BIG) self._bg_big_pressed = gui_app.texture("icons_mici/offroad_alerts/big_alert_pressed.png", self.ALERT_WIDTH, self.ALERT_HEIGHT_BIG) # Load warning icons self._icon_orange = gui_app.texture("icons_mici/offroad_alerts/orange_warning.png", self.ICON_SIZE, self.ICON_SIZE) self._icon_red = gui_app.texture("icons_mici/offroad_alerts/red_warning.png", self.ICON_SIZE, self.ICON_SIZE) self._icon_green = gui_app.texture("icons_mici/offroad_alerts/green_wheel.png", self.ICON_SIZE, self.ICON_SIZE) self._title_label = UnifiedLabel(text="", font_size=32, font_weight=FontWeight.SEMI_BOLD, text_color=self.TEXT_COLOR, alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, line_height=0.95) self._body_label = UnifiedLabel(text="", font_size=28, font_weight=FontWeight.ROMAN, text_color=self.TEXT_COLOR, alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, line_height=0.95) self._title_text = "" self._body_text = "" self._alert_size = AlertSize.SMALL self._update_content() def _split_text(self, text: str) -> tuple[str, str]: """Split text into title (first sentence) and body (remaining text).""" # Find the end of the first sentence (period, exclamation, or question mark followed by space or end) match = re.search(r'[.!?](?:\s+|$)', text) if match: # Found a sentence boundary - split at the end of the sentence title = text[:match.start()].strip() body = text[match.end():].strip() return title, body else: # No sentence boundary found, return full text as title return "", text def _update_content(self): """Update text and calculate height.""" if not self.alert_data.visible or not self.alert_data.text: self.set_visible(False) return self.set_visible(True) # Split text into title and body self._title_text, self._body_text = self._split_text(self.alert_data.text) # Calculate text width (alert width minus padding and icon space on right) title_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) - self.ICON_SIZE - self.ICON_MARGIN body_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) # Update labels self._title_label.set_text(self._title_text) self._body_label.set_text(self._body_text) # Calculate content height title_height = self._title_label.get_content_height(title_width) if self._title_text else 0 body_height = self._body_label.get_content_height(body_width) if self._body_text else 0 spacing = self.TITLE_BODY_SPACING if (self._title_text and self._body_text) else 0 total_text_height = title_height + spacing + body_height # Determine which background size to use based on content height min_height_with_padding = total_text_height + (self.ALERT_PADDING * 2) if min_height_with_padding > self.ALERT_HEIGHT_MED: self._alert_size = AlertSize.BIG height = self.ALERT_HEIGHT_BIG elif min_height_with_padding > self.ALERT_HEIGHT_SMALL: self._alert_size = AlertSize.MEDIUM height = self.ALERT_HEIGHT_MED else: self._alert_size = AlertSize.SMALL height = self.ALERT_HEIGHT_SMALL # Set rect size self.set_rect(rl.Rectangle(0, 0, self.ALERT_WIDTH, height)) def update_alert_data(self, alert_data: AlertData): """Update alert data and refresh display.""" self.alert_data = alert_data self._update_content() def _render(self, _): if not self.alert_data.visible or not self.alert_data.text: return # Choose background based on size if self._alert_size == AlertSize.BIG: bg_texture = self._bg_big_pressed if self.is_pressed else self._bg_big elif self._alert_size == AlertSize.MEDIUM: bg_texture = self._bg_medium_pressed if self.is_pressed else self._bg_medium else: # AlertSize.SMALL bg_texture = self._bg_small_pressed if self.is_pressed else self._bg_small # Draw background rl.draw_texture(bg_texture, int(self._rect.x), int(self._rect.y), rl.WHITE) # Calculate text area (left side, avoiding icon on right) title_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) - self.ICON_SIZE - self.ICON_MARGIN body_width = self.ALERT_WIDTH - (self.ALERT_PADDING * 2) text_x = self._rect.x + self.ALERT_PADDING text_y = self._rect.y + self.ALERT_PADDING # Draw title label if self._title_text: title_rect = rl.Rectangle( text_x, text_y, title_width, self._title_label.get_content_height(title_width), ) self._title_label.render(title_rect) text_y += title_rect.height + self.TITLE_BODY_SPACING # Draw body label if self._body_text: body_rect = rl.Rectangle( text_x, text_y, body_width, self._rect.height - text_y + self._rect.y - self.ALERT_PADDING, ) self._body_label.render(body_rect) # Draw warning icon on the right side # Use green icon for update alerts (severity = -1), red for high severity, orange for low severity if self.alert_data.severity == -1: icon_texture = self._icon_green elif self.alert_data.severity > 0: icon_texture = self._icon_red else: icon_texture = self._icon_orange icon_x = self._rect.x + self.ALERT_WIDTH - self.ALERT_PADDING - self.ICON_SIZE icon_y = self._rect.y + self.ALERT_PADDING rl.draw_texture(icon_texture, int(icon_x), int(icon_y), rl.WHITE) class MiciOffroadAlerts(Scroller): """Offroad alerts layout with vertical scrolling.""" def __init__(self): # Create vertical scroller super().__init__(horizontal=False, spacing=12, pad=0) self.params = Params() self.sorted_alerts: list[AlertData] = [] self.alert_items: list[AlertItem] = [] self._last_refresh = 0.0 # Create empty state label self._empty_label = UnifiedLabel(tr("no alerts"), 65, FontWeight.DISPLAY, rl.WHITE, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) # Build initial alert list self._build_alerts() def active_alerts(self) -> int: return sum(alert.visible for alert in self.sorted_alerts) def scrolling(self): return self._scroller.scroll_panel.is_touch_valid() def _build_alerts(self): """Build sorted list of alerts from OFFROAD_ALERTS.""" self.sorted_alerts = [] # Add UpdateAvailable alert at the top (severity = -1 to indicate special handling) update_alert_data = AlertData(key="UpdateAvailable", text="", severity=-1) self.sorted_alerts.append(update_alert_data) update_alert_item = AlertItem(update_alert_data) update_alert_item.set_click_callback(lambda: HARDWARE.reboot()) self.alert_items.append(update_alert_item) self._scroller.add_widget(update_alert_item) # Add regular alerts sorted by severity for key, config in sorted(OFFROAD_ALERTS.items(), key=lambda x: x[1].get("severity", 0), reverse=True): severity = config.get("severity", 0) alert_data = AlertData(key=key, text="", severity=severity) self.sorted_alerts.append(alert_data) # Create alert item widget alert_item = AlertItem(alert_data) self.alert_items.append(alert_item) self._scroller.add_widget(alert_item) def refresh(self) -> int: """Refresh alerts from params and return active count.""" active_count = 0 # Handle UpdateAvailable alert specially update_available = self.params.get_bool("UpdateAvailable") update_alert_data = next((alert_data for alert_data in self.sorted_alerts if alert_data.key == "UpdateAvailable"), None) if update_alert_data: if update_available: version_string = "" # Get new version description and parse version and date new_desc = self.params.get("UpdaterNewDescription") or "" if new_desc: # format: "version / branch / commit / date" parts = new_desc.split(" / ") if len(parts) > 3: version, date = parts[0], parts[3] version_string = f"\nopenpilot {version}, {date}\n" update_alert_data.text = f"Update available {version_string}. Click to update. Read the release notes at blog.comma.ai." update_alert_data.visible = True active_count += 1 else: update_alert_data.text = "" update_alert_data.visible = False # Handle regular alerts for alert_data in self.sorted_alerts: if alert_data.key == "UpdateAvailable": continue # Skip, already handled above text = "" alert_json = self.params.get(alert_data.key) if alert_json: text = alert_json.get("text", "").replace("%1", alert_json.get("extra", "")) alert_data.text = text alert_data.visible = bool(text) if alert_data.visible: active_count += 1 # Update alert items (they reference the same alert_data objects) for alert_item in self.alert_items: alert_item.update_alert_data(alert_item.alert_data) return active_count def show_event(self): """Reset scroll position when shown and refresh alerts.""" super().show_event() self._last_refresh = time.monotonic() self.refresh() def _update_state(self): """Periodically refresh alerts.""" # Refresh alerts periodically, not every frame current_time = time.monotonic() if current_time - self._last_refresh >= REFRESH_INTERVAL: self.refresh() self._last_refresh = current_time def _render(self, rect: rl.Rectangle): """Render the alerts scroller or empty state.""" if self.active_alerts() == 0: self._empty_label.render(rect) else: self._scroller.render(rect)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/offroad_alerts.py", "license": "MIT License", "lines": 250, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/layouts/onboarding.py
from enum import IntEnum import weakref import math import numpy as np import pyray as rl from openpilot.common.filter_simple import FirstOrderFilter from openpilot.system.hardware import HARDWARE from openpilot.system.ui.lib.application import FontWeight, gui_app from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.button import SmallButton, SmallCircleIconButton from openpilot.system.ui.widgets.label import UnifiedLabel from openpilot.system.ui.widgets.slider import SmallSlider from openpilot.system.ui.mici_setup import TermsHeader, TermsPage as SetupTermsPage from openpilot.selfdrive.ui.ui_state import ui_state, device from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import BaseDriverCameraDialog from openpilot.system.ui.widgets.label import gui_label from openpilot.system.ui.lib.multilang import tr from openpilot.system.version import terms_version, training_version class OnboardingState(IntEnum): TERMS = 0 ONBOARDING = 1 DECLINE = 2 class DriverCameraSetupDialog(BaseDriverCameraDialog): def __init__(self): super().__init__() self.driver_state_renderer = DriverStateRenderer(inset=True) self.driver_state_renderer.set_rect(rl.Rectangle(0, 0, 120, 120)) self.driver_state_renderer.load_icons() self.driver_state_renderer.set_force_active(True) def _render(self, rect): rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) self._camera_view._render(rect) if not self._camera_view.frame: gui_label(rect, tr("camera starting"), font_size=64, font_weight=FontWeight.BOLD, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) rl.end_scissor_mode() return # Position dmoji on opposite side from driver is_rhd = self.driver_state_renderer.is_rhd self.driver_state_renderer.set_position( rect.x + 8 if is_rhd else rect.x + rect.width - self.driver_state_renderer.rect.width - 8, rect.y + 8, ) self.driver_state_renderer.render() self._draw_face_detection(rect) rl.end_scissor_mode() class TrainingGuidePreDMTutorial(SetupTermsPage): def __init__(self, continue_callback): super().__init__(continue_callback, continue_text="continue") self._title_header = TermsHeader("driver monitoring setup", gui_app.texture("icons_mici/setup/green_dm.png", 60, 60)) self._dm_label = UnifiedLabel("Next, we'll ensure comma four is mounted properly.\n\nIf it does not have a clear view of the driver, " + "unplug and remount before continuing.", 42, FontWeight.ROMAN) def show_event(self): super().show_event() # Get driver monitoring model ready for next step ui_state.params.put_bool("IsDriverViewEnabled", True) @property def _content_height(self): return self._dm_label.rect.y + self._dm_label.rect.height - self._scroll_panel.get_offset() def _render_content(self, scroll_offset): self._title_header.render(rl.Rectangle( self._rect.x + 16, self._rect.y + 16 + scroll_offset, self._title_header.rect.width, self._title_header.rect.height, )) self._dm_label.render(rl.Rectangle( self._rect.x + 16, self._title_header.rect.y + self._title_header.rect.height + 16, self._rect.width - 32, self._dm_label.get_content_height(int(self._rect.width - 32)), )) class DMBadFaceDetected(SetupTermsPage): def __init__(self, continue_callback, back_callback): super().__init__(continue_callback, back_callback, continue_text="power off") self._title_header = TermsHeader("make sure comma four can see your face", gui_app.texture("icons_mici/setup/orange_dm.png", 60, 60)) self._dm_label = UnifiedLabel("Re-mount if your face is occluded or driver monitoring has difficulty tracking your face.", 42, FontWeight.ROMAN) @property def _content_height(self): return self._dm_label.rect.y + self._dm_label.rect.height - self._scroll_panel.get_offset() def _render_content(self, scroll_offset): self._title_header.render(rl.Rectangle( self._rect.x + 16, self._rect.y + 16 + scroll_offset, self._title_header.rect.width, self._title_header.rect.height, )) self._dm_label.render(rl.Rectangle( self._rect.x + 16, self._title_header.rect.y + self._title_header.rect.height + 16, self._rect.width - 32, self._dm_label.get_content_height(int(self._rect.width - 32)), )) class TrainingGuideDMTutorial(Widget): PROGRESS_DURATION = 4 LOOKING_THRESHOLD_DEG = 30.0 def __init__(self, continue_callback): super().__init__() self_ref = weakref.ref(self) self._back_button = SmallCircleIconButton(gui_app.texture("icons_mici/setup/driver_monitoring/dm_question.png", 28, 48)) self._back_button.set_click_callback(lambda: self_ref() and self_ref()._show_bad_face_page()) self._good_button = SmallCircleIconButton(gui_app.texture("icons_mici/setup/driver_monitoring/dm_check.png", 42, 42)) # Wrap the continue callback to restore settings def wrapped_continue_callback(): device.set_offroad_brightness(None) continue_callback() self._good_button.set_click_callback(wrapped_continue_callback) self._good_button.set_enabled(False) self._progress = FirstOrderFilter(0.0, 0.5, 1 / gui_app.target_fps) self._dialog = DriverCameraSetupDialog() self._bad_face_page = DMBadFaceDetected(HARDWARE.shutdown, lambda: self_ref() and self_ref()._hide_bad_face_page()) self._should_show_bad_face_page = False # Disable driver monitoring model when device times out for inactivity def inactivity_callback(): ui_state.params.put_bool("IsDriverViewEnabled", False) device.add_interactive_timeout_callback(inactivity_callback) def _show_bad_face_page(self): self._bad_face_page.show_event() self.hide_event() self._should_show_bad_face_page = True def _hide_bad_face_page(self): self._bad_face_page.hide_event() self.show_event() self._should_show_bad_face_page = False def show_event(self): super().show_event() self._dialog.show_event() self._progress.x = 0.0 device.set_offroad_brightness(100) def _update_state(self): super()._update_state() if device.awake and not ui_state.params.get_bool("IsDriverViewEnabled"): ui_state.params.put_bool_nonblocking("IsDriverViewEnabled", True) sm = ui_state.sm if sm.recv_frame.get("driverMonitoringState", 0) == 0: return dm_state = sm["driverMonitoringState"] driver_data = self._dialog.driver_state_renderer.get_driver_data() if len(driver_data.faceOrientation) == 3: pitch, yaw, _ = driver_data.faceOrientation looking_center = abs(math.degrees(pitch)) < self.LOOKING_THRESHOLD_DEG and abs(math.degrees(yaw)) < self.LOOKING_THRESHOLD_DEG else: looking_center = False # stay at 100% once reached if (dm_state.faceDetected and looking_center) or self._progress.x > 0.99: slow = self._progress.x < 0.25 duration = self.PROGRESS_DURATION * 2 if slow else self.PROGRESS_DURATION self._progress.x += 1.0 / (duration * gui_app.target_fps) self._progress.x = min(1.0, self._progress.x) else: self._progress.update(0.0) self._good_button.set_enabled(self._progress.x >= 0.999) def _render(self, _): if self._should_show_bad_face_page: return self._bad_face_page.render(self._rect) self._dialog.render(self._rect) rl.draw_rectangle_gradient_v(int(self._rect.x), int(self._rect.y + self._rect.height - 80), int(self._rect.width), 80, rl.BLANK, rl.BLACK) # draw white ring around dm icon to indicate progress ring_thickness = 8 # DM icon is 120x120, positioned on opposite side from driver dm_size = 120 is_rhd = self._dialog.driver_state_renderer._is_rhd dm_center_x = (self._rect.x + dm_size / 2 + 8) if is_rhd else (self._rect.x + self._rect.width - dm_size / 2 - 8) dm_center_y = self._rect.y + dm_size / 2 + 8 icon_edge_radius = dm_size / 2 outer_radius = icon_edge_radius + 1 # 2px outward from icon edge inner_radius = outer_radius - ring_thickness # Inset by ring_thickness start_angle = 90.0 # Start from bottom end_angle = start_angle + self._progress.x * 360.0 # Clockwise # Fade in alpha current_angle = end_angle - start_angle alpha = int(np.interp(current_angle, [0.0, 45.0], [0, 255])) # White to green color_t = np.clip(np.interp(current_angle, [45.0, 360.0], [0.0, 1.0]), 0.0, 1.0) r = int(np.interp(color_t, [0.0, 1.0], [255, 0])) g = int(np.interp(color_t, [0.0, 1.0], [255, 255])) b = int(np.interp(color_t, [0.0, 1.0], [255, 64])) ring_color = rl.Color(r, g, b, alpha) rl.draw_ring( rl.Vector2(dm_center_x, dm_center_y), inner_radius, outer_radius, start_angle, end_angle, 36, ring_color, ) if self._dialog._camera_view.frame: self._back_button.render(rl.Rectangle( self._rect.x + 8, self._rect.y + self._rect.height - self._back_button.rect.height, self._back_button.rect.width, self._back_button.rect.height, )) self._good_button.render(rl.Rectangle( self._rect.x + self._rect.width - self._good_button.rect.width - 8, self._rect.y + self._rect.height - self._good_button.rect.height, self._good_button.rect.width, self._good_button.rect.height, )) # rounded border rl.draw_rectangle_rounded_lines_ex(self._rect, 0.2 * 1.02, 10, 50, rl.BLACK) class TrainingGuideRecordFront(SetupTermsPage): def __init__(self, continue_callback): def on_back(): ui_state.params.put_bool("RecordFront", False) continue_callback() def on_continue(): ui_state.params.put_bool("RecordFront", True) continue_callback() super().__init__(on_continue, back_callback=on_back, back_text="no", continue_text="yes") self._title_header = TermsHeader("improve driver monitoring", gui_app.texture("icons_mici/setup/green_dm.png", 60, 60)) self._dm_label = UnifiedLabel("Do you want to upload driver camera data?", 42, FontWeight.ROMAN) def show_event(self): super().show_event() # Disable driver monitoring model after last step ui_state.params.put_bool("IsDriverViewEnabled", False) @property def _content_height(self): return self._dm_label.rect.y + self._dm_label.rect.height - self._scroll_panel.get_offset() def _render_content(self, scroll_offset): self._title_header.render(rl.Rectangle( self._rect.x + 16, self._rect.y + 16 + scroll_offset, self._title_header.rect.width, self._title_header.rect.height, )) self._dm_label.render(rl.Rectangle( self._rect.x + 16, self._title_header.rect.y + self._title_header.rect.height + 16, self._rect.width - 32, self._dm_label.get_content_height(int(self._rect.width - 32)), )) 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" + "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, FontWeight.ROMAN) @property def _content_height(self): return self._warning_label.rect.y + self._warning_label.rect.height - self._scroll_panel.get_offset() def _render_content(self, scroll_offset): self._title_header.render(rl.Rectangle( self._rect.x + 16, self._rect.y + 16 + scroll_offset, self._title_header.rect.width, self._title_header.rect.height, )) self._warning_label.render(rl.Rectangle( self._rect.x + 16, self._title_header.rect.y + self._title_header.rect.height + 16, self._rect.width - 32, self._warning_label.get_content_height(int(self._rect.width - 32)), )) class TrainingGuide(Widget): def __init__(self, completed_callback=None): super().__init__() self._completed_callback = completed_callback self._step = 0 self_ref = weakref.ref(self) def on_continue(): if obj := self_ref(): obj._advance_step() self._steps = [ TrainingGuideAttentionNotice(continue_callback=on_continue), TrainingGuidePreDMTutorial(continue_callback=on_continue), TrainingGuideDMTutorial(continue_callback=on_continue), TrainingGuideRecordFront(continue_callback=on_continue), ] def show_event(self): super().show_event() device.set_override_interactive_timeout(300) def hide_event(self): super().hide_event() device.set_override_interactive_timeout(None) def _advance_step(self): if self._step < len(self._steps) - 1: self._step += 1 self._steps[self._step].show_event() else: self._step = 0 if self._completed_callback: self._completed_callback() def _render(self, _): rl.draw_rectangle_rec(self._rect, rl.BLACK) if self._step < len(self._steps): self._steps[self._step].render(self._rect) class DeclinePage(Widget): def __init__(self, back_callback=None): super().__init__() self._uninstall_slider = SmallSlider("uninstall openpilot", 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", gui_app.texture("icons_mici/setup/red_warning.png", 66, 60)) def _on_uninstall(self): ui_state.params.put_bool("DoUninstall", True) gui_app.request_close() def _render(self, _): self._warning_header.render(rl.Rectangle( self._rect.x + 16, self._rect.y + 16, self._warning_header.rect.width, self._warning_header.rect.height, )) self._back_button.set_opacity(1 - self._uninstall_slider.slider_percentage) self._back_button.render(rl.Rectangle( self._rect.x + 8, self._rect.y + self._rect.height - self._back_button.rect.height, self._back_button.rect.width, self._back_button.rect.height, )) self._uninstall_slider.render(rl.Rectangle( self._rect.x + self._rect.width - self._uninstall_slider.rect.width, self._rect.y + self._rect.height - self._uninstall_slider.rect.height, self._uninstall_slider.rect.width, self._uninstall_slider.rect.height, )) class TermsPage(SetupTermsPage): def __init__(self, on_accept=None, on_decline=None): super().__init__(on_accept, on_decline, "decline") 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. " + "Read the latest terms at https://comma.ai/terms before continuing.", 36, FontWeight.ROMAN) @property def _content_height(self): return self._terms_label.rect.y + self._terms_label.rect.height - self._scroll_panel.get_offset() def _render_content(self, scroll_offset): self._title_header.set_position(self._rect.x + 16, self._rect.y + 12 + scroll_offset) self._title_header.render() self._terms_label.render(rl.Rectangle( self._rect.x + 16, self._title_header.rect.y + self._title_header.rect.height + self.ITEM_SPACING, self._rect.width - 100, self._terms_label.get_content_height(int(self._rect.width - 100)), )) class OnboardingWindow(Widget): def __init__(self): super().__init__() self._accepted_terms: bool = ui_state.params.get("HasAcceptedTerms") == terms_version self._training_done: bool = ui_state.params.get("CompletedTrainingVersion") == training_version self._state = OnboardingState.TERMS if not self._accepted_terms else OnboardingState.ONBOARDING self.set_rect(rl.Rectangle(0, 0, 458, gui_app.height)) # Windows self._terms = TermsPage(on_accept=self._on_terms_accepted, on_decline=self._on_terms_declined) self._training_guide = TrainingGuide(completed_callback=self._on_completed_training) self._decline_page = DeclinePage(back_callback=self._on_decline_back) def show_event(self): super().show_event() device.set_override_interactive_timeout(300) def hide_event(self): super().hide_event() device.set_override_interactive_timeout(None) @property def completed(self) -> bool: return self._accepted_terms and self._training_done def _on_terms_declined(self): self._state = OnboardingState.DECLINE def _on_decline_back(self): self._state = OnboardingState.TERMS def close(self): ui_state.params.put_bool("IsDriverViewEnabled", False) gui_app.pop_widget() def _on_terms_accepted(self): ui_state.params.put("HasAcceptedTerms", terms_version) self._state = OnboardingState.ONBOARDING def _on_completed_training(self): ui_state.params.put("CompletedTrainingVersion", training_version) self.close() def _render(self, _): rl.draw_rectangle_rec(self._rect, rl.BLACK) if self._state == OnboardingState.TERMS: self._terms.render(self._rect) elif self._state == OnboardingState.ONBOARDING: self._training_guide.render(self._rect) elif self._state == OnboardingState.DECLINE: self._decline_page.render(self._rect)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/onboarding.py", "license": "MIT License", "lines": 387, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/layouts/settings/developer.py
from openpilot.common.time_helpers import system_time_valid from openpilot.system.ui.widgets.scroller import NavScroller from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigToggle, BigParamControl, BigCircleParamControl from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigInputDialog from openpilot.system.ui.lib.application import gui_app from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.selfdrive.ui.widgets.ssh_key import SshKeyAction class DeveloperLayoutMici(NavScroller): def __init__(self): super().__init__() def github_username_callback(username: str): if username: ssh_keys = SshKeyAction() ssh_keys._fetch_ssh_key(username) if not ssh_keys._error_message: self._ssh_keys_btn.set_value(username) else: dlg = BigDialog("", ssh_keys._error_message) gui_app.push_widget(dlg) else: ui_state.params.remove("GithubUsername") ui_state.params.remove("GithubSshKeys") self._ssh_keys_btn.set_value("Not set") def ssh_keys_callback(): github_username = ui_state.params.get("GithubUsername") or "" dlg = BigInputDialog("enter GitHub username...", github_username, minimum_length=0, confirm_callback=github_username_callback) if not system_time_valid(): dlg = BigDialog("Please connect to Wi-Fi to fetch your key", "") gui_app.push_widget(dlg) return gui_app.push_widget(dlg) txt_ssh = gui_app.texture("icons_mici/settings/developer/ssh.png", 56, 64) github_username = ui_state.params.get("GithubUsername") or "" self._ssh_keys_btn = BigButton("SSH keys", "Not set" if not github_username else github_username, icon=txt_ssh) self._ssh_keys_btn.set_click_callback(ssh_keys_callback) # adb, ssh, ssh keys, debug mode, joystick debug mode, longitudinal maneuver mode, ip address # ******** Main Scroller ******** self._adb_toggle = BigCircleParamControl("icons_mici/adb_short.png", "AdbEnabled", icon_size=(82, 82), icon_offset=(0, 12)) self._ssh_toggle = BigCircleParamControl("icons_mici/ssh_short.png", "SshEnabled", icon_size=(82, 82), icon_offset=(0, 12)) self._joystick_toggle = BigToggle("joystick debug mode", initial_state=ui_state.params.get_bool("JoystickDebugMode"), toggle_callback=self._on_joystick_debug_mode) self._long_maneuver_toggle = BigToggle("longitudinal maneuver mode", initial_state=ui_state.params.get_bool("LongitudinalManeuverMode"), toggle_callback=self._on_long_maneuver_mode) self._alpha_long_toggle = BigToggle("alpha longitudinal", initial_state=ui_state.params.get_bool("AlphaLongitudinalEnabled"), toggle_callback=self._on_alpha_long_enabled) self._debug_mode_toggle = BigParamControl("ui debug mode", "ShowDebugInfo", toggle_callback=lambda checked: (gui_app.set_show_touches(checked), gui_app.set_show_fps(checked))) self._scroller.add_widgets([ self._adb_toggle, self._ssh_toggle, self._ssh_keys_btn, self._joystick_toggle, self._long_maneuver_toggle, self._alpha_long_toggle, self._debug_mode_toggle, ]) # Toggle lists self._refresh_toggles = ( ("AdbEnabled", self._adb_toggle), ("SshEnabled", self._ssh_toggle), ("JoystickDebugMode", self._joystick_toggle), ("LongitudinalManeuverMode", self._long_maneuver_toggle), ("AlphaLongitudinalEnabled", self._alpha_long_toggle), ("ShowDebugInfo", self._debug_mode_toggle), ) onroad_blocked_toggles = (self._adb_toggle, self._joystick_toggle) release_blocked_toggles = (self._joystick_toggle, self._long_maneuver_toggle, self._alpha_long_toggle) engaged_blocked_toggles = (self._long_maneuver_toggle, self._alpha_long_toggle) # Hide non-release toggles on release builds for item in release_blocked_toggles: item.set_visible(not ui_state.is_release) # Disable toggles that require offroad for item in onroad_blocked_toggles: item.set_enabled(lambda: ui_state.is_offroad()) # Disable toggles that require not engaged for item in engaged_blocked_toggles: item.set_enabled(lambda: not ui_state.engaged) # Set initial state if ui_state.params.get_bool("ShowDebugInfo"): gui_app.set_show_touches(True) gui_app.set_show_fps(True) ui_state.add_offroad_transition_callback(self._update_toggles) def show_event(self): super().show_event() self._update_toggles() def _update_toggles(self): ui_state.update_params() # CP gating if ui_state.CP is not None: alpha_avail = ui_state.CP.alphaLongitudinalAvailable if not alpha_avail or ui_state.is_release: self._alpha_long_toggle.set_visible(False) ui_state.params.remove("AlphaLongitudinalEnabled") else: self._alpha_long_toggle.set_visible(True) long_man_enabled = ui_state.has_longitudinal_control and ui_state.is_offroad() self._long_maneuver_toggle.set_enabled(long_man_enabled) if not long_man_enabled: self._long_maneuver_toggle.set_checked(False) ui_state.params.put_bool("LongitudinalManeuverMode", False) else: self._long_maneuver_toggle.set_enabled(False) self._alpha_long_toggle.set_visible(False) # Refresh toggles from params to mirror external changes for key, item in self._refresh_toggles: item.set_checked(ui_state.params.get_bool(key)) def _on_joystick_debug_mode(self, state: bool): ui_state.params.put_bool("JoystickDebugMode", state) ui_state.params.put_bool("LongitudinalManeuverMode", False) self._long_maneuver_toggle.set_checked(False) def _on_long_maneuver_mode(self, state: bool): ui_state.params.put_bool("LongitudinalManeuverMode", state) ui_state.params.put_bool("JoystickDebugMode", False) self._joystick_toggle.set_checked(False) restart_needed_callback(state) def _on_alpha_long_enabled(self, state: bool): # TODO: show confirmation dialog before enabling ui_state.params.put_bool("AlphaLongitudinalEnabled", state) restart_needed_callback(state) self._update_toggles()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/settings/developer.py", "license": "MIT License", "lines": 125, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/mici/layouts/settings/device.py
import os import threading import pyray as rl from enum import IntEnum from collections.abc import Callable from openpilot.common.basedir import BASEDIR from openpilot.common.params import Params from openpilot.common.time_helpers import system_time_valid from openpilot.system.ui.widgets.scroller import NavRawScrollPanel, NavScroller from openpilot.selfdrive.ui.mici.widgets.button import BigButton, BigCircleButton from openpilot.selfdrive.ui.mici.widgets.dialog import BigDialog, BigConfirmationDialogV2 from openpilot.selfdrive.ui.mici.widgets.pairing_dialog import PairingDialog from openpilot.selfdrive.ui.mici.onroad.driver_camera_dialog import DriverCameraDialog from openpilot.selfdrive.ui.mici.layouts.onboarding import TrainingGuide, TermsPage from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets import Widget from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.system.ui.widgets.label import MiciLabel from openpilot.system.ui.widgets.html_render import HtmlModal, HtmlRenderer from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID class MiciFccModal(NavRawScrollPanel): def __init__(self, file_path: str | None = None, text: str | None = None): super().__init__() self._content = HtmlRenderer(file_path=file_path, text=text) self._fcc_logo = gui_app.texture("icons_mici/settings/device/fcc_logo.png", 76, 64) def _render(self, rect: rl.Rectangle): content_height = self._content.get_total_height(int(rect.width)) content_height += self._fcc_logo.height + 20 scroll_content_rect = rl.Rectangle(rect.x, rect.y, rect.width, content_height) scroll_offset = round(self._scroll_panel.update(rect, scroll_content_rect.height)) fcc_pos = rl.Vector2(rect.x + 20, rect.y + 20 + scroll_offset) scroll_content_rect.y += scroll_offset + self._fcc_logo.height + 20 self._content.render(scroll_content_rect) rl.draw_texture_ex(self._fcc_logo, fcc_pos, 0.0, 1.0, rl.WHITE) def _engaged_confirmation_callback(callback: Callable, action_text: str): if not ui_state.engaged: def confirm_callback(): # Check engaged again in case it changed while the dialog was open if not ui_state.engaged: callback() red = False if action_text == "power off": icon = "icons_mici/settings/device/power.png" red = True elif action_text == "reboot": icon = "icons_mici/settings/device/reboot.png" elif action_text == "reset": icon = "icons_mici/settings/device/lkas.png" elif action_text == "uninstall": icon = "icons_mici/settings/device/uninstall.png" else: # TODO: check icon = "icons_mici/settings/comma_icon.png" dlg: BigConfirmationDialogV2 | BigDialog = BigConfirmationDialogV2(f"slide to\n{action_text.lower()}", icon, red=red, exit_on_confirm=action_text == "reset", confirm_callback=confirm_callback) gui_app.push_widget(dlg) else: dlg = BigDialog(f"Disengage to {action_text}", "") gui_app.push_widget(dlg) class DeviceInfoLayoutMici(Widget): def __init__(self): super().__init__() self.set_rect(rl.Rectangle(0, 0, 360, 180)) params = Params() header_color = rl.Color(255, 255, 255, int(255 * 0.9)) subheader_color = rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)) max_width = int(self._rect.width - 20) self._dongle_id_label = MiciLabel("device ID", 48, width=max_width, color=header_color, font_weight=FontWeight.DISPLAY) self._dongle_id_text_label = MiciLabel(params.get("DongleId") or 'N/A', 32, width=max_width, color=subheader_color, font_weight=FontWeight.ROMAN) self._serial_number_label = MiciLabel("serial", 48, color=header_color, font_weight=FontWeight.DISPLAY) self._serial_number_text_label = MiciLabel(params.get("HardwareSerial") or 'N/A', 32, width=max_width, color=subheader_color, font_weight=FontWeight.ROMAN) def _render(self, _): self._dongle_id_label.set_position(self._rect.x + 20, self._rect.y - 10) self._dongle_id_label.render() self._dongle_id_text_label.set_position(self._rect.x + 20, self._rect.y + 68 - 25) self._dongle_id_text_label.render() self._serial_number_label.set_position(self._rect.x + 20, self._rect.y + 114 - 30) self._serial_number_label.render() self._serial_number_text_label.set_position(self._rect.x + 20, self._rect.y + 161 - 25) self._serial_number_text_label.render() class UpdaterState(IntEnum): IDLE = 0 WAITING_FOR_UPDATER = 1 UPDATER_RESPONDING = 2 class PairBigButton(BigButton): def __init__(self): super().__init__("pair", "connect.comma.ai", "icons_mici/settings/comma_icon.png", icon_size=(33, 60)) def _get_label_font_size(self): return 64 def _update_state(self): super()._update_state() if ui_state.prime_state.is_paired(): self.set_text("paired") if ui_state.prime_state.is_prime(): self.set_value("subscribed") else: self.set_value("upgrade to prime") else: self.set_text("pair") self.set_value("connect.comma.ai") def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) # TODO: show ad dialog when clicked if not prime if ui_state.prime_state.is_paired(): return dlg: BigDialog | PairingDialog if not system_time_valid(): dlg = BigDialog(tr("Please connect to Wi-Fi to complete initial pairing"), "") elif UNREGISTERED_DONGLE_ID == (ui_state.params.get("DongleId") or UNREGISTERED_DONGLE_ID): dlg = BigDialog(tr("Device must be registered with the comma.ai backend to pair"), "") else: dlg = PairingDialog() gui_app.push_widget(dlg) UPDATER_TIMEOUT = 10.0 # seconds to wait for updater to respond class UpdateOpenpilotBigButton(BigButton): def __init__(self): self._txt_update_icon = gui_app.texture("icons_mici/settings/device/update.png", 64, 75) self._txt_reboot_icon = gui_app.texture("icons_mici/settings/device/reboot.png", 64, 70) 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) self._waiting_for_updater_t: float | None = None self._hide_value_t: float | None = None self._state: UpdaterState = UpdaterState.IDLE ui_state.add_offroad_transition_callback(self.offroad_transition) def offroad_transition(self): if ui_state.is_offroad(): self.set_enabled(True) def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) if not system_time_valid(): dlg = BigDialog(tr("Please connect to Wi-Fi to update"), "") gui_app.push_widget(dlg) return self.set_enabled(False) self._state = UpdaterState.WAITING_FOR_UPDATER self.set_icon(self._txt_update_icon) def run(): if self.get_value() == "download update": os.system("pkill -SIGHUP -f system.updated.updated") elif self.get_value() == "update now": ui_state.params.put_bool("DoReboot", True) else: os.system("pkill -SIGUSR1 -f system.updated.updated") threading.Thread(target=run, daemon=True).start() def set_value(self, value: str): super().set_value(value) if value: self.set_text("") else: self.set_text("update openpilot") def _update_state(self): super()._update_state() if ui_state.started: self.set_enabled(False) return updater_state = ui_state.params.get("UpdaterState") or "" failed_count = ui_state.params.get("UpdateFailedCount") failed = False if failed_count is None else int(failed_count) > 0 if ui_state.params.get_bool("UpdateAvailable"): self.set_rotate_icon(False) self.set_enabled(True) if self.get_value() != "update now": self.set_value("update now") self.set_icon(self._txt_reboot_icon) elif self._state == UpdaterState.WAITING_FOR_UPDATER: self.set_rotate_icon(True) if updater_state != "idle": self._state = UpdaterState.UPDATER_RESPONDING # Recover from updater not responding (time invalid shortly after boot) if self._waiting_for_updater_t is None: self._waiting_for_updater_t = rl.get_time() if self._waiting_for_updater_t is not None and rl.get_time() - self._waiting_for_updater_t > UPDATER_TIMEOUT: self.set_rotate_icon(False) self.set_value("updater failed\nto respond") self._state = UpdaterState.IDLE self._hide_value_t = rl.get_time() elif self._state == UpdaterState.UPDATER_RESPONDING: if updater_state == "idle": self.set_rotate_icon(False) self._state = UpdaterState.IDLE self._hide_value_t = rl.get_time() else: if self.get_value() != updater_state: self.set_value(updater_state) elif self._state == UpdaterState.IDLE: self.set_rotate_icon(False) if failed: if self.get_value() != "failed to update": self.set_value("failed to update") elif ui_state.params.get_bool("UpdaterFetchAvailable"): self.set_enabled(True) if self.get_value() != "download update": self.set_value("download update") elif self._hide_value_t is not None: self.set_enabled(True) if self.get_value() == "checking...": self.set_value("up to date") self.set_icon(self._txt_up_to_date_icon) # Hide previous text after short amount of time (up to date or failed) if rl.get_time() - self._hide_value_t > 3.0: self._hide_value_t = None self.set_value("") self.set_icon(self._txt_update_icon) else: if self.get_value() != "": self.set_value("") if self._state != UpdaterState.WAITING_FOR_UPDATER: self._waiting_for_updater_t = None class DeviceLayoutMici(NavScroller): def __init__(self): super().__init__() self._fcc_dialog: HtmlModal | None = None def power_off_callback(): ui_state.params.put_bool("DoShutdown", True) def reboot_callback(): ui_state.params.put_bool("DoReboot", True) def reset_calibration_callback(): params = ui_state.params params.remove("CalibrationParams") params.remove("LiveTorqueParameters") params.remove("LiveParameters") params.remove("LiveParametersV2") params.remove("LiveDelay") params.put_bool("OnroadCycleRequested", True) def uninstall_openpilot_callback(): ui_state.params.put_bool("DoUninstall", True) reset_calibration_btn = BigButton("reset calibration", "", "icons_mici/settings/device/lkas.png", icon_size=(114, 60)) 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.set_click_callback(lambda: _engaged_confirmation_callback(uninstall_openpilot_callback, "uninstall")) reboot_btn = BigCircleButton("icons_mici/settings/device/reboot.png", red=False, icon_size=(64, 70)) reboot_btn.set_click_callback(lambda: _engaged_confirmation_callback(reboot_callback, "reboot")) self._power_off_btn = BigCircleButton("icons_mici/settings/device/power.png", red=True, icon_size=(64, 66)) self._power_off_btn.set_click_callback(lambda: _engaged_confirmation_callback(power_off_callback, "power off")) self._power_off_btn.set_visible(lambda: not ui_state.ignition) regulatory_btn = BigButton("regulatory info", "", "icons_mici/settings/device/info.png") regulatory_btn.set_click_callback(self._on_regulatory) driver_cam_btn = BigButton("driver\ncamera preview", "", "icons_mici/settings/device/cameras.png") driver_cam_btn.set_click_callback(lambda: gui_app.push_widget(DriverCameraDialog())) driver_cam_btn.set_enabled(lambda: ui_state.is_offroad()) review_training_guide_btn = BigButton("review\ntraining guide", "", "icons_mici/settings/device/info.png") review_training_guide_btn.set_click_callback(lambda: gui_app.push_widget(TrainingGuide(completed_callback=gui_app.pop_widget))) review_training_guide_btn.set_enabled(lambda: ui_state.is_offroad()) terms_btn = BigButton("terms &\nconditions", "", "icons_mici/settings/device/info.png") terms_btn.set_click_callback(lambda: gui_app.push_widget(TermsPage(on_accept=gui_app.pop_widget))) terms_btn.set_enabled(lambda: ui_state.is_offroad()) self._scroller.add_widgets([ DeviceInfoLayoutMici(), UpdateOpenpilotBigButton(), PairBigButton(), review_training_guide_btn, driver_cam_btn, terms_btn, regulatory_btn, reset_calibration_btn, uninstall_openpilot_btn, reboot_btn, self._power_off_btn, ]) def _on_regulatory(self): if not self._fcc_dialog: self._fcc_dialog = MiciFccModal(os.path.join(BASEDIR, "selfdrive/assets/offroad/mici_fcc.html")) gui_app.push_widget(self._fcc_dialog)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/settings/device.py", "license": "MIT License", "lines": 265, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/layouts/settings/firehose.py
import requests import threading import time import pyray as rl from openpilot.common.api import api_get from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog from openpilot.selfdrive.ui.lib.api_helpers import get_token from openpilot.selfdrive.ui.ui_state import ui_state, device from openpilot.system.athena.registration import UNREGISTERED_DONGLE_ID from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE from openpilot.system.ui.lib.wrap_text import wrap_text from openpilot.system.ui.lib.scroll_panel2 import GuiScrollPanel2 from openpilot.system.ui.lib.multilang import tr, trn, tr_noop from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.scroller import NavRawScrollPanel TITLE = tr_noop("Firehose Mode") DESCRIPTION = tr_noop( "openpilot 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." ) INSTRUCTIONS_INTRO = tr_noop( "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card." ) FAQ_HEADER = tr_noop("Frequently Asked Questions") FAQ_ITEMS = [ (tr_noop("Does it matter how or where I drive?"), tr_noop("Nope, just drive as you normally would.")), (tr_noop("Do all of my segments get pulled in Firehose Mode?"), tr_noop("No, we selectively pull a subset of your segments.")), (tr_noop("What's a good USB-C adapter?"), tr_noop("Any fast phone or laptop charger should be fine.")), (tr_noop("Does it matter which software I run?"), tr_noop("Yes, only upstream openpilot (and particular forks) are able to be used for training.")), ] class FirehoseLayoutBase(Widget): PARAM_KEY = "ApiCache_FirehoseStats" GREEN = rl.Color(46, 204, 113, 255) RED = rl.Color(231, 76, 60, 255) GRAY = rl.Color(68, 68, 68, 255) LIGHT_GRAY = rl.Color(228, 228, 228, 255) UPDATE_INTERVAL = 30 # seconds def __init__(self): super().__init__() self._params = Params() self._session = requests.Session() # reuse session to reduce SSL handshake overhead self._segment_count = self._get_segment_count() self._scroll_panel = GuiScrollPanel2(horizontal=False) self._content_height = 0 self._running = True self._update_thread = threading.Thread(target=self._update_loop, daemon=True) self._update_thread.start() def __del__(self): self._running = False try: if self._update_thread and self._update_thread.is_alive(): self._update_thread.join(timeout=1.0) except Exception: pass def show_event(self): super().show_event() self._scroll_panel.set_offset(0) def _get_segment_count(self) -> int: stats = self._params.get(self.PARAM_KEY) if not stats: return 0 try: return int(stats.get("firehose", 0)) except Exception: cloudlog.exception(f"Failed to decode firehose stats: {stats}") return 0 def _render(self, rect: rl.Rectangle): # compute total content height for scrolling content_height = self._measure_content_height(rect) scroll_offset = round(self._scroll_panel.update(rect, content_height)) # start drawing with offset x = int(rect.x + 40) y = int(rect.y + 40 + scroll_offset) w = int(rect.width - 80) # Title title_text = tr(TITLE) title_font = gui_app.font(FontWeight.BOLD) title_size = 64 rl.draw_text_ex(title_font, title_text, rl.Vector2(x, y), title_size, 0, rl.WHITE) y += int(title_size * FONT_SCALE) + 20 # Description y = self._draw_wrapped_text(x, y, w, tr(DESCRIPTION), gui_app.font(FontWeight.ROMAN), 36, rl.WHITE) y += 20 # Separator rl.draw_rectangle(x, y, w, 2, self.GRAY) y += 20 # Status status_text, status_color = self._get_status() y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 48, status_color) y += 20 # Contribution count (if available) if self._segment_count > 0: contrib_text = trn("{} segment of your driving is in the training dataset so far.", "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 42, rl.WHITE) y += 20 # Separator rl.draw_rectangle(x, y, w, 2, self.GRAY) y += 20 # Instructions intro y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS_INTRO), gui_app.font(FontWeight.ROMAN), 32, self.LIGHT_GRAY) y += 20 # FAQ Header y = self._draw_wrapped_text(x, y, w, tr(FAQ_HEADER), gui_app.font(FontWeight.BOLD), 44, rl.WHITE) y += 20 # FAQ Items for question, answer in FAQ_ITEMS: y = self._draw_wrapped_text(x, y, w, tr(question), gui_app.font(FontWeight.BOLD), 32, self.LIGHT_GRAY) y = self._draw_wrapped_text(x, y, w, tr(answer), gui_app.font(FontWeight.ROMAN), 32, self.LIGHT_GRAY) y += 20 def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): wrapped = wrap_text(font, text, font_size, width) for line in wrapped: rl.draw_text_ex(font, line, rl.Vector2(x, y), font_size, 0, color) y += int(font_size * FONT_SCALE) return y def _measure_content_height(self, rect: rl.Rectangle) -> int: # Rough measurement using the same wrapping as rendering w = int(rect.width - 80) y = 40 # Title title_size = 72 y += int(title_size * FONT_SCALE) + 20 # Description desc_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(DESCRIPTION), 36, w) y += int(len(desc_lines) * 36 * FONT_SCALE) + 20 # Separator + Status y += 2 + 20 status_text, _ = self._get_status() status_lines = wrap_text(gui_app.font(FontWeight.BOLD), status_text, 48, w) y += int(len(status_lines) * 48 * FONT_SCALE) + 20 # Contribution count if self._segment_count > 0: contrib_text = trn("{} segment of your driving is in the training dataset so far.", "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) contrib_lines = wrap_text(gui_app.font(FontWeight.BOLD), contrib_text, 42, w) y += int(len(contrib_lines) * 42 * FONT_SCALE) + 20 # Separator + Instructions y += 2 + 20 # Instructions intro intro_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(INSTRUCTIONS_INTRO), 32, w) y += int(len(intro_lines) * 32 * FONT_SCALE) + 20 # FAQ Header faq_header_lines = wrap_text(gui_app.font(FontWeight.BOLD), tr(FAQ_HEADER), 44, w) y += int(len(faq_header_lines) * 44 * FONT_SCALE) + 20 # FAQ Items for question, answer in FAQ_ITEMS: q_lines = wrap_text(gui_app.font(FontWeight.BOLD), tr(question), 32, w) y += int(len(q_lines) * 32 * FONT_SCALE) a_lines = wrap_text(gui_app.font(FontWeight.ROMAN), tr(answer), 32, w) y += int(len(a_lines) * 32 * FONT_SCALE) + 20 # bottom padding y += 40 return y def _get_status(self) -> tuple[str, rl.Color]: network_type = ui_state.sm["deviceState"].networkType network_metered = ui_state.sm["deviceState"].networkMetered if not network_metered and network_type != 0: # Not metered and connected return tr("ACTIVE"), self.GREEN else: return tr("INACTIVE: connect to an unmetered network"), self.RED def _fetch_firehose_stats(self): try: dongle_id = self._params.get("DongleId") if not dongle_id or dongle_id == UNREGISTERED_DONGLE_ID: return identity_token = get_token(dongle_id) response = api_get(f"v1/devices/{dongle_id}/firehose_stats", access_token=identity_token, session=self._session) if response.status_code == 200: data = response.json() self._segment_count = data.get("firehose", 0) self._params.put(self.PARAM_KEY, data) except Exception as e: cloudlog.error(f"Failed to fetch firehose stats: {e}") def _update_loop(self): while self._running: if not ui_state.started and device._awake: self._fetch_firehose_stats() time.sleep(self.UPDATE_INTERVAL) class FirehoseLayout(NavRawScrollPanel, FirehoseLayoutBase): pass
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/settings/firehose.py", "license": "MIT License", "lines": 184, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/layouts/settings/settings.py
from openpilot.common.params import Params from openpilot.system.ui.widgets.scroller import NavScroller from openpilot.selfdrive.ui.mici.widgets.button import BigButton from openpilot.selfdrive.ui.mici.layouts.settings.toggles import TogglesLayoutMici from openpilot.selfdrive.ui.mici.layouts.settings.network import NetworkLayoutMici from openpilot.selfdrive.ui.mici.layouts.settings.device import DeviceLayoutMici, PairBigButton from openpilot.selfdrive.ui.mici.layouts.settings.developer import DeveloperLayoutMici from openpilot.selfdrive.ui.mici.layouts.settings.firehose import FirehoseLayout from openpilot.system.ui.lib.application import gui_app, FontWeight class SettingsBigButton(BigButton): def _get_label_font_size(self): return 64 class SettingsLayout(NavScroller): def __init__(self): super().__init__() self._params = Params() toggles_panel = TogglesLayoutMici() toggles_btn = SettingsBigButton("toggles", "", "icons_mici/settings.png") toggles_btn.set_click_callback(lambda: gui_app.push_widget(toggles_panel)) network_panel = NetworkLayoutMici() network_btn = SettingsBigButton("network", "", "icons_mici/settings/network/wifi_strength_full.png", icon_size=(76, 56)) network_btn.set_click_callback(lambda: gui_app.push_widget(network_panel)) device_panel = DeviceLayoutMici() device_btn = SettingsBigButton("device", "", "icons_mici/settings/device_icon.png", icon_size=(74, 60)) device_btn.set_click_callback(lambda: gui_app.push_widget(device_panel)) developer_panel = DeveloperLayoutMici() developer_btn = SettingsBigButton("developer", "", "icons_mici/settings/developer_icon.png", icon_size=(64, 60)) developer_btn.set_click_callback(lambda: gui_app.push_widget(developer_panel)) firehose_panel = FirehoseLayout() firehose_btn = SettingsBigButton("firehose", "", "icons_mici/settings/firehose.png", icon_size=(52, 62)) firehose_btn.set_click_callback(lambda: gui_app.push_widget(firehose_panel)) self._scroller.add_widgets([ toggles_btn, network_btn, device_btn, PairBigButton(), #BigDialogButton("manual", "", "icons_mici/settings/manual_icon.png", "Check out the mici user\nmanual at comma.ai/setup"), firehose_btn, developer_btn, ]) self._font_medium = gui_app.font(FontWeight.MEDIUM)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/settings/settings.py", "license": "MIT License", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/mici/layouts/settings/toggles.py
from cereal import log from openpilot.system.ui.widgets.scroller import NavScroller from openpilot.selfdrive.ui.mici.widgets.button import BigParamControl, BigMultiParamToggle from openpilot.system.ui.lib.application import gui_app from openpilot.selfdrive.ui.layouts.settings.common import restart_needed_callback from openpilot.selfdrive.ui.ui_state import ui_state PERSONALITY_TO_INT = log.LongitudinalPersonality.schema.enumerants class TogglesLayoutMici(NavScroller): def __init__(self): super().__init__() self._personality_toggle = BigMultiParamToggle("driving personality", "LongitudinalPersonality", ["aggressive", "standard", "relaxed"]) self._experimental_btn = BigParamControl("experimental mode", "ExperimentalMode") is_metric_toggle = BigParamControl("use metric units", "IsMetric") ldw_toggle = BigParamControl("lane departure warnings", "IsLdwEnabled") 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) self._scroller.add_widgets([ self._personality_toggle, self._experimental_btn, is_metric_toggle, ldw_toggle, always_on_dm_toggle, record_front, record_mic, enable_openpilot, ]) # Toggle lists self._refresh_toggles = ( ("ExperimentalMode", self._experimental_btn), ("IsMetric", is_metric_toggle), ("IsLdwEnabled", ldw_toggle), ("AlwaysOnDM", always_on_dm_toggle), ("RecordFront", record_front), ("RecordAudio", record_mic), ("OpenpilotEnabledToggle", enable_openpilot), ) enable_openpilot.set_enabled(lambda: not ui_state.engaged) record_front.set_enabled(False if ui_state.params.get_bool("RecordFrontLock") else (lambda: not ui_state.engaged)) record_mic.set_enabled(lambda: not ui_state.engaged) if ui_state.params.get_bool("ShowDebugInfo"): gui_app.set_show_touches(True) gui_app.set_show_fps(True) ui_state.add_engaged_transition_callback(self._update_toggles) def _update_state(self): super()._update_state() if ui_state.sm.updated["selfdriveState"]: personality = PERSONALITY_TO_INT[ui_state.sm["selfdriveState"].personality] if personality != ui_state.personality and ui_state.started: self._personality_toggle.set_value(self._personality_toggle._options[personality]) ui_state.personality = personality def show_event(self): super().show_event() self._update_toggles() def _update_toggles(self): ui_state.update_params() # CP gating for experimental mode if ui_state.CP is not None: if ui_state.has_longitudinal_control: self._experimental_btn.set_visible(True) self._personality_toggle.set_visible(True) else: # no long for now self._experimental_btn.set_visible(False) self._experimental_btn.set_checked(False) self._personality_toggle.set_visible(False) ui_state.params.remove("ExperimentalMode") # Refresh toggles from params to mirror external changes for key, item in self._refresh_toggles: item.set_checked(ui_state.params.get_bool(key))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/layouts/settings/toggles.py", "license": "MIT License", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/mici/onroad/alert_renderer.py
import time from enum import StrEnum from typing import NamedTuple import pyray as rl import random import string from dataclasses import dataclass from cereal import messaging, log, car from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter from openpilot.system.hardware import TICI from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.label import UnifiedLabel AlertSize = log.SelfdriveState.AlertSize AlertStatus = log.SelfdriveState.AlertStatus ALERT_MARGIN = 18 ALERT_FONT_SMALL = 66 - 50 ALERT_FONT_BIG = 88 - 40 SELFDRIVE_STATE_TIMEOUT = 5 # Seconds SELFDRIVE_UNRESPONSIVE_TIMEOUT = 10 # Seconds # Constants ALERT_COLORS = { AlertStatus.normal: rl.Color(0, 0, 0, 255), AlertStatus.userPrompt: rl.Color(255, 115, 0, 255), AlertStatus.critical: rl.Color(255, 0, 21, 255), } TURN_SIGNAL_BLINK_PERIOD = 1 / (80 / 60) # Mazda heartbeat turn signal BPM DEBUG = False class IconSide(StrEnum): left = 'left' right = 'right' class IconLayout(NamedTuple): texture: rl.Texture side: IconSide margin_x: int margin_y: int class AlertLayout(NamedTuple): text_rect: rl.Rectangle icon: IconLayout | None @dataclass class Alert: text1: str = "" text2: str = "" size: int = 0 status: int = 0 visual_alert: int = car.CarControl.HUDControl.VisualAlert.none alert_type: str = "" # Pre-defined alert instances ALERT_STARTUP_PENDING = Alert( text1="openpilot Unavailable", text2="Waiting to start", size=AlertSize.mid, status=AlertStatus.normal, ) ALERT_CRITICAL_TIMEOUT = Alert( text1="TAKE CONTROL IMMEDIATELY", text2="System Unresponsive", size=AlertSize.full, status=AlertStatus.critical, ) ALERT_CRITICAL_REBOOT = Alert( text1="System Unresponsive", text2="Reboot Device", size=AlertSize.full, status=AlertStatus.critical, ) class AlertRenderer(Widget): def __init__(self): super().__init__() self._alert_text1_label = UnifiedLabel(text="", font_size=ALERT_FONT_BIG, font_weight=FontWeight.DISPLAY, line_height=0.86, letter_spacing=-0.02) self._alert_text2_label = UnifiedLabel(text="", font_size=ALERT_FONT_SMALL, font_weight=FontWeight.ROMAN, line_height=0.86, letter_spacing=0.025) self._prev_alert: Alert | None = None self._text_gen_time = 0 self._alert_text2_gen = '' # animation filters # TODO: use 0.1 but with proper alert height calculation self._alert_y_filter = BounceFilter(0, 0.1, 1 / gui_app.target_fps) self._alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) self._turn_signal_timer = 0.0 self._turn_signal_alpha_filter = FirstOrderFilter(0.0, 0.3, 1 / gui_app.target_fps) self._last_icon_side: IconSide | None = None self._load_icons() def _load_icons(self): self._txt_turn_signal_left = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 104, 96) self._txt_turn_signal_right = gui_app.texture('icons_mici/onroad/turn_signal_left.png', 104, 96, flip_x=True) self._txt_blind_spot_left = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 134, 150) self._txt_blind_spot_right = gui_app.texture('icons_mici/onroad/blind_spot_left.png', 134, 150, flip_x=True) def get_alert(self, sm: messaging.SubMaster) -> Alert | None: """Generate the current alert based on selfdrive state.""" ss = sm['selfdriveState'] # Check if selfdriveState messages have stopped arriving if not sm.updated['selfdriveState']: recv_frame = sm.recv_frame['selfdriveState'] time_since_onroad = time.monotonic() - ui_state.started_time # 1. Never received selfdriveState since going onroad waiting_for_startup = recv_frame < ui_state.started_frame if waiting_for_startup and time_since_onroad > 5: return ALERT_STARTUP_PENDING # 2. Lost communication with selfdriveState after receiving it if TICI and not waiting_for_startup: ss_missing = time.monotonic() - sm.recv_time['selfdriveState'] if ss_missing > SELFDRIVE_STATE_TIMEOUT: if ss.enabled and (ss_missing - SELFDRIVE_STATE_TIMEOUT) < SELFDRIVE_UNRESPONSIVE_TIMEOUT: return ALERT_CRITICAL_TIMEOUT return ALERT_CRITICAL_REBOOT # No alert if size is none if ss.alertSize == 0: return None # Return current alert ret = Alert(text1=ss.alertText1, text2=ss.alertText2, size=ss.alertSize.raw, status=ss.alertStatus.raw, visual_alert=ss.alertHudVisual, alert_type=ss.alertType) self._prev_alert = ret return ret def will_render(self) -> tuple[Alert | None, bool]: alert = self.get_alert(ui_state.sm) return alert or self._prev_alert, alert is None def _icon_helper(self, alert: Alert) -> AlertLayout: icon_side = None txt_icon = None icon_margin_x = 20 icon_margin_y = 18 # alert_type format is "EventName/eventType" (e.g., "preLaneChangeLeft/warning") event_name = alert.alert_type.split('/')[0] if alert.alert_type else '' if event_name == 'preLaneChangeLeft': icon_side = IconSide.left txt_icon = self._txt_turn_signal_left icon_margin_x = 2 icon_margin_y = 5 elif event_name == 'preLaneChangeRight': icon_side = IconSide.right txt_icon = self._txt_turn_signal_right icon_margin_x = 2 icon_margin_y = 5 elif event_name == 'laneChange': icon_side = self._last_icon_side txt_icon = self._txt_turn_signal_left if self._last_icon_side == 'left' else self._txt_turn_signal_right icon_margin_x = 2 icon_margin_y = 5 elif event_name == 'laneChangeBlocked': CS = ui_state.sm['carState'] if CS.leftBlinker: icon_side = IconSide.left elif CS.rightBlinker: icon_side = IconSide.right else: icon_side = self._last_icon_side txt_icon = self._txt_blind_spot_left if icon_side == 'left' else self._txt_blind_spot_right icon_margin_x = 8 icon_margin_y = 0 else: self._turn_signal_timer = 0.0 self._last_icon_side = icon_side # create text rect based on icon presence text_x = self._rect.x + ALERT_MARGIN text_width = self._rect.width - ALERT_MARGIN if icon_side == 'left': text_x = self._rect.x + self._txt_turn_signal_right.width text_width = self._rect.width - ALERT_MARGIN - self._txt_turn_signal_right.width elif icon_side == 'right': text_x = self._rect.x + ALERT_MARGIN text_width = self._rect.width - ALERT_MARGIN - self._txt_turn_signal_right.width text_rect = rl.Rectangle( text_x, self._alert_y_filter.x, text_width, self._rect.height, ) icon_layout = IconLayout(txt_icon, icon_side, icon_margin_x, icon_margin_y) if txt_icon is not None and icon_side is not None else None return AlertLayout(text_rect, icon_layout) def _render(self, rect: rl.Rectangle) -> bool: alert = self.get_alert(ui_state.sm) # Animate fade and slide in/out self._alert_y_filter.update(self._rect.y - 50 if alert is None else self._rect.y) self._alpha_filter.update(0 if alert is None else 1) if alert is None: # If still animating out, keep the previous alert if self._alpha_filter.x > 0.01 and self._prev_alert is not None: alert = self._prev_alert else: self._prev_alert = None return False self._draw_background(alert) alert_layout = self._icon_helper(alert) self._draw_text(alert, alert_layout) self._draw_icons(alert_layout) return True def _draw_icons(self, alert_layout: AlertLayout) -> None: if alert_layout.icon is None: return if time.monotonic() - self._turn_signal_timer > TURN_SIGNAL_BLINK_PERIOD: self._turn_signal_timer = time.monotonic() self._turn_signal_alpha_filter.x = 255 * 2 else: self._turn_signal_alpha_filter.update(255 * 0.2) if alert_layout.icon.side == 'left': pos_x = int(self._rect.x + alert_layout.icon.margin_x) else: pos_x = int(self._rect.x + self._rect.width - alert_layout.icon.margin_x - alert_layout.icon.texture.width) if alert_layout.icon.texture not in (self._txt_turn_signal_left, self._txt_turn_signal_right): icon_alpha = 255 else: icon_alpha = int(min(self._turn_signal_alpha_filter.x, 255)) rl.draw_texture(alert_layout.icon.texture, pos_x, int(self._rect.y + alert_layout.icon.margin_y), rl.Color(255, 255, 255, int(icon_alpha * self._alpha_filter.x))) def _draw_background(self, alert: Alert) -> None: # draw top gradient for alert text at top color = ALERT_COLORS.get(alert.status, ALERT_COLORS[AlertStatus.normal]) color = rl.Color(color.r, color.g, color.b, int(255 * 0.90 * self._alpha_filter.x)) translucent_color = rl.Color(color.r, color.g, color.b, int(0 * self._alpha_filter.x)) small_alert_height = round(self._rect.height * 0.583) # 140px at mici height medium_alert_height = round(self._rect.height * 0.833) # 200px at mici height # alert_type format is "EventName/eventType" (e.g., "preLaneChangeLeft/warning") event_name = alert.alert_type.split('/')[0] if alert.alert_type else '' if event_name == 'preLaneChangeLeft': bg_height = small_alert_height elif event_name == 'preLaneChangeRight': bg_height = small_alert_height elif event_name == 'laneChange': bg_height = small_alert_height elif event_name == 'laneChangeBlocked': bg_height = medium_alert_height else: bg_height = int(self._rect.height) solid_height = round(bg_height * 0.2) rl.draw_rectangle(int(self._rect.x), int(self._rect.y), int(self._rect.width), solid_height, color) rl.draw_rectangle_gradient_v(int(self._rect.x), int(self._rect.y + solid_height), int(self._rect.width), int(bg_height - solid_height), color, translucent_color) def _draw_text(self, alert: Alert, alert_layout: AlertLayout) -> None: icon_side = alert_layout.icon.side if alert_layout.icon is not None else None # TODO: hack alert_text1 = alert.text1.lower().replace('calibrating: ', 'calibrating:\n') can_draw_second_line = False # TODO: there should be a common way to determine font size based on text length to maximize rect if len(alert_text1) <= 12: can_draw_second_line = True font_size = 92 - 10 elif len(alert_text1) <= 16: can_draw_second_line = True font_size = 70 else: font_size = 64 - 10 if icon_side is not None: font_size -= 10 color = rl.Color(255, 255, 255, int(255 * 0.9 * self._alpha_filter.x)) text1_y_offset = 11 if font_size >= 70 else 4 text_rect1 = rl.Rectangle( alert_layout.text_rect.x, alert_layout.text_rect.y - text1_y_offset, alert_layout.text_rect.width, alert_layout.text_rect.height, ) self._alert_text1_label.set_text(alert_text1) self._alert_text1_label.set_text_color(color) self._alert_text1_label.set_font_size(font_size) self._alert_text1_label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_LEFT if icon_side != 'left' else rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) self._alert_text1_label.render(text_rect1) alert_text2 = alert.text2.lower() # randomize chars and length for testing if DEBUG: if time.monotonic() - self._text_gen_time > 0.5: self._alert_text2_gen = ''.join(random.choices(string.ascii_lowercase + ' ', k=random.randint(0, 40))) self._text_gen_time = time.monotonic() alert_text2 = self._alert_text2_gen or alert_text2 if can_draw_second_line and alert_text2: last_line_h = self._alert_text1_label.rect.y + self._alert_text1_label.get_content_height(int(alert_layout.text_rect.width)) last_line_h -= 4 if len(alert_text2) > 18: small_font_size = 36 elif len(alert_text2) > 24: small_font_size = 32 else: small_font_size = 40 text_rect2 = rl.Rectangle( alert_layout.text_rect.x, last_line_h, alert_layout.text_rect.width, alert_layout.text_rect.height - last_line_h ) color = rl.Color(255, 255, 255, int(255 * 0.65 * self._alpha_filter.x)) self._alert_text2_label.set_text(alert_text2) self._alert_text2_label.set_text_color(color) self._alert_text2_label.set_font_size(small_font_size) self._alert_text2_label.set_alignment(rl.GuiTextAlignment.TEXT_ALIGN_LEFT if icon_side != 'left' else rl.GuiTextAlignment.TEXT_ALIGN_RIGHT) self._alert_text2_label.render(text_rect2)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/alert_renderer.py", "license": "MIT License", "lines": 288, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/augmented_road_view.py
import time import numpy as np import pyray as rl from cereal import messaging, car, log from msgq.visionipc import VisionStreamType from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH from openpilot.selfdrive.ui.mici.onroad.alert_renderer import AlertRenderer from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer from openpilot.selfdrive.ui.mici.onroad.hud_renderer import HudRenderer from openpilot.selfdrive.ui.mici.onroad.model_renderer import ModelRenderer from openpilot.selfdrive.ui.mici.onroad.confidence_ball import ConfidenceBall from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView from openpilot.system.ui.lib.application import FontWeight, gui_app, MousePos, MouseEvent from openpilot.system.ui.widgets.label import UnifiedLabel from openpilot.system.ui.widgets import Widget from openpilot.common.filter_simple import BounceFilter from openpilot.common.transformations.camera import DEVICE_CAMERAS, DeviceCameraConfig, view_frame_from_device_frame from openpilot.common.transformations.orientation import rot_from_euler from enum import IntEnum OpState = log.SelfdriveState.OpenpilotState CALIBRATED = log.LiveCalibrationData.Status.calibrated ROAD_CAM = VisionStreamType.VISION_STREAM_ROAD WIDE_CAM = VisionStreamType.VISION_STREAM_WIDE_ROAD DEFAULT_DEVICE_CAMERA = DEVICE_CAMERAS["tici", "ar0231"] class BookmarkState(IntEnum): HIDDEN = 0 DRAGGING = 1 TRIGGERED = 2 WIDE_CAM_MAX_SPEED = 5.0 # m/s (10 mph) ROAD_CAM_MIN_SPEED = 10 # m/s (25 mph) CAM_Y_OFFSET = 20 class BookmarkIcon(Widget): PEEK_THRESHOLD = 50 # If icon peeks out this much, snap it fully visible FULL_VISIBLE_OFFSET = 200 # How far onscreen when fully visible HIDDEN_OFFSET = -50 # How far offscreen when hidden def __init__(self, bookmark_callback): super().__init__() self._bookmark_callback = bookmark_callback self._icon = gui_app.texture("icons_mici/onroad/bookmark.png", 180, 180) self._offset_filter = BounceFilter(0.0, 0.1, 1 / gui_app.target_fps) # State self._interacting = False self._state = BookmarkState.HIDDEN self._swipe_start_x = 0.0 self._swipe_current_x = 0.0 self._is_swiping = False self._is_swiping_left: bool = False self._triggered_time: float = 0.0 def is_swiping_left(self) -> bool: """Check if currently swiping left (for scroller to disable).""" return self._is_swiping_left def interacting(self): interacting, self._interacting = self._interacting, False return interacting def _update_state(self): if self._state == BookmarkState.DRAGGING: # Allow pulling past activated position with rubber band effect swipe_offset = self._swipe_start_x - self._swipe_current_x swipe_offset = min(swipe_offset, self.FULL_VISIBLE_OFFSET + 50) self._offset_filter.update(swipe_offset) elif self._state == BookmarkState.TRIGGERED: # Continue animating to fully visible self._offset_filter.update(self.FULL_VISIBLE_OFFSET) # Stay in TRIGGERED state for 1 second if rl.get_time() - self._triggered_time >= 1.5: self._state = BookmarkState.HIDDEN elif self._state == BookmarkState.HIDDEN: self._offset_filter.update(self.HIDDEN_OFFSET) if self._offset_filter.x < 1e-3: self._interacting = False def _handle_mouse_event(self, mouse_event: MouseEvent): if not ui_state.started: return if mouse_event.left_pressed: # Store relative position within widget self._swipe_start_x = mouse_event.pos.x self._swipe_current_x = mouse_event.pos.x self._is_swiping = True self._is_swiping_left = False self._state = BookmarkState.DRAGGING elif mouse_event.left_down and self._is_swiping: self._swipe_current_x = mouse_event.pos.x swipe_offset = self._swipe_start_x - self._swipe_current_x self._is_swiping_left = swipe_offset > 0 if self._is_swiping_left: self._interacting = True elif mouse_event.left_released: if self._is_swiping: swipe_distance = self._swipe_start_x - self._swipe_current_x # If peeking past threshold, transition to animating to fully visible and bookmark if swipe_distance > self.PEEK_THRESHOLD: self._state = BookmarkState.TRIGGERED self._triggered_time = rl.get_time() self._bookmark_callback() else: # Otherwise, transition back to hidden self._state = BookmarkState.HIDDEN # Reset swipe state self._is_swiping = False self._is_swiping_left = False def _render(self, _): """Render the bookmark icon.""" if self._offset_filter.x > 0: icon_x = self.rect.x + self.rect.width - round(self._offset_filter.x) icon_y = self.rect.y + (self.rect.height - self._icon.height) / 2 # Vertically centered rl.draw_texture(self._icon, int(icon_x), int(icon_y), rl.WHITE) class AugmentedRoadView(CameraView): def __init__(self, bookmark_callback=None, stream_type: VisionStreamType = VisionStreamType.VISION_STREAM_ROAD): super().__init__("camerad", stream_type) self._bookmark_callback = bookmark_callback self._set_placeholder_color(rl.BLACK) self.device_camera: DeviceCameraConfig | None = None self.view_from_calib = view_frame_from_device_frame.copy() self.view_from_wide_calib = view_frame_from_device_frame.copy() self._last_calib_time: float = 0 self._last_rect_dims = (0.0, 0.0) self._last_stream_type = stream_type self._cached_matrix: np.ndarray | None = None self._content_rect = rl.Rectangle() self._last_click_time = 0.0 # Bookmark icon with swipe gesture self._bookmark_icon = BookmarkIcon(bookmark_callback) self._model_renderer = ModelRenderer() self._hud_renderer = HudRenderer() 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, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE) self._fade_texture = gui_app.texture("icons_mici/onroad/onroad_fade.png") # debug self._pm = messaging.PubMaster(['uiDebug']) def is_swiping_left(self) -> bool: """Check if currently swiping left (for scroller to disable).""" return self._bookmark_icon.is_swiping_left() def _update_state(self): super()._update_state() # update offroad label 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") def _handle_mouse_release(self, mouse_pos: MousePos): # Don't trigger click callback if bookmark was triggered if not self._bookmark_icon.interacting(): super()._handle_mouse_release(mouse_pos) def _render(self, _): start_draw = time.monotonic() self._switch_stream_if_needed(ui_state.sm) # Update calibration before rendering self._update_calibration() # Create inner content area with border padding self._content_rect = rl.Rectangle( self.rect.x, self.rect.y, self.rect.width - SIDE_PANEL_WIDTH, self.rect.height, ) # Enable scissor mode to clip all rendering within content rectangle boundaries # This creates a rendering viewport that prevents graphics from drawing outside the border rl.begin_scissor_mode( int(self._content_rect.x), int(self._content_rect.y), int(self._content_rect.width), int(self._content_rect.height) ) # Render the base camera view super()._render(self._content_rect) # Draw all UI overlays self._model_renderer.render(self._content_rect) # Fade out bottom of overlays for looks rl.draw_texture_ex(self._fade_texture, rl.Vector2(self._content_rect.x, self._content_rect.y), 0.0, 1.0, rl.WHITE) alert_to_render, not_animating_out = self._alert_renderer.will_render() # Hide DMoji when disengaged unless AlwaysOnDM is enabled should_draw_dmoji = (not self._hud_renderer.drawing_top_icons() and ui_state.is_onroad() and (ui_state.status != UIStatus.DISENGAGED or ui_state.always_on_dm)) self._driver_state_renderer.set_should_draw(should_draw_dmoji) self._driver_state_renderer.set_position(self._rect.x + 16, self._rect.y + 10) self._driver_state_renderer.render() self._hud_renderer.set_can_draw_top_icons(alert_to_render is None) self._hud_renderer.set_wheel_critical_icon(alert_to_render is not None and not not_animating_out and alert_to_render.visual_alert == car.CarControl.HUDControl.VisualAlert.steerRequired) # TODO: have alert renderer draw offroad mici label below if ui_state.started: self._alert_renderer.render(self._content_rect) self._hud_renderer.render(self._content_rect) # Draw fake rounded border rl.draw_rectangle_rounded_lines_ex(self._content_rect, 0.2 * 1.02, 10, 50, rl.BLACK) # End clipping region rl.end_scissor_mode() # Custom UI extension point - add custom overlays here # Use self._content_rect for positioning within camera bounds self._confidence_ball.render(self.rect) self._bookmark_icon.render(self.rect) # Draw darkened background and text if not onroad if not ui_state.started: rl.draw_rectangle(int(self.rect.x), int(self.rect.y), int(self.rect.width), int(self.rect.height), rl.Color(0, 0, 0, 175)) self._offroad_label.render(self._content_rect) # publish uiDebug msg = messaging.new_message('uiDebug') msg.uiDebug.drawTimeMillis = (time.monotonic() - start_draw) * 1000 self._pm.send('uiDebug', msg) def _switch_stream_if_needed(self, sm): if sm['selfdriveState'].experimentalMode and WIDE_CAM in self.available_streams: v_ego = sm['carState'].vEgo if v_ego < WIDE_CAM_MAX_SPEED: target = WIDE_CAM elif v_ego > ROAD_CAM_MIN_SPEED: target = ROAD_CAM else: # Hysteresis zone - keep current stream target = self.stream_type else: target = ROAD_CAM if self.stream_type != target: self.switch_stream(target) def _update_calibration(self): # Update device camera if not already set sm = ui_state.sm if not self.device_camera and sm.seen['roadCameraState'] and sm.seen['deviceState']: self.device_camera = DEVICE_CAMERAS[(str(sm['deviceState'].deviceType), str(sm['roadCameraState'].sensor))] # Check if live calibration data is available and valid if not (sm.updated["liveCalibration"] and sm.valid['liveCalibration']): return calib = sm['liveCalibration'] if len(calib.rpyCalib) != 3 or calib.calStatus != CALIBRATED: return # Update view_from_calib matrix device_from_calib = rot_from_euler(calib.rpyCalib) self.view_from_calib = view_frame_from_device_frame @ device_from_calib # Update wide calibration if available if hasattr(calib, 'wideFromDeviceEuler') and len(calib.wideFromDeviceEuler) == 3: wide_from_device = rot_from_euler(calib.wideFromDeviceEuler) self.view_from_wide_calib = view_frame_from_device_frame @ wide_from_device @ device_from_calib def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: # Get camera configuration # TODO: cache with vEgo? calib_time = ui_state.sm.recv_frame['liveCalibration'] current_dims = (self._content_rect.width, self._content_rect.height) device_camera = self.device_camera or DEFAULT_DEVICE_CAMERA is_wide_camera = self.stream_type == WIDE_CAM intrinsic = device_camera.ecam.intrinsics if is_wide_camera else device_camera.fcam.intrinsics calibration = self.view_from_wide_calib if is_wide_camera else self.view_from_calib if is_wide_camera: zoom = 0.7 * 1.5 else: zoom = np.interp(ui_state.sm['carState'].vEgo, [10, 30], [0.8, 1.0]) # Calculate transforms for vanishing point inf_point = np.array([1000.0, 0.0, 0.0]) calib_transform = intrinsic @ calibration kep = calib_transform @ inf_point # Calculate center points and dimensions x, y = self._content_rect.x, self._content_rect.y w, h = self._content_rect.width, self._content_rect.height cx, cy = intrinsic[0, 2], intrinsic[1, 2] # Calculate max allowed offsets with margins margin = 5 max_x_offset = cx * zoom - w / 2 - margin max_y_offset = cy * zoom - h / 2 - margin # Calculate and clamp offsets to prevent out-of-bounds issues try: if abs(kep[2]) > 1e-6: x_offset = np.clip((kep[0] / kep[2] - cx) * zoom, -max_x_offset, max_x_offset) y_offset = np.clip((kep[1] / kep[2] - cy) * zoom + CAM_Y_OFFSET, -max_y_offset, max_y_offset) else: x_offset, y_offset = 0, 0 except (ZeroDivisionError, OverflowError): x_offset, y_offset = 0, 0 # Cache the computed transformation matrix to avoid recalculations self._last_calib_time = calib_time self._last_rect_dims = current_dims self._last_stream_type = self.stream_type self._cached_matrix = np.array([ [zoom * 2 * cx / w, 0, -x_offset / w * 2], [0, zoom * 2 * cy / h, -y_offset / h * 2], [0, 0, 1.0] ]) video_transform = np.array([ [zoom, 0.0, (w / 2 + x - x_offset) - (cx * zoom)], [0.0, zoom, (h / 2 + y - y_offset) - (cy * zoom)], [0.0, 0.0, 1.0] ]) self._model_renderer.set_transform(video_transform @ calib_transform) return self._cached_matrix if __name__ == "__main__": gui_app.init_window("OnRoad Camera View") road_camera_view = AugmentedRoadView(lambda: None, stream_type=ROAD_CAM) print("***press space to switch camera view***") try: for _ in gui_app.render(): ui_state.update() if rl.is_key_released(rl.KeyboardKey.KEY_SPACE): if WIDE_CAM in road_camera_view.available_streams: stream = ROAD_CAM if road_camera_view.stream_type == WIDE_CAM else WIDE_CAM road_camera_view.switch_stream(stream) road_camera_view.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) finally: road_camera_view.close()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/augmented_road_view.py", "license": "MIT License", "lines": 301, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/cameraview.py
import platform import numpy as np import pyray as rl from msgq.visionipc import VisionIpcClient, VisionStreamType, VisionBuf from openpilot.common.swaglog import cloudlog from openpilot.system.hardware import TICI from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.lib.egl import init_egl, create_egl_image, destroy_egl_image, bind_egl_image_to_texture, EGLImage from openpilot.system.ui.widgets import Widget from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus CONNECTION_RETRY_INTERVAL = 0.2 # seconds between connection attempts VERSION = """ #version 300 es precision mediump float; """ if platform.system() == "Darwin": VERSION = """ #version 330 core """ VERTEX_SHADER = VERSION + """ in vec3 vertexPosition; in vec2 vertexTexCoord; in vec3 vertexNormal; in vec4 vertexColor; uniform mat4 mvp; out vec2 fragTexCoord; out vec4 fragColor; void main() { fragTexCoord = vertexTexCoord; fragColor = vertexColor; gl_Position = mvp * vec4(vertexPosition, 1.0); } """ # Choose fragment shader based on platform capabilities if TICI: FRAME_FRAGMENT_SHADER = """ #version 300 es #extension GL_OES_EGL_image_external_essl3 : enable precision mediump float; in vec2 fragTexCoord; uniform samplerExternalOES texture0; out vec4 fragColor; uniform int engaged; uniform int enhance_driver; void main() { vec4 color = texture(texture0, fragTexCoord); if (engaged == 1) { float gray = dot(color.rgb, vec3(0.299, 0.587, 0.114)); // Luma color.rgb = mix(vec3(gray), color.rgb, 0.2); // 20% saturation color.rgb = clamp((color.rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); // +20% contrast color.rgb = pow(color.rgb, vec3(1.0/1.28)); fragColor = vec4(color.rgb, color.a); } else { color.rgb *= 0.85; // 85% opacity } if (enhance_driver == 1) { float brightness = 1.1; color.rgb = color.rgb + 0.15; color.rgb = clamp((color.rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); color.rgb = color.rgb * color.rgb * (3.0 - 2.0 * color.rgb); color.rgb = pow(color.rgb, vec3(0.8)); } fragColor = vec4(color.rgb, color.a); } """ else: FRAME_FRAGMENT_SHADER = VERSION + """ in vec2 fragTexCoord; uniform sampler2D texture0; uniform sampler2D texture1; out vec4 fragColor; uniform int engaged; uniform int enhance_driver; void main() { float y = texture(texture0, fragTexCoord).r; vec2 uv = texture(texture1, fragTexCoord).ra - 0.5; vec3 rgb = vec3(y + 1.402*uv.y, y - 0.344*uv.x - 0.714*uv.y, y + 1.772*uv.x); if (engaged == 1) { float gray = dot(rgb, vec3(0.299, 0.587, 0.114)); rgb = mix(vec3(gray), rgb, 0.2); // 20% saturation rgb = clamp((rgb - 0.5) * 1.2 + 0.5, 0.0, 1.0); // +20% contrast } else { rgb *= 0.85; // 85% opacity } // TODO: the images out of camerad need some more correction and // the ui should apply a gamma curve for the device display if (enhance_driver == 1) { float brightness = 1.1; rgb = rgb + 0.15; rgb = clamp((rgb - 0.5) * (brightness * 0.8) + 0.5, 0.0, 1.0); rgb = rgb * rgb * (3.0 - 2.0 * rgb); rgb = pow(rgb, vec3(0.8)); } fragColor = vec4(rgb, 1.0); } """ class CameraView(Widget): def __init__(self, name: str, stream_type: VisionStreamType): super().__init__() self._name = name # Primary stream self.client = VisionIpcClient(name, stream_type, conflate=True) self._stream_type = stream_type self.available_streams: list[VisionStreamType] = [] # Target stream for switching self._target_client: VisionIpcClient | None = None self._target_stream_type: VisionStreamType | None = None self._switching: bool = False self._texture_needs_update = True self.last_connection_attempt: float = 0.0 self.shader = rl.load_shader_from_memory(VERTEX_SHADER, FRAME_FRAGMENT_SHADER) self._texture1_loc: int = rl.get_shader_location(self.shader, "texture1") if not TICI else -1 self._engaged_loc = rl.get_shader_location(self.shader, "engaged") self._engaged_val = rl.ffi.new("int[1]", [1]) self._enhance_driver_loc = rl.get_shader_location(self.shader, "enhance_driver") self._enhance_driver_val = rl.ffi.new("int[1]", [1 if stream_type == VisionStreamType.VISION_STREAM_DRIVER else 0]) self.frame: VisionBuf | None = None self.texture_y: rl.Texture | None = None self.texture_uv: rl.Texture | None = None # EGL resources self.egl_images: dict[int, EGLImage] = {} self.egl_texture: rl.Texture | None = None self._placeholder_color: rl.Color | None = None # Initialize EGL for zero-copy rendering on TICI if TICI: if not init_egl(): raise RuntimeError("Failed to initialize EGL") # Create a 1x1 pixel placeholder texture for EGL image binding temp_image = rl.gen_image_color(1, 1, rl.BLACK) self.egl_texture = rl.load_texture_from_image(temp_image) rl.unload_image(temp_image) ui_state.add_offroad_transition_callback(self._offroad_transition) def _offroad_transition(self): # Reconnect if not first time going onroad if ui_state.is_onroad() and self.frame is not None: # Prevent old frames from showing when going onroad. Qt has a separate thread # which drains the VisionIpcClient SubSocket for us. Re-connecting is not enough # and only clears internal buffers, not the message queue. self.frame = None self.available_streams.clear() if self.client: del self.client self.client = VisionIpcClient(self._name, self._stream_type, conflate=True) def _set_placeholder_color(self, color: rl.Color): """Set a placeholder color to be drawn when no frame is available.""" self._placeholder_color = color def switch_stream(self, stream_type: VisionStreamType) -> None: if self._stream_type == stream_type: return if self._switching and self._target_stream_type == stream_type: return cloudlog.debug(f'Preparing switch from {self._stream_type} to {stream_type}') if self._target_client: del self._target_client self._target_stream_type = stream_type self._target_client = VisionIpcClient(self._name, stream_type, conflate=True) self._switching = True @property def stream_type(self) -> VisionStreamType: return self._stream_type def close(self) -> None: self._clear_textures() # Clean up EGL texture if TICI and self.egl_texture: rl.unload_texture(self.egl_texture) self.egl_texture = None # Clean up shader if self.shader and self.shader.id: rl.unload_shader(self.shader) self.shader.id = 0 self.frame = None self.available_streams.clear() self.client = None def __del__(self): self.close() def _calc_frame_matrix(self, rect: rl.Rectangle) -> np.ndarray: if not self.frame: return np.eye(3) # Calculate aspect ratios widget_aspect_ratio = rect.width / rect.height frame_aspect_ratio = self.frame.width / self.frame.height # Calculate scaling factors to maintain aspect ratio zx = min(frame_aspect_ratio / widget_aspect_ratio, 1.0) zy = min(widget_aspect_ratio / frame_aspect_ratio, 1.0) return np.array([ [zx, 0.0, 0.0], [0.0, zy, 0.0], [0.0, 0.0, 1.0] ]) def _render(self, rect: rl.Rectangle): if self._switching: self._handle_switch() if not self._ensure_connection(): self._draw_placeholder(rect) return # Try to get a new buffer without blocking buffer = self.client.recv(timeout_ms=0) if buffer: self._texture_needs_update = True self.frame = buffer elif not self.client.is_connected(): # ensure we clear the displayed frame when the connection is lost self.frame = None if not self.frame: self._draw_placeholder(rect) return transform = self._calc_frame_matrix(rect) src_rect = rl.Rectangle(0, 0, float(self.frame.width), float(self.frame.height)) # Flip driver camera horizontally if self._stream_type == VisionStreamType.VISION_STREAM_DRIVER: src_rect.width = -src_rect.width # Calculate scale scale_x = rect.width * transform[0, 0] # zx scale_y = rect.height * transform[1, 1] # zy # Calculate base position (centered) x_offset = rect.x + (rect.width - scale_x) / 2 y_offset = rect.y + (rect.height - scale_y) / 2 x_offset += transform[0, 2] * rect.width / 2 y_offset += transform[1, 2] * rect.height / 2 dst_rect = rl.Rectangle(x_offset, y_offset, scale_x, scale_y) # Render with appropriate method if TICI: self._render_egl(src_rect, dst_rect) else: self._render_textures(src_rect, dst_rect) def _draw_placeholder(self, rect: rl.Rectangle): if self._placeholder_color: rl.draw_rectangle_rec(rect, self._placeholder_color) def _render_egl(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: """Render using EGL for direct buffer access""" if self.frame is None or self.egl_texture is None: return idx = self.frame.idx egl_image = self.egl_images.get(idx) # Create EGL image if needed if egl_image is None: egl_image = create_egl_image(self.frame.width, self.frame.height, self.frame.stride, self.frame.fd, self.frame.uv_offset) if egl_image: self.egl_images[idx] = egl_image else: return # Update texture dimensions to match current frame self.egl_texture.width = self.frame.width self.egl_texture.height = self.frame.height # Bind the EGL image to our texture bind_egl_image_to_texture(self.egl_texture.id, egl_image) # Render with shader rl.begin_shader_mode(self.shader) self._update_texture_color_filtering() rl.draw_texture_pro(self.egl_texture, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) rl.end_shader_mode() def _render_textures(self, src_rect: rl.Rectangle, dst_rect: rl.Rectangle) -> None: """Render using texture copies""" if not self.texture_y or not self.texture_uv or self.frame is None: return # Update textures with new frame data if self._texture_needs_update: y_data = self.frame.data[: self.frame.uv_offset] uv_data = self.frame.data[self.frame.uv_offset:] rl.update_texture(self.texture_y, rl.ffi.cast("void *", y_data.ctypes.data)) rl.update_texture(self.texture_uv, rl.ffi.cast("void *", uv_data.ctypes.data)) self._texture_needs_update = False # Render with shader rl.begin_shader_mode(self.shader) self._update_texture_color_filtering() rl.set_shader_value_texture(self.shader, self._texture1_loc, self.texture_uv) rl.draw_texture_pro(self.texture_y, src_rect, dst_rect, rl.Vector2(0, 0), 0.0, rl.WHITE) rl.end_shader_mode() def _update_texture_color_filtering(self): self._engaged_val[0] = 1 if ui_state.status != UIStatus.DISENGAGED else 0 rl.set_shader_value(self.shader, self._engaged_loc, self._engaged_val, rl.ShaderUniformDataType.SHADER_UNIFORM_INT) rl.set_shader_value(self.shader, self._enhance_driver_loc, self._enhance_driver_val, rl.ShaderUniformDataType.SHADER_UNIFORM_INT) def _ensure_connection(self) -> bool: if not self.client.is_connected(): self.frame = None self.available_streams.clear() # Throttle connection attempts current_time = rl.get_time() if current_time - self.last_connection_attempt < CONNECTION_RETRY_INTERVAL: return False self.last_connection_attempt = current_time if not self.client.connect(False) or not self.client.num_buffers: return False cloudlog.debug(f"Connected to {self._name} stream: {self._stream_type}, buffers: {self.client.num_buffers}") self._initialize_textures() self.available_streams = self.client.available_streams(self._name, block=False) return True def _handle_switch(self) -> None: """Check if target stream is ready and switch immediately.""" if not self._target_client or not self._switching: return # Try to connect target if needed if not self._target_client.is_connected(): if not self._target_client.connect(False) or not self._target_client.num_buffers: return cloudlog.debug(f"Target stream connected: {self._target_stream_type}") # Check if target has frames ready target_frame = self._target_client.recv(timeout_ms=0) if target_frame: self.frame = target_frame # Update current frame to target frame self._complete_switch() def _complete_switch(self) -> None: """Instantly switch to target stream.""" cloudlog.debug(f"Switching to {self._target_stream_type}") # Clean up current resources if self.client: del self.client # Switch to target self.client = self._target_client self._stream_type = self._target_stream_type self._texture_needs_update = True # Reset state self._target_client = None self._target_stream_type = None self._switching = False # Initialize textures for new stream self._initialize_textures() def _initialize_textures(self): self._clear_textures() if not TICI: self.texture_y = rl.load_texture_from_image(rl.Image(None, int(self.client.stride), int(self.client.height), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAYSCALE)) self.texture_uv = rl.load_texture_from_image(rl.Image(None, int(self.client.stride // 2), int(self.client.height // 2), 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA)) def _clear_textures(self): if self.texture_y and self.texture_y.id: rl.unload_texture(self.texture_y) self.texture_y = None if self.texture_uv and self.texture_uv.id: rl.unload_texture(self.texture_uv) self.texture_uv = None # Clean up EGL resources if TICI: for data in self.egl_images.values(): destroy_egl_image(data) self.egl_images = {} if __name__ == "__main__": gui_app.init_window("camera view") road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) for _ in gui_app.render(): road.render(rl.Rectangle(0, 0, gui_app.width, gui_app.height))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/cameraview.py", "license": "MIT License", "lines": 341, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/confidence_ball.py
import math import pyray as rl from openpilot.selfdrive.ui.mici.onroad import SIDE_PANEL_WIDTH from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus from openpilot.system.ui.widgets import Widget from openpilot.system.ui.lib.application import gui_app from openpilot.common.filter_simple import FirstOrderFilter def draw_circle_gradient(center_x: float, center_y: float, radius: int, top: rl.Color, bottom: rl.Color) -> None: # Draw a square with the gradient rl.draw_rectangle_gradient_v(int(center_x - radius), int(center_y - radius), radius * 2, radius * 2, top, bottom) # Paint over square with a ring outer_radius = math.ceil(radius * math.sqrt(2)) + 1 rl.draw_ring(rl.Vector2(int(center_x), int(center_y)), radius, outer_radius, 0.0, 360.0, 20, rl.BLACK) class ConfidenceBall(Widget): def __init__(self, demo: bool = False): super().__init__() self._demo = demo self._confidence_filter = FirstOrderFilter(-0.5, 0.5, 1 / gui_app.target_fps) def update_filter(self, value: float): self._confidence_filter.update(value) def _update_state(self): if self._demo: return # animate status dot in from bottom if ui_state.status == UIStatus.DISENGAGED: self._confidence_filter.update(-0.5) else: self._confidence_filter.update((1 - max(ui_state.sm['modelV2'].meta.disengagePredictions.brakeDisengageProbs or [1])) * (1 - max(ui_state.sm['modelV2'].meta.disengagePredictions.steerOverrideProbs or [1]))) def _render(self, _): content_rect = rl.Rectangle( self.rect.x + self.rect.width - SIDE_PANEL_WIDTH, self.rect.y, SIDE_PANEL_WIDTH, self.rect.height, ) status_dot_radius = 24 dot_height = (1 - self._confidence_filter.x) * (content_rect.height - 2 * status_dot_radius) + status_dot_radius dot_height = self._rect.y + dot_height # confidence zones if ui_state.status == UIStatus.ENGAGED or self._demo: if self._confidence_filter.x > 0.5: top_dot_color = rl.Color(0, 255, 204, 255) bottom_dot_color = rl.Color(0, 255, 38, 255) elif self._confidence_filter.x > 0.2: top_dot_color = rl.Color(255, 200, 0, 255) bottom_dot_color = rl.Color(255, 115, 0, 255) else: top_dot_color = rl.Color(255, 0, 21, 255) bottom_dot_color = rl.Color(255, 0, 89, 255) elif ui_state.status == UIStatus.OVERRIDE: top_dot_color = rl.Color(255, 255, 255, 255) bottom_dot_color = rl.Color(82, 82, 82, 255) else: top_dot_color = rl.Color(50, 50, 50, 255) bottom_dot_color = rl.Color(13, 13, 13, 255) draw_circle_gradient(content_rect.x + content_rect.width - status_dot_radius, dot_height, status_dot_radius, top_dot_color, bottom_dot_color)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/confidence_ball.py", "license": "MIT License", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/mici/onroad/driver_camera_dialog.py
import pyray as rl from cereal import log, messaging from msgq.visionipc import VisionStreamType from openpilot.selfdrive.ui.mici.onroad.cameraview import CameraView from openpilot.selfdrive.ui.mici.onroad.driver_state import DriverStateRenderer from openpilot.selfdrive.ui.ui_state import ui_state, device from openpilot.selfdrive.selfdrived.events import EVENTS, ET from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.nav_widget import NavWidget from openpilot.system.ui.widgets.label import gui_label EventName = log.OnroadEvent.EventName EVENT_TO_INT = EventName.schema.enumerants class DriverCameraView(CameraView): def _calc_frame_matrix(self, rect: rl.Rectangle): base = super()._calc_frame_matrix(rect) driver_view_ratio = 1.5 base[0, 0] *= driver_view_ratio base[1, 1] *= driver_view_ratio return base class BaseDriverCameraDialog(Widget): # Not a NavWidget so training guide can use this without back navigation def __init__(self): super().__init__() self._camera_view = DriverCameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) self.driver_state_renderer = DriverStateRenderer(lines=True) self.driver_state_renderer.set_rect(rl.Rectangle(0, 0, 200, 200)) self.driver_state_renderer.load_icons() self._pm: messaging.PubMaster | None = None # Load eye icons self._eye_fill_texture = None self._eye_orange_texture = None self._eye_size = 74 self._glasses_texture = None self._glasses_size = 171 self._load_eye_textures() def show_event(self): super().show_event() ui_state.params.put_bool("IsDriverViewEnabled", True) self._publish_alert_sound(None) device.set_override_interactive_timeout(300) ui_state.params.remove("DriverTooDistracted") self._pm = messaging.PubMaster(['selfdriveState']) def hide_event(self): super().hide_event() ui_state.params.put_bool("IsDriverViewEnabled", False) device.set_override_interactive_timeout(None) def _handle_mouse_release(self, _): ui_state.params.remove("DriverTooDistracted") def __del__(self): self.close() def close(self): if self._camera_view: self._camera_view.close() def _update_state(self): if self._camera_view: self._camera_view._update_state() # Enable driver state renderer to show Dmoji in preview self.driver_state_renderer.set_should_draw(True) self.driver_state_renderer.set_force_active(True) super()._update_state() def _render(self, rect): rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) self._camera_view._render(rect) if not self._camera_view.frame: gui_label(rect, tr("camera starting"), font_size=54, font_weight=FontWeight.BOLD, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) rl.end_scissor_mode() self._publish_alert_sound(None) return driver_data = self._draw_face_detection(rect) if driver_data is not None: self._draw_eyes(rect, driver_data) # Position dmoji on opposite side from driver driver_state_rect = ( rect.x if self.driver_state_renderer.is_rhd else rect.x + rect.width - self.driver_state_renderer.rect.width, rect.y + (rect.height - self.driver_state_renderer.rect.height) / 2, ) self.driver_state_renderer.set_position(*driver_state_rect) self.driver_state_renderer.render() # Render driver monitoring alerts self._render_dm_alerts(rect) rl.end_scissor_mode() return def _publish_alert_sound(self, dm_state): """Publish selfdriveState with only alertSound field set""" if self._pm is None: return msg = messaging.new_message('selfdriveState') if dm_state is not None and len(dm_state.events): event_name = EVENT_TO_INT[dm_state.events[0].name] if event_name is not None and event_name in EVENTS and ET.PERMANENT in EVENTS[event_name]: msg.selfdriveState.alertSound = EVENTS[event_name][ET.PERMANENT].audible_alert self._pm.send('selfdriveState', msg) def _render_dm_alerts(self, rect: rl.Rectangle): """Render driver monitoring event names""" dm_state = ui_state.sm["driverMonitoringState"] self._publish_alert_sound(dm_state) gui_label(rl.Rectangle(rect.x + 2, rect.y + 2, rect.width, rect.height), f"Awareness: {dm_state.awarenessStatus * 100:.0f}%", font_size=44, font_weight=FontWeight.MEDIUM, alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, color=rl.Color(0, 0, 0, 180)) gui_label(rect, f"Awareness: {dm_state.awarenessStatus * 100:.0f}%", font_size=44, font_weight=FontWeight.MEDIUM, alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP, color=rl.Color(255, 255, 255, int(255 * 0.9))) if not dm_state.events: return # Show first event (only one should be active at a time) event_name_str = str(dm_state.events[0].name).split('.')[-1] alignment = rl.GuiTextAlignment.TEXT_ALIGN_RIGHT if self.driver_state_renderer.is_rhd else rl.GuiTextAlignment.TEXT_ALIGN_LEFT shadow_rect = rl.Rectangle(rect.x + 2, rect.y + 2, rect.width, rect.height) gui_label(shadow_rect, event_name_str, font_size=40, font_weight=FontWeight.BOLD, alignment=alignment, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, color=rl.Color(0, 0, 0, 180)) gui_label(rect, event_name_str, font_size=40, font_weight=FontWeight.BOLD, alignment=alignment, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, color=rl.Color(255, 255, 255, int(255 * 0.9))) def _load_eye_textures(self): """Lazy load eye textures""" if self._eye_fill_texture is None: self._eye_fill_texture = gui_app.texture("icons_mici/onroad/eye_fill.png", self._eye_size, self._eye_size) if self._eye_orange_texture is None: self._eye_orange_texture = gui_app.texture("icons_mici/onroad/eye_orange.png", self._eye_size, self._eye_size) if self._glasses_texture is None: self._glasses_texture = gui_app.texture("icons_mici/onroad/glasses.png", self._glasses_size, self._glasses_size) def _draw_face_detection(self, rect: rl.Rectangle): dm_state = ui_state.sm["driverMonitoringState"] driver_data = self.driver_state_renderer.get_driver_data() if not dm_state.faceDetected: return # Get face position and orientation face_x, face_y = driver_data.facePosition face_std = max(driver_data.faceOrientationStd[0], driver_data.faceOrientationStd[1]) alpha = 0.7 if face_std > 0.15: alpha = max(0.7 - (face_std - 0.15) * 3.5, 0.0) # use approx instead of distort_points # TODO: replace with distort_points tici_x = 1080.0 - 1714.0 * face_x tici_y = -135.0 + (504.0 + abs(face_x) * 112.0) + (1205.0 - abs(face_x) * 724.0) * face_y # Tici coords are relative to center, scale offset offset_x = (tici_x - 1080.0) * 1.25 offset_y = (tici_y - 540.0) * 1.25 # Map to mici screen (scale from 2160x1080 to rect dimensions) scale_x = rect.width / 2160.0 scale_y = rect.height / 1080.0 fbox_x = rect.x + rect.width / 2 + offset_x * scale_x fbox_y = rect.y + rect.height / 2 + offset_y * scale_y box_size = 75 line_thickness = 3 line_color = rl.Color(255, 255, 255, int(alpha * 255)) rl.draw_rectangle_rounded_lines_ex( rl.Rectangle(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size), 35.0 / box_size / 2, line_thickness, line_thickness, line_color, ) return driver_data def _draw_eyes(self, rect: rl.Rectangle, driver_data): # Draw eye indicators based on eye probabilities eye_offset_x = 10 eye_offset_y = 10 eye_spacing = self._eye_size + 15 left_eye_x = rect.x + eye_offset_x left_eye_y = rect.y + eye_offset_y left_eye_prob = driver_data.leftEyeProb right_eye_x = rect.x + eye_offset_x + eye_spacing right_eye_y = rect.y + eye_offset_y right_eye_prob = driver_data.rightEyeProb # Draw eyes with opacity based on probability for eye_x, eye_y, eye_prob in [(left_eye_x, left_eye_y, left_eye_prob), (right_eye_x, right_eye_y, right_eye_prob)]: fill_opacity = eye_prob orange_opacity = 1.0 - eye_prob rl.draw_texture_v(self._eye_orange_texture, (eye_x, eye_y), rl.Color(255, 255, 255, int(255 * orange_opacity))) rl.draw_texture_v(self._eye_fill_texture, (eye_x, eye_y), rl.Color(255, 255, 255, int(255 * fill_opacity))) # Draw sunglasses indicator based on sunglasses probability # Position glasses centered between the two eyes at top left glasses_x = rect.x + eye_offset_x - 4 glasses_y = rect.y glasses_pos = rl.Vector2(glasses_x, glasses_y) glasses_prob = driver_data.sunglassesProb rl.draw_texture_v(self._glasses_texture, glasses_pos, rl.Color(70, 80, 161, int(255 * glasses_prob))) class DriverCameraDialog(NavWidget, BaseDriverCameraDialog): def __init__(self): super().__init__() # TODO: this can grow unbounded, should be given some thought device.add_interactive_timeout_callback(gui_app.pop_widget) if __name__ == "__main__": gui_app.init_window("Driver Camera View (mici)") driver_camera_view = DriverCameraDialog() gui_app.push_widget(driver_camera_view) try: for _ in gui_app.render(): ui_state.update() finally: driver_camera_view.close()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/driver_camera_dialog.py", "license": "MIT License", "lines": 202, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/driver_state.py
import pyray as rl import numpy as np import math from cereal import log from openpilot.common.filter_simple import FirstOrderFilter from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.widgets import Widget from openpilot.selfdrive.ui.ui_state import ui_state AlertSize = log.SelfdriveState.AlertSize DEBUG = False LOOKING_CENTER_THRESHOLD_UPPER = math.radians(6) LOOKING_CENTER_THRESHOLD_LOWER = math.radians(3) class DriverStateRenderer(Widget): BASE_SIZE = 60 LINES_ANGLE_INCREMENT = 5 LINES_STALE_ANGLES = 3.0 # seconds def __init__(self, lines: bool = False, inset: bool = False): super().__init__() self.set_rect(rl.Rectangle(0, 0, self.BASE_SIZE, self.BASE_SIZE)) self._lines = lines self._inset = inset # In line mode, track smoothed angles assert 360 % self.LINES_ANGLE_INCREMENT == 0 self._head_angles = {i * self.LINES_ANGLE_INCREMENT: FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) for i in range(360 // self.LINES_ANGLE_INCREMENT)} self._is_active = False self._is_rhd = False self._face_detected = False self._should_draw = False self._force_active = False self._looking_center = False self._fade_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps) self._pitch_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps, initialized=False) self._yaw_filter = FirstOrderFilter(0.0, 0.05, 1 / gui_app.target_fps, initialized=False) self._rotation_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps, initialized=False) self._looking_center_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) # Load the driver face icons self.load_icons() def load_icons(self): """Load or reload the driver face icon texture""" cone_and_person_size = round(52 / self.BASE_SIZE * self._rect.width) # If inset is enabled, push cone and person smaller by 2x the current inset space if self._inset: # Current inset space = (rect.width - cone_and_person_size) / 2 current_inset = (self._rect.width - cone_and_person_size) / 2 # Reduce size by 2x the current inset (1x on each side) cone_and_person_size = round(cone_and_person_size - current_inset * 2) self._dm_person = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_person.png", cone_and_person_size, cone_and_person_size) self._dm_cone = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_cone.png", cone_and_person_size, cone_and_person_size) center_size = round(36 / self.BASE_SIZE * self._rect.width) self._dm_center = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_center.png", center_size, center_size) self._dm_background = gui_app.texture("icons_mici/onroad/driver_monitoring/dm_background.png", self._rect.width, self._rect.height) def set_should_draw(self, should_draw: bool): self._should_draw = should_draw @property def should_draw(self): return (self._should_draw and ui_state.sm["selfdriveState"].alertSize == AlertSize.none and ui_state.sm.recv_frame["driverStateV2"] > ui_state.started_frame) def set_force_active(self, force_active: bool): """Force the dmoji to always appear active (green) regardless of actual state""" self._force_active = force_active @property def effective_active(self) -> bool: """Returns True if dmoji should appear active (either actually active or forced)""" return bool(self._force_active or self._is_active) @property def is_rhd(self) -> bool: return self._is_rhd def _render(self, _): if DEBUG: rl.draw_rectangle_lines_ex(self._rect, 1, rl.RED) rl.draw_texture(self._dm_background, int(self._rect.x), int(self._rect.y), rl.Color(255, 255, 255, int(255 * self._fade_filter.x))) rl.draw_texture(self._dm_person, int(self._rect.x + (self._rect.width - self._dm_person.width) / 2), int(self._rect.y + (self._rect.height - self._dm_person.height) / 2), rl.Color(255, 255, 255, int(255 * 0.9 * self._fade_filter.x))) if self.effective_active: source_rect = rl.Rectangle(0, 0, self._dm_cone.width, self._dm_cone.height) dest_rect = rl.Rectangle( self._rect.x + self._rect.width / 2, self._rect.y + self._rect.height / 2, self._dm_cone.width, self._dm_cone.height, ) if not self._lines: rl.draw_texture_pro( self._dm_cone, source_rect, dest_rect, rl.Vector2(dest_rect.width / 2, dest_rect.height / 2), self._rotation_filter.x - 90, rl.Color(255, 255, 255, int(255 * self._fade_filter.x * (1 - self._looking_center_filter.x))), ) rl.draw_texture_ex( self._dm_center, (int(self._rect.x + (self._rect.width - self._dm_center.width) / 2), int(self._rect.y + (self._rect.height - self._dm_center.height) / 2)), 0, 1.0, rl.Color(255, 255, 255, int(255 * self._fade_filter.x * self._looking_center_filter.x)), ) else: # remove old angles for angle, f in self._head_angles.items(): dst_from_current = ((angle - self._rotation_filter.x) % 360) - 180 target = 1.0 if abs(dst_from_current) <= self.LINES_ANGLE_INCREMENT * 5 else 0.0 if not self._face_detected: target = 0.0 # Reduce all line lengths when looking center if self._looking_center: target = np.interp(self._looking_center_filter.x, [0.0, 1.0], [target, 0.45]) f.update(target) self._draw_line(angle, f, self._looking_center) def _draw_line(self, angle: int, f: FirstOrderFilter, grey: bool): line_length = self._rect.width / 6 line_length = round(np.interp(f.x, [0.0, 1.0], [0, line_length])) line_offset = self._rect.width / 2 - line_length * 2 # ensure line ends within rect center_x = self._rect.x + self._rect.width / 2 center_y = self._rect.y + self._rect.height / 2 start_x = center_x + (line_offset + line_length) * math.cos(math.radians(angle)) start_y = center_y + (line_offset + line_length) * math.sin(math.radians(angle)) end_x = start_x + line_length * math.cos(math.radians(angle)) end_y = start_y + line_length * math.sin(math.radians(angle)) color = rl.Color(0, 255, 64, 255) if grey: color = rl.Color(166, 166, 166, 255) if f.x > 0.01: rl.draw_line_ex((start_x, start_y), (end_x, end_y), 12, color) def get_driver_data(self): sm = ui_state.sm dm_state = sm["driverMonitoringState"] self._is_active = dm_state.isActiveMode self._is_rhd = dm_state.isRHD self._face_detected = dm_state.faceDetected driverstate = sm["driverStateV2"] driver_data = driverstate.rightDriverData if self._is_rhd else driverstate.leftDriverData return driver_data def _update_state(self): # Get monitoring state driver_data = self.get_driver_data() driver_orient = driver_data.faceOrientation if len(driver_orient) != 3: return pitch, yaw, roll = driver_orient pitch = self._pitch_filter.update(pitch) yaw = self._yaw_filter.update(yaw) # hysteresis on looking center if abs(pitch) < LOOKING_CENTER_THRESHOLD_LOWER and abs(yaw) < LOOKING_CENTER_THRESHOLD_LOWER: self._looking_center = True elif abs(pitch) > LOOKING_CENTER_THRESHOLD_UPPER or abs(yaw) > LOOKING_CENTER_THRESHOLD_UPPER: self._looking_center = False self._looking_center_filter.update(1 if self._looking_center else 0) if DEBUG: pitchd = math.degrees(pitch) yawd = math.degrees(yaw) rolld = math.degrees(roll) rl.draw_line_ex((0, 100), (200, 100), 3, rl.RED) rl.draw_line_ex((0, 120), (200, 120), 3, rl.RED) rl.draw_line_ex((0, 140), (200, 140), 3, rl.RED) pitch_x = 100 + pitchd yaw_x = 100 + yawd roll_x = 100 + rolld rl.draw_circle(int(pitch_x), 100, 5, rl.GREEN) rl.draw_circle(int(yaw_x), 120, 5, rl.GREEN) rl.draw_circle(int(roll_x), 140, 5, rl.GREEN) # filter head rotation, handling wrap-around rotation = math.degrees(math.atan2(pitch, yaw)) angle_diff = rotation - self._rotation_filter.x angle_diff = ((angle_diff + 180) % 360) - 180 self._rotation_filter.update(self._rotation_filter.x + angle_diff) if not self.should_draw: self._fade_filter.update(0.0) elif not self.effective_active: self._fade_filter.update(0.35) else: self._fade_filter.update(1.0)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/driver_state.py", "license": "MIT License", "lines": 178, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/hud_renderer.py
import pyray as rl from dataclasses import dataclass from openpilot.common.constants import CV from openpilot.selfdrive.ui.mici.onroad.torque_bar import TorqueBar from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.lib.text_measure import measure_text_cached from openpilot.system.ui.widgets import Widget from openpilot.common.filter_simple import FirstOrderFilter from cereal import log EventName = log.OnroadEvent.EventName # Constants SET_SPEED_NA = 255 KM_TO_MILE = 0.621371 CRUISE_DISABLED_CHAR = '–' SET_SPEED_PERSISTENCE = 2.5 # seconds @dataclass(frozen=True) class FontSizes: current_speed: int = 176 speed_unit: int = 66 max_speed: int = 36 set_speed: int = 112 @dataclass(frozen=True) class Colors: WHITE = rl.WHITE WHITE_TRANSLUCENT = rl.Color(255, 255, 255, 200) FONT_SIZES = FontSizes() COLORS = Colors() class TurnIntent(Widget): FADE_IN_ANGLE = 30 # degrees def __init__(self): super().__init__() self._pre = False self._turn_intent_direction: int = 0 self._turn_intent_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) self._turn_intent_rotation_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) self._txt_turn_intent_left: rl.Texture = gui_app.texture('icons_mici/turn_intent_left.png', 50, 20) self._txt_turn_intent_right: rl.Texture = gui_app.texture('icons_mici/turn_intent_left.png', 50, 20, flip_x=True) def _render(self, _): if self._turn_intent_alpha_filter.x > 1e-2: turn_intent_texture = self._txt_turn_intent_right if self._turn_intent_direction == 1 else self._txt_turn_intent_left src_rect = rl.Rectangle(0, 0, turn_intent_texture.width, turn_intent_texture.height) dest_rect = rl.Rectangle(self._rect.x + self._rect.width / 2, self._rect.y + self._rect.height / 2, turn_intent_texture.width, turn_intent_texture.height) origin = (turn_intent_texture.width / 2, self._rect.height / 2) color = rl.Color(255, 255, 255, int(255 * self._turn_intent_alpha_filter.x)) rl.draw_texture_pro(turn_intent_texture, src_rect, dest_rect, origin, self._turn_intent_rotation_filter.x, color) def _update_state(self) -> None: sm = ui_state.sm left = any(e.name == EventName.preLaneChangeLeft for e in sm['onroadEvents']) right = any(e.name == EventName.preLaneChangeRight for e in sm['onroadEvents']) if left or right: # pre lane change if not self._pre: self._turn_intent_rotation_filter.x = self.FADE_IN_ANGLE if left else -self.FADE_IN_ANGLE self._pre = True self._turn_intent_direction = -1 if left else 1 self._turn_intent_alpha_filter.update(1) self._turn_intent_rotation_filter.update(0) elif any(e.name == EventName.laneChange for e in sm['onroadEvents']): # fade out and rotate away self._pre = False self._turn_intent_alpha_filter.update(0) if self._turn_intent_direction == 0: # unknown. missed pre frame? self._turn_intent_rotation_filter.update(0) else: self._turn_intent_rotation_filter.update(self._turn_intent_direction * self.FADE_IN_ANGLE) else: # didn't complete lane change, just hide self._pre = False self._turn_intent_direction = 0 self._turn_intent_alpha_filter.update(0) self._turn_intent_rotation_filter.update(0) class HudRenderer(Widget): def __init__(self): super().__init__() """Initialize the HUD renderer.""" self.is_cruise_set: bool = False self.is_cruise_available: bool = True self.set_speed: float = SET_SPEED_NA self._set_speed_changed_time: float = 0 self.speed: float = 0.0 self.v_ego_cluster_seen: bool = False self._engaged: bool = False self._can_draw_top_icons = True self._show_wheel_critical = False self._font_bold: rl.Font = gui_app.font(FontWeight.BOLD) self._font_medium: rl.Font = gui_app.font(FontWeight.MEDIUM) self._font_semi_bold: rl.Font = gui_app.font(FontWeight.SEMI_BOLD) self._font_display: rl.Font = gui_app.font(FontWeight.DISPLAY) self._turn_intent = TurnIntent() self._torque_bar = TorqueBar() self._txt_wheel: rl.Texture = gui_app.texture('icons_mici/wheel.png', 50, 50) self._txt_wheel_critical: rl.Texture = gui_app.texture('icons_mici/wheel_critical.png', 50, 50) self._txt_exclamation_point: rl.Texture = gui_app.texture('icons_mici/exclamation_point.png', 44, 44) self._wheel_alpha_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) self._wheel_y_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) self._set_speed_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) def set_wheel_critical_icon(self, critical: bool): """Set the wheel icon to critical or normal state.""" self._show_wheel_critical = critical def set_can_draw_top_icons(self, can_draw_top_icons: bool): """Set whether to draw the top part of the HUD.""" self._can_draw_top_icons = can_draw_top_icons def drawing_top_icons(self) -> bool: # whether we're drawing any top icons currently return bool(self._set_speed_alpha_filter.x > 1e-2) def _update_state(self) -> None: """Update HUD state based on car state and controls state.""" sm = ui_state.sm if sm.recv_frame["carState"] < ui_state.started_frame: self.is_cruise_set = False self.set_speed = SET_SPEED_NA self.speed = 0.0 return controls_state = sm['controlsState'] car_state = sm['carState'] v_cruise_cluster = car_state.vCruiseCluster set_speed = ( controls_state.vCruiseDEPRECATED if v_cruise_cluster == 0.0 else v_cruise_cluster ) engaged = sm['selfdriveState'].enabled if (set_speed != self.set_speed and engaged) or (engaged and not self._engaged): self._set_speed_changed_time = rl.get_time() self._engaged = engaged self.set_speed = set_speed self.is_cruise_set = 0 < self.set_speed < SET_SPEED_NA self.is_cruise_available = self.set_speed != -1 v_ego_cluster = car_state.vEgoCluster self.v_ego_cluster_seen = self.v_ego_cluster_seen or v_ego_cluster != 0.0 v_ego = v_ego_cluster if self.v_ego_cluster_seen else car_state.vEgo speed_conversion = CV.MS_TO_KPH if ui_state.is_metric else CV.MS_TO_MPH self.speed = max(0.0, v_ego * speed_conversion) def _render(self, rect: rl.Rectangle) -> None: """Render HUD elements to the screen.""" if ui_state.sm['controlsState'].lateralControlState.which() != 'angleState': self._torque_bar.render(rect) if self.is_cruise_set: self._draw_set_speed(rect) self._draw_steering_wheel(rect) def _draw_steering_wheel(self, rect: rl.Rectangle) -> None: wheel_txt = self._txt_wheel_critical if self._show_wheel_critical else self._txt_wheel if self._show_wheel_critical: self._wheel_alpha_filter.update(255) self._wheel_y_filter.update(0) else: if ui_state.status == UIStatus.DISENGAGED: self._wheel_alpha_filter.update(0) self._wheel_y_filter.update(wheel_txt.height / 2) else: self._wheel_alpha_filter.update(255 * 0.9) self._wheel_y_filter.update(0) # pos pos_x = int(rect.x + 21 + wheel_txt.width / 2) pos_y = int(rect.y + rect.height - 14 - wheel_txt.height / 2 + self._wheel_y_filter.x) rotation = -ui_state.sm['carState'].steeringAngleDeg turn_intent_margin = 25 self._turn_intent.render(rl.Rectangle( pos_x - wheel_txt.width / 2 - turn_intent_margin, pos_y - wheel_txt.height / 2 - turn_intent_margin, wheel_txt.width + turn_intent_margin * 2, wheel_txt.height + turn_intent_margin * 2, )) src_rect = rl.Rectangle(0, 0, wheel_txt.width, wheel_txt.height) dest_rect = rl.Rectangle(pos_x, pos_y, wheel_txt.width, wheel_txt.height) origin = (wheel_txt.width / 2, wheel_txt.height / 2) # color and draw color = rl.Color(255, 255, 255, int(self._wheel_alpha_filter.x)) rl.draw_texture_pro(wheel_txt, src_rect, dest_rect, origin, rotation, color) if self._show_wheel_critical: # Draw exclamation point icon EXCLAMATION_POINT_SPACING = 10 exclamation_pos_x = pos_x - self._txt_exclamation_point.width / 2 + wheel_txt.width / 2 + EXCLAMATION_POINT_SPACING exclamation_pos_y = pos_y - self._txt_exclamation_point.height / 2 rl.draw_texture(self._txt_exclamation_point, int(exclamation_pos_x), int(exclamation_pos_y), rl.WHITE) def _draw_set_speed(self, rect: rl.Rectangle) -> None: """Draw the MAX speed indicator box.""" alpha = self._set_speed_alpha_filter.update(0 < rl.get_time() - self._set_speed_changed_time < SET_SPEED_PERSISTENCE and self._can_draw_top_icons and self._engaged) if alpha < 1e-2: return x = rect.x y = rect.y # draw drop shadow circle_radius = 162 // 2 rl.draw_circle_gradient(int(x + circle_radius), int(y + circle_radius), circle_radius, rl.Color(0, 0, 0, int(255 / 2 * alpha)), rl.BLANK) set_speed_color = rl.Color(255, 255, 255, int(255 * 0.9 * alpha)) max_color = rl.Color(255, 255, 255, int(255 * 0.9 * alpha)) set_speed = self.set_speed if self.is_cruise_set and not ui_state.is_metric: set_speed *= KM_TO_MILE set_speed_text = CRUISE_DISABLED_CHAR if not self.is_cruise_set else str(round(set_speed)) rl.draw_text_ex( self._font_display, set_speed_text, rl.Vector2(x + 13 + 4, y + 3 - 8 - 3 + 4), FONT_SIZES.set_speed, 0, set_speed_color, ) max_text = tr("MAX") rl.draw_text_ex( self._font_semi_bold, max_text, rl.Vector2(x + 25, y + FONT_SIZES.set_speed - 7 + 4), FONT_SIZES.max_speed, 0, max_color, ) def _draw_current_speed(self, rect: rl.Rectangle) -> None: """Draw the current vehicle speed and unit.""" speed_text = str(round(self.speed)) speed_text_size = measure_text_cached(self._font_bold, speed_text, FONT_SIZES.current_speed) speed_pos = rl.Vector2(rect.x + rect.width / 2 - speed_text_size.x / 2, 180 - speed_text_size.y / 2) rl.draw_text_ex(self._font_bold, speed_text, speed_pos, FONT_SIZES.current_speed, 0, COLORS.WHITE) unit_text = tr("km/h") if ui_state.is_metric else tr("mph") unit_text_size = measure_text_cached(self._font_medium, unit_text, FONT_SIZES.speed_unit) unit_pos = rl.Vector2(rect.x + rect.width / 2 - unit_text_size.x / 2, 290 - unit_text_size.y / 2) rl.draw_text_ex(self._font_medium, unit_text, unit_pos, FONT_SIZES.speed_unit, 0, COLORS.WHITE_TRANSLUCENT)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/hud_renderer.py", "license": "MIT License", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/model_renderer.py
import colorsys import numpy as np import pyray as rl from cereal import messaging, car from dataclasses import dataclass, field from openpilot.common.params import Params from openpilot.common.filter_simple import FirstOrderFilter from openpilot.selfdrive.locationd.calibrationd import HEIGHT_INIT from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus from openpilot.selfdrive.ui.mici.onroad import blend_colors from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient from openpilot.system.ui.widgets import Widget CLIP_MARGIN = 500 MIN_DRAW_DISTANCE = 10.0 MAX_DRAW_DISTANCE = 100.0 THROTTLE_COLORS = [ rl.Color(13, 248, 122, 102), # HSLF(148/360, 0.94, 0.51, 0.4) rl.Color(114, 255, 92, 89), # HSLF(112/360, 1.0, 0.68, 0.35) rl.Color(114, 255, 92, 0), # HSLF(112/360, 1.0, 0.68, 0.0) ] NO_THROTTLE_COLORS = [ rl.Color(242, 242, 242, 102), # HSLF(148/360, 0.0, 0.95, 0.4) rl.Color(242, 242, 242, 89), # HSLF(112/360, 0.0, 0.95, 0.35) rl.Color(242, 242, 242, 0), # HSLF(112/360, 0.0, 0.95, 0.0) ] LANE_LINE_COLORS = { UIStatus.DISENGAGED: rl.Color(200, 200, 200, 255), UIStatus.OVERRIDE: rl.Color(255, 255, 255, 255), UIStatus.ENGAGED: rl.Color(0, 255, 64, 255), } @dataclass class ModelPoints: raw_points: np.ndarray = field(default_factory=lambda: np.empty((0, 3), dtype=np.float32)) projected_points: np.ndarray = field(default_factory=lambda: np.empty((0, 2), dtype=np.float32)) @dataclass class LeadVehicle: glow: list[float] = field(default_factory=list) chevron: list[float] = field(default_factory=list) fill_alpha: int = 0 class ModelRenderer(Widget): def __init__(self): super().__init__() self._longitudinal_control = False self._experimental_mode = False self._blend_filter = FirstOrderFilter(1.0, 0.25, 1 / gui_app.target_fps) self._prev_allow_throttle = True self._lane_line_probs = np.zeros(4, dtype=np.float32) self._road_edge_stds = np.zeros(2, dtype=np.float32) self._lead_vehicles = [LeadVehicle(), LeadVehicle()] self._path_offset_z = HEIGHT_INIT[0] # Initialize ModelPoints objects self._path = ModelPoints() self._lane_lines = [ModelPoints() for _ in range(4)] self._road_edges = [ModelPoints() for _ in range(2)] self._acceleration_x = np.empty((0,), dtype=np.float32) self._acceleration_x_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) self._acceleration_x_filter2 = FirstOrderFilter(0.0, 1, 1 / gui_app.target_fps) self._torque_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) self._ll_color_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) # Transform matrix (3x3 for car space to screen space) self._car_space_transform = np.zeros((3, 3), dtype=np.float32) self._transform_dirty = True self._clip_region = None self._exp_gradient = Gradient( start=(0.0, 1.0), # Bottom of path end=(0.0, 0.0), # Top of path colors=[], stops=[], ) # Get longitudinal control setting from car parameters if car_params := Params().get("CarParams"): cp = messaging.log_from_bytes(car_params, car.CarParams) self._longitudinal_control = cp.openpilotLongitudinalControl def set_transform(self, transform: np.ndarray): self._car_space_transform = transform.astype(np.float32) self._transform_dirty = True def _render(self, rect: rl.Rectangle): sm = ui_state.sm self._torque_filter.update(-ui_state.sm['carOutput'].actuatorsOutput.torque) # Check if data is up-to-date if (sm.recv_frame["liveCalibration"] < ui_state.started_frame or sm.recv_frame["modelV2"] < ui_state.started_frame): return # Set up clipping region self._clip_region = rl.Rectangle( rect.x - CLIP_MARGIN, rect.y - CLIP_MARGIN, rect.width + 2 * CLIP_MARGIN, rect.height + 2 * CLIP_MARGIN ) # Update state self._experimental_mode = sm['selfdriveState'].experimentalMode live_calib = sm['liveCalibration'] self._path_offset_z = live_calib.height[0] if live_calib.height else HEIGHT_INIT[0] if sm.updated['carParams']: self._longitudinal_control = sm['carParams'].openpilotLongitudinalControl model = sm['modelV2'] radar_state = sm['radarState'] if sm.valid['radarState'] else None lead_one = radar_state.leadOne if radar_state else None render_lead_indicator = self._longitudinal_control and radar_state is not None # Update model data when needed model_updated = sm.updated['modelV2'] if model_updated or sm.updated['radarState'] or self._transform_dirty: if model_updated: self._update_raw_points(model) path_x_array = self._path.raw_points[:, 0] if path_x_array.size == 0: return self._update_model(lead_one, path_x_array) if render_lead_indicator: self._update_leads(radar_state, path_x_array) self._transform_dirty = False # Draw elements (hide when disengaged) if ui_state.status != UIStatus.DISENGAGED: self._draw_lane_lines() self._draw_path(sm) # if render_lead_indicator and radar_state: # self._draw_lead_indicator() def _update_raw_points(self, model): """Update raw 3D points from model data""" self._path.raw_points = np.array([model.position.x, model.position.y, model.position.z], dtype=np.float32).T for i, lane_line in enumerate(model.laneLines): self._lane_lines[i].raw_points = np.array([lane_line.x, lane_line.y, lane_line.z], dtype=np.float32).T for i, road_edge in enumerate(model.roadEdges): self._road_edges[i].raw_points = np.array([road_edge.x, road_edge.y, road_edge.z], dtype=np.float32).T self._lane_line_probs = np.array(model.laneLineProbs, dtype=np.float32) self._road_edge_stds = np.array(model.roadEdgeStds, dtype=np.float32) self._acceleration_x = np.array(model.acceleration.x, dtype=np.float32) def _update_leads(self, radar_state, path_x_array): """Update positions of lead vehicles""" self._lead_vehicles = [LeadVehicle(), LeadVehicle()] leads = [radar_state.leadOne, radar_state.leadTwo] for i, lead_data in enumerate(leads): if lead_data and lead_data.status: d_rel, y_rel, v_rel = lead_data.dRel, lead_data.yRel, lead_data.vRel idx = self._get_path_length_idx(path_x_array, d_rel) # Get z-coordinate from path at the lead vehicle position z = self._path.raw_points[idx, 2] if idx < len(self._path.raw_points) else 0.0 point = self._map_to_screen(d_rel, -y_rel, z + self._path_offset_z) if point: self._lead_vehicles[i] = self._update_lead_vehicle(d_rel, v_rel, point, self._rect) def _update_model(self, lead, path_x_array): """Update model visualization data based on model message""" max_distance = np.clip(path_x_array[-1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE) max_idx = self._get_path_length_idx(self._lane_lines[0].raw_points[:, 0], max_distance) # Update lane lines using raw points line_width_factor = 0.12 for i, lane_line in enumerate(self._lane_lines): if i in (1, 2): line_width_factor = 0.16 lane_line.projected_points = self._map_line_to_polygon( lane_line.raw_points, line_width_factor * self._lane_line_probs[i], 0.0, max_idx ) # Update road edges using raw points for road_edge in self._road_edges: road_edge.projected_points = self._map_line_to_polygon(road_edge.raw_points, line_width_factor, 0.0, max_idx) # Update path using raw points if lead and lead.status: lead_d = lead.dRel * 2.0 max_distance = np.clip(lead_d - min(lead_d * 0.35, 10.0), 0.0, max_distance) soon_acceleration = self._acceleration_x[len(self._acceleration_x) // 4] if len(self._acceleration_x) > 0 else 0 self._acceleration_x_filter.update(soon_acceleration) self._acceleration_x_filter2.update(soon_acceleration) # make path width wider/thinner when initially braking/accelerating if self._experimental_mode and False: high_pass_acceleration = self._acceleration_x_filter.x - self._acceleration_x_filter2.x y_off = np.interp(high_pass_acceleration, [-1, 0, 1], [0.9 * 2, 0.9, 0.9 / 2]) else: y_off = 0.9 max_idx = self._get_path_length_idx(path_x_array, max_distance) self._path.projected_points = self._map_line_to_polygon( self._path.raw_points, y_off, self._path_offset_z, max_idx, allow_invert=False ) self._update_experimental_gradient() def _update_experimental_gradient(self): """Pre-calculate experimental mode gradient colors""" if not self._experimental_mode: return max_len = min(len(self._path.projected_points) // 2, len(self._acceleration_x)) segment_colors = [] gradient_stops = [] i = 0 while i < max_len: # Some points (screen space) are out of frame (rect space) track_y = self._path.projected_points[i][1] if track_y < self._rect.y or track_y > (self._rect.y + self._rect.height): i += 1 continue # Calculate color based on acceleration (0 is bottom, 1 is top) lin_grad_point = 1 - (track_y - self._rect.y) / self._rect.height # speed up: 120, slow down: 0 path_hue = np.clip(60 + self._acceleration_x[i] * 35, 0, 120) saturation = min(abs(self._acceleration_x[i] * 1.5), 1) lightness = np.interp(saturation, [0.0, 1.0], [0.95, 0.62]) alpha = np.interp(lin_grad_point, [0.75 / 2.0, 0.75], [0.4, 0.0]) # Use HSL to RGB conversion color = self._hsla_to_color(path_hue / 360.0, saturation, lightness, alpha) gradient_stops.append(lin_grad_point) segment_colors.append(color) # Skip a point, unless next is last i += 1 + (1 if (i + 2) < max_len else 0) # Store the gradient in the path object self._exp_gradient.colors = segment_colors self._exp_gradient.stops = gradient_stops def _update_lead_vehicle(self, d_rel, v_rel, point, rect): speed_buff, lead_buff = 10.0, 40.0 # Calculate fill alpha fill_alpha = 0 if d_rel < lead_buff: fill_alpha = 255 * (1.0 - (d_rel / lead_buff)) if v_rel < 0: fill_alpha += 255 * (-1 * (v_rel / speed_buff)) fill_alpha = min(fill_alpha, 255) # Calculate size and position sz = np.clip((25 * 30) / (d_rel / 3 + 30), 15.0, 30.0) * 1 x = np.clip(point[0], 0.0, rect.width - sz / 2) y = min(point[1], rect.height - sz * 0.6) g_xo = sz / 5 g_yo = sz / 10 glow = [(x + (sz * 1.35) + g_xo, y + sz + g_yo), (x, y - g_yo), (x - (sz * 1.35) - g_xo, y + sz + g_yo)] chevron = [(x + (sz * 1.25), y + sz), (x, y), (x - (sz * 1.25), y + sz)] return LeadVehicle(glow=glow, chevron=chevron, fill_alpha=int(fill_alpha)) def _get_ll_color(self, prob: float, adjacent: bool, left: bool): alpha = np.clip(prob, 0.0, 0.7) if adjacent: _base_color = LANE_LINE_COLORS.get(ui_state.status, LANE_LINE_COLORS[UIStatus.DISENGAGED]) color = rl.Color(_base_color.r, _base_color.g, _base_color.b, int(alpha * 255)) # turn adjacent lls orange if torque is high torque = self._torque_filter.x high_torque = abs(torque) > 0.6 if high_torque and (left == (torque > 0)): color = blend_colors( color, rl.Color(255, 115, 0, int(alpha * 255)), # orange np.interp(abs(torque), [0.6, 0.8], [0.0, 1.0]) ) else: color = rl.Color(255, 255, 255, int(alpha * 255)) if ui_state.status == UIStatus.DISENGAGED: color = rl.Color(0, 0, 0, int(alpha * 255)) return color def _draw_lane_lines(self): """Draw lane lines and road edges""" """Two closest lines should be green (lane line or road edges)""" for i, lane_line in enumerate(self._lane_lines): if lane_line.projected_points.size == 0: continue color = self._get_ll_color(float(self._lane_line_probs[i]), i in (1, 2), i in (0, 1)) draw_polygon(self._rect, lane_line.projected_points, color) for i, road_edge in enumerate(self._road_edges): if road_edge.projected_points.size == 0: continue # if closest lane lines are not confident, make road edges green color = self._get_ll_color(float(1.0 - self._road_edge_stds[i]), float(self._lane_line_probs[i + 1]) < 0.25, i == 0) draw_polygon(self._rect, road_edge.projected_points, color) def _draw_path(self, sm): """Draw path with dynamic coloring based on mode and throttle state.""" if not self._path.projected_points.size: return allow_throttle = sm['longitudinalPlan'].allowThrottle or not self._longitudinal_control self._blend_filter.update(int(allow_throttle)) if self._experimental_mode: # Draw with acceleration coloring if ui_state.status == UIStatus.DISENGAGED: draw_polygon(self._rect, self._path.projected_points, rl.Color(0, 0, 0, 90)) elif len(self._exp_gradient.colors) > 1: draw_polygon(self._rect, self._path.projected_points, gradient=self._exp_gradient) else: draw_polygon(self._rect, self._path.projected_points, rl.Color(255, 255, 255, 30)) else: # Blend throttle/no throttle colors based on transition blend_factor = round(self._blend_filter.x * 100) / 100 blended_colors = self._blend_colors(NO_THROTTLE_COLORS, THROTTLE_COLORS, blend_factor) gradient = Gradient( start=(0.0, 1.0), # Bottom of path end=(0.0, 0.0), # Top of path colors=blended_colors, stops=[0.0, 0.5, 1.0], ) if ui_state.status == UIStatus.DISENGAGED: draw_polygon(self._rect, self._path.projected_points, rl.Color(0, 0, 0, 90)) else: draw_polygon(self._rect, self._path.projected_points, gradient=gradient) def _draw_lead_indicator(self): # Draw lead vehicles if available for lead in self._lead_vehicles: if not lead.glow or not lead.chevron: continue rl.draw_triangle_fan(lead.glow, len(lead.glow), rl.Color(218, 202, 37, 255)) rl.draw_triangle_fan(lead.chevron, len(lead.chevron), rl.Color(201, 34, 49, lead.fill_alpha)) @staticmethod def _get_path_length_idx(pos_x_array: np.ndarray, path_height: float) -> int: """Get the index corresponding to the given path height""" if len(pos_x_array) == 0: return 0 indices = np.where(pos_x_array <= path_height)[0] return indices[-1] if indices.size > 0 else 0 def _map_to_screen(self, in_x, in_y, in_z): """Project a point in car space to screen space""" input_pt = np.array([in_x, in_y, in_z]) pt = self._car_space_transform @ input_pt if abs(pt[2]) < 1e-6: return None x, y = pt[0] / pt[2], pt[1] / pt[2] clip = self._clip_region if not (clip.x <= x <= clip.x + clip.width and clip.y <= y <= clip.y + clip.height): return None return (x, y) def _map_line_to_polygon(self, line: np.ndarray, y_off: float, z_off: float, max_idx: int, allow_invert: bool = True) -> np.ndarray: """Convert 3D line to 2D polygon for rendering.""" if line.shape[0] == 0: return np.empty((0, 2), dtype=np.float32) # Slice points and filter non-negative x-coordinates points = line[:max_idx + 1] points = points[points[:, 0] >= 0] if points.shape[0] == 0: return np.empty((0, 2), dtype=np.float32) N = points.shape[0] # Generate left and right 3D points in one array using broadcasting offsets = np.array([[0, -y_off, z_off], [0, y_off, z_off]], dtype=np.float32) points_3d = points[None, :, :] + offsets[:, None, :] # Shape: 2xNx3 points_3d = points_3d.reshape(2 * N, 3) # Shape: (2*N)x3 # Transform all points to projected space in one operation proj = self._car_space_transform @ points_3d.T # Shape: 3x(2*N) proj = proj.reshape(3, 2, N) left_proj = proj[:, 0, :] right_proj = proj[:, 1, :] # Filter points where z is sufficiently large valid_proj = (np.abs(left_proj[2]) >= 1e-6) & (np.abs(right_proj[2]) >= 1e-6) if not np.any(valid_proj): return np.empty((0, 2), dtype=np.float32) # Compute screen coordinates left_screen = left_proj[:2, valid_proj] / left_proj[2, valid_proj][None, :] right_screen = right_proj[:2, valid_proj] / right_proj[2, valid_proj][None, :] # Define clip region bounds clip = self._clip_region x_min, x_max = clip.x, clip.x + clip.width y_min, y_max = clip.y, clip.y + clip.height # Filter points within clip region left_in_clip = ( (left_screen[0] >= x_min) & (left_screen[0] <= x_max) & (left_screen[1] >= y_min) & (left_screen[1] <= y_max) ) right_in_clip = ( (right_screen[0] >= x_min) & (right_screen[0] <= x_max) & (right_screen[1] >= y_min) & (right_screen[1] <= y_max) ) both_in_clip = left_in_clip & right_in_clip if not np.any(both_in_clip): return np.empty((0, 2), dtype=np.float32) # Select valid and clipped points left_screen = left_screen[:, both_in_clip] right_screen = right_screen[:, both_in_clip] # Handle Y-coordinate inversion on hills if not allow_invert and left_screen.shape[1] > 1: y = left_screen[1, :] # y-coordinates keep = y == np.minimum.accumulate(y) if not np.any(keep): return np.empty((0, 2), dtype=np.float32) left_screen = left_screen[:, keep] right_screen = right_screen[:, keep] return np.vstack((left_screen.T, right_screen[:, ::-1].T)).astype(np.float32) @staticmethod def _hsla_to_color(h, s, l, a): rgb = colorsys.hls_to_rgb(h, l, s) return rl.Color( int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255), int(a * 255) ) @staticmethod def _blend_colors(begin_colors, end_colors, t): if t >= 1.0: return end_colors if t <= 0.0: return begin_colors inv_t = 1.0 - t return [rl.Color( int(inv_t * start.r + t * end.r), int(inv_t * start.g + t * end.g), int(inv_t * start.b + t * end.b), int(inv_t * start.a + t * end.a) ) for start, end in zip(begin_colors, end_colors, strict=True)]
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/model_renderer.py", "license": "MIT License", "lines": 382, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/onroad/torque_bar.py
import math import time from functools import wraps from collections import OrderedDict import numpy as np import pyray as rl from opendbc.car import ACCELERATION_DUE_TO_GRAVITY from openpilot.selfdrive.ui.mici.onroad import blend_colors from openpilot.selfdrive.ui.ui_state import ui_state, UIStatus from openpilot.system.ui.lib.application import gui_app from openpilot.system.ui.lib.shader_polygon import draw_polygon, Gradient from openpilot.system.ui.widgets import Widget from openpilot.common.filter_simple import FirstOrderFilter # TODO: arc_bar_pts doesn't consider rounded end caps part of the angle span TORQUE_ANGLE_SPAN = 12.7 DEBUG = False def quantized_lru_cache(maxsize=128): def decorator(func): cache = OrderedDict() @wraps(func) def wrapper(cx, cy, r_mid, thickness, a0_deg, a1_deg, **kwargs): # Quantize inputs: balanced for smoothness vs cache effectiveness key = (round(cx), round(cy), round(r_mid), round(thickness), # 1px precision for smoother height transitions round(a0_deg * 10) / 10, # 0.1° precision for smoother angle transitions round(a1_deg * 10) / 10, tuple(sorted(kwargs.items()))) if key in cache: cache.move_to_end(key) else: if len(cache) >= maxsize: cache.popitem(last=False) result = func(cx, cy, r_mid, thickness, a0_deg, a1_deg, **kwargs) cache[key] = result return cache[key] return wrapper return decorator @quantized_lru_cache(maxsize=256) def arc_bar_pts(cx: float, cy: float, r_mid: float, thickness: float, a0_deg: float, a1_deg: float, *, max_points: int = 100, cap_segs: int = 10, cap_radius: float = 7, px_per_seg: float = 2.0) -> np.ndarray: """Return Nx2 np.float32 points for a single closed polygon (rounded thick arc).""" def get_cap(left: bool, a_deg: float): # end cap at a1: center (a1), sweep a1→a1+180 (skip endpoints to avoid dupes) # quarter arc (outer corner) at a1 with fixed pixel radius cap_radius nx, ny = math.cos(math.radians(a_deg)), math.sin(math.radians(a_deg)) # outward normal tx, ty = -ny, nx # tangent (CCW) mx, my = cx + nx * r_mid, cy + ny * r_mid # mid-point at a1 if DEBUG: rl.draw_circle(int(mx), int(my), 4, rl.PURPLE) ex = mx + nx * (half - cap_radius) ey = my + ny * (half - cap_radius) if DEBUG: rl.draw_circle(int(ex), int(ey), 2, rl.WHITE) # sweep 90° in the local (t,n) frame: from outer edge toward inside if not left: alpha = np.deg2rad(np.linspace(90, 0, cap_segs + 2))[1:-1] else: alpha = np.deg2rad(np.linspace(180, 90, cap_segs + 2))[1:-1] cap_end = np.c_[ex + np.cos(alpha) * cap_radius * tx + np.sin(alpha) * cap_radius * nx, ey + np.cos(alpha) * cap_radius * ty + np.sin(alpha) * cap_radius * ny] # bottom quarter (inner corner) at a1 ex2 = mx + nx * (-half + cap_radius) ey2 = my + ny * (-half + cap_radius) if DEBUG: rl.draw_circle(int(ex2), int(ey2), 2, rl.WHITE) if not left: alpha2 = np.deg2rad(np.linspace(0, -90, cap_segs + 1))[:-1] # include 0 once, exclude -90 else: alpha2 = np.deg2rad(np.linspace(90 - 90 - 90, 0 - 90 - 90, cap_segs + 1))[:-1] cap_end_bot = np.c_[ex2 + np.cos(alpha2) * cap_radius * tx + np.sin(alpha2) * cap_radius * nx, ey2 + np.cos(alpha2) * cap_radius * ty + np.sin(alpha2) * cap_radius * ny] # append to the top quarter if not left: cap_end = np.vstack((cap_end, cap_end_bot)) else: cap_end = np.vstack((cap_end_bot, cap_end)) return cap_end if a1_deg < a0_deg: a0_deg, a1_deg = a1_deg, a0_deg half = thickness * 0.5 cap_radius = min(cap_radius, half) span = max(1e-3, a1_deg - a0_deg) # pick arc segment count from arc length, clamp to shader points[] budget arc_len = r_mid * math.radians(span) arc_segs = max(6, int(arc_len / px_per_seg)) max_arc = (max_points - (4 * cap_segs + 3)) // 2 arc_segs = max(6, min(arc_segs, max_arc)) # outer arc a0→a1 ang_o = np.deg2rad(np.linspace(a0_deg, a1_deg, arc_segs + 1)) outer = np.c_[cx + np.cos(ang_o) * (r_mid + half), cy + np.sin(ang_o) * (r_mid + half)] # end cap at a1 cap_end = get_cap(False, a1_deg) # inner arc a1→a0 ang_i = np.deg2rad(np.linspace(a1_deg, a0_deg, arc_segs + 1)) inner = np.c_[cx + np.cos(ang_i) * (r_mid - half), cy + np.sin(ang_i) * (r_mid - half)] # start cap at a0 cap_start = get_cap(True, a0_deg) pts = np.vstack((outer, cap_end, inner, cap_start, outer[:1])).astype(np.float32) # Rotate to start from middle of cap for proper triangulation pts = np.roll(pts, cap_segs, axis=0) if DEBUG: n = len(pts) idx = int(time.monotonic() * 12) % max(1, n) # speed: 12 pts/sec for i, (x, y) in enumerate(pts): j = (i - idx) % n # rotate the gradient t = j / n color = rl.Color(255, int(255 * (1 - t)), int(255 * t), 255) rl.draw_circle(int(x), int(y), 2, color) return pts class TorqueBar(Widget): def __init__(self, demo: bool = False): super().__init__() self._demo = demo self._torque_filter = FirstOrderFilter(0, 0.1, 1 / gui_app.target_fps) self._torque_line_alpha_filter = FirstOrderFilter(0.0, 0.1, 1 / gui_app.target_fps) def update_filter(self, value: float): """Update the torque filter value (for demo mode).""" self._torque_filter.update(value) def _update_state(self): if self._demo: return # torque line if ui_state.sm['controlsState'].lateralControlState.which() == 'angleState': controls_state = ui_state.sm['controlsState'] car_state = ui_state.sm['carState'] live_parameters = ui_state.sm['liveParameters'] lateral_acceleration = controls_state.curvature * car_state.vEgo ** 2 - live_parameters.roll * ACCELERATION_DUE_TO_GRAVITY # TODO: pull from carparams max_lateral_acceleration = 3 # from selfdrived actual_lateral_accel = controls_state.curvature * car_state.vEgo ** 2 desired_lateral_accel = controls_state.desiredCurvature * car_state.vEgo ** 2 accel_diff = (desired_lateral_accel - actual_lateral_accel) self._torque_filter.update(min(max(lateral_acceleration / max_lateral_acceleration + accel_diff, -1), 1)) else: self._torque_filter.update(-ui_state.sm['carOutput'].actuatorsOutput.torque) def _render(self, rect: rl.Rectangle) -> None: # adjust y pos with torque torque_line_offset = np.interp(abs(self._torque_filter.x), [0.5, 1], [22, 26]) torque_line_height = np.interp(abs(self._torque_filter.x), [0.5, 1], [14, 56]) # animate alpha and angle span if not self._demo: self._torque_line_alpha_filter.update(ui_state.status != UIStatus.DISENGAGED) else: self._torque_line_alpha_filter.update(1.0) torque_line_bg_alpha = np.interp(abs(self._torque_filter.x), [0.5, 1.0], [0.25, 0.5]) torque_line_bg_color = rl.Color(255, 255, 255, int(255 * torque_line_bg_alpha * self._torque_line_alpha_filter.x)) if ui_state.status != UIStatus.ENGAGED and not self._demo: torque_line_bg_color = rl.Color(255, 255, 255, int(255 * 0.15 * self._torque_line_alpha_filter.x)) # draw curved line polygon torque bar torque_line_radius = 1200 top_angle = -90 torque_bg_angle_span = self._torque_line_alpha_filter.x * TORQUE_ANGLE_SPAN torque_start_angle = top_angle - torque_bg_angle_span / 2 torque_end_angle = top_angle + torque_bg_angle_span / 2 # centerline radius & center (you already have these values) mid_r = torque_line_radius + torque_line_height / 2 cx = rect.x + rect.width / 2 + 8 # offset 8px to right of camera feed cy = rect.y + rect.height + torque_line_radius - torque_line_offset # draw bg torque indicator line bg_pts = arc_bar_pts(cx, cy, mid_r, torque_line_height, torque_start_angle, torque_end_angle) draw_polygon(rect, bg_pts, color=torque_line_bg_color) # draw torque indicator line a0s = top_angle a1s = a0s + torque_bg_angle_span / 2 * self._torque_filter.x sl_pts = arc_bar_pts(cx, cy, mid_r, torque_line_height, a0s, a1s) # draw beautiful gradient from center to 65% of the bg torque bar width start_grad_pt = cx / rect.width if self._torque_filter.x < 0: end_grad_pt = (cx * (1 - 0.65) + (min(bg_pts[:, 0]) * 0.65)) / rect.width else: end_grad_pt = (cx * (1 - 0.65) + (max(bg_pts[:, 0]) * 0.65)) / rect.width # fade to orange as we approach max torque start_color = blend_colors( rl.Color(255, 255, 255, int(255 * 0.9 * self._torque_line_alpha_filter.x)), rl.Color(255, 200, 0, int(255 * self._torque_line_alpha_filter.x)), # yellow max(0, abs(self._torque_filter.x) - 0.75) * 4, ) end_color = blend_colors( rl.Color(255, 255, 255, int(255 * 0.9 * self._torque_line_alpha_filter.x)), rl.Color(255, 115, 0, int(255 * self._torque_line_alpha_filter.x)), # orange max(0, abs(self._torque_filter.x) - 0.75) * 4, ) if ui_state.status != UIStatus.ENGAGED and not self._demo: start_color = end_color = rl.Color(255, 255, 255, int(255 * 0.35 * self._torque_line_alpha_filter.x)) gradient = Gradient( start=(start_grad_pt, 0), end=(end_grad_pt, 0), colors=[ start_color, end_color, ], stops=[0.0, 1.0], ) draw_polygon(rect, sl_pts, gradient=gradient) # draw center torque bar dot if abs(self._torque_filter.x) < 0.5: dot_y = self._rect.y + self._rect.height - torque_line_offset - torque_line_height / 2 rl.draw_circle(int(cx), int(dot_y), 10 // 2, rl.Color(182, 182, 182, int(255 * 0.9 * self._torque_line_alpha_filter.x)))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/onroad/torque_bar.py", "license": "MIT License", "lines": 205, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/widgets/button.py
import math import pyray as rl from typing import Union from enum import Enum from collections.abc import Callable from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.label import UnifiedLabel from openpilot.system.ui.widgets.scroller import DO_ZOOM from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos from openpilot.common.filter_simple import BounceFilter try: from openpilot.common.params import Params except ImportError: Params = None SCROLLING_SPEED_PX_S = 50 COMPLICATION_SIZE = 36 LABEL_COLOR = rl.Color(255, 255, 255, int(255 * 0.9)) COMPLICATION_GREY = rl.Color(0xAA, 0xAA, 0xAA, 255) PRESSED_SCALE = 1.15 if DO_ZOOM else 1.07 class ScrollState(Enum): PRE_SCROLL = 0 SCROLLING = 1 POST_SCROLL = 2 class BigCircleButton(Widget): def __init__(self, icon: str, red: bool = False, icon_size: tuple[int, int] = (64, 53), icon_offset: tuple[int, int] = (0, 0)): super().__init__() self._red = red self._icon_offset = icon_offset # State self.set_rect(rl.Rectangle(0, 0, 180, 180)) self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) self._click_delay = 0.075 # Icons self._txt_icon = gui_app.texture(icon, *icon_size) self._txt_btn_disabled_bg = gui_app.texture("icons_mici/buttons/button_circle_disabled.png", 180, 180) self._txt_btn_bg = gui_app.texture("icons_mici/buttons/button_circle.png", 180, 180) self._txt_btn_pressed_bg = gui_app.texture("icons_mici/buttons/button_circle_pressed.png", 180, 180) self._txt_btn_red_bg = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) self._txt_btn_red_pressed_bg = gui_app.texture("icons_mici/buttons/button_circle_red_pressed.png", 180, 180) def _draw_content(self, btn_y: float): # draw icon icon_color = rl.Color(255, 255, 255, int(255 * 0.9)) if self.enabled else rl.Color(255, 255, 255, int(255 * 0.35)) rl.draw_texture_ex(self._txt_icon, (self._rect.x + (self._rect.width - self._txt_icon.width) / 2 + self._icon_offset[0], btn_y + (self._rect.height - self._txt_icon.height) / 2 + self._icon_offset[1]), 0, 1.0, icon_color) def _render(self, _): # draw background txt_bg = self._txt_btn_bg if not self._red else self._txt_btn_red_bg if not self.enabled: txt_bg = self._txt_btn_disabled_bg elif self.is_pressed: txt_bg = self._txt_btn_pressed_bg if not self._red else self._txt_btn_red_pressed_bg scale = self._scale_filter.update(PRESSED_SCALE if self.is_pressed else 1.0) btn_x = self._rect.x + (self._rect.width * (1 - scale)) / 2 btn_y = self._rect.y + (self._rect.height * (1 - scale)) / 2 rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) self._draw_content(btn_y) class BigCircleToggle(BigCircleButton): def __init__(self, icon: str, toggle_callback: Callable | None = None, icon_size: tuple[int, int] = (64, 53), icon_offset: tuple[int, int] = (0, 0)): super().__init__(icon, False, icon_size=icon_size, icon_offset=icon_offset) self._toggle_callback = toggle_callback # State self._checked = False # Icons self._txt_toggle_enabled = gui_app.texture("icons_mici/buttons/toggle_dot_enabled.png", 66, 66) self._txt_toggle_disabled = gui_app.texture("icons_mici/buttons/toggle_dot_disabled.png", 66, 66) def set_checked(self, checked: bool): self._checked = checked def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) self._checked = not self._checked if self._toggle_callback: self._toggle_callback(self._checked) def _draw_content(self, btn_y: float): super()._draw_content(btn_y) # draw status icon rl.draw_texture_ex(self._txt_toggle_enabled if self._checked else self._txt_toggle_disabled, (self._rect.x + (self._rect.width - self._txt_toggle_enabled.width) / 2, btn_y + 5), 0, 1.0, rl.WHITE) class BigButton(Widget): LABEL_HORIZONTAL_PADDING = 40 LABEL_VERTICAL_PADDING = 23 # visually matches 30 in figma """A lightweight stand-in for the Qt BigButton, drawn & updated each frame.""" def __init__(self, text: str, value: str = "", icon: Union[str, rl.Texture] = "", icon_size: tuple[int, int] = (64, 64), scroll: bool = False): super().__init__() self.set_rect(rl.Rectangle(0, 0, 402, 180)) self.text = text self.value = value self._icon_size = icon_size self._scroll = scroll self.set_icon(icon) self._scale_filter = BounceFilter(1.0, 0.1, 1 / gui_app.target_fps) self._click_delay = 0.075 self._shake_start: float | None = None self._rotate_icon_t: float | None = None self._label = UnifiedLabel(text, font_size=self._get_label_font_size(), font_weight=FontWeight.BOLD, text_color=LABEL_COLOR, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM, scroll=scroll, line_height=0.9) self._sub_label = UnifiedLabel(value, font_size=COMPLICATION_SIZE, font_weight=FontWeight.ROMAN, text_color=COMPLICATION_GREY, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) self._update_label_layout() self._load_images() def set_icon(self, icon: Union[str, rl.Texture]): self._txt_icon = gui_app.texture(icon, *self._icon_size) if isinstance(icon, str) and len(icon) else icon def set_rotate_icon(self, rotate: bool): if rotate and self._rotate_icon_t is not None: return self._rotate_icon_t = rl.get_time() if rotate else None def _load_images(self): self._txt_default_bg = gui_app.texture("icons_mici/buttons/button_rectangle.png", 402, 180) self._txt_pressed_bg = gui_app.texture("icons_mici/buttons/button_rectangle_pressed.png", 402, 180) self._txt_disabled_bg = gui_app.texture("icons_mici/buttons/button_rectangle_disabled.png", 402, 180) def _width_hint(self) -> int: # Single line if scrolling, so hide behind icon if exists icon_size = self._icon_size[0] if self._txt_icon and self._scroll and self.value else 0 return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2 - icon_size) def _get_label_font_size(self): if len(self.text) <= 18: return 48 else: return 42 def _update_label_layout(self): self._label.set_font_size(self._get_label_font_size()) if self.value: self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_TOP) else: self._label.set_alignment_vertical(rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) def set_text(self, text: str): self.text = text self._label.set_text(text) self._update_label_layout() def set_value(self, value: str): self.value = value self._sub_label.set_text(value) self._update_label_layout() def get_value(self) -> str: return self.value def get_text(self): return self.text def trigger_shake(self): self._shake_start = rl.get_time() @property def _shake_offset(self) -> float: SHAKE_DURATION = 0.5 SHAKE_AMPLITUDE = 24.0 SHAKE_FREQUENCY = 32.0 t = rl.get_time() - (self._shake_start or 0.0) if t > SHAKE_DURATION: return 0.0 decay = 1.0 - t / SHAKE_DURATION return decay * SHAKE_AMPLITUDE * math.sin(t * SHAKE_FREQUENCY) def set_position(self, x: float, y: float) -> None: super().set_position(x + self._shake_offset, y) def _handle_background(self) -> tuple[rl.Texture, float, float, float]: # draw _txt_default_bg txt_bg = self._txt_default_bg if not self.enabled: txt_bg = self._txt_disabled_bg elif self.is_pressed: txt_bg = self._txt_pressed_bg scale = self._scale_filter.update(PRESSED_SCALE if self.is_pressed else 1.0) btn_x = self._rect.x + (self._rect.width * (1 - scale)) / 2 btn_y = self._rect.y + (self._rect.height * (1 - scale)) / 2 return txt_bg, btn_x, btn_y, scale def _draw_content(self, btn_y: float): # LABEL ------------------------------------------------------------------ label_x = self._rect.x + self.LABEL_HORIZONTAL_PADDING label_color = LABEL_COLOR if self.enabled else rl.Color(255, 255, 255, int(255 * 0.35)) self._label.set_color(label_color) label_rect = rl.Rectangle(label_x, btn_y + self.LABEL_VERTICAL_PADDING, self._width_hint(), self._rect.height - self.LABEL_VERTICAL_PADDING * 2) self._label.render(label_rect) if self.value: label_y = btn_y + self.LABEL_VERTICAL_PADDING + self._label.get_content_height(self._width_hint()) sub_label_height = btn_y + self._rect.height - self.LABEL_VERTICAL_PADDING - label_y sub_label_rect = rl.Rectangle(label_x, label_y, self._width_hint(), sub_label_height) self._sub_label.render(sub_label_rect) # ICON ------------------------------------------------------------------- if self._txt_icon: rotation = 0 if self._rotate_icon_t is not None: rotation = (rl.get_time() - self._rotate_icon_t) * 180 # draw top right with 30px padding x = self._rect.x + self._rect.width - 30 - self._txt_icon.width / 2 y = btn_y + 30 + self._txt_icon.height / 2 source_rec = rl.Rectangle(0, 0, self._txt_icon.width, self._txt_icon.height) dest_rec = rl.Rectangle(x, y, self._txt_icon.width, self._txt_icon.height) origin = rl.Vector2(self._txt_icon.width / 2, self._txt_icon.height / 2) rl.draw_texture_pro(self._txt_icon, source_rec, dest_rec, origin, rotation, rl.Color(255, 255, 255, int(255 * 0.9))) def _render(self, _): txt_bg, btn_x, btn_y, scale = self._handle_background() if self._scroll: # draw black background since images are transparent scaled_rect = rl.Rectangle(btn_x, btn_y, self._rect.width * scale, self._rect.height * scale) rl.draw_rectangle_rounded(scaled_rect, 0.4, 7, rl.Color(0, 0, 0, int(255 * 0.5))) self._draw_content(btn_y) rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) else: rl.draw_texture_ex(txt_bg, (btn_x, btn_y), 0, scale, rl.WHITE) self._draw_content(btn_y) class BigToggle(BigButton): def __init__(self, text: str, value: str = "", initial_state: bool = False, toggle_callback: Callable | None = None): super().__init__(text, value, "") self._checked = initial_state self._toggle_callback = toggle_callback def _load_images(self): super()._load_images() self._txt_enabled_toggle = gui_app.texture("icons_mici/buttons/toggle_pill_enabled.png", 84, 66) self._txt_disabled_toggle = gui_app.texture("icons_mici/buttons/toggle_pill_disabled.png", 84, 66) def set_checked(self, checked: bool): self._checked = checked def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) self._checked = not self._checked if self._toggle_callback: self._toggle_callback(self._checked) def _draw_pill(self, x: float, y: float, checked: bool): # draw toggle icon top right if checked: rl.draw_texture_ex(self._txt_enabled_toggle, (x, y), 0, 1.0, rl.WHITE) else: rl.draw_texture_ex(self._txt_disabled_toggle, (x, y), 0, 1.0, rl.WHITE) def _draw_content(self, btn_y: float): super()._draw_content(btn_y) x = self._rect.x + self._rect.width - self._txt_enabled_toggle.width y = btn_y self._draw_pill(x, y, self._checked) class BigMultiToggle(BigToggle): def __init__(self, text: str, options: list[str], toggle_callback: Callable | None = None, select_callback: Callable | None = None): super().__init__(text, "", toggle_callback=toggle_callback) assert len(options) > 0 self._options = options self._select_callback = select_callback self.set_value(self._options[0]) def _width_hint(self) -> int: return int(self._rect.width - self.LABEL_HORIZONTAL_PADDING * 2 - self._txt_enabled_toggle.width) def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) cur_idx = self._options.index(self.value) new_idx = (cur_idx + 1) % len(self._options) self.set_value(self._options[new_idx]) if self._select_callback: self._select_callback(self.value) def _draw_content(self, btn_y: float): # don't draw pill from BigToggle BigButton._draw_content(self, btn_y) checked_idx = self._options.index(self.value) x = self._rect.x + self._rect.width - self._txt_enabled_toggle.width y = btn_y for i in range(len(self._options)): self._draw_pill(x, y, checked_idx == i) y += 35 class BigMultiParamToggle(BigMultiToggle): def __init__(self, text: str, param: str, options: list[str], toggle_callback: Callable | None = None, select_callback: Callable | None = None): super().__init__(text, options, toggle_callback, select_callback) self._param = param self._params = Params() self._load_value() def _load_value(self): self.set_value(self._options[self._params.get(self._param) or 0]) def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) new_idx = self._options.index(self.value) self._params.put_nonblocking(self._param, new_idx) class BigParamControl(BigToggle): def __init__(self, text: str, param: str, toggle_callback: Callable | None = None): super().__init__(text, "", toggle_callback=toggle_callback) self.param = param self.params = Params() self.set_checked(self.params.get_bool(self.param, False)) def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) self.params.put_bool(self.param, self._checked) def refresh(self): self.set_checked(self.params.get_bool(self.param, False)) # TODO: param control base class class BigCircleParamControl(BigCircleToggle): def __init__(self, icon: str, param: str, toggle_callback: Callable | None = None, icon_size: tuple[int, int] = (64, 53), icon_offset: tuple[int, int] = (0, 0)): super().__init__(icon, toggle_callback, icon_size=icon_size, icon_offset=icon_offset) self._param = param self.params = Params() self.set_checked(self.params.get_bool(self._param, False)) def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) self.params.put_bool(self._param, self._checked) def refresh(self): self.set_checked(self.params.get_bool(self._param, False))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/widgets/button.py", "license": "MIT License", "lines": 290, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/widgets/dialog.py
import abc import math import pyray as rl from typing import Union from collections.abc import Callable from openpilot.system.ui.widgets.nav_widget import NavWidget from openpilot.system.ui.widgets.label import UnifiedLabel, gui_label from openpilot.system.ui.widgets.mici_keyboard import MiciKeyboard from openpilot.system.ui.lib.text_measure import measure_text_cached from openpilot.system.ui.lib.wrap_text import wrap_text from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos from openpilot.system.ui.widgets.slider import RedBigSlider, BigSlider from openpilot.common.filter_simple import FirstOrderFilter from openpilot.selfdrive.ui.mici.widgets.button import BigButton DEBUG = False PADDING = 20 class BigDialogBase(NavWidget, abc.ABC): def __init__(self): super().__init__() self.set_rect(rl.Rectangle(0, 0, gui_app.width, gui_app.height)) class BigDialog(BigDialogBase): def __init__(self, title: str, description: str): super().__init__() self._title = title self._description = description def _render(self, _): super()._render(_) # draw title # TODO: we desperately need layouts # TODO: coming up with these numbers manually is a pain and not scalable # TODO: no clue what any of these numbers mean. VBox and HBox would remove all of this shite max_width = self._rect.width - PADDING * 2 title_wrapped = '\n'.join(wrap_text(gui_app.font(FontWeight.BOLD), self._title, 50, int(max_width))) title_size = measure_text_cached(gui_app.font(FontWeight.BOLD), title_wrapped, 50) text_x_offset = 0 title_rect = rl.Rectangle(int(self._rect.x + text_x_offset + PADDING), int(self._rect.y + PADDING), int(max_width), int(title_size.y)) gui_label(title_rect, title_wrapped, 50, font_weight=FontWeight.BOLD, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) # draw description desc_wrapped = '\n'.join(wrap_text(gui_app.font(FontWeight.MEDIUM), self._description, 30, int(max_width))) desc_size = measure_text_cached(gui_app.font(FontWeight.MEDIUM), desc_wrapped, 30) desc_rect = rl.Rectangle(int(self._rect.x + text_x_offset + PADDING), int(self._rect.y + self._rect.height / 3), int(max_width), int(desc_size.y)) # TODO: text align doesn't seem to work properly with newlines gui_label(desc_rect, desc_wrapped, 30, font_weight=FontWeight.MEDIUM, alignment=rl.GuiTextAlignment.TEXT_ALIGN_CENTER) class BigConfirmationDialogV2(BigDialogBase): def __init__(self, title: str, icon: str, red: bool = False, exit_on_confirm: bool = True, confirm_callback: Callable | None = None): super().__init__() self._confirm_callback = confirm_callback self._exit_on_confirm = exit_on_confirm icon_txt = gui_app.texture(icon, 64, 53) self._slider: BigSlider | RedBigSlider if red: self._slider = RedBigSlider(title, icon_txt, confirm_callback=self._on_confirm) else: self._slider = BigSlider(title, icon_txt, confirm_callback=self._on_confirm) self._slider.set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + NavWidget def _on_confirm(self): if self._exit_on_confirm: self.dismiss(self._confirm_callback) elif self._confirm_callback: self._confirm_callback() def _update_state(self): super()._update_state() if self.is_dismissing and not self._slider.confirmed: self._slider.reset() def _render(self, _): self._slider.render(self._rect) class BigInputDialog(BigDialogBase): BACK_TOUCH_AREA_PERCENTAGE = 0.2 BACKSPACE_RATE = 25 # hz TEXT_INPUT_SIZE = 35 def __init__(self, hint: str, default_text: str = "", minimum_length: int = 1, confirm_callback: Callable[[str], None] | None = None): super().__init__() self._hint_label = UnifiedLabel(hint, font_size=35, text_color=rl.Color(255, 255, 255, int(255 * 0.35)), font_weight=FontWeight.MEDIUM) self._keyboard = MiciKeyboard() self._keyboard.set_text(default_text) self._keyboard.set_enabled(lambda: self.enabled and not self.is_dismissing) # for nav stack + NavWidget self._minimum_length = minimum_length self._backspace_held_time: float | None = None self._backspace_img = gui_app.texture("icons_mici/settings/keyboard/backspace.png", 42, 36) self._backspace_img_alpha = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) self._enter_img = gui_app.texture("icons_mici/settings/keyboard/enter.png", 76, 62) self._enter_disabled_img = gui_app.texture("icons_mici/settings/keyboard/enter_disabled.png", 76, 62) self._enter_img_alpha = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) # rects for top buttons self._top_left_button_rect = rl.Rectangle(0, 0, 0, 0) self._top_right_button_rect = rl.Rectangle(0, 0, 0, 0) def confirm_callback_wrapper(): text = self._keyboard.text() self.dismiss((lambda: confirm_callback(text)) if confirm_callback else None) self._confirm_callback = confirm_callback_wrapper def _update_state(self): super()._update_state() if self.is_dismissing: self._backspace_held_time = None return last_mouse_event = gui_app.last_mouse_event if last_mouse_event.left_down and rl.check_collision_point_rec(last_mouse_event.pos, self._top_right_button_rect) and self._backspace_img_alpha.x > 1: if self._backspace_held_time is None: self._backspace_held_time = rl.get_time() if rl.get_time() - self._backspace_held_time > 0.5: if gui_app.frame % round(gui_app.target_fps / self.BACKSPACE_RATE) == 0: self._keyboard.backspace() else: self._backspace_held_time = None def _render(self, _): # draw current text so far below everything. text floats left but always stays in view text = self._keyboard.text() candidate_char = self._keyboard.get_candidate_character() text_size = measure_text_cached(gui_app.font(FontWeight.ROMAN), text + candidate_char or self._hint_label.text, self.TEXT_INPUT_SIZE) bg_block_margin = 5 text_x = PADDING / 2 + self._enter_img.width + PADDING text_field_rect = rl.Rectangle(text_x, int(self._rect.y + PADDING) - bg_block_margin, int(self._rect.width - text_x * 2), int(text_size.y)) # draw text input # push text left with a gradient on left side if too long if text_size.x > text_field_rect.width: text_x -= text_size.x - text_field_rect.width rl.begin_scissor_mode(int(text_field_rect.x), int(text_field_rect.y), int(text_field_rect.width), int(text_field_rect.height)) rl.draw_text_ex(gui_app.font(FontWeight.ROMAN), text, rl.Vector2(text_x, text_field_rect.y), self.TEXT_INPUT_SIZE, 0, rl.WHITE) # draw grayed out character user is hovering over if candidate_char: candidate_char_size = measure_text_cached(gui_app.font(FontWeight.ROMAN), candidate_char, self.TEXT_INPUT_SIZE) rl.draw_text_ex(gui_app.font(FontWeight.ROMAN), candidate_char, rl.Vector2(min(text_x + text_size.x, text_field_rect.x + text_field_rect.width) - candidate_char_size.x, text_field_rect.y), self.TEXT_INPUT_SIZE, 0, rl.Color(255, 255, 255, 128)) rl.end_scissor_mode() # draw gradient on left side to indicate more text if text_size.x > text_field_rect.width: rl.draw_rectangle_gradient_h(int(text_field_rect.x), int(text_field_rect.y), 80, int(text_field_rect.height), rl.BLACK, rl.BLANK) # draw cursor blink_alpha = (math.sin(rl.get_time() * 6) + 1) / 2 if text: cursor_x = min(text_x + text_size.x + 3, text_field_rect.x + text_field_rect.width) else: cursor_x = text_field_rect.x - 6 rl.draw_rectangle_rounded(rl.Rectangle(int(cursor_x), int(text_field_rect.y), 4, int(text_size.y)), 1, 4, rl.Color(255, 255, 255, int(255 * blink_alpha))) # draw backspace icon with nice fade self._backspace_img_alpha.update(255 * bool(text)) if self._backspace_img_alpha.x > 1: color = rl.Color(255, 255, 255, int(self._backspace_img_alpha.x)) rl.draw_texture(self._backspace_img, int(self._rect.width - self._backspace_img.width - 27), int(self._rect.y + 14), color) if not text and self._hint_label.text and not candidate_char: # draw description if no text entered yet and not drawing candidate char hint_rect = rl.Rectangle(text_field_rect.x, text_field_rect.y, self._rect.width - text_field_rect.x - PADDING, text_field_rect.height) self._hint_label.render(hint_rect) # TODO: move to update state # make rect take up entire area so it's easier to click self._top_left_button_rect = rl.Rectangle(self._rect.x, self._rect.y, text_field_rect.x, self._rect.height - self._keyboard.get_keyboard_height()) self._top_right_button_rect = rl.Rectangle(text_field_rect.x + text_field_rect.width, self._rect.y, self._rect.width - (text_field_rect.x + text_field_rect.width), self._top_left_button_rect.height) # draw enter button self._enter_img_alpha.update(255 if len(text) >= self._minimum_length else 0) color = rl.Color(255, 255, 255, int(self._enter_img_alpha.x)) rl.draw_texture(self._enter_img, int(self._rect.x + PADDING / 2), int(self._rect.y), color) color = rl.Color(255, 255, 255, 255 - int(self._enter_img_alpha.x)) rl.draw_texture(self._enter_disabled_img, int(self._rect.x + PADDING / 2), int(self._rect.y), color) # keyboard goes over everything self._keyboard.render(self._rect) # draw debugging rect bounds if DEBUG: rl.draw_rectangle_lines_ex(text_field_rect, 1, rl.Color(100, 100, 100, 255)) rl.draw_rectangle_lines_ex(self._top_right_button_rect, 1, rl.Color(0, 255, 0, 255)) rl.draw_rectangle_lines_ex(self._top_left_button_rect, 1, rl.Color(0, 255, 0, 255)) def _handle_mouse_press(self, mouse_pos: MousePos): super()._handle_mouse_press(mouse_pos) # TODO: need to track where press was so enter and back can activate on release rather than press # or turn into icon widgets :eyes_open: if self.is_dismissing: return # handle backspace icon click if rl.check_collision_point_rec(mouse_pos, self._top_right_button_rect) and self._backspace_img_alpha.x > 254: self._keyboard.backspace() elif rl.check_collision_point_rec(mouse_pos, self._top_left_button_rect) and self._enter_img_alpha.x > 254: # handle enter icon click self._confirm_callback() class BigDialogButton(BigButton): def __init__(self, text: str, value: str = "", icon: Union[str, rl.Texture] = "", description: str = ""): super().__init__(text, value, icon) self._description = description def _handle_mouse_release(self, mouse_pos: MousePos): super()._handle_mouse_release(mouse_pos) dlg = BigDialog(self.text, self._description) gui_app.push_widget(dlg)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/widgets/dialog.py", "license": "MIT License", "lines": 205, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/mici/widgets/pairing_dialog.py
import pyray as rl import qrcode import numpy as np import time from openpilot.common.api import Api from openpilot.common.swaglog import cloudlog from openpilot.common.params import Params from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.system.ui.widgets.nav_widget import NavWidget from openpilot.system.ui.lib.application import FontWeight, gui_app from openpilot.system.ui.widgets.label import MiciLabel class PairingDialog(NavWidget): """Dialog for device pairing with QR code.""" QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds def __init__(self): super().__init__() self._params = Params() self._qr_texture: rl.Texture | None = None self._last_qr_generation = float("-inf") self._txt_pair = gui_app.texture("icons_mici/settings/device/pair.png", 33, 60) self._pair_label = MiciLabel("pair with comma connect", 48, font_weight=FontWeight.BOLD, color=rl.Color(255, 255, 255, int(255 * 0.9)), line_height=40, wrap_text=True) def _get_pairing_url(self) -> str: try: dongle_id = self._params.get("DongleId") or "" token = Api(dongle_id).get_token({'pair': True}) except Exception as e: cloudlog.warning(f"Failed to get pairing token: {e}") token = "" return f"https://connect.comma.ai/?pair={token}" def _generate_qr_code(self) -> None: try: qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=0) qr.add_data(self._get_pairing_url()) qr.make(fit=True) pil_img = qr.make_image(fill_color="white", back_color="black").convert('RGBA') img_array = np.array(pil_img, dtype=np.uint8) if self._qr_texture and self._qr_texture.id != 0: rl.unload_texture(self._qr_texture) rl_image = rl.Image() rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) rl_image.width = pil_img.width rl_image.height = pil_img.height rl_image.mipmaps = 1 rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 self._qr_texture = rl.load_texture_from_image(rl_image) except Exception as e: cloudlog.warning(f"QR code generation failed: {e}") self._qr_texture = None def _check_qr_refresh(self) -> None: current_time = time.monotonic() if current_time - self._last_qr_generation >= self.QR_REFRESH_INTERVAL: self._generate_qr_code() self._last_qr_generation = current_time def _update_state(self): super()._update_state() if ui_state.prime_state.is_paired() and not self.is_dismissing: self.dismiss() def _render(self, rect: rl.Rectangle): self._check_qr_refresh() self._render_qr_code() label_x = self._rect.x + 8 + self._rect.height + 24 self._pair_label.set_width(int(self._rect.width - label_x)) self._pair_label.set_position(label_x, self._rect.y + 16) self._pair_label.render() rl.draw_texture_ex(self._txt_pair, rl.Vector2(label_x, self._rect.y + self._rect.height - self._txt_pair.height - 16), 0.0, 1.0, rl.Color(255, 255, 255, int(255 * 0.35))) def _render_qr_code(self) -> None: if not self._qr_texture: error_font = gui_app.font(FontWeight.BOLD) rl.draw_text_ex( error_font, "QR Code Error", rl.Vector2(self._rect.x + 20, self._rect.y + self._rect.height // 2 - 15), 30, 0.0, rl.RED ) return scale = self._rect.height / self._qr_texture.height pos = rl.Vector2(self._rect.x + 8, self._rect.y) rl.draw_texture_ex(self._qr_texture, pos, 0.0, scale, rl.WHITE) def __del__(self): if self._qr_texture and self._qr_texture.id != 0: rl.unload_texture(self._qr_texture) if __name__ == "__main__": gui_app.init_window("pairing device") pairing = PairingDialog() gui_app.push_widget(pairing) try: for _ in gui_app.render(): pass finally: del pairing
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/mici/widgets/pairing_dialog.py", "license": "MIT License", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/lib/scroll_panel2.py
import os import math import pyray as rl from collections.abc import Callable from enum import Enum from typing import cast from openpilot.system.ui.lib.application import gui_app, MouseEvent from openpilot.system.hardware import TICI from collections import deque MIN_VELOCITY = 10 # px/s, changes from auto scroll to steady state MIN_VELOCITY_FOR_CLICKING = 2 * 60 # px/s, accepts clicks while auto scrolling below this velocity MIN_DRAG_PIXELS = 12 AUTO_SCROLL_TC_SNAP = 0.025 AUTO_SCROLL_TC = 0.18 BOUNCE_RETURN_RATE = 10.0 REJECT_DECELERATION_FACTOR = 3 MAX_SPEED = 10000.0 # px/s DEBUG = os.getenv("DEBUG_SCROLL", "0") == "1" # from https://ariya.io/2011/10/flick-list-with-its-momentum-scrolling-and-deceleration class ScrollState(Enum): STEADY = 0 PRESSED = 1 MANUAL_SCROLL = 2 AUTO_SCROLL = 3 class GuiScrollPanel2: def __init__(self, horizontal: bool = True, handle_out_of_bounds: bool = True) -> None: self._horizontal = horizontal self._handle_out_of_bounds = handle_out_of_bounds self._AUTO_SCROLL_TC = AUTO_SCROLL_TC_SNAP if not self._handle_out_of_bounds else AUTO_SCROLL_TC self._state = ScrollState.STEADY self._offset: rl.Vector2 = rl.Vector2(0, 0) self._initial_click_event: MouseEvent | None = None self._previous_mouse_event: MouseEvent | None = None self._velocity = 0.0 # pixels per second self._velocity_buffer: deque[float] = deque(maxlen=12 if TICI else 6) self._enabled: bool | Callable[[], bool] = True def set_enabled(self, enabled: bool | Callable[[], bool]) -> None: self._enabled = enabled @property def enabled(self) -> bool: return self._enabled() if callable(self._enabled) else self._enabled def update(self, bounds: rl.Rectangle, content_size: float) -> float: if DEBUG: print('Old state:', self._state) bounds_size = bounds.width if self._horizontal else bounds.height for mouse_event in gui_app.mouse_events: self._handle_mouse_event(mouse_event, bounds, bounds_size, content_size) self._previous_mouse_event = mouse_event self._update_state(bounds_size, content_size) if DEBUG: print('Velocity:', self._velocity) print('Offset X:', self._offset.x, 'Y:', self._offset.y) print('New state:', self._state) print() return self.get_offset() def _get_offset_bounds(self, bounds_size: float, content_size: float) -> tuple[float, float]: """Returns (max_offset, min_offset) for the given bounds and content size.""" return 0.0, min(0.0, bounds_size - content_size) def _update_state(self, bounds_size: float, content_size: float) -> None: """Runs per render frame, independent of mouse events. Updates auto-scrolling state and velocity.""" max_offset, min_offset = self._get_offset_bounds(bounds_size, content_size) if self._state == ScrollState.STEADY: # if we find ourselves out of bounds, scroll back in (from external layout dimension changes, etc.) if self.get_offset() > max_offset or self.get_offset() < min_offset: self._state = ScrollState.AUTO_SCROLL elif self._state == ScrollState.AUTO_SCROLL: # simple exponential return if out of bounds out_of_bounds = self.get_offset() > max_offset or self.get_offset() < min_offset if out_of_bounds and self._handle_out_of_bounds: target = max_offset if self.get_offset() > max_offset else min_offset dt = rl.get_frame_time() or 1e-6 factor = 1.0 - math.exp(-BOUNCE_RETURN_RATE * dt) dist = target - self.get_offset() self.set_offset(self.get_offset() + dist * factor) # ease toward the edge self._velocity *= (1.0 - factor) # damp any leftover fling # Steady once we are close enough to the target if abs(dist) < 1 and abs(self._velocity) < MIN_VELOCITY: self.set_offset(target) self._velocity = 0.0 self._state = ScrollState.STEADY elif abs(self._velocity) < MIN_VELOCITY: self._velocity = 0.0 self._state = ScrollState.STEADY # Update the offset based on the current velocity dt = rl.get_frame_time() self.set_offset(self.get_offset() + self._velocity * dt) # Adjust the offset based on velocity alpha = 1 - (dt / (self._AUTO_SCROLL_TC + dt)) self._velocity *= alpha def _handle_mouse_event(self, mouse_event: MouseEvent, bounds: rl.Rectangle, bounds_size: float, content_size: float) -> None: max_offset, min_offset = self._get_offset_bounds(bounds_size, content_size) # simple exponential return if out of bounds out_of_bounds = self.get_offset() > max_offset or self.get_offset() < min_offset if DEBUG: print('Mouse event:', mouse_event) mouse_pos = self._get_mouse_pos(mouse_event) if not self.enabled: # Reset state if not enabled self._state = ScrollState.STEADY self._velocity = 0.0 self._velocity_buffer.clear() elif self._state == ScrollState.STEADY: if rl.check_collision_point_rec(mouse_event.pos, bounds): if mouse_event.left_pressed: self._state = ScrollState.PRESSED self._initial_click_event = mouse_event elif self._state == ScrollState.PRESSED: initial_click_pos = self._get_mouse_pos(cast(MouseEvent, self._initial_click_event)) diff = abs(mouse_pos - initial_click_pos) if mouse_event.left_released: # Special handling for down and up clicks across two frames # TODO: not sure what that means or if it's accurate anymore if out_of_bounds: self._state = ScrollState.AUTO_SCROLL elif diff <= MIN_DRAG_PIXELS: self._state = ScrollState.STEADY else: self._state = ScrollState.MANUAL_SCROLL elif diff > MIN_DRAG_PIXELS: self._state = ScrollState.MANUAL_SCROLL elif self._state == ScrollState.MANUAL_SCROLL: if mouse_event.left_released: # Touch rejection: when releasing finger after swiping and stopping, panel # reports a few erroneous touch events with high velocity, try to ignore. # If velocity decelerates very quickly, assume user doesn't intend to auto scroll high_decel = False if len(self._velocity_buffer) > 2: # We limit max to first half since final few velocities can surpass first few abs_velocity_buffer = [(abs(v), i) for i, v in enumerate(self._velocity_buffer)] max_idx = max(abs_velocity_buffer[:len(abs_velocity_buffer) // 2])[1] min_idx = min(abs_velocity_buffer)[1] if DEBUG: print('min_idx:', min_idx, 'max_idx:', max_idx, 'velocity buffer:', self._velocity_buffer) if (abs(self._velocity_buffer[min_idx]) * REJECT_DECELERATION_FACTOR < abs(self._velocity_buffer[max_idx]) and max_idx < min_idx): if DEBUG: print('deceleration too high, going to STEADY') high_decel = True # If final velocity is below some threshold, switch to steady state too low_speed = abs(self._velocity) <= MIN_VELOCITY_FOR_CLICKING * 1.5 # plus some margin if out_of_bounds or not (high_decel or low_speed): self._state = ScrollState.AUTO_SCROLL else: # TODO: we should just set velocity and let autoscroll go back to steady. delays one frame but who cares self._velocity = 0.0 self._state = ScrollState.STEADY self._velocity_buffer.clear() else: # Update velocity for when we release the mouse button. # Do not update velocity on the same frame the mouse was released previous_mouse_pos = self._get_mouse_pos(cast(MouseEvent, self._previous_mouse_event)) delta_x = mouse_pos - previous_mouse_pos delta_t = max((mouse_event.t - cast(MouseEvent, self._previous_mouse_event).t), 1e-6) self._velocity = delta_x / delta_t self._velocity = max(-MAX_SPEED, min(MAX_SPEED, self._velocity)) self._velocity_buffer.append(self._velocity) # rubber-banding: reduce dragging when out of bounds # TODO: this drifts when dragging quickly if out_of_bounds: delta_x *= 0.25 # Update the offset based on the mouse movement # Use internal _offset directly to preserve precision (don't round via get_offset()) # TODO: make get_offset return float current_offset = self._offset.x if self._horizontal else self._offset.y self.set_offset(current_offset + delta_x) elif self._state == ScrollState.AUTO_SCROLL: if mouse_event.left_pressed: # Decide whether to click or scroll (block click if moving too fast) if abs(self._velocity) <= MIN_VELOCITY_FOR_CLICKING: # Traveling slow enough, click self._state = ScrollState.PRESSED self._initial_click_event = mouse_event else: # Go straight into manual scrolling to block erroneous input self._state = ScrollState.MANUAL_SCROLL # Reset velocity for touch down and up events that happen in back-to-back frames self._velocity = 0.0 def _get_mouse_pos(self, mouse_event: MouseEvent) -> float: return mouse_event.pos.x if self._horizontal else mouse_event.pos.y def get_offset(self) -> float: return self._offset.x if self._horizontal else self._offset.y def set_offset(self, value: float) -> None: if self._horizontal: self._offset.x = value else: self._offset.y = value @property def state(self) -> ScrollState: return self._state def is_touch_valid(self) -> bool: # MIN_VELOCITY_FOR_CLICKING is checked in auto-scroll state return bool(self._state != ScrollState.MANUAL_SCROLL)
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/lib/scroll_panel2.py", "license": "MIT License", "lines": 192, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/mici_reset.py
#!/usr/bin/env python3 import os import sys import threading import time from enum import IntEnum import pyray as rl from openpilot.system.hardware import PC from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.slider import SmallSlider from openpilot.system.ui.widgets.button import SmallButton, FullRoundedButton from openpilot.system.ui.widgets.label import gui_label, gui_text_box USERDATA = "/dev/disk/by-partlabel/userdata" TIMEOUT = 3*60 class ResetMode(IntEnum): USER_RESET = 0 # user initiated a factory reset from openpilot RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover FORMAT = 2 # finish up a factory reset from a tool that doesn't flash an empty partition to userdata class ResetState(IntEnum): NONE = 0 RESETTING = 1 FAILED = 2 class Reset(Widget): def __init__(self, mode): super().__init__() self._mode = mode self._previous_reset_state = None self._reset_state = ResetState.NONE self._cancel_button = SmallButton("cancel") self._cancel_button.set_click_callback(gui_app.request_close) self._reboot_button = FullRoundedButton("reboot") self._reboot_button.set_click_callback(self._do_reboot) self._confirm_slider = SmallSlider("reset", self._confirm) def _do_reboot(self): if PC: return os.system("sudo reboot") def _do_erase(self): if PC: return # Removing data and formatting rm = os.system("sudo rm -rf /data/*") os.system(f"sudo umount {USERDATA}") fmt = os.system(f"yes | sudo mkfs.ext4 {USERDATA}") if rm == 0 or fmt == 0: os.system("sudo reboot") else: self._reset_state = ResetState.FAILED def start_reset(self): self._reset_state = ResetState.RESETTING threading.Timer(0.1, self._do_erase).start() def _update_state(self): if self._reset_state != self._previous_reset_state: self._previous_reset_state = self._reset_state self._timeout_st = time.monotonic() elif self._reset_state != ResetState.RESETTING and (time.monotonic() - self._timeout_st) > TIMEOUT: exit(0) def _render(self, rect: rl.Rectangle): label_rect = rl.Rectangle(rect.x + 8, rect.y + 8, rect.width, 50) gui_label(label_rect, "factory reset", 48, font_weight=FontWeight.BOLD, color=rl.Color(255, 255, 255, int(255 * 0.9))) text_rect = rl.Rectangle(rect.x + 8, rect.y + 56, rect.width - 8 * 2, rect.height - 80) gui_text_box(text_rect, self._get_body_text(), 36, font_weight=FontWeight.ROMAN, line_scale=0.9) if self._reset_state != ResetState.RESETTING: # fade out cancel button as slider is moved, set visible to prevent pressing invisible cancel self._cancel_button.set_opacity(1.0 - self._confirm_slider.slider_percentage) self._cancel_button.set_visible(self._confirm_slider.slider_percentage < 0.8) if self._mode == ResetMode.RECOVER: self._cancel_button.set_text("reboot") self._cancel_button.render(rl.Rectangle( rect.x + 8, rect.y + rect.height - self._cancel_button.rect.height, self._cancel_button.rect.width, self._cancel_button.rect.height)) elif self._mode == ResetMode.USER_RESET and self._reset_state != ResetState.FAILED: self._cancel_button.render(rl.Rectangle( rect.x + 8, rect.y + rect.height - self._cancel_button.rect.height, self._cancel_button.rect.width, self._cancel_button.rect.height)) if self._reset_state != ResetState.FAILED: self._confirm_slider.render(rl.Rectangle( rect.x + rect.width - self._confirm_slider.rect.width, rect.y + rect.height - self._confirm_slider.rect.height, self._confirm_slider.rect.width, self._confirm_slider.rect.height)) else: self._reboot_button.render(rl.Rectangle( rect.x + 8, rect.y + rect.height - self._reboot_button.rect.height, self._reboot_button.rect.width, self._reboot_button.rect.height)) def _confirm(self): self.start_reset() def _get_body_text(self): if self._reset_state == ResetState.RESETTING: return "Resetting device... This may take up to a minute." if self._reset_state == ResetState.FAILED: return "Reset failed. Reboot to try again." if self._mode == ResetMode.RECOVER: return "Unable to mount data partition. It may be corrupted." return "All content and settings will be erased." def main(): mode = ResetMode.USER_RESET if len(sys.argv) > 1: if sys.argv[1] == '--recover': mode = ResetMode.RECOVER elif sys.argv[1] == "--format": mode = ResetMode.FORMAT gui_app.init_window("System Reset") reset = Reset(mode) if mode == ResetMode.FORMAT: reset.start_reset() gui_app.push_widget(reset) for _ in gui_app.render(): pass if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/mici_reset.py", "license": "MIT License", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/mici_updater.py
#!/usr/bin/env python3 import sys import subprocess import threading import pyray as rl from enum import IntEnum from openpilot.system.hardware import HARDWARE from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.lib.wifi_manager import WifiManager from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.label import UnifiedLabel from openpilot.system.ui.widgets.button import FullRoundedButton from openpilot.system.ui.mici_setup import NetworkSetupPage, FailedPage, NetworkConnectivityMonitor class Screen(IntEnum): PROMPT = 0 WIFI = 1 PROGRESS = 2 FAILED = 3 class Updater(Widget): def __init__(self, updater_path, manifest_path): super().__init__() self.updater = updater_path self.manifest = manifest_path self.current_screen = Screen.PROMPT self.progress_value = 0 self.progress_text = "loading" self.process = None self.update_thread = None self._wifi_manager = WifiManager() self._wifi_manager.set_active(True) self._network_setup_page = NetworkSetupPage(self._wifi_manager, self._network_setup_continue_callback, self._network_setup_back_callback) self._network_setup_page.set_enabled(lambda: self.enabled) # for nav stack self._network_monitor = NetworkConnectivityMonitor() self._network_monitor.start() # Buttons self._continue_button = FullRoundedButton("continue") self._continue_button.set_click_callback(lambda: self.set_current_screen(Screen.WIFI)) self._title_label = UnifiedLabel("update required", 48, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), font_weight=FontWeight.DISPLAY) self._subtitle_label = UnifiedLabel("The download size is approximately 1GB.", 36, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), font_weight=FontWeight.ROMAN) self._update_failed_page = FailedPage(HARDWARE.reboot, self._update_failed_retry_callback, title="update failed") self._progress_title_label = UnifiedLabel("", 64, text_color=rl.Color(255, 255, 255, int(255 * 0.9)), font_weight=FontWeight.DISPLAY, line_height=0.8) self._progress_percent_label = UnifiedLabel("", 132, text_color=rl.Color(255, 255, 255, int(255 * 0.9 * 0.65)), font_weight=FontWeight.ROMAN, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_BOTTOM) def _network_setup_back_callback(self): self.set_current_screen(Screen.PROMPT) def _network_setup_continue_callback(self): self.install_update() def _update_failed_retry_callback(self): self.set_current_screen(Screen.PROMPT) def set_current_screen(self, screen: Screen): if self.current_screen != screen: if screen == Screen.PROGRESS: if self._network_setup_page: self._network_setup_page.hide_event() elif screen == Screen.WIFI: if self._network_setup_page: self._network_setup_page.show_event() elif screen == Screen.PROMPT: if self._network_setup_page: self._network_setup_page.hide_event() elif screen == Screen.FAILED: if self._network_setup_page: self._network_setup_page.hide_event() self.current_screen = screen def install_update(self): self.set_current_screen(Screen.PROGRESS) self.progress_value = 0 self.progress_text = "downloading" # Start the update process in a separate thread self.update_thread = threading.Thread(target=self._run_update_process) self.update_thread.daemon = True self.update_thread.start() def _run_update_process(self): # TODO: just import it and run in a thread without a subprocess cmd = [self.updater, "--swap", self.manifest] self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, universal_newlines=True) if self.process.stdout is not None: for line in self.process.stdout: parts = line.strip().split(":") if len(parts) == 2: self.progress_text = parts[0].lower() try: self.progress_value = int(float(parts[1])) except ValueError: pass exit_code = self.process.wait() if exit_code == 0: HARDWARE.reboot() else: self.set_current_screen(Screen.FAILED) def render_prompt_screen(self, rect: rl.Rectangle): self._title_label.render(rl.Rectangle( rect.x + 8, rect.y - 5, rect.width, 48, )) subtitle_width = rect.width - 16 subtitle_height = self._subtitle_label.get_content_height(int(subtitle_width)) self._subtitle_label.render(rl.Rectangle( rect.x + 8, rect.y + 48, subtitle_width, subtitle_height, )) self._continue_button.render(rl.Rectangle( rect.x + 8, rect.y + rect.height - self._continue_button.rect.height, self._continue_button.rect.width, self._continue_button.rect.height, )) def render_progress_screen(self, rect: rl.Rectangle): self._progress_title_label.set_text(self.progress_text.replace("_", "_\n") + "...") self._progress_title_label.render(rl.Rectangle( rect.x + 12, rect.y + 2, rect.width, self._progress_title_label.get_content_height(int(rect.width - 20)), )) self._progress_percent_label.set_text(f"{self.progress_value}%") self._progress_percent_label.render(rl.Rectangle( rect.x + 12, rect.y + 18, rect.width, rect.height, )) def _update_state(self): self._wifi_manager.process_callbacks() def _render(self, rect: rl.Rectangle): if self.current_screen == Screen.PROMPT: self.render_prompt_screen(rect) elif self.current_screen == Screen.WIFI: self._network_setup_page.set_has_internet(self._network_monitor.network_connected.is_set()) self._network_setup_page.render(rect) elif self.current_screen == Screen.PROGRESS: self.render_progress_screen(rect) elif self.current_screen == Screen.FAILED: self._update_failed_page.render(rect) def close(self): self._network_monitor.stop() def main(): if len(sys.argv) < 3: print("Usage: updater.py <updater_path> <manifest_path>") sys.exit(1) updater_path = sys.argv[1] manifest_path = sys.argv[2] try: gui_app.init_window("System Update") updater = Updater(updater_path, manifest_path) gui_app.push_widget(updater) for _ in gui_app.render(): pass updater.close() except Exception as e: print(f"Updater error: {e}") finally: gui_app.close() if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/mici_updater.py", "license": "MIT License", "lines": 167, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/tici_reset.py
#!/usr/bin/env python3 import os import sys import threading import time from enum import IntEnum import pyray as rl from openpilot.system.hardware import PC from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.button import Button, ButtonStyle from openpilot.system.ui.widgets.label import gui_label, gui_text_box USERDATA = "/dev/disk/by-partlabel/userdata" TIMEOUT = 3*60 class ResetMode(IntEnum): USER_RESET = 0 # user initiated a factory reset from openpilot RECOVER = 1 # userdata is corrupt for some reason, give a chance to recover FORMAT = 2 # finish up a factory reset from a tool that doesn't flash an empty partition to userdata class ResetState(IntEnum): NONE = 0 CONFIRM = 1 RESETTING = 2 FAILED = 3 class Reset(Widget): def __init__(self, mode): super().__init__() self._mode = mode self._previous_reset_state = None self._reset_state = ResetState.NONE self._cancel_button = Button("Cancel", gui_app.request_close) self._confirm_button = Button("Confirm", self._confirm, button_style=ButtonStyle.PRIMARY) self._reboot_button = Button("Reboot", lambda: os.system("sudo reboot")) def _do_erase(self): if PC: return # Removing data and formatting rm = os.system("sudo rm -rf /data/*") os.system(f"sudo umount {USERDATA}") fmt = os.system(f"yes | sudo mkfs.ext4 {USERDATA}") if rm == 0 or fmt == 0: os.system("sudo reboot") else: self._reset_state = ResetState.FAILED def start_reset(self): self._reset_state = ResetState.RESETTING threading.Timer(0.1, self._do_erase).start() def _update_state(self): if self._reset_state != self._previous_reset_state: self._previous_reset_state = self._reset_state self._timeout_st = time.monotonic() elif self._reset_state != ResetState.RESETTING and (time.monotonic() - self._timeout_st) > TIMEOUT: exit(0) def _render(self, _): content_rect = rl.Rectangle(45, 200, self._rect.width - 90, self._rect.height - 245) label_rect = rl.Rectangle(content_rect.x + 140, content_rect.y, content_rect.width - 280, 100 * FONT_SCALE) gui_label(label_rect, "System Reset", 100, font_weight=FontWeight.BOLD) text_rect = rl.Rectangle(content_rect.x + 140, content_rect.y + 140, content_rect.width - 280, content_rect.height - 90 - 100 * FONT_SCALE) gui_text_box(text_rect, self._get_body_text(), 90) button_height = 160 button_spacing = 50 button_top = content_rect.y + content_rect.height - button_height button_width = (content_rect.width - button_spacing) / 2.0 if self._reset_state != ResetState.RESETTING: if self._mode == ResetMode.RECOVER: self._reboot_button.render(rl.Rectangle(content_rect.x, button_top, button_width, button_height)) elif self._mode == ResetMode.USER_RESET: self._cancel_button.render(rl.Rectangle(content_rect.x, button_top, button_width, button_height)) if self._reset_state != ResetState.FAILED: self._confirm_button.render(rl.Rectangle(content_rect.x + button_width + 50, button_top, button_width, button_height)) else: self._reboot_button.render(rl.Rectangle(content_rect.x, button_top, content_rect.width, button_height)) def _confirm(self): if self._reset_state == ResetState.CONFIRM: self.start_reset() else: self._reset_state = ResetState.CONFIRM def _get_body_text(self): if self._reset_state == ResetState.CONFIRM: return "Are you sure you want to reset your device?" if self._reset_state == ResetState.RESETTING: return "Resetting device...\nThis may take up to a minute." if self._reset_state == ResetState.FAILED: return "Reset failed. Reboot to try again." if self._mode == ResetMode.RECOVER: return "Unable to mount data partition. Partition may be corrupted. Press confirm to erase and reset your device." return "System reset triggered. Press confirm to erase all content and settings. Press cancel to resume boot." def main(): mode = ResetMode.USER_RESET if len(sys.argv) > 1: if sys.argv[1] == '--recover': mode = ResetMode.RECOVER elif sys.argv[1] == "--format": mode = ResetMode.FORMAT gui_app.init_window("System Reset", 20) reset = Reset(mode) if mode == ResetMode.FORMAT: reset.start_reset() gui_app.push_widget(reset) for _ in gui_app.render(): pass if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/tici_reset.py", "license": "MIT License", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/tici_updater.py
#!/usr/bin/env python3 import sys import subprocess import threading import pyray as rl from enum import IntEnum from openpilot.system.hardware import HARDWARE from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE from openpilot.system.ui.lib.wifi_manager import WifiManager from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.button import Button, ButtonStyle from openpilot.system.ui.widgets.label import gui_text_box, gui_label from openpilot.system.ui.widgets.network import WifiManagerUI # Constants MARGIN = 50 BUTTON_HEIGHT = 160 BUTTON_WIDTH = 400 PROGRESS_BAR_HEIGHT = 72 TITLE_FONT_SIZE = 80 BODY_FONT_SIZE = 65 BACKGROUND_COLOR = rl.BLACK PROGRESS_BG_COLOR = rl.Color(41, 41, 41, 255) PROGRESS_COLOR = rl.Color(54, 77, 239, 255) class Screen(IntEnum): PROMPT = 0 WIFI = 1 PROGRESS = 2 class Updater(Widget): def __init__(self, updater_path, manifest_path): super().__init__() self.updater = updater_path self.manifest = manifest_path self.current_screen = Screen.PROMPT self.progress_value = 0 self.progress_text = "Loading..." self.show_reboot_button = False self.process = None self.update_thread = None self.wifi_manager_ui = WifiManagerUI(WifiManager()) # Buttons self._wifi_button = Button("Connect to Wi-Fi", click_callback=lambda: self.set_current_screen(Screen.WIFI)) self._install_button = Button("Install", click_callback=self.install_update, button_style=ButtonStyle.PRIMARY) self._back_button = Button("Back", click_callback=lambda: self.set_current_screen(Screen.PROMPT)) self._reboot_button = Button("Reboot", click_callback=lambda: HARDWARE.reboot()) def set_current_screen(self, screen: Screen): self.current_screen = screen def install_update(self): self.set_current_screen(Screen.PROGRESS) self.progress_value = 0 self.progress_text = "Downloading..." self.show_reboot_button = False # Start the update process in a separate thread self.update_thread = threading.Thread(target=self._run_update_process) self.update_thread.daemon = True self.update_thread.start() def _run_update_process(self): # TODO: just import it and run in a thread without a subprocess cmd = [self.updater, "--swap", self.manifest] self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, universal_newlines=True) if self.process.stdout is not None: for line in self.process.stdout: parts = line.strip().split(":") if len(parts) == 2: self.progress_text = parts[0] try: self.progress_value = int(float(parts[1])) except ValueError: pass exit_code = self.process.wait() if exit_code == 0: HARDWARE.reboot() else: self.progress_text = "Update failed" self.show_reboot_button = True def render_prompt_screen(self, rect: rl.Rectangle): # Title title_rect = rl.Rectangle(MARGIN + 50, 250, rect.width - MARGIN * 2 - 100, TITLE_FONT_SIZE * FONT_SCALE) gui_label(title_rect, "Update Required", TITLE_FONT_SIZE, font_weight=FontWeight.BOLD) # Description desc_text = ("An operating system update is required. Connect your device to Wi-Fi for the fastest update experience. " + "The download size is approximately 1GB.") desc_rect = rl.Rectangle(MARGIN + 50, 250 + TITLE_FONT_SIZE * FONT_SCALE + 75, rect.width - MARGIN * 2 - 100, BODY_FONT_SIZE * FONT_SCALE * 4) gui_text_box(desc_rect, desc_text, BODY_FONT_SIZE) # Buttons at the bottom button_y = rect.height - MARGIN - BUTTON_HEIGHT button_width = (rect.width - MARGIN * 3) // 2 # WiFi button wifi_button_rect = rl.Rectangle(MARGIN, button_y, button_width, BUTTON_HEIGHT) self._wifi_button.render(wifi_button_rect) # Install button install_button_rect = rl.Rectangle(MARGIN * 2 + button_width, button_y, button_width, BUTTON_HEIGHT) self._install_button.render(install_button_rect) def render_wifi_screen(self, rect: rl.Rectangle): # Draw the Wi-Fi manager UI wifi_rect = rl.Rectangle(rect.x + MARGIN, rect.y + MARGIN, rect.width - MARGIN * 2, rect.height - BUTTON_HEIGHT - MARGIN * 3) rl.draw_rectangle_rounded(wifi_rect, 0.035, 10, rl.Color(51, 51, 51, 255)) wifi_content_rect = rl.Rectangle(wifi_rect.x + 50, wifi_rect.y, wifi_rect.width - 100, wifi_rect.height) self.wifi_manager_ui.render(wifi_content_rect) back_button_rect = rl.Rectangle(MARGIN, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) self._back_button.render(back_button_rect) def render_progress_screen(self, rect: rl.Rectangle): title_rect = rl.Rectangle(MARGIN + 100, 330, rect.width - MARGIN * 2 - 200, 100) gui_label(title_rect, self.progress_text, 90, font_weight=FontWeight.SEMI_BOLD) # Progress bar bar_rect = rl.Rectangle(MARGIN + 100, 330 + 100 + 100, rect.width - MARGIN * 2 - 200, PROGRESS_BAR_HEIGHT) rl.draw_rectangle_rounded(bar_rect, 0.5, 10, PROGRESS_BG_COLOR) # Calculate the width of the progress chunk progress_width = (bar_rect.width * self.progress_value) / 100 if progress_width > 0: progress_rect = rl.Rectangle(bar_rect.x, bar_rect.y, progress_width, bar_rect.height) rl.draw_rectangle_rounded(progress_rect, 0.5, 10, PROGRESS_COLOR) # Show reboot button if needed if self.show_reboot_button: reboot_rect = rl.Rectangle(MARGIN + 100, rect.height - MARGIN - BUTTON_HEIGHT, BUTTON_WIDTH, BUTTON_HEIGHT) self._reboot_button.render(reboot_rect) def _render(self, rect: rl.Rectangle): if self.current_screen == Screen.PROMPT: self.render_prompt_screen(rect) elif self.current_screen == Screen.WIFI: self.render_wifi_screen(rect) elif self.current_screen == Screen.PROGRESS: self.render_progress_screen(rect) def main(): if len(sys.argv) < 3: print("Usage: updater.py <updater_path> <manifest_path>") sys.exit(1) updater_path = sys.argv[1] manifest_path = sys.argv[2] try: gui_app.init_window("System Update") gui_app.push_widget(Updater(updater_path, manifest_path)) for _ in gui_app.render(): pass finally: # Make sure we clean up even if there's an error gui_app.close() if __name__ == "__main__": main()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/tici_updater.py", "license": "MIT License", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/widgets/mici_keyboard.py
from enum import IntEnum import pyray as rl import numpy as np from openpilot.system.ui.lib.application import gui_app, FontWeight, MousePos, MouseEvent from openpilot.system.ui.lib.text_measure import measure_text_cached from openpilot.system.ui.widgets import Widget from openpilot.common.filter_simple import BounceFilter, FirstOrderFilter CHAR_FONT_SIZE = 42 CHAR_NEAR_FONT_SIZE = CHAR_FONT_SIZE * 2 SELECTED_CHAR_FONT_SIZE = 128 CHAR_CAPS_FONT_SIZE = 38 # TODO: implement this NUMBER_LAYER_SWITCH_FONT_SIZE = 24 KEYBOARD_COLUMN_PADDING = 33 KEYBOARD_ROW_PADDING = {0: 44, 1: 33, 2: 44} # TODO: 2 should be 116 with extra control keys added in KEY_TOUCH_AREA_OFFSET = 10 # px KEY_DRAG_HYSTERESIS = 5 # px KEY_MIN_ANIMATION_TIME = 0.075 # s DEBUG = False ANIMATION_SCALE = 0.65 def zip_repeat(a, b): la, lb = len(a), len(b) for i in range(max(la, lb)): yield (a[i] if i < la else a[-1], b[i] if i < lb else b[-1]) def fast_euclidean_distance(dx, dy): # https://en.wikibooks.org/wiki/Algorithms/Distance_approximations max_d, min_d = abs(dx), abs(dy) if max_d < min_d: max_d, min_d = min_d, max_d return 0.941246 * max_d + 0.41 * min_d class Key(Widget): def __init__(self, char: str, font_weight: FontWeight = FontWeight.SEMI_BOLD): super().__init__() self.char = char self._font = gui_app.font(font_weight) self._x_filter = BounceFilter(0.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) self._y_filter = BounceFilter(0.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) self._size_filter = BounceFilter(CHAR_FONT_SIZE, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) self._alpha_filter = BounceFilter(1.0, 0.075 * ANIMATION_SCALE, 1 / gui_app.target_fps) self._color = rl.Color(255, 255, 255, 255) self._position_initialized = False self.original_position = rl.Vector2(0, 0) def set_position(self, x: float, y: float, smooth: bool = True): # Smooth keys within parent rect base_y = self._parent_rect.y if self._parent_rect else 0.0 local_y = y - base_y if not self._position_initialized: self._x_filter.x = x self._y_filter.x = local_y # keep track of original position so dragging around feels consistent. also move touch area down a bit self.original_position = rl.Vector2(x, local_y + KEY_TOUCH_AREA_OFFSET) self._position_initialized = True if not smooth: self._x_filter.x = x self._y_filter.x = local_y self._rect.x = self._x_filter.update(x) self._rect.y = base_y + self._y_filter.update(local_y) def set_alpha(self, alpha: float): self._alpha_filter.update(alpha) def get_position(self) -> tuple[float, float]: return self._rect.x, self._rect.y def _update_state(self): self._color.a = min(int(255 * self._alpha_filter.x), 255) def _render(self, _): # center char at rect position text_size = measure_text_cached(self._font, self.char, self._get_font_size()) x = self._rect.x + self._rect.width / 2 - text_size.x / 2 y = self._rect.y + self._rect.height / 2 - text_size.y / 2 rl.draw_text_ex(self._font, self.char, (x, y), self._get_font_size(), 0, self._color) if DEBUG: rl.draw_circle(int(self._rect.x), int(self._rect.y), 5, rl.RED) # Debug: draw circle around key rl.draw_rectangle_lines_ex(self._rect, 2, rl.RED) def set_font_size(self, size: float): self._size_filter.update(size) def _get_font_size(self) -> int: return int(round(self._size_filter.x)) class SmallKey(Key): def __init__(self, chars: str): super().__init__(chars, FontWeight.BOLD) self._size_filter.x = NUMBER_LAYER_SWITCH_FONT_SIZE def set_font_size(self, size: float): self._size_filter.update(size * (NUMBER_LAYER_SWITCH_FONT_SIZE / CHAR_FONT_SIZE)) class IconKey(Key): def __init__(self, icon: str, vertical_align: str = "center", char: str = "", icon_size: tuple[int, int] = (38, 38)): super().__init__(char) self._icon_size = icon_size self._icon = gui_app.texture(icon, *icon_size) self._vertical_align = vertical_align def set_icon(self, icon: str, icon_size: tuple[int, int] | None = None): size = icon_size if icon_size is not None else self._icon_size self._icon = gui_app.texture(icon, *size) def _render(self, _): scale = np.interp(self._size_filter.x, [CHAR_FONT_SIZE, CHAR_NEAR_FONT_SIZE], [1, 1.5]) if self._vertical_align == "center": dest_rec = rl.Rectangle(self._rect.x + (self._rect.width - self._icon.width * scale) / 2, self._rect.y + (self._rect.height - self._icon.height * scale) / 2, self._icon.width * scale, self._icon.height * scale) src_rec = rl.Rectangle(0, 0, self._icon.width, self._icon.height) rl.draw_texture_pro(self._icon, src_rec, dest_rec, rl.Vector2(0, 0), 0, self._color) elif self._vertical_align == "bottom": dest_rec = rl.Rectangle(self._rect.x + (self._rect.width - self._icon.width * scale) / 2, self._rect.y, self._icon.width * scale, self._icon.height * scale) src_rec = rl.Rectangle(0, 0, self._icon.width, self._icon.height) rl.draw_texture_pro(self._icon, src_rec, dest_rec, rl.Vector2(0, 0), 0, self._color) if DEBUG: rl.draw_circle(int(self._rect.x), int(self._rect.y), 5, rl.RED) # Debug: draw circle around key rl.draw_rectangle_lines_ex(self._rect, 2, rl.RED) class CapsState(IntEnum): LOWER = 0 UPPER = 1 LOCK = 2 class MiciKeyboard(Widget): def __init__(self): super().__init__() lower_chars = [ "qwertyuiop", "asdfghjkl", "zxcvbnm", ] upper_chars = ["".join([char.upper() for char in row]) for row in lower_chars] special_chars = [ "1234567890", "-/:;()$&@\"", "~.,?!'#%", ] super_special_chars = [ "1234567890", "`[]{}^*+=_", "\\|<>¥€£•", ] self._lower_keys = [[Key(char) for char in row] for row in lower_chars] self._upper_keys = [[Key(char) for char in row] for row in upper_chars] self._special_keys = [[Key(char) for char in row] for row in special_chars] self._super_special_keys = [[Key(char) for char in row] for row in super_special_chars] # control keys self._space_key = IconKey("icons_mici/settings/keyboard/space.png", char=" ", vertical_align="bottom", icon_size=(43, 14)) self._caps_key = IconKey("icons_mici/settings/keyboard/caps_lower.png", icon_size=(38, 33)) # these two are in different places on some layouts self._123_key, self._123_key2 = SmallKey("123"), SmallKey("123") self._abc_key = SmallKey("abc") self._super_special_key = SmallKey("#+=") # insert control keys for keys in (self._lower_keys, self._upper_keys): keys[2].insert(0, self._caps_key) keys[2].append(self._123_key) for keys in (self._lower_keys, self._upper_keys, self._special_keys, self._super_special_keys): keys[1].append(self._space_key) for keys in (self._special_keys, self._super_special_keys): keys[2].append(self._abc_key) self._special_keys[2].insert(0, self._super_special_key) self._super_special_keys[2].insert(0, self._123_key2) # set initial keys self._current_keys: list[list[Key]] = [] self._set_keys(self._lower_keys) self._caps_state = CapsState.LOWER self._initialized = False self._load_images() self._closest_key: tuple[Key | None, float] = None, float('inf') self._selected_key_t: float | None = None # time key was initially selected self._unselect_key_t: float | None = None # time to unselect key after release self._dragging_on_keyboard = False self._text: str = "" self._bg_scale_filter = BounceFilter(1.0, 0.1 * ANIMATION_SCALE, 1 / gui_app.target_fps) self._selected_key_filter = FirstOrderFilter(0.0, 0.075 * ANIMATION_SCALE, 1 / gui_app.target_fps) def get_candidate_character(self) -> str: # return str of character about to be added to text key = self._closest_key[0] return key.char if key is not None and key.__class__ is Key and self._dragging_on_keyboard else "" def get_keyboard_height(self) -> int: return int(self._txt_bg.height) def _load_images(self): self._txt_bg = gui_app.texture("icons_mici/settings/keyboard/keyboard_background.png", 520, 170, keep_aspect_ratio=False) def _set_keys(self, keys: list[list[Key]]): # inherit previous keys' positions to fix switching animation for current_row, row in zip(self._current_keys, keys, strict=False): # not all layouts have the same number of keys for current_key, key in zip_repeat(current_row, row): # reset parent rect for new keys key.set_parent_rect(self._rect) current_pos = current_key.get_position() key.set_position(current_pos[0], current_pos[1], smooth=False) self._current_keys = keys def set_text(self, text: str): self._text = text def text(self) -> str: return self._text def _handle_mouse_event(self, mouse_event: MouseEvent) -> None: keyboard_pos_y = self._rect.y + self._rect.height - self._txt_bg.height if mouse_event.left_pressed: if mouse_event.pos.y > keyboard_pos_y: self._dragging_on_keyboard = True elif mouse_event.left_released: self._dragging_on_keyboard = False if mouse_event.left_down and self._dragging_on_keyboard: self._closest_key = self._get_closest_key() if self._selected_key_t is None: self._selected_key_t = rl.get_time() # unselect key temporarily if mouse goes above keyboard if mouse_event.pos.y <= keyboard_pos_y: self._closest_key = (None, float('inf')) if DEBUG: print('HANDLE MOUSE EVENT', mouse_event, self._closest_key[0].char if self._closest_key[0] else 'None') def _get_closest_key(self) -> tuple[Key | None, float]: closest_key: tuple[Key | None, float] = (None, float('inf')) for row in self._current_keys: for key in row: mouse_pos = gui_app.last_mouse_event.pos # approximate distance for comparison is accurate enough # use local y coords so parent widget offset (e.g. during NavWidget animate-in) doesn't affect hit testing dist = abs(key.original_position.x - mouse_pos.x) + abs(key.original_position.y - (mouse_pos.y - self._rect.y)) if dist < closest_key[1]: if self._closest_key[0] is None or key is self._closest_key[0] or dist < self._closest_key[1] - KEY_DRAG_HYSTERESIS: closest_key = (key, dist) return closest_key def _set_uppercase(self, cycle: bool): self._set_keys(self._upper_keys if cycle else self._lower_keys) if not cycle: self._caps_state = CapsState.LOWER self._caps_key.set_icon("icons_mici/settings/keyboard/caps_lower.png", icon_size=(38, 33)) else: if self._caps_state == CapsState.LOWER: self._caps_state = CapsState.UPPER self._caps_key.set_icon("icons_mici/settings/keyboard/caps_upper.png", icon_size=(38, 33)) elif self._caps_state == CapsState.UPPER: self._caps_state = CapsState.LOCK self._caps_key.set_icon("icons_mici/settings/keyboard/caps_lock.png", icon_size=(39, 38)) else: self._set_uppercase(False) def _handle_mouse_release(self, mouse_pos: MousePos): if self._closest_key[0] is not None: if self._closest_key[0] == self._caps_key: self._set_uppercase(True) elif self._closest_key[0] in (self._123_key, self._123_key2): self._set_keys(self._special_keys) elif self._closest_key[0] == self._abc_key: self._set_uppercase(False) elif self._closest_key[0] == self._super_special_key: self._set_keys(self._super_special_keys) else: self._text += self._closest_key[0].char # Reset caps state if self._caps_state == CapsState.UPPER: self._set_uppercase(False) # ensure minimum selected animation time key_selected_dt = rl.get_time() - (self._selected_key_t or 0) cur_t = rl.get_time() self._unselect_key_t = cur_t + KEY_MIN_ANIMATION_TIME if (key_selected_dt < KEY_MIN_ANIMATION_TIME) else cur_t def backspace(self): if self._text: self._text = self._text[:-1] def space(self): self._text += ' ' def _update_state(self): # update selected key filter self._selected_key_filter.update(self._closest_key[0] is not None) # unselect key after animation plays if (self._unselect_key_t is not None and rl.get_time() > self._unselect_key_t) or not self.enabled: self._closest_key = (None, float('inf')) self._unselect_key_t = None self._selected_key_t = None def _lay_out_keys(self, bg_x, bg_y, keys: list[list[Key]]): key_rect = rl.Rectangle(bg_x, bg_y, self._txt_bg.width, self._txt_bg.height) for row_idx, row in enumerate(keys): padding = KEYBOARD_ROW_PADDING[row_idx] step_y = (key_rect.height - 2 * KEYBOARD_COLUMN_PADDING) / (len(keys) - 1) for key_idx, key in enumerate(row): key_x = key_rect.x + padding + key_idx * ((key_rect.width - 2 * padding) / (len(row) - 1)) key_y = key_rect.y + KEYBOARD_COLUMN_PADDING + row_idx * step_y if self._closest_key[0] is None: key.set_alpha(1.0) key.set_font_size(CHAR_FONT_SIZE) elif key == self._closest_key[0]: # push key up with a max and inward so user can see key easier key_y = max(key_y - 120, 40) key_x += np.interp(key_x, [self._rect.x, self._rect.x + self._rect.width], [100, -100]) key.set_alpha(1.0) key.set_font_size(SELECTED_CHAR_FONT_SIZE) # draw black circle behind selected key circle_alpha = int(self._selected_key_filter.x * 225) rl.draw_circle_gradient(int(key_x + key.rect.width / 2), int(key_y + key.rect.height / 2), SELECTED_CHAR_FONT_SIZE, rl.Color(0, 0, 0, circle_alpha), rl.BLANK) else: # move other keys away from selected key a bit dx = key.original_position.x - self._closest_key[0].original_position.x dy = key.original_position.y - self._closest_key[0].original_position.y distance_from_selected_key = fast_euclidean_distance(dx, dy) inv = 1 / (distance_from_selected_key or 1.0) ux = dx * inv uy = dy * inv # NOTE: hardcode to 20 to get entire keyboard to move push_pixels = np.interp(distance_from_selected_key, [0, 250], [20, 0]) key_x += ux * push_pixels key_y += uy * push_pixels # TODO: slow enough to use an approximation or nah? also caching might work font_size = np.interp(distance_from_selected_key, [0, 150], [CHAR_NEAR_FONT_SIZE, CHAR_FONT_SIZE]) key_alpha = np.interp(distance_from_selected_key, [0, 100], [1.0, 0.35]) key.set_alpha(key_alpha) key.set_font_size(font_size) # TODO: I like the push amount, so we should clip the pos inside the keyboard rect key.set_parent_rect(self._rect) key.set_position(key_x, key_y) def _render(self, _): # draw bg bg_x = self._rect.x + (self._rect.width - self._txt_bg.width) / 2 bg_y = self._rect.y + self._rect.height - self._txt_bg.height scale = self._bg_scale_filter.update(1.0307692307692307 if self._closest_key[0] is not None else 1.0) src_rec = rl.Rectangle(0, 0, self._txt_bg.width, self._txt_bg.height) dest_rec = rl.Rectangle(self._rect.x + self._rect.width / 2 - self._txt_bg.width * scale / 2, bg_y, self._txt_bg.width * scale, self._txt_bg.height) rl.draw_texture_pro(self._txt_bg, src_rec, dest_rec, rl.Vector2(0, 0), 0.0, rl.WHITE) # draw keys if not self._initialized: for keys in (self._lower_keys, self._upper_keys, self._special_keys, self._super_special_keys): self._lay_out_keys(bg_x, bg_y, keys) self._initialized = True self._lay_out_keys(bg_x, bg_y, self._current_keys) for row in self._current_keys: for key in row: key.render()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/mici_keyboard.py", "license": "MIT License", "lines": 319, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/widgets/scroller_tici.py
import pyray as rl from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel from openpilot.system.ui.widgets import Widget ITEM_SPACING = 40 LINE_COLOR = rl.GRAY LINE_PADDING = 40 class LineSeparator(Widget): def __init__(self, height: int = 1): super().__init__() self._rect = rl.Rectangle(0, 0, 0, height) def set_parent_rect(self, parent_rect: rl.Rectangle) -> None: super().set_parent_rect(parent_rect) self._rect.width = parent_rect.width def _render(self, _): 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) class Scroller(Widget): def __init__(self, items: list[Widget], spacing: int = ITEM_SPACING, line_separator: bool = False, pad_end: bool = True): super().__init__() self._items: list[Widget] = [] self._spacing = spacing self._line_separator = LineSeparator() if line_separator else None self._pad_end = pad_end self.scroll_panel = GuiScrollPanel() for item in items: self.add_widget(item) def add_widget(self, item: Widget) -> None: self._items.append(item) item.set_touch_valid_callback(self.scroll_panel.is_touch_valid) def _render(self, _): # TODO: don't draw items that are not in the viewport visible_items = [item for item in self._items if item.is_visible] # Add line separator between items if self._line_separator is not None: l = len(visible_items) for i in range(1, len(visible_items)): visible_items.insert(l - i, self._line_separator) content_height = sum(item.rect.height for item in visible_items) + self._spacing * (len(visible_items)) if not self._pad_end: content_height -= self._spacing scroll = self.scroll_panel.update(self._rect, rl.Rectangle(0, 0, self._rect.width, content_height)) rl.begin_scissor_mode(int(self._rect.x), int(self._rect.y), int(self._rect.width), int(self._rect.height)) cur_height = 0 for idx, item in enumerate(visible_items): if not item.is_visible: continue # Nicely lay out items vertically x = self._rect.x y = self._rect.y + cur_height + self._spacing * (idx != 0) cur_height += item.rect.height + self._spacing * (idx != 0) # Consider scroll y += scroll # Update item state item.set_position(x, y) item.set_parent_rect(self._rect) item.render() rl.end_scissor_mode() def show_event(self): super().show_event() # Reset to top self.scroll_panel.set_offset(0) for item in self._items: item.show_event() def hide_event(self): super().hide_event() for item in self._items: item.hide_event()
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/scroller_tici.py", "license": "MIT License", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ui/widgets/slider.py
from collections.abc import Callable import pyray as rl from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.label import UnifiedLabel from openpilot.common.filter_simple import FirstOrderFilter class SmallSlider(Widget): HORIZONTAL_PADDING = 8 CONFIRM_DELAY = 0.2 def __init__(self, title: str, confirm_callback: Callable | None = None): # TODO: unify this with BigConfirmationDialogV2 super().__init__() self._confirm_callback = confirm_callback self._font = gui_app.font(FontWeight.DISPLAY) self._load_assets() self._drag_threshold = -self._rect.width // 2 # State self._opacity_filter = FirstOrderFilter(1.0, 0.1, 1 / gui_app.target_fps) self._confirmed_time = 0.0 self._confirm_callback_called = False # we keep dialog open by default, only call once self._start_x_circle = 0.0 self._scroll_x_circle = 0.0 self._scroll_x_circle_filter = FirstOrderFilter(0, 0.05, 1 / gui_app.target_fps) self._is_dragging_circle = False self._label = UnifiedLabel(title, font_size=36, font_weight=FontWeight.SEMI_BOLD, text_color=rl.Color(255, 255, 255, int(255 * 0.65)), alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, line_height=0.9) def _load_assets(self): self.set_rect(rl.Rectangle(0, 0, 316 + self.HORIZONTAL_PADDING * 2, 100)) self._bg_txt = gui_app.texture("icons_mici/setup/small_slider/slider_bg.png", 316, 100) self._circle_bg_txt = gui_app.texture("icons_mici/setup/small_slider/slider_red_circle.png", 100, 100) self._circle_bg_pressed_txt = gui_app.texture("icons_mici/setup/small_slider/slider_red_circle_pressed.png", 100, 100) self._circle_arrow_txt = gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 37, 32) @property def confirmed(self) -> bool: return self._confirmed_time > 0.0 def reset(self): # reset all slider state self._is_dragging_circle = False self._confirmed_time = 0.0 self._confirm_callback_called = False def set_opacity(self, opacity: float, smooth: bool = False): if smooth: self._opacity_filter.update(opacity) else: self._opacity_filter.x = opacity @property def slider_percentage(self): activated_pos = -self._bg_txt.width + self._circle_bg_txt.width return min(max(-self._scroll_x_circle_filter.x / abs(activated_pos), 0.0), 1.0) def _on_confirm(self): if self._confirm_callback: self._confirm_callback() def _handle_mouse_event(self, mouse_event): super()._handle_mouse_event(mouse_event) if mouse_event.left_pressed: # touch rect goes to the padding circle_button_rect = rl.Rectangle( self._rect.x + (self._rect.width - self._circle_bg_txt.width) + self._scroll_x_circle_filter.x - self.HORIZONTAL_PADDING * 2, self._rect.y, self._circle_bg_txt.width + self.HORIZONTAL_PADDING * 2, self._rect.height, ) if rl.check_collision_point_rec(mouse_event.pos, circle_button_rect): self._start_x_circle = mouse_event.pos.x self._is_dragging_circle = True elif mouse_event.left_released: # swiped to left if self._scroll_x_circle_filter.x < self._drag_threshold: self._confirmed_time = rl.get_time() self._is_dragging_circle = False if self._is_dragging_circle: self._scroll_x_circle = mouse_event.pos.x - self._start_x_circle def _update_state(self): super()._update_state() # TODO: this math can probably be cleaned up to remove duplicate stuff activated_pos = int(-self._bg_txt.width + self._circle_bg_txt.width) self._scroll_x_circle = max(min(self._scroll_x_circle, 0), activated_pos) if self._confirmed_time > 0: # swiped left to confirm self._scroll_x_circle_filter.update(activated_pos) # activate once animation completes, small threshold for small floats if self._scroll_x_circle_filter.x < (activated_pos + 1): if not self._confirm_callback_called and (rl.get_time() - self._confirmed_time) >= self.CONFIRM_DELAY: self._confirm_callback_called = True self._on_confirm() elif not self._is_dragging_circle: # reset back to right self._scroll_x_circle_filter.update(0) else: # not activated yet, keep movement 1:1 self._scroll_x_circle_filter.x = self._scroll_x_circle def _render(self, _): # TODO: iOS text shimmering animation white = rl.Color(255, 255, 255, int(255 * self._opacity_filter.x)) bg_txt_x = self._rect.x + (self._rect.width - self._bg_txt.width) / 2 bg_txt_y = self._rect.y + (self._rect.height - self._bg_txt.height) / 2 rl.draw_texture_ex(self._bg_txt, rl.Vector2(bg_txt_x, bg_txt_y), 0.0, 1.0, white) btn_x = bg_txt_x + self._bg_txt.width - self._circle_bg_txt.width + self._scroll_x_circle_filter.x btn_y = self._rect.y + (self._rect.height - self._circle_bg_txt.height) / 2 if self._confirmed_time == 0.0 or self._scroll_x_circle > 0: self._label.set_text_color(rl.Color(255, 255, 255, int(255 * 0.65 * (1.0 - self.slider_percentage) * self._opacity_filter.x))) label_rect = rl.Rectangle( self._rect.x + 20, self._rect.y, self._rect.width - self._circle_bg_txt.width - 20 * 2.5, self._rect.height, ) self._label.render(label_rect) # circle and arrow circle_bg_txt = self._circle_bg_pressed_txt if self._is_dragging_circle or self._confirmed_time > 0 else self._circle_bg_txt rl.draw_texture_ex(circle_bg_txt, rl.Vector2(btn_x, btn_y), 0.0, 1.0, white) arrow_x = btn_x + (self._circle_bg_txt.width - self._circle_arrow_txt.width) / 2 arrow_y = btn_y + (self._circle_bg_txt.height - self._circle_arrow_txt.height) / 2 rl.draw_texture_ex(self._circle_arrow_txt, rl.Vector2(arrow_x, arrow_y), 0.0, 1.0, white) class LargerSlider(SmallSlider): def __init__(self, title: str, confirm_callback: Callable | None = None, green: bool = True): self._green = green super().__init__(title, confirm_callback=confirm_callback) def _load_assets(self): self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 115)) self._bg_txt = gui_app.texture("icons_mici/setup/small_slider/slider_bg_larger.png", 520, 115) circle_fn = "slider_green_rounded_rectangle" if self._green else "slider_black_rounded_rectangle" self._circle_bg_txt = gui_app.texture(f"icons_mici/setup/small_slider/{circle_fn}.png", 180, 115) self._circle_bg_pressed_txt = gui_app.texture(f"icons_mici/setup/small_slider/{circle_fn}_pressed.png", 180, 115) self._circle_arrow_txt = gui_app.texture("icons_mici/setup/small_slider/slider_arrow.png", 64, 55) class BigSlider(SmallSlider): def __init__(self, title: str, icon: rl.Texture, confirm_callback: Callable | None = None): self._icon = icon super().__init__(title, confirm_callback=confirm_callback) self._label = UnifiedLabel(title, font_size=48, font_weight=FontWeight.DISPLAY, text_color=rl.Color(255, 255, 255, int(255 * 0.65)), alignment=rl.GuiTextAlignment.TEXT_ALIGN_RIGHT, alignment_vertical=rl.GuiTextAlignmentVertical.TEXT_ALIGN_MIDDLE, line_height=0.875) def _load_assets(self): self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 180)) self._bg_txt = gui_app.texture("icons_mici/buttons/slider_bg.png", 520, 180) self._circle_bg_txt = gui_app.texture("icons_mici/buttons/button_circle.png", 180, 180) self._circle_bg_pressed_txt = gui_app.texture("icons_mici/buttons/button_circle_pressed.png", 180, 180) self._circle_arrow_txt = self._icon class RedBigSlider(BigSlider): def _load_assets(self): self.set_rect(rl.Rectangle(0, 0, 520 + self.HORIZONTAL_PADDING * 2, 180)) self._bg_txt = gui_app.texture("icons_mici/buttons/slider_bg.png", 520, 180) self._circle_bg_txt = gui_app.texture("icons_mici/buttons/button_circle_red.png", 180, 180) self._circle_bg_pressed_txt = gui_app.texture("icons_mici/buttons/button_circle_red_pressed.png", 180, 180) self._circle_arrow_txt = self._icon
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/slider.py", "license": "MIT License", "lines": 146, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/tests/profile_onroad.py
#!/usr/bin/env python3 import os import time import cProfile import pyray as rl import numpy as np from msgq.visionipc import VisionIpcServer, VisionStreamType from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.selfdrive.ui.mici.layouts.main import MiciMainLayout from openpilot.system.ui.lib.application import gui_app from openpilot.tools.lib.logreader import LogReader FPS = 60 def chunk_messages_by_time(messages): dt_ns = 1e9 / FPS chunks = [] current_services = {} next_time = messages[0].logMonoTime + dt_ns if messages else 0 for msg in messages: if msg.logMonoTime >= next_time: chunks.append(current_services) current_services = {} next_time += dt_ns * ((msg.logMonoTime - next_time) // dt_ns + 1) current_services[msg.which()] = msg if current_services: chunks.append(current_services) return chunks def patch_submaster(message_chunks): def mock_update(timeout=None): sm = ui_state.sm sm.updated = dict.fromkeys(sm.services, False) current_time = time.monotonic() for service, msg in message_chunks[sm.frame].items(): if service in sm.data: sm.seen[service] = True sm.updated[service] = True msg_builder = msg.as_builder() sm.data[service] = getattr(msg_builder, service) sm.logMonoTime[service] = msg.logMonoTime sm.recv_time[service] = current_time sm.recv_frame[service] = sm.frame sm.valid[service] = True sm.frame += 1 ui_state.sm.update = mock_update if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Profile openpilot UI rendering and state updates') parser.add_argument('route', type=str, nargs='?', default="302bab07c1511180/00000006--0b9a7005f1/3", help='Route to use for profiling') parser.add_argument('--loop', type=int, default=1, help='Number of times to loop the log (default: 1)') parser.add_argument('--output', type=str, default='cachegrind.out.ui', help='Output file prefix (default: cachegrind.out.ui)') parser.add_argument('--max-seconds', type=float, default=None, help='Maximum seconds of messages to process (default: all)') parser.add_argument('--headless', action='store_true', help='Run in headless mode without GPU (for CI/testing)') args = parser.parse_args() print(f"Loading log from {args.route}...") lr = LogReader(args.route, sort_by_time=True) messages = list(lr) * args.loop print("Chunking messages...") message_chunks = chunk_messages_by_time(messages) if args.max_seconds: message_chunks = message_chunks[:int(args.max_seconds * FPS)] print("Initializing UI with GPU rendering...") if args.headless: os.environ['SDL_VIDEODRIVER'] = 'dummy' gui_app.init_window("UI Profiling", fps=600) main_layout = MiciMainLayout() print("Running...") patch_submaster(message_chunks) W, H = 2048, 1216 vipc = VisionIpcServer("camerad") vipc.create_buffers(VisionStreamType.VISION_STREAM_ROAD, 5, W, H) vipc.start_listener() yuv_buffer_size = W * H + (W // 2) * (H // 2) * 2 yuv_data = np.random.randint(0, 256, yuv_buffer_size, dtype=np.uint8).tobytes() with cProfile.Profile() as pr: for _ in gui_app.render(): if ui_state.sm.frame >= len(message_chunks): break if ui_state.sm.frame % 3 == 0: eof = int((ui_state.sm.frame % 3) * 0.05 * 1e9) vipc.send(VisionStreamType.VISION_STREAM_ROAD, yuv_data, ui_state.sm.frame % 3, eof, eof) ui_state.update() pr.dump_stats(f'{args.output}_deterministic.stats') rl.close_window() print("\nProfiling complete!") print(f" run: python -m pstats {args.output}_deterministic.stats")
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/tests/profile_onroad.py", "license": "MIT License", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/assets/fonts/process.py
#!/usr/bin/env python3 from pathlib import Path import json import pyray as rl FONT_DIR = Path(__file__).resolve().parent SELFDRIVE_DIR = FONT_DIR.parents[1] TRANSLATIONS_DIR = SELFDRIVE_DIR / "ui" / "translations" LANGUAGES_FILE = TRANSLATIONS_DIR / "languages.json" GLYPH_PADDING = 6 EXTRA_CHARS = "–‑✓×°§•X⚙✕◀▶✔⌫⇧␣○●↳çêüñ–‑✓×°§•€£¥" UNIFONT_LANGUAGES = {"th", "zh-CHT", "zh-CHS", "ko", "ja"} def _languages(): if not LANGUAGES_FILE.exists(): return {} with LANGUAGES_FILE.open(encoding="utf-8") as f: return json.load(f) def _char_sets(): base = set(map(chr, range(32, 127))) | set(EXTRA_CHARS) unifont = set(base) for language, code in _languages().items(): unifont.update(language) po_path = TRANSLATIONS_DIR / f"app_{code}.po" try: chars = set(po_path.read_text(encoding="utf-8")) except FileNotFoundError: continue (unifont if code in UNIFONT_LANGUAGES else base).update(chars) return tuple(sorted(ord(c) for c in base)), tuple(sorted(ord(c) for c in unifont)) def _glyph_metrics(glyphs, rects, codepoints): entries = [] min_offset_y, max_extent = None, 0 for idx, codepoint in enumerate(codepoints): glyph = glyphs[idx] rect = rects[idx] width = int(round(rect.width)) height = int(round(rect.height)) offset_y = int(round(glyph.offsetY)) min_offset_y = offset_y if min_offset_y is None else min(min_offset_y, offset_y) max_extent = max(max_extent, offset_y + height) entries.append({ "id": codepoint, "x": int(round(rect.x)), "y": int(round(rect.y)), "width": width, "height": height, "xoffset": int(round(glyph.offsetX)), "yoffset": offset_y, "xadvance": int(round(glyph.advanceX)), }) if min_offset_y is None: raise RuntimeError("No glyphs were generated") line_height = int(round(max_extent - min_offset_y)) base = int(round(max_extent)) return entries, line_height, base def _write_bmfont(path: Path, font_size: int, face: str, atlas_name: str, line_height: int, base: int, atlas_size, entries): # TODO: why doesn't raylib calculate these metrics correctly? if line_height != font_size: print("using font size for line height", atlas_name) line_height = font_size lines = [ f"info face=\"{face}\" size=-{font_size} bold=0 italic=0 charset=\"\" unicode=1 stretchH=100 smooth=0 aa=1 padding=0,0,0,0 spacing=0,0 outline=0", f"common lineHeight={line_height} base={base} scaleW={atlas_size[0]} scaleH={atlas_size[1]} pages=1 packed=0 alphaChnl=0 redChnl=4 greenChnl=4 blueChnl=4", f"page id=0 file=\"{atlas_name}\"", f"chars count={len(entries)}", ] for entry in entries: lines.append( ("char id={id:<4} x={x:<5} y={y:<5} width={width:<5} height={height:<5} " + "xoffset={xoffset:<5} yoffset={yoffset:<5} xadvance={xadvance:<5} page=0 chnl=15").format(**entry) ) path.write_text("\n".join(lines) + "\n") def _process_font(font_path: Path, codepoints: tuple[int, ...]): print(f"Processing {font_path.name}...") font_size = { "unifont.otf": 16, # unifont is only 16x8 or 16x16 pixels per glyph }.get(font_path.name, 200) data = font_path.read_bytes() file_buf = rl.ffi.new("unsigned char[]", data) cp_buffer = rl.ffi.new("int[]", codepoints) cp_ptr = rl.ffi.cast("int *", cp_buffer) glyphs = rl.load_font_data(rl.ffi.cast("unsigned char *", file_buf), len(data), font_size, cp_ptr, len(codepoints), rl.FontType.FONT_DEFAULT) if glyphs == rl.ffi.NULL: raise RuntimeError("raylib failed to load font data") rects_ptr = rl.ffi.new("Rectangle **") image = rl.gen_image_font_atlas(glyphs, rects_ptr, len(codepoints), font_size, GLYPH_PADDING, 0) if image.width == 0 or image.height == 0: raise RuntimeError("raylib returned an empty atlas") rects = rects_ptr[0] atlas_name = f"{font_path.stem}.png" atlas_path = FONT_DIR / atlas_name entries, line_height, base = _glyph_metrics(glyphs, rects, codepoints) if not rl.export_image(image, atlas_path.as_posix()): raise RuntimeError("Failed to export atlas image") _write_bmfont(FONT_DIR / f"{font_path.stem}.fnt", font_size, font_path.stem, atlas_name, line_height, base, (image.width, image.height), entries) def main(): base_cp, unifont_cp = _char_sets() fonts = sorted(FONT_DIR.glob("*.ttf")) + sorted(FONT_DIR.glob("*.otf")) for font in fonts: if "emoji" in font.name.lower(): continue glyphs = unifont_cp if font.stem.lower().startswith("unifont") else base_cp _process_font(font, glyphs) return 0 if __name__ == "__main__": raise SystemExit(main())
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/assets/fonts/process.py", "license": "MIT License", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/lib/multilang.py
from importlib.resources import files import json import os import re from openpilot.common.basedir import BASEDIR from openpilot.common.swaglog import cloudlog try: from openpilot.common.params import Params except ImportError: Params = None SYSTEM_UI_DIR = os.path.join(BASEDIR, "system", "ui") UI_DIR = files("openpilot.selfdrive.ui") TRANSLATIONS_DIR = UI_DIR.joinpath("translations") LANGUAGES_FILE = TRANSLATIONS_DIR.joinpath("languages.json") UNIFONT_LANGUAGES = [ "th", "zh-CHT", "zh-CHS", "ko", "ja", ] # Plural form selectors for supported languages PLURAL_SELECTORS = { 'en': lambda n: 0 if n == 1 else 1, 'de': lambda n: 0 if n == 1 else 1, 'fr': lambda n: 0 if n <= 1 else 1, 'pt-BR': lambda n: 0 if n <= 1 else 1, 'es': lambda n: 0 if n == 1 else 1, 'tr': lambda n: 0 if n == 1 else 1, 'uk': lambda n: 0 if n % 10 == 1 and n % 100 != 11 else (1 if 2 <= n % 10 <= 4 and not 12 <= n % 100 <= 14 else 2), 'th': lambda n: 0, 'zh-CHT': lambda n: 0, 'zh-CHS': lambda n: 0, 'ko': lambda n: 0, 'ja': lambda n: 0, } def _parse_quoted(s: str) -> str: """Parse a PO-format quoted string.""" s = s.strip() if not (s.startswith('"') and s.endswith('"')): raise ValueError(f"Expected quoted string: {s!r}") s = s[1:-1] result: list[str] = [] i = 0 while i < len(s): if s[i] == '\\' and i + 1 < len(s): c = s[i + 1] if c == 'n': result.append('\n') elif c == 't': result.append('\t') elif c == '"': result.append('"') elif c == '\\': result.append('\\') else: result.append(s[i:i + 2]) i += 2 else: result.append(s[i]) i += 1 return ''.join(result) def load_translations(path) -> tuple[dict[str, str], dict[str, list[str]]]: """Parse a .po file and return (translations, plurals) dicts. translations: msgid -> msgstr plurals: msgid -> [msgstr[0], msgstr[1], ...] """ with open(str(path), encoding='utf-8') as f: lines = f.readlines() translations: dict[str, str] = {} plurals: dict[str, list[str]] = {} # Parser state msgid = msgid_plural = msgstr = "" msgstr_plurals: dict[int, str] = {} field: str | None = None plural_idx = 0 def finish(): nonlocal msgid, msgid_plural, msgstr, msgstr_plurals, field if msgid: # skip header (empty msgid) if msgid_plural: max_idx = max(msgstr_plurals.keys()) if msgstr_plurals else 0 plurals[msgid] = [msgstr_plurals.get(i, '') for i in range(max_idx + 1)] else: translations[msgid] = msgstr msgid = msgid_plural = msgstr = "" msgstr_plurals = {} field = None for raw in lines: line = raw.strip() if not line: finish() continue if line.startswith('#'): continue if line.startswith('msgid_plural '): msgid_plural = _parse_quoted(line[len('msgid_plural '):]) field = 'msgid_plural' continue if line.startswith('msgid '): msgid = _parse_quoted(line[len('msgid '):]) field = 'msgid' continue m = re.match(r'msgstr\[(\d+)]\s+(.*)', line) if m: plural_idx = int(m.group(1)) msgstr_plurals[plural_idx] = _parse_quoted(m.group(2)) field = 'msgstr_plural' continue if line.startswith('msgstr '): msgstr = _parse_quoted(line[len('msgstr '):]) field = 'msgstr' continue if line.startswith('"'): val = _parse_quoted(line) if field == 'msgid': msgid += val elif field == 'msgid_plural': msgid_plural += val elif field == 'msgstr': msgstr += val elif field == 'msgstr_plural': msgstr_plurals[plural_idx] += val finish() return translations, plurals class Multilang: def __init__(self): self._params = Params() if Params is not None else None self._language: str = "en" self.languages: dict[str, str] = {} self.codes: dict[str, str] = {} self._translations: dict[str, str] = {} self._plurals: dict[str, list[str]] = {} self._plural_selector = PLURAL_SELECTORS.get('en', lambda n: 0) self._load_languages() @property def language(self) -> str: return self._language def requires_unifont(self) -> bool: """Certain languages require unifont to render their glyphs.""" return self._language in UNIFONT_LANGUAGES def setup(self): try: po_path = TRANSLATIONS_DIR.joinpath(f'app_{self._language}.po') self._translations, self._plurals = load_translations(po_path) self._plural_selector = PLURAL_SELECTORS.get(self._language, lambda n: 0) cloudlog.debug(f"Loaded translations for language: {self._language}") except FileNotFoundError: cloudlog.error(f"No translation file found for language: {self._language}, using default.") self._translations = {} self._plurals = {} def change_language(self, language_code: str) -> None: self._params.put("LanguageSetting", language_code) self._language = language_code self.setup() def tr(self, text: str) -> str: return self._translations.get(text, text) or text def trn(self, singular: str, plural: str, n: int) -> str: if singular in self._plurals: idx = self._plural_selector(n) forms = self._plurals[singular] if idx < len(forms) and forms[idx]: return forms[idx] return singular if n == 1 else plural def _load_languages(self): with LANGUAGES_FILE.open(encoding='utf-8') as f: self.languages = json.load(f) self.codes = {v: k for k, v in self.languages.items()} if self._params is not None: lang = str(self._params.get("LanguageSetting")).removeprefix("main_") if lang in self.codes: self._language = lang multilang = Multilang() multilang.setup() tr, trn = multilang.tr, multilang.trn # no-op marker for static strings translated later def tr_noop(s: str) -> str: return s
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/lib/multilang.py", "license": "MIT License", "lines": 177, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/layouts/onboarding.py
import os import re import threading from enum import IntEnum import pyray as rl from openpilot.common.basedir import BASEDIR from openpilot.system.ui.lib.application import FontWeight, gui_app from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.button import Button, ButtonStyle from openpilot.system.ui.widgets.label import Label from openpilot.selfdrive.ui.ui_state import ui_state from openpilot.system.version import terms_version, training_version DEBUG = False STEP_RECTS = [rl.Rectangle(104, 800, 633, 175), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1835, 0, 2156, 1080), rl.Rectangle(1526, 473, 427, 472), rl.Rectangle(1643, 441, 217, 223), rl.Rectangle(1835, 0, 2155, 1080), rl.Rectangle(1786, 591, 267, 236), rl.Rectangle(1353, 0, 804, 1080), rl.Rectangle(1458, 485, 633, 211), rl.Rectangle(95, 794, 1158, 187), rl.Rectangle(1560, 170, 392, 397), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1351, 0, 807, 1080), rl.Rectangle(1835, 0, 2158, 1080), rl.Rectangle(1531, 82, 441, 920), rl.Rectangle(1336, 438, 490, 393), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(1835, 0, 2159, 1080), rl.Rectangle(87, 795, 1187, 186)] DM_RECORD_STEP = 9 DM_RECORD_YES_RECT = rl.Rectangle(695, 794, 558, 187) RESTART_TRAINING_RECT = rl.Rectangle(87, 795, 472, 186) class OnboardingState(IntEnum): TERMS = 0 ONBOARDING = 1 DECLINE = 2 class TrainingGuide(Widget): def __init__(self, completed_callback=None): super().__init__() self._completed_callback = completed_callback self._step = 0 self._load_image_paths() # Load first image now so we show something immediately self._textures = [gui_app.texture(self._image_paths[0])] self._image_objs = [] threading.Thread(target=self._preload_thread, daemon=True).start() def _load_image_paths(self): paths = [fn for fn in os.listdir(os.path.join(BASEDIR, "selfdrive/assets/training")) if re.match(r'^step\d*\.png$', fn)] paths = sorted(paths, key=lambda x: int(re.search(r'\d+', x).group())) self._image_paths = [os.path.join(BASEDIR, "selfdrive/assets/training", fn) for fn in paths] def _preload_thread(self): # PNG loading is slow in raylib, so we preload in a thread and upload to GPU in main thread # We've already loaded the first image on init for path in self._image_paths[1:]: self._image_objs.append(gui_app._load_image_from_path(path)) def _handle_mouse_release(self, mouse_pos): if rl.check_collision_point_rec(mouse_pos, STEP_RECTS[self._step]): # Record DM camera? if self._step == DM_RECORD_STEP: yes = rl.check_collision_point_rec(mouse_pos, DM_RECORD_YES_RECT) print(f"putting RecordFront to {yes}") ui_state.params.put_bool("RecordFront", yes) # Restart training? elif self._step == len(self._image_paths) - 1: if rl.check_collision_point_rec(mouse_pos, RESTART_TRAINING_RECT): self._step = -1 self._step += 1 # Finished? if self._step >= len(self._image_paths): self._step = 0 if self._completed_callback: self._completed_callback() # NOTE: this pops OnboardingWindow during real onboarding gui_app.pop_widget() def _update_state(self): if len(self._image_objs): self._textures.append(gui_app._load_texture_from_image(self._image_objs.pop(0))) def _render(self, _): # Safeguard against fast tapping step = min(self._step, len(self._textures) - 1) rl.draw_texture(self._textures[step], 0, 0, rl.WHITE) # progress bar if 0 < step < len(STEP_RECTS) - 1: h = 20 w = int((step / (len(STEP_RECTS) - 1)) * self._rect.width) rl.draw_rectangle(int(self._rect.x), int(self._rect.y + self._rect.height - h), w, h, rl.Color(70, 91, 234, 255)) if DEBUG: rl.draw_rectangle_lines_ex(STEP_RECTS[step], 3, rl.RED) return -1 class TermsPage(Widget): def __init__(self, on_accept=None, on_decline=None): super().__init__() 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."), font_size=90, font_weight=FontWeight.MEDIUM, text_alignment=rl.GuiTextAlignment.TEXT_ALIGN_LEFT) self._decline_btn = Button(tr("Decline"), click_callback=on_decline) self._accept_btn = Button(tr("Agree"), button_style=ButtonStyle.PRIMARY, click_callback=on_accept) def _render(self, _): welcome_x = self._rect.x + 165 welcome_y = self._rect.y + 165 welcome_rect = rl.Rectangle(welcome_x, welcome_y, self._rect.width - welcome_x, 90) self._title.render(welcome_rect) desc_x = welcome_x # TODO: Label doesn't top align when wrapping desc_y = welcome_y - 100 desc_rect = rl.Rectangle(desc_x, desc_y, self._rect.width - desc_x, self._rect.height - desc_y - 250) self._desc.render(desc_rect) btn_y = self._rect.y + self._rect.height - 160 - 45 btn_width = (self._rect.width - 45 * 3) / 2 self._decline_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) self._accept_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) if DEBUG: rl.draw_rectangle_lines_ex(welcome_rect, 3, rl.RED) rl.draw_rectangle_lines_ex(desc_rect, 3, rl.RED) return -1 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."), 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, click_callback=self._on_uninstall_clicked) def _on_uninstall_clicked(self): ui_state.params.put_bool("DoUninstall", True) gui_app.request_close() def _render(self, _): btn_y = self._rect.y + self._rect.height - 160 - 45 btn_width = (self._rect.width - 45 * 3) / 2 self._back_btn.render(rl.Rectangle(self._rect.x + 45, btn_y, btn_width, 160)) self._uninstall_btn.render(rl.Rectangle(self._rect.x + 45 * 2 + btn_width, btn_y, btn_width, 160)) # text rect in middle of top and button text_height = btn_y - (200 + 45) text_rect = rl.Rectangle(self._rect.x + 165, self._rect.y + (btn_y - text_height) / 2 + 10, self._rect.width - (165 * 2), text_height) if DEBUG: rl.draw_rectangle_lines_ex(text_rect, 3, rl.RED) self._text.render(text_rect) class OnboardingWindow(Widget): def __init__(self): super().__init__() self._accepted_terms: bool = ui_state.params.get("HasAcceptedTerms") == terms_version self._training_done: bool = ui_state.params.get("CompletedTrainingVersion") == training_version self._state = OnboardingState.TERMS if not self._accepted_terms else OnboardingState.ONBOARDING # Windows self._terms = TermsPage(on_accept=self._on_terms_accepted, on_decline=self._on_terms_declined) self._training_guide: TrainingGuide | None = None self._decline_page = DeclinePage(back_callback=self._on_decline_back) @property def completed(self) -> bool: return self._accepted_terms and self._training_done def _on_terms_declined(self): self._state = OnboardingState.DECLINE def _on_decline_back(self): self._state = OnboardingState.TERMS def _on_terms_accepted(self): ui_state.params.put("HasAcceptedTerms", terms_version) self._state = OnboardingState.ONBOARDING if self._training_done: gui_app.pop_widget() def _on_completed_training(self): ui_state.params.put("CompletedTrainingVersion", training_version) def _render(self, _): if self._training_guide is None: self._training_guide = TrainingGuide(completed_callback=self._on_completed_training) if self._state == OnboardingState.TERMS: self._terms.render(self._rect) if self._state == OnboardingState.ONBOARDING: self._training_guide.render(self._rect) elif self._state == OnboardingState.DECLINE: self._decline_page.render(self._rect) return -1
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/layouts/onboarding.py", "license": "MIT License", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ubloxd/ubloxd.py
#!/usr/bin/env python3 import math import capnp import calendar import numpy as np from collections import defaultdict from dataclasses import dataclass from cereal import log from cereal import messaging from openpilot.system.ubloxd.ubx import Ubx from openpilot.system.ubloxd.gps import Gps from openpilot.system.ubloxd.glonass import Glonass SECS_IN_MIN = 60 SECS_IN_HR = 60 * SECS_IN_MIN SECS_IN_DAY = 24 * SECS_IN_HR SECS_IN_WEEK = 7 * SECS_IN_DAY class UbxFramer: PREAMBLE1 = 0xB5 PREAMBLE2 = 0x62 HEADER_SIZE = 6 CHECKSUM_SIZE = 2 def __init__(self) -> None: self.buf = bytearray() self.last_log_time = 0.0 def reset(self) -> None: self.buf.clear() @staticmethod def _checksum_ok(frame: bytes) -> bool: ck_a = 0 ck_b = 0 for b in frame[2:-2]: ck_a = (ck_a + b) & 0xFF ck_b = (ck_b + ck_a) & 0xFF return ck_a == frame[-2] and ck_b == frame[-1] def add_data(self, log_time: float, incoming: bytes) -> list[bytes]: self.last_log_time = log_time out: list[bytes] = [] if not incoming: return out self.buf += incoming while True: # find preamble if len(self.buf) < 2: break start = self.buf.find(b"\xb5\x62") if start < 0: # no preamble in buffer self.buf.clear() break if start > 0: # drop garbage before preamble self.buf = self.buf[start:] if len(self.buf) < self.HEADER_SIZE: break length_le = int.from_bytes(self.buf[4:6], 'little', signed=False) total_len = self.HEADER_SIZE + length_le + self.CHECKSUM_SIZE if len(self.buf) < total_len: break candidate = bytes(self.buf[:total_len]) if self._checksum_ok(candidate): out.append(candidate) # consume this frame self.buf = self.buf[total_len:] else: # drop first byte and retry self.buf = self.buf[1:] return out def _bit(b: int, shift: int) -> bool: return (b & (1 << shift)) != 0 @dataclass class EphemerisCaches: gps_subframes: defaultdict[int, dict[int, bytes]] glonass_strings: defaultdict[int, dict[int, bytes]] glonass_string_times: defaultdict[int, dict[int, float]] glonass_string_superframes: defaultdict[int, dict[int, int]] class UbloxMsgParser: gpsPi = 3.1415926535898 # user range accuracy in meters glonass_URA_lookup: dict[int, float] = { 0: 1, 1: 2, 2: 2.5, 3: 4, 4: 5, 5: 7, 6: 10, 7: 12, 8: 14, 9: 16, 10: 32, 11: 64, 12: 128, 13: 256, 14: 512, 15: 1024, } def __init__(self) -> None: self.framer = UbxFramer() self.caches = EphemerisCaches( gps_subframes=defaultdict(dict), glonass_strings=defaultdict(dict), glonass_string_times=defaultdict(dict), glonass_string_superframes=defaultdict(dict), ) # Message generation entry point def parse_frame(self, frame: bytes) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: # Quick header parse msg_type = int.from_bytes(frame[2:4], 'big') payload = frame[6:-2] if msg_type == 0x0107: body = Ubx.NavPvt.from_bytes(payload) return self._gen_nav_pvt(body) if msg_type == 0x0213: # Manually parse RXM-SFRBX to avoid EOF on some frames if len(payload) < 8: return None gnss_id = payload[0] sv_id = payload[1] freq_id = payload[3] num_words = payload[4] exp = 8 + 4 * num_words if exp != len(payload): return None words: list[int] = [] off = 8 for _ in range(num_words): words.append(int.from_bytes(payload[off : off + 4], 'little')) off += 4 class _SfrbxView: def __init__(self, gid: int, sid: int, fid: int, body: list[int]): self.gnss_id = Ubx.GnssType(gid) self.sv_id = sid self.freq_id = fid self.body = body view = _SfrbxView(gnss_id, sv_id, freq_id, words) return self._gen_rxm_sfrbx(view) if msg_type == 0x0215: body = Ubx.RxmRawx.from_bytes(payload) return self._gen_rxm_rawx(body) if msg_type == 0x0A09: body = Ubx.MonHw.from_bytes(payload) return self._gen_mon_hw(body) if msg_type == 0x0A0B: body = Ubx.MonHw2.from_bytes(payload) return self._gen_mon_hw2(body) if msg_type == 0x0135: body = Ubx.NavSat.from_bytes(payload) return self._gen_nav_sat(body) return None # NAV-PVT -> gpsLocationExternal def _gen_nav_pvt(self, msg: Ubx.NavPvt) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: dat = messaging.new_message('gpsLocationExternal', valid=True) gps = dat.gpsLocationExternal gps.source = log.GpsLocationData.SensorSource.ublox gps.flags = msg.flags gps.hasFix = (msg.flags % 2) == 1 gps.latitude = msg.lat * 1e-07 gps.longitude = msg.lon * 1e-07 gps.altitude = msg.height * 1e-03 gps.speed = msg.g_speed * 1e-03 gps.bearingDeg = msg.head_mot * 1e-5 gps.horizontalAccuracy = msg.h_acc * 1e-03 gps.satelliteCount = msg.num_sv # build UTC timestamp millis (NAV-PVT is in UTC) # tolerate invalid or unset date values like C++ timegm try: utc_tt = calendar.timegm((msg.year, msg.month, msg.day, msg.hour, msg.min, msg.sec, 0, 0, 0)) except Exception: utc_tt = 0 gps.unixTimestampMillis = int(utc_tt * 1e3 + (msg.nano * 1e-6)) # match C++ float32 rounding semantics exactly gps.vNED = [ float(np.float32(msg.vel_n) * np.float32(1e-03)), float(np.float32(msg.vel_e) * np.float32(1e-03)), float(np.float32(msg.vel_d) * np.float32(1e-03)), ] gps.verticalAccuracy = msg.v_acc * 1e-03 gps.speedAccuracy = msg.s_acc * 1e-03 gps.bearingAccuracyDeg = msg.head_acc * 1e-05 return ('gpsLocationExternal', dat) # RXM-SFRBX dispatch to GPS or GLONASS ephemeris def _gen_rxm_sfrbx(self, msg) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: if msg.gnss_id == Ubx.GnssType.gps: return self._parse_gps_ephemeris(msg) if msg.gnss_id == Ubx.GnssType.glonass: return self._parse_glonass_ephemeris(msg) return None def _parse_gps_ephemeris(self, msg: Ubx.RxmSfrbx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: # body is list of 10 words; convert to 30-byte subframe (strip parity/padding) body = msg.body if len(body) != 10: return None subframe_data = bytearray() for word in body: word >>= 6 subframe_data.append((word >> 16) & 0xFF) subframe_data.append((word >> 8) & 0xFF) subframe_data.append(word & 0xFF) sf = Gps.from_bytes(bytes(subframe_data)) subframe_id = sf.how.subframe_id if subframe_id < 1 or subframe_id > 3: return None self.caches.gps_subframes[msg.sv_id][subframe_id] = bytes(subframe_data) if len(self.caches.gps_subframes[msg.sv_id]) != 3: return None dat = messaging.new_message('ubloxGnss', valid=True) eph = dat.ubloxGnss.init('ephemeris') eph.svId = msg.sv_id iode_s2 = 0 iode_s3 = 0 iodc_lsb = 0 week = 0 # Subframe 1 sf1 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][1]) s1 = sf1.body assert isinstance(s1, Gps.Subframe1) week = s1.week_no week += 1024 if week < 1877: week += 1024 eph.tgd = s1.t_gd * math.pow(2, -31) eph.toc = s1.t_oc * math.pow(2, 4) eph.af2 = s1.af_2 * math.pow(2, -55) eph.af1 = s1.af_1 * math.pow(2, -43) eph.af0 = s1.af_0 * math.pow(2, -31) eph.svHealth = s1.sv_health eph.towCount = sf1.how.tow_count iodc_lsb = s1.iodc_lsb # Subframe 2 sf2 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][2]) s2 = sf2.body assert isinstance(s2, Gps.Subframe2) if s2.t_oe == 0 and sf2.how.tow_count * 6 >= (SECS_IN_WEEK - 2 * SECS_IN_HR): week += 1 eph.crs = s2.c_rs * math.pow(2, -5) eph.deltaN = s2.delta_n * math.pow(2, -43) * self.gpsPi eph.m0 = s2.m_0 * math.pow(2, -31) * self.gpsPi eph.cuc = s2.c_uc * math.pow(2, -29) eph.ecc = s2.e * math.pow(2, -33) eph.cus = s2.c_us * math.pow(2, -29) eph.a = math.pow(s2.sqrt_a * math.pow(2, -19), 2.0) eph.toe = s2.t_oe * math.pow(2, 4) iode_s2 = s2.iode # Subframe 3 sf3 = Gps.from_bytes(self.caches.gps_subframes[msg.sv_id][3]) s3 = sf3.body assert isinstance(s3, Gps.Subframe3) eph.cic = s3.c_ic * math.pow(2, -29) eph.omega0 = s3.omega_0 * math.pow(2, -31) * self.gpsPi eph.cis = s3.c_is * math.pow(2, -29) eph.i0 = s3.i_0 * math.pow(2, -31) * self.gpsPi eph.crc = s3.c_rc * math.pow(2, -5) eph.omega = s3.omega * math.pow(2, -31) * self.gpsPi eph.omegaDot = s3.omega_dot * math.pow(2, -43) * self.gpsPi eph.iode = s3.iode eph.iDot = s3.idot * math.pow(2, -43) * self.gpsPi iode_s3 = s3.iode eph.toeWeek = week eph.tocWeek = week # clear cache for this SV self.caches.gps_subframes[msg.sv_id].clear() if not (iodc_lsb == iode_s2 == iode_s3): return None return ('ubloxGnss', dat) def _parse_glonass_ephemeris(self, msg: Ubx.RxmSfrbx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder] | None: # words are 4 bytes each; Glonass parser expects 16 bytes (string) body = msg.body if len(body) != 4: return None string_bytes = bytearray() for word in body: for i in (3, 2, 1, 0): string_bytes.append((word >> (8 * i)) & 0xFF) gl = Glonass.from_bytes(bytes(string_bytes)) string_number = gl.string_number if string_number < 1 or string_number > 5 or gl.idle_chip: return None # correlate by superframe and timing, similar to C++ logic freq_id = msg.freq_id superframe_unknown = False needs_clear = False for i in range(1, 6): if i not in self.caches.glonass_strings[freq_id]: continue sf_prev = self.caches.glonass_string_superframes[freq_id].get(i, 0) if sf_prev == 0 or gl.superframe_number == 0: superframe_unknown = True elif sf_prev != gl.superframe_number: needs_clear = True if superframe_unknown: prev_time = self.caches.glonass_string_times[freq_id].get(i, 0.0) if abs((prev_time - 2.0 * i) - (self.framer.last_log_time - 2.0 * string_number)) > 10: needs_clear = True if needs_clear: self.caches.glonass_strings[freq_id].clear() self.caches.glonass_string_superframes[freq_id].clear() self.caches.glonass_string_times[freq_id].clear() self.caches.glonass_strings[freq_id][string_number] = bytes(string_bytes) self.caches.glonass_string_superframes[freq_id][string_number] = gl.superframe_number self.caches.glonass_string_times[freq_id][string_number] = self.framer.last_log_time if msg.sv_id == 255: # unknown SV id return None if len(self.caches.glonass_strings[freq_id]) != 5: return None dat = messaging.new_message('ubloxGnss', valid=True) eph = dat.ubloxGnss.init('glonassEphemeris') eph.svId = msg.sv_id eph.freqNum = msg.freq_id - 7 current_day = 0 tk = 0 # string 1 try: s1 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][1]).data except Exception: return None assert isinstance(s1, Glonass.String1) eph.p1 = int(s1.p1) tk = int(s1.t_k) eph.tkDEPRECATED = tk eph.xVel = float(s1.x_vel) * math.pow(2, -20) eph.xAccel = float(s1.x_accel) * math.pow(2, -30) eph.x = float(s1.x) * math.pow(2, -11) # string 2 try: s2 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][2]).data except Exception: return None assert isinstance(s2, Glonass.String2) eph.svHealth = int(s2.b_n >> 2) eph.p2 = int(s2.p2) eph.tb = int(s2.t_b) eph.yVel = float(s2.y_vel) * math.pow(2, -20) eph.yAccel = float(s2.y_accel) * math.pow(2, -30) eph.y = float(s2.y) * math.pow(2, -11) # string 3 try: s3 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][3]).data except Exception: return None assert isinstance(s3, Glonass.String3) eph.p3 = int(s3.p3) eph.gammaN = float(s3.gamma_n) * math.pow(2, -40) eph.svHealth = int(eph.svHealth | (1 if s3.l_n else 0)) eph.zVel = float(s3.z_vel) * math.pow(2, -20) eph.zAccel = float(s3.z_accel) * math.pow(2, -30) eph.z = float(s3.z) * math.pow(2, -11) # string 4 try: s4 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][4]).data except Exception: return None assert isinstance(s4, Glonass.String4) current_day = int(s4.n_t) eph.nt = current_day eph.tauN = float(s4.tau_n) * math.pow(2, -30) eph.deltaTauN = float(s4.delta_tau_n) * math.pow(2, -30) eph.age = int(s4.e_n) eph.p4 = int(s4.p4) eph.svURA = float(self.glonass_URA_lookup.get(int(s4.f_t), 0.0)) # consistency check: SV slot number # if it doesn't match, keep going but note mismatch (no logging here) eph.svType = int(s4.m) # string 5 try: s5 = Glonass.from_bytes(self.caches.glonass_strings[freq_id][5]).data except Exception: return None assert isinstance(s5, Glonass.String5) eph.n4 = int(s5.n_4) tk_seconds = int(SECS_IN_HR * ((tk >> 7) & 0x1F) + SECS_IN_MIN * ((tk >> 1) & 0x3F) + (tk & 0x1) * 30) eph.tkSeconds = tk_seconds self.caches.glonass_strings[freq_id].clear() return ('ubloxGnss', dat) def _gen_rxm_rawx(self, msg: Ubx.RxmRawx) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: dat = messaging.new_message('ubloxGnss', valid=True) mr = dat.ubloxGnss.init('measurementReport') mr.rcvTow = msg.rcv_tow mr.gpsWeek = msg.week mr.leapSeconds = msg.leap_s mb = mr.init('measurements', msg.num_meas) for i, m in enumerate(msg.meas): mb[i].svId = m.sv_id mb[i].pseudorange = m.pr_mes mb[i].carrierCycles = m.cp_mes mb[i].doppler = m.do_mes mb[i].gnssId = int(m.gnss_id.value) mb[i].glonassFrequencyIndex = m.freq_id mb[i].locktime = m.lock_time mb[i].cno = m.cno mb[i].pseudorangeStdev = 0.01 * (math.pow(2, (m.pr_stdev & 15))) mb[i].carrierPhaseStdev = 0.004 * (m.cp_stdev & 15) mb[i].dopplerStdev = 0.002 * (math.pow(2, (m.do_stdev & 15))) ts = mb[i].init('trackingStatus') trk = m.trk_stat ts.pseudorangeValid = _bit(trk, 0) ts.carrierPhaseValid = _bit(trk, 1) ts.halfCycleValid = _bit(trk, 2) ts.halfCycleSubtracted = _bit(trk, 3) mr.numMeas = msg.num_meas rs = mr.init('receiverStatus') rs.leapSecValid = _bit(msg.rec_stat, 0) rs.clkReset = _bit(msg.rec_stat, 2) return ('ubloxGnss', dat) def _gen_nav_sat(self, msg: Ubx.NavSat) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: dat = messaging.new_message('ubloxGnss', valid=True) sr = dat.ubloxGnss.init('satReport') sr.iTow = msg.itow svs = sr.init('svs', msg.num_svs) for i, s in enumerate(msg.svs): svs[i].svId = s.sv_id svs[i].gnssId = int(s.gnss_id.value) svs[i].flagsBitfield = s.flags svs[i].cno = s.cno svs[i].elevationDeg = s.elev svs[i].azimuthDeg = s.azim svs[i].pseudorangeResidual = s.pr_res * 0.1 return ('ubloxGnss', dat) def _gen_mon_hw(self, msg: Ubx.MonHw) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: dat = messaging.new_message('ubloxGnss', valid=True) hw = dat.ubloxGnss.init('hwStatus') hw.noisePerMS = msg.noise_per_ms hw.flags = msg.flags hw.agcCnt = msg.agc_cnt hw.aStatus = int(msg.a_status.value) hw.aPower = int(msg.a_power.value) hw.jamInd = msg.jam_ind return ('ubloxGnss', dat) def _gen_mon_hw2(self, msg: Ubx.MonHw2) -> tuple[str, capnp.lib.capnp._DynamicStructBuilder]: dat = messaging.new_message('ubloxGnss', valid=True) hw = dat.ubloxGnss.init('hwStatus2') hw.ofsI = msg.ofs_i hw.magI = msg.mag_i hw.ofsQ = msg.ofs_q hw.magQ = msg.mag_q # Map Ubx enum to cereal enum {undefined=0, rom=1, otp=2, configpins=3, flash=4} cfg_map = { Ubx.MonHw2.ConfigSource.rom: 1, Ubx.MonHw2.ConfigSource.otp: 2, Ubx.MonHw2.ConfigSource.config_pins: 3, Ubx.MonHw2.ConfigSource.flash: 4, } hw.cfgSource = cfg_map.get(msg.cfg_source, 0) hw.lowLevCfg = msg.low_lev_cfg hw.postStatus = msg.post_status return ('ubloxGnss', dat) def main(): parser = UbloxMsgParser() pm = messaging.PubMaster(['ubloxGnss', 'gpsLocationExternal']) sock = messaging.sub_sock('ubloxRaw', timeout=100, conflate=False) while True: msg = messaging.recv_one(sock) if msg is None: continue data = bytes(msg.ubloxRaw) log_time = msg.logMonoTime * 1e-9 frames = parser.framer.add_data(log_time, data) for frame in frames: try: res = parser.parse_frame(frame) except Exception: continue if not res: continue service, dat = res pm.send(service, dat) if __name__ == '__main__': main()
{ "repo_id": "commaai/openpilot", "file_path": "system/ubloxd/ubloxd.py", "license": "MIT License", "lines": 468, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/journald.py
#!/usr/bin/env python3 import json import subprocess import cereal.messaging as messaging from openpilot.common.swaglog import cloudlog def main(): pm = messaging.PubMaster(['androidLog']) cmd = ['journalctl', '-f', '-o', 'json'] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True) assert proc.stdout is not None try: for line in proc.stdout: line = line.strip() if not line: continue try: kv = json.loads(line) except json.JSONDecodeError: cloudlog.exception("failed to parse journalctl output") continue msg = messaging.new_message('androidLog') entry = msg.androidLog entry.ts = int(kv.get('__REALTIME_TIMESTAMP', 0)) entry.message = json.dumps(kv) if '_PID' in kv: entry.pid = int(kv['_PID']) if 'PRIORITY' in kv: entry.priority = int(kv['PRIORITY']) if 'SYSLOG_IDENTIFIER' in kv: entry.tag = kv['SYSLOG_IDENTIFIER'] pm.send('androidLog', msg) finally: proc.terminate() proc.wait() if __name__ == '__main__': main()
{ "repo_id": "commaai/openpilot", "file_path": "system/journald.py", "license": "MIT License", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/proclogd.py
#!/usr/bin/env python3 import os from typing import NoReturn, TypedDict from cereal import messaging from openpilot.common.realtime import Ratekeeper from openpilot.common.swaglog import cloudlog JIFFY = os.sysconf(os.sysconf_names['SC_CLK_TCK']) PAGE_SIZE = os.sysconf(os.sysconf_names['SC_PAGE_SIZE']) def _cpu_times() -> list[dict[str, float]]: cpu_times: list[dict[str, float]] = [] try: with open('/proc/stat') as f: lines = f.readlines()[1:] for line in lines: if not line.startswith('cpu') or len(line) < 4 or not line[3].isdigit(): break parts = line.split() cpu_times.append({ 'cpuNum': int(parts[0][3:]), 'user': float(parts[1]) / JIFFY, 'nice': float(parts[2]) / JIFFY, 'system': float(parts[3]) / JIFFY, 'idle': float(parts[4]) / JIFFY, 'iowait': float(parts[5]) / JIFFY, 'irq': float(parts[6]) / JIFFY, 'softirq': float(parts[7]) / JIFFY, }) except Exception: cloudlog.exception("failed to read /proc/stat") return cpu_times def _mem_info() -> dict[str, int]: keys = ["MemTotal:", "MemFree:", "MemAvailable:", "Buffers:", "Cached:", "Active:", "Inactive:", "Shmem:"] info: dict[str, int] = dict.fromkeys(keys, 0) try: with open('/proc/meminfo') as f: for line in f: parts = line.split() if parts and parts[0] in info: info[parts[0]] = int(parts[1]) * 1024 except Exception: cloudlog.exception("failed to read /proc/meminfo") return info _STAT_POS = { 'pid': 1, 'state': 3, 'ppid': 4, 'utime': 14, 'stime': 15, 'cutime': 16, 'cstime': 17, 'priority': 18, 'nice': 19, 'num_threads': 20, 'starttime': 22, 'vsize': 23, 'rss': 24, 'processor': 39, } class ProcStat(TypedDict): name: str pid: int state: str ppid: int utime: int stime: int cutime: int cstime: int priority: int nice: int num_threads: int starttime: int vms: int rss: int processor: int def _parse_proc_stat(stat: str) -> ProcStat | None: open_paren = stat.find('(') close_paren = stat.rfind(')') if open_paren == -1 or close_paren == -1 or open_paren > close_paren: return None name = stat[open_paren + 1:close_paren] stat = stat[:open_paren] + stat[open_paren:close_paren].replace(' ', '_') + stat[close_paren:] parts = stat.split() if len(parts) < 52: return None try: return { 'name': name, 'pid': int(parts[_STAT_POS['pid'] - 1]), 'state': parts[_STAT_POS['state'] - 1][0], 'ppid': int(parts[_STAT_POS['ppid'] - 1]), 'utime': int(parts[_STAT_POS['utime'] - 1]), 'stime': int(parts[_STAT_POS['stime'] - 1]), 'cutime': int(parts[_STAT_POS['cutime'] - 1]), 'cstime': int(parts[_STAT_POS['cstime'] - 1]), 'priority': int(parts[_STAT_POS['priority'] - 1]), 'nice': int(parts[_STAT_POS['nice'] - 1]), 'num_threads': int(parts[_STAT_POS['num_threads'] - 1]), 'starttime': int(parts[_STAT_POS['starttime'] - 1]), 'vms': int(parts[_STAT_POS['vsize'] - 1]), 'rss': int(parts[_STAT_POS['rss'] - 1]), 'processor': int(parts[_STAT_POS['processor'] - 1]), } except Exception: cloudlog.exception("failed to parse /proc/<pid>/stat") return None class SmapsData(TypedDict): pss: int # bytes pss_anon: int # bytes pss_shmem: int # bytes _SMAPS_KEYS = {b'Pss:', b'Pss_Anon:', b'Pss_Shmem:'} # smaps_rollup (kernel 4.14+) is ideal but missing on some BSP kernels; # fall back to per-VMA smaps (any kernel). Pss_Anon/Pss_Shmem only in 5.x+. _smaps_path: str | None = None # auto-detected on first call # per-VMA smaps is expensive (kernel walks page tables for every VMA). # cache results and only refresh every N cycles to keep CPU low. _smaps_cache: dict[int, SmapsData] = {} _smaps_cycle = 0 _SMAPS_EVERY = 20 # refresh every 20th cycle (40s at 0.5Hz) def _read_smaps(pid: int) -> SmapsData: global _smaps_path try: if _smaps_path is None: _smaps_path = 'smaps_rollup' if os.path.exists(f'/proc/{pid}/smaps_rollup') else 'smaps' result: SmapsData = {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0} with open(f'/proc/{pid}/{_smaps_path}', 'rb') as f: for line in f: parts = line.split() if len(parts) >= 2 and parts[0] in _SMAPS_KEYS: val = int(parts[1]) * 1024 # kB -> bytes if parts[0] == b'Pss:': result['pss'] += val elif parts[0] == b'Pss_Anon:': result['pss_anon'] += val elif parts[0] == b'Pss_Shmem:': result['pss_shmem'] += val return result except (FileNotFoundError, PermissionError, ProcessLookupError, OSError): return {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0} def _get_smaps_cached(pid: int) -> SmapsData: """Return cached smaps data, refreshing every _SMAPS_EVERY cycles.""" if _smaps_cycle == 0 or pid not in _smaps_cache: _smaps_cache[pid] = _read_smaps(pid) return _smaps_cache.get(pid, {'pss': 0, 'pss_anon': 0, 'pss_shmem': 0}) class ProcExtra(TypedDict): pid: int name: str exe: str cmdline: list[str] _proc_cache: dict[int, ProcExtra] = {} def _get_proc_extra(pid: int, name: str) -> ProcExtra: cache: ProcExtra | None = _proc_cache.get(pid) if cache is None or cache.get('name') != name: exe = '' cmdline: list[str] = [] try: exe = os.readlink(f'/proc/{pid}/exe') except OSError: pass try: with open(f'/proc/{pid}/cmdline', 'rb') as f: cmdline = [c.decode('utf-8', errors='replace') for c in f.read().split(b'\0') if c] except OSError: pass cache = {'pid': pid, 'name': name, 'exe': exe, 'cmdline': cmdline} _proc_cache[pid] = cache return cache def _procs() -> list[ProcStat]: stats: list[ProcStat] = [] for pid_str in os.listdir('/proc'): if not pid_str.isdigit(): continue try: with open(f'/proc/{pid_str}/stat') as f: stat = f.read() parsed = _parse_proc_stat(stat) if parsed is not None: stats.append(parsed) except OSError: continue return stats def build_proc_log_message(msg) -> None: pl = msg.procLog procs = _procs() l = pl.init('procs', len(procs)) for i, r in enumerate(procs): proc = l[i] proc.pid = r['pid'] proc.state = ord(r['state'][0]) proc.ppid = r['ppid'] proc.cpuUser = r['utime'] / JIFFY proc.cpuSystem = r['stime'] / JIFFY proc.cpuChildrenUser = r['cutime'] / JIFFY proc.cpuChildrenSystem = r['cstime'] / JIFFY proc.priority = r['priority'] proc.nice = r['nice'] proc.numThreads = r['num_threads'] proc.startTime = r['starttime'] / JIFFY proc.memVms = r['vms'] proc.memRss = r['rss'] * PAGE_SIZE proc.processor = r['processor'] proc.name = r['name'] extra = _get_proc_extra(r['pid'], r['name']) proc.exe = extra['exe'] cmdline = proc.init('cmdline', len(extra['cmdline'])) for j, arg in enumerate(extra['cmdline']): cmdline[j] = arg # smaps is expensive (kernel walks page tables); skip small processes, use cache if r['rss'] * PAGE_SIZE > 5 * 1024 * 1024: smaps = _get_smaps_cached(r['pid']) proc.memPss = smaps['pss'] proc.memPssAnon = smaps['pss_anon'] proc.memPssShmem = smaps['pss_shmem'] cpu_times = _cpu_times() cpu_list = pl.init('cpuTimes', len(cpu_times)) for i, ct in enumerate(cpu_times): cpu = cpu_list[i] cpu.cpuNum = ct['cpuNum'] cpu.user = ct['user'] cpu.nice = ct['nice'] cpu.system = ct['system'] cpu.idle = ct['idle'] cpu.iowait = ct['iowait'] cpu.irq = ct['irq'] cpu.softirq = ct['softirq'] mem_info = _mem_info() pl.mem.total = mem_info["MemTotal:"] pl.mem.free = mem_info["MemFree:"] pl.mem.available = mem_info["MemAvailable:"] pl.mem.buffers = mem_info["Buffers:"] pl.mem.cached = mem_info["Cached:"] pl.mem.active = mem_info["Active:"] pl.mem.inactive = mem_info["Inactive:"] pl.mem.shared = mem_info["Shmem:"] global _smaps_cycle _smaps_cycle = (_smaps_cycle + 1) % _SMAPS_EVERY def main() -> NoReturn: pm = messaging.PubMaster(['procLog']) rk = Ratekeeper(0.5) while True: msg = messaging.new_message('procLog', valid=True) build_proc_log_message(msg) pm.send('procLog', msg) rk.keep_time() if __name__ == '__main__': main()
{ "repo_id": "commaai/openpilot", "file_path": "system/proclogd.py", "license": "MIT License", "lines": 245, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/controls/tests/test_torqued_lat_accel_offset.py
import numpy as np from cereal import car, messaging from opendbc.car import ACCELERATION_DUE_TO_GRAVITY from opendbc.car import structs from opendbc.car.lateral import get_friction, FRICTION_THRESHOLD from openpilot.common.realtime import DT_MDL from openpilot.selfdrive.locationd.torqued import TorqueEstimator, MIN_BUCKET_POINTS, POINTS_PER_BUCKET, STEER_BUCKET_BOUNDS np.random.seed(0) LA_ERR_STD = 1.0 INPUT_NOISE_STD = 0.08 V_EGO = 30.0 WARMUP_BUCKET_POINTS = (1.5*MIN_BUCKET_POINTS).astype(int) STRAIGHT_ROAD_LA_BOUNDS = (0.02, 0.03) ROLL_BIAS_DEG = 2.0 ROLL_COMPENSATION_BIAS = ACCELERATION_DUE_TO_GRAVITY*float(np.sin(np.deg2rad(ROLL_BIAS_DEG))) TORQUE_TUNE = structs.CarParams.LateralTorqueTuning(latAccelFactor=2.0, latAccelOffset=0.0, friction=0.2) TORQUE_TUNE_BIASED = structs.CarParams.LateralTorqueTuning(latAccelFactor=2.0, latAccelOffset=-ROLL_COMPENSATION_BIAS, friction=0.2) def generate_inputs(torque_tune, la_err_std, input_noise_std=None): rng = np.random.default_rng(0) steer_torques = np.concat([rng.uniform(bnd[0], bnd[1], pts) for bnd, pts in zip(STEER_BUCKET_BOUNDS, WARMUP_BUCKET_POINTS, strict=True)]) la_errs = rng.normal(scale=la_err_std, size=steer_torques.size) frictions = np.array([get_friction(la_err, 0.0, FRICTION_THRESHOLD, torque_tune) for la_err in la_errs]) lat_accels = torque_tune.latAccelFactor*steer_torques + torque_tune.latAccelOffset + frictions if input_noise_std is not None: steer_torques += rng.normal(scale=input_noise_std, size=steer_torques.size) lat_accels += rng.normal(scale=input_noise_std, size=steer_torques.size) return steer_torques, lat_accels def get_warmed_up_estimator(steer_torques, lat_accels): est = TorqueEstimator(car.CarParams()) for steer_torque, lat_accel in zip(steer_torques, lat_accels, strict=True): est.filtered_points.add_point(steer_torque, lat_accel) return est def simulate_straight_road_msgs(est): carControl = messaging.new_message('carControl').carControl carOutput = messaging.new_message('carOutput').carOutput carState = messaging.new_message('carState').carState livePose = messaging.new_message('livePose').livePose carControl.latActive = True carState.vEgo = V_EGO carState.steeringPressed = False ts = DT_MDL*np.arange(2*POINTS_PER_BUCKET) steer_torques = np.concat((np.linspace(-0.03, -0.02, POINTS_PER_BUCKET), np.linspace(0.02, 0.03, POINTS_PER_BUCKET))) lat_accels = TORQUE_TUNE.latAccelFactor * steer_torques for t, steer_torque, lat_accel in zip(ts, steer_torques, lat_accels, strict=True): carOutput.actuatorsOutput.torque = float(-steer_torque) livePose.orientationNED.x = float(np.deg2rad(ROLL_BIAS_DEG)) livePose.angularVelocityDevice.z = float(lat_accel / V_EGO) for which, msg in (('carControl', carControl), ('carOutput', carOutput), ('carState', carState), ('livePose', livePose)): est.handle_log(t, which, msg) def test_estimated_offset(): steer_torques, lat_accels = generate_inputs(TORQUE_TUNE_BIASED, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD) est = get_warmed_up_estimator(steer_torques, lat_accels) msg = est.get_msg() # TODO add lataccelfactor and friction check when we have more accurate estimates assert abs(msg.liveTorqueParameters.latAccelOffsetRaw - TORQUE_TUNE_BIASED.latAccelOffset) < 0.1 def test_straight_road_roll_bias(): steer_torques, lat_accels = generate_inputs(TORQUE_TUNE, la_err_std=LA_ERR_STD, input_noise_std=INPUT_NOISE_STD) est = get_warmed_up_estimator(steer_torques, lat_accels) simulate_straight_road_msgs(est) msg = est.get_msg() assert (msg.liveTorqueParameters.latAccelOffsetRaw < -0.05) and np.isfinite(msg.liveTorqueParameters.latAccelOffsetRaw)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/controls/tests/test_torqued_lat_accel_offset.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/ui/lib/api_helpers.py
import time from functools import lru_cache from openpilot.common.api import Api from openpilot.common.time_helpers import system_time_valid TOKEN_EXPIRY_HOURS = 2 @lru_cache(maxsize=1) def _get_token(dongle_id: str, t: int): if not system_time_valid(): raise RuntimeError("System time is not valid, cannot generate token") return Api(dongle_id).get_token(expiry_hours=TOKEN_EXPIRY_HOURS) def get_token(dongle_id: str): return _get_token(dongle_id, int(time.monotonic() / (TOKEN_EXPIRY_HOURS / 2 * 60 * 60)))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/lib/api_helpers.py", "license": "MIT License", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:system/ui/lib/networkmanager.py
from enum import IntEnum # NetworkManager device states class NMDeviceState(IntEnum): # https://networkmanager.dev/docs/api/1.46/nm-dbus-types.html#NMDeviceState UNKNOWN = 0 UNMANAGED = 10 UNAVAILABLE = 20 DISCONNECTED = 30 PREPARE = 40 CONFIG = 50 NEED_AUTH = 60 IP_CONFIG = 70 IP_CHECK = 80 SECONDARIES = 90 ACTIVATED = 100 DEACTIVATING = 110 FAILED = 120 class NMDeviceStateReason(IntEnum): # https://networkmanager.dev/docs/api/1.46/nm-dbus-types.html#NMDeviceStateReason NONE = 0 UNKNOWN = 1 IP_CONFIG_UNAVAILABLE = 5 NO_SECRETS = 7 SUPPLICANT_DISCONNECT = 8 SUPPLICANT_TIMEOUT = 11 CONNECTION_REMOVED = 38 USER_REQUESTED = 39 SSID_NOT_FOUND = 53 NEW_ACTIVATION = 60 # NetworkManager constants NM = "org.freedesktop.NetworkManager" NM_PATH = '/org/freedesktop/NetworkManager' NM_IFACE = 'org.freedesktop.NetworkManager' NM_ACCESS_POINT_IFACE = 'org.freedesktop.NetworkManager.AccessPoint' NM_SETTINGS_PATH = '/org/freedesktop/NetworkManager/Settings' NM_SETTINGS_IFACE = 'org.freedesktop.NetworkManager.Settings' NM_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Settings.Connection' NM_ACTIVE_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Connection.Active' NM_WIRELESS_IFACE = 'org.freedesktop.NetworkManager.Device.Wireless' NM_PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' NM_DEVICE_IFACE = 'org.freedesktop.NetworkManager.Device' NM_IP4_CONFIG_IFACE = 'org.freedesktop.NetworkManager.IP4Config' NM_DEVICE_TYPE_WIFI = 2 NM_DEVICE_TYPE_MODEM = 8 # https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags NM_802_11_AP_FLAGS_NONE = 0x0 NM_802_11_AP_FLAGS_PRIVACY = 0x1 NM_802_11_AP_FLAGS_WPS = 0x2 # https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001 NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002 NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010 NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020 NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100 NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/lib/networkmanager.py", "license": "MIT License", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:tools/lib/file_sources.py
from collections.abc import Callable from openpilot.tools.lib.comma_car_segments import get_url as get_comma_segments_url from openpilot.tools.lib.openpilotci import get_url from openpilot.tools.lib.filereader import DATA_ENDPOINT, file_exists, internal_source_available from openpilot.tools.lib.route import Route, SegmentRange, FileName # When passed a tuple of file names, each source will return the first that exists (rlog.zst, rlog.bz2) FileNames = tuple[str, ...] Source = Callable[[SegmentRange, list[int], FileNames], dict[int, str]] InternalUnavailableException = Exception("Internal source not available") def comma_api_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames) -> dict[int, str]: route = Route(sr.route_name) # comma api will have already checked if the file exists if fns == FileName.RLOG: return {seg: route.log_paths()[seg] for seg in seg_idxs if route.log_paths()[seg] is not None} else: return {seg: route.qlog_paths()[seg] for seg in seg_idxs if route.qlog_paths()[seg] is not None} def internal_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames, endpoint_url: str = DATA_ENDPOINT) -> dict[int, str]: if not internal_source_available(endpoint_url): raise InternalUnavailableException def get_internal_url(sr: SegmentRange, seg, file): return f"{endpoint_url.rstrip('/')}/{sr.dongle_id}/{sr.log_id}/{seg}/{file}" return eval_source({seg: [get_internal_url(sr, seg, fn) for fn in fns] for seg in seg_idxs}) def openpilotci_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames) -> dict[int, str]: return eval_source({seg: [get_url(sr.route_name, seg, fn) for fn in fns] for seg in seg_idxs}) def comma_car_segments_source(sr: SegmentRange, seg_idxs: list[int], fns: FileNames) -> dict[int, str]: return eval_source({seg: get_comma_segments_url(sr.route_name, seg) for seg in seg_idxs}) def eval_source(files: dict[int, list[str] | str]) -> dict[int, str]: # Returns valid file URLs given a list of possible file URLs for each segment (e.g. rlog.bz2, rlog.zst) valid_files: dict[int, str] = {} for seg_idx, urls in files.items(): if isinstance(urls, str): urls = [urls] # Add first valid file URL for url in urls: if file_exists(url): valid_files[seg_idx] = url break return valid_files
{ "repo_id": "commaai/openpilot", "file_path": "tools/lib/file_sources.py", "license": "MIT License", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/watch3.py
#!/usr/bin/env python3 import pyray as rl from msgq.visionipc import VisionStreamType from openpilot.system.ui.lib.application import gui_app from openpilot.selfdrive.ui.onroad.cameraview import CameraView if __name__ == "__main__": gui_app.init_window("watch3") road = CameraView("camerad", VisionStreamType.VISION_STREAM_ROAD) driver = CameraView("camerad", VisionStreamType.VISION_STREAM_DRIVER) wide = CameraView("camerad", VisionStreamType.VISION_STREAM_WIDE_ROAD) for _ in gui_app.render(): road.render(rl.Rectangle(gui_app.width // 4, 0, gui_app.width // 2, gui_app.height // 2)) driver.render(rl.Rectangle(0, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2)) wide.render(rl.Rectangle(gui_app.width // 2, gui_app.height // 2, gui_app.width // 2, gui_app.height // 2))
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/watch3.py", "license": "MIT License", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/tests/test_raylib_ui.py
import time from openpilot.selfdrive.test.helpers import with_processes @with_processes(["ui"]) def test_raylib_ui(): """Test initialization of the UI widgets is successful.""" time.sleep(1)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/tests/test_raylib_ui.py", "license": "MIT License", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:system/ui/lib/emoji.py
import io import re from PIL import Image, ImageDraw, ImageFont import pyray as rl from openpilot.system.ui.lib.application import FONT_DIR _emoji_font: ImageFont.FreeTypeFont | None = None _cache: dict[str, rl.Texture] = {} EMOJI_REGEX = re.compile( """[\U0001F600-\U0001F64F \U0001F300-\U0001F5FF \U0001F680-\U0001F6FF \U0001F1E0-\U0001F1FF \U00002700-\U000027BF \U0001F900-\U0001F9FF \U00002600-\U000026FF \U00002300-\U000023FF \U00002B00-\U00002BFF \U0001FA70-\U0001FAFF \U0001F700-\U0001F77F \u2640-\u2642 \u2600-\u2B55 \u200d \u23cf \u23e9 \u231a \ufe0f \u3030 ]+""".replace("\n", ""), flags=re.UNICODE ) def _load_emoji_font() -> ImageFont.FreeTypeFont | None: global _emoji_font if _emoji_font is None: _emoji_font = ImageFont.truetype(str(FONT_DIR.joinpath("NotoColorEmoji.ttf")), 109) return _emoji_font def find_emoji(text): return [(m.start(), m.end(), m.group()) for m in EMOJI_REGEX.finditer(text)] def emoji_tex(emoji): if emoji not in _cache: img = Image.new("RGBA", (128, 128), (0, 0, 0, 0)) draw = ImageDraw.Draw(img) draw.text((0, 0), emoji, font=_load_emoji_font(), embedded_color=True) with io.BytesIO() as buffer: img.save(buffer, format="PNG") l = buffer.tell() buffer.seek(0) _cache[emoji] = rl.load_texture_from_image(rl.load_image_from_memory(".png", buffer.getvalue(), l)) return _cache[emoji]
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/lib/emoji.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
commaai/openpilot:selfdrive/selfdrived/helpers.py
import math from enum import StrEnum, auto from cereal import car, messaging from openpilot.common.realtime import DT_CTRL from openpilot.selfdrive.locationd.helpers import Pose from opendbc.car import ACCELERATION_DUE_TO_GRAVITY from opendbc.car.lateral import ISO_LATERAL_ACCEL from opendbc.car.interfaces import ACCEL_MIN, ACCEL_MAX MIN_EXCESSIVE_ACTUATION_COUNT = int(0.25 / DT_CTRL) MIN_LATERAL_ENGAGE_BUFFER = int(1 / DT_CTRL) class ExcessiveActuationType(StrEnum): LONGITUDINAL = auto() LATERAL = auto() class ExcessiveActuationCheck: def __init__(self): self._excessive_counter = 0 self._engaged_counter = 0 def update(self, sm: messaging.SubMaster, CS: car.CarState, calibrated_pose: Pose) -> ExcessiveActuationType | None: # CS.aEgo can be noisy to bumps in the road, transitioning from standstill, losing traction, etc. # longitudinal accel_calibrated = calibrated_pose.acceleration.x excessive_long_actuation = sm['carControl'].longActive and (accel_calibrated > ACCEL_MAX * 2 or accel_calibrated < ACCEL_MIN * 2) # lateral yaw_rate = calibrated_pose.angular_velocity.yaw roll = sm['liveParameters'].roll roll_compensated_lateral_accel = (CS.vEgo * yaw_rate) - (math.sin(roll) * ACCELERATION_DUE_TO_GRAVITY) # Prevent false positives after overriding excessive_lat_actuation = False self._engaged_counter = self._engaged_counter + 1 if sm['carControl'].latActive and not CS.steeringPressed else 0 if self._engaged_counter > MIN_LATERAL_ENGAGE_BUFFER: if abs(roll_compensated_lateral_accel) > ISO_LATERAL_ACCEL * 2: excessive_lat_actuation = True # livePose acceleration can be noisy due to bad mounting or aliased livePose measurements livepose_valid = abs(CS.aEgo - accel_calibrated) < 2 self._excessive_counter = self._excessive_counter + 1 if livepose_valid and (excessive_long_actuation or excessive_lat_actuation) else 0 excessive_type = None if self._excessive_counter > MIN_EXCESSIVE_ACTUATION_COUNT: if excessive_long_actuation: excessive_type = ExcessiveActuationType.LONGITUDINAL else: excessive_type = ExcessiveActuationType.LATERAL return excessive_type
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/selfdrived/helpers.py", "license": "MIT License", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/feedback/feedbackd.py
#!/usr/bin/env python3 import cereal.messaging as messaging from openpilot.common.params import Params from openpilot.common.swaglog import cloudlog from cereal import car from openpilot.system.micd import SAMPLE_RATE, SAMPLE_BUFFER FEEDBACK_MAX_DURATION = 10.0 ButtonType = car.CarState.ButtonEvent.Type def main(): params = Params() pm = messaging.PubMaster(['userBookmark', 'audioFeedback']) sm = messaging.SubMaster(['rawAudioData', 'bookmarkButton', 'carState']) should_record_audio = False block_num = 0 waiting_for_release = False early_stop_triggered = False while True: sm.update() should_send_bookmark = False # TODO: https://github.com/commaai/openpilot/issues/36015 if False and sm.updated['carState'] and sm['carState'].canValid: for be in sm['carState'].buttonEvents: if be.type == ButtonType.lkas: if be.pressed: if not should_record_audio: if params.get_bool("RecordAudioFeedback"): # Start recording on first press if toggle set should_record_audio = True block_num = 0 waiting_for_release = False early_stop_triggered = False cloudlog.info("LKAS button pressed - starting 10-second audio feedback") else: should_send_bookmark = True # immediately send bookmark if toggle false cloudlog.info("LKAS button pressed - bookmarking") elif should_record_audio and not waiting_for_release: # Wait for release of second press to stop recording early waiting_for_release = True elif waiting_for_release: # Second press released waiting_for_release = False early_stop_triggered = True cloudlog.info("LKAS button released - ending recording early") if should_record_audio and sm.updated['rawAudioData']: raw_audio = sm['rawAudioData'] msg = messaging.new_message('audioFeedback', valid=True) msg.audioFeedback.audio.data = raw_audio.data msg.audioFeedback.audio.sampleRate = raw_audio.sampleRate msg.audioFeedback.blockNum = block_num block_num += 1 if (block_num * SAMPLE_BUFFER / SAMPLE_RATE) >= FEEDBACK_MAX_DURATION or early_stop_triggered: # Check for timeout or early stop should_send_bookmark = True # send bookmark at end of audio segment should_record_audio = False early_stop_triggered = False cloudlog.info("10-second recording completed or second button press - stopping audio feedback") pm.send('audioFeedback', msg) if sm.updated['bookmarkButton']: cloudlog.info("Bookmark button pressed!") should_send_bookmark = True if should_send_bookmark: msg = messaging.new_message('userBookmark', valid=True) pm.send('userBookmark', msg) if __name__ == '__main__': main()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/feedback/feedbackd.py", "license": "MIT License", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/tests/test_feedbackd.py
import pytest import cereal.messaging as messaging from cereal import car from openpilot.common.params import Params from openpilot.system.manager.process_config import managed_processes @pytest.mark.skip("tmp disabled") class TestFeedbackd: def setup_method(self): self.pm = messaging.PubMaster(['carState', 'rawAudioData']) self.sm = messaging.SubMaster(['audioFeedback']) def _send_lkas_button(self, pressed: bool): msg = messaging.new_message('carState') msg.carState.canValid = True msg.carState.buttonEvents = [{'type': car.CarState.ButtonEvent.Type.lkas, 'pressed': pressed}] self.pm.send('carState', msg) def _send_audio_data(self, count: int = 5): for _ in range(count): audio_msg = messaging.new_message('rawAudioData') audio_msg.rawAudioData.data = bytes(1600) # 800 samples of int16 audio_msg.rawAudioData.sampleRate = 16000 self.pm.send('rawAudioData', audio_msg) self.sm.update(timeout=100) @pytest.mark.parametrize("record_feedback", [False, True]) def test_audio_feedback(self, record_feedback): Params().put_bool("RecordAudioFeedback", record_feedback) managed_processes["feedbackd"].start() assert self.pm.wait_for_readers_to_update('carState', timeout=5) assert self.pm.wait_for_readers_to_update('rawAudioData', timeout=5) self._send_lkas_button(pressed=True) self._send_audio_data() self._send_lkas_button(pressed=False) self._send_audio_data() if record_feedback: assert self.sm.updated['audioFeedback'], "audioFeedback should be published when enabled" else: assert not self.sm.updated['audioFeedback'], "audioFeedback should not be published when disabled" self._send_lkas_button(pressed=True) self._send_audio_data() self._send_lkas_button(pressed=False) self._send_audio_data() assert not self.sm.updated['audioFeedback'], "audioFeedback should not be published after second press" managed_processes["feedbackd"].stop()
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/tests/test_feedbackd.py", "license": "MIT License", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:tools/scripts/ssh.py
#!/usr/bin/env python3 import os import sys import argparse import re from openpilot.common.basedir import BASEDIR from openpilot.tools.lib.auth_config import get_token from openpilot.tools.lib.api import CommaApi if __name__ == "__main__": parser = argparse.ArgumentParser(description="A helper for connecting to devices over the comma prime SSH proxy.\ Adding your SSH key to your SSH config is recommended for more convenient use; see https://docs.comma.ai/how-to/connect-to-comma/.") parser.add_argument("device", help="device name or dongle id") parser.add_argument("--host", help="ssh jump server host", default="ssh.comma.ai") parser.add_argument("--port", help="ssh jump server port", default=22, type=int) parser.add_argument("--key", help="ssh key", default=os.path.join(BASEDIR, "system/hardware/tici/id_rsa")) parser.add_argument("--debug", help="enable debug output", action="store_true") args = parser.parse_args() r = CommaApi(get_token()).get("v1/me/devices") devices = {x['dongle_id']: x['alias'] for x in r} if not re.match("[0-9a-zA-Z]{16}", args.device): user_input = args.device.replace(" ", "").lower() matches = { k: v for k, v in devices.items() if isinstance(v, str) and user_input in v.replace(" ", "").lower() } if len(matches) == 1: dongle_id = list(matches.keys())[0] else: print(f"failed to look up dongle id for \"{args.device}\"", file=sys.stderr) if len(matches) > 1: print("found multiple matches:", file=sys.stderr) for k, v in matches.items(): print(f" \"{v}\" ({k})", file=sys.stderr) exit(1) else: dongle_id = args.device name = dongle_id if dongle_id in devices: name = f"{devices[dongle_id]} ({dongle_id})" print(f"connecting to {name} through {args.host}:{args.port} ...") command = [ "ssh", "-i", args.key, "-o", f"ProxyCommand=ssh -i {args.key} -W %h:%p -p %p %h@{args.host}", "-p", str(args.port), ] if args.debug: command += ["-v"] command += [ f"comma@comma-{dongle_id}", ] if args.debug: print(" ".join([f"'{c}'" if " " in c else c for c in command])) os.execvp(command[0], command)
{ "repo_id": "commaai/openpilot", "file_path": "tools/scripts/ssh.py", "license": "MIT License", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:tools/scripts/extract_audio.py
#!/usr/bin/env python3 import os import sys import wave import argparse import numpy as np from openpilot.tools.lib.logreader import LogReader, ReadMode def extract_audio(route_or_segment_name, output_file=None, play=False): lr = LogReader(route_or_segment_name, default_mode=ReadMode.AUTO_INTERACTIVE) audio_messages = list(lr.filter("rawAudioData")) if not audio_messages: print("No rawAudioData messages found in logs") return sample_rate = audio_messages[0].sampleRate audio_chunks = [] total_frames = 0 for msg in audio_messages: audio_array = np.frombuffer(msg.data, dtype=np.int16) audio_chunks.append(audio_array) total_frames += len(audio_array) full_audio = np.concatenate(audio_chunks) print(f"Found {total_frames} frames from {len(audio_messages)} audio messages at {sample_rate} Hz") if output_file: if write_wav_file(output_file, full_audio, sample_rate): print(f"Audio written to {output_file}") else: print("Audio extraction canceled.") if play: play_audio(full_audio, sample_rate) def write_wav_file(filename, audio_data, sample_rate): if os.path.exists(filename): if input(f"File '{filename}' exists. Overwrite? (y/N): ").lower() not in ['y', 'yes']: return False with wave.open(filename, 'wb') as wav_file: wav_file.setnchannels(1) # Mono wav_file.setsampwidth(2) # 16-bit wav_file.setframerate(sample_rate) wav_file.writeframes(audio_data.tobytes()) return True def play_audio(audio_data, sample_rate): try: import sounddevice as sd print("Playing audio... Press Ctrl+C to stop") sd.play(audio_data, sample_rate) sd.wait() except KeyboardInterrupt: print("\nPlayback stopped") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Extract audio data from openpilot logs") parser.add_argument("-o", "--output", help="Output WAV file path") parser.add_argument("--play", action="store_true", help="Play audio with sounddevice") parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name") if len(sys.argv) == 1: parser.print_help() sys.exit() args = parser.parse_args() output_file = args.output if not args.output and not args.play: output_file = "extracted_audio.wav" extract_audio(args.route_or_segment_name.strip(), output_file, args.play)
{ "repo_id": "commaai/openpilot", "file_path": "tools/scripts/extract_audio.py", "license": "MIT License", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:system/ui/widgets/html_render.py
import re import pyray as rl from dataclasses import dataclass from enum import Enum from typing import Any from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel from openpilot.system.ui.lib.wrap_text import wrap_text from openpilot.system.ui.widgets import Widget from openpilot.system.ui.widgets.button import Button, ButtonStyle from openpilot.system.ui.lib.text_measure import measure_text_cached LIST_INDENT_PX = 40 class ElementType(Enum): H1 = "h1" H2 = "h2" H3 = "h3" H4 = "h4" H5 = "h5" H6 = "h6" P = "p" B = "b" UL = "ul" LI = "li" BR = "br" TAG_NAMES = '|'.join([t.value for t in ElementType]) START_TAG_RE = re.compile(f'<({TAG_NAMES})>') END_TAG_RE = re.compile(f'</({TAG_NAMES})>') COMMENT_RE = re.compile(r'<!--.*?-->', flags=re.DOTALL) DOCTYPE_RE = re.compile(r'<!DOCTYPE[^>]*>') HTML_BODY_TAGS_RE = re.compile(r'</?(?:html|head|body)[^>]*>') TOKEN_RE = re.compile(r'</[^>]+>|<[^>]+>|[^<\s]+') def is_tag(token: str) -> tuple[bool, bool, ElementType | None]: supported_tag = bool(START_TAG_RE.fullmatch(token)) supported_end_tag = bool(END_TAG_RE.fullmatch(token)) tag = ElementType(token[1:-1].strip('/')) if supported_tag or supported_end_tag else None return supported_tag, supported_end_tag, tag @dataclass class HtmlElement: type: ElementType content: str font_size: int font_weight: FontWeight margin_top: int margin_bottom: int line_height: float = 0.9 # matches Qt visually, unsure why not default 1.2 indent_level: int = 0 class HtmlRenderer(Widget): def __init__(self, file_path: str | None = None, text: str | None = None, text_size: dict | None = None, text_color: rl.Color = rl.WHITE, center_text: bool = False): super().__init__() self._text_color = text_color self._center_text = center_text self._normal_font = gui_app.font(FontWeight.NORMAL) self._bold_font = gui_app.font(FontWeight.BOLD) self._indent_level = 0 if text_size is None: text_size = {} self._cached_height: float | None = None self._cached_width: int = -1 # Base paragraph size (Qt stylesheet default is 48px in offroad alerts) base_p_size = int(text_size.get(ElementType.P, 48)) # Untagged text defaults to <p> self.styles: dict[ElementType, dict[str, Any]] = { ElementType.H1: {"size": round(base_p_size * 2), "weight": FontWeight.BOLD, "margin_top": 20, "margin_bottom": 16}, ElementType.H2: {"size": round(base_p_size * 1.50), "weight": FontWeight.BOLD, "margin_top": 24, "margin_bottom": 12}, ElementType.H3: {"size": round(base_p_size * 1.17), "weight": FontWeight.BOLD, "margin_top": 20, "margin_bottom": 10}, ElementType.H4: {"size": round(base_p_size * 1.00), "weight": FontWeight.BOLD, "margin_top": 16, "margin_bottom": 8}, ElementType.H5: {"size": round(base_p_size * 0.83), "weight": FontWeight.BOLD, "margin_top": 12, "margin_bottom": 6}, ElementType.H6: {"size": round(base_p_size * 0.67), "weight": FontWeight.BOLD, "margin_top": 10, "margin_bottom": 4}, ElementType.P: {"size": base_p_size, "weight": FontWeight.NORMAL, "margin_top": 8, "margin_bottom": 12}, ElementType.B: {"size": base_p_size, "weight": FontWeight.BOLD, "margin_top": 8, "margin_bottom": 12}, ElementType.LI: {"size": base_p_size, "weight": FontWeight.NORMAL, "color": rl.Color(40, 40, 40, 255), "margin_top": 6, "margin_bottom": 6}, ElementType.BR: {"size": 0, "weight": FontWeight.NORMAL, "margin_top": 0, "margin_bottom": 12}, } self.elements: list[HtmlElement] = [] if file_path is not None: self.parse_html_file(file_path) elif text is not None: self.parse_html_content(text) else: raise ValueError("Either file_path or text must be provided") def parse_html_file(self, file_path: str) -> None: with open(file_path, encoding='utf-8') as file: content = file.read() self.parse_html_content(content) def parse_html_content(self, html_content: str) -> None: self.elements.clear() self._cached_height = None self._cached_width = -1 # Remove HTML comments html_content = COMMENT_RE.sub('', html_content) # Remove DOCTYPE, html, head, body tags but keep their content html_content = DOCTYPE_RE.sub('', html_content) html_content = HTML_BODY_TAGS_RE.sub('', html_content) # Parse HTML tokens = TOKEN_RE.findall(html_content) def close_tag(): nonlocal current_content nonlocal current_tag # If no tag is set, default to paragraph so we don't lose text if current_tag is None: current_tag = ElementType.P text = ' '.join(current_content).strip() current_content = [] if text: if current_tag == ElementType.LI: text = '• ' + text self._add_element(current_tag, text) current_content: list[str] = [] current_tag: ElementType | None = None for token in tokens: is_start_tag, is_end_tag, tag = is_tag(token) if tag is not None: if tag == ElementType.BR: # Close current tag and add a line break close_tag() self._add_element(ElementType.BR, "") elif is_start_tag or is_end_tag: # Always add content regardless of opening or closing tag close_tag() if is_start_tag: current_tag = tag else: current_tag = None # increment after we add the content for the current tag if tag == ElementType.UL: self._indent_level = self._indent_level + 1 if is_start_tag else max(0, self._indent_level - 1) else: current_content.append(token) if current_content: close_tag() def _add_element(self, element_type: ElementType, content: str) -> None: style = self.styles[element_type] element = HtmlElement( type=element_type, content=content, font_size=style["size"], font_weight=style["weight"], margin_top=style["margin_top"], margin_bottom=style["margin_bottom"], indent_level=self._indent_level, ) self.elements.append(element) def _render(self, rect: rl.Rectangle): # TODO: speed up by removing duplicate calculations across renders current_y = rect.y padding = 20 content_width = rect.width - (padding * 2) for element in self.elements: if element.type == ElementType.BR: current_y += element.margin_bottom continue current_y += element.margin_top if current_y > rect.y + rect.height: break if element.content: font = self._get_font(element.font_weight) wrapped_lines = wrap_text(font, element.content, element.font_size, int(content_width)) for line in wrapped_lines: # Use FONT_SCALE from wrapped raylib text functions to match what is drawn if current_y < rect.y - element.font_size * FONT_SCALE: current_y += element.font_size * FONT_SCALE * element.line_height continue if current_y > rect.y + rect.height: break if self._center_text: text_width = measure_text_cached(font, line, element.font_size).x text_x = rect.x + (rect.width - text_width) / 2 else: # left align text_x = rect.x + (max(element.indent_level - 1, 0) * LIST_INDENT_PX) rl.draw_text_ex(font, line, rl.Vector2(text_x + padding, current_y), element.font_size, 0, self._text_color) current_y += element.font_size * FONT_SCALE * element.line_height # Apply bottom margin current_y += element.margin_bottom return current_y - rect.y def get_total_height(self, content_width: int) -> float: if self._cached_height is not None and self._cached_width == content_width: return self._cached_height total_height = 0.0 padding = 20 usable_width = content_width - (padding * 2) for element in self.elements: if element.type == ElementType.BR: total_height += element.margin_bottom continue total_height += element.margin_top if element.content: font = self._get_font(element.font_weight) wrapped_lines = wrap_text(font, element.content, element.font_size, int(usable_width)) for _ in wrapped_lines: total_height += element.font_size * FONT_SCALE * element.line_height total_height += element.margin_bottom # Store result in cache self._cached_height = total_height self._cached_width = content_width return total_height def _get_font(self, weight: FontWeight): if weight == FontWeight.BOLD: return self._bold_font return self._normal_font class HtmlModal(Widget): def __init__(self, file_path: str | None = None, text: str | None = None): super().__init__() self._content = HtmlRenderer(file_path=file_path, text=text) self._scroll_panel = GuiScrollPanel() self._ok_button = Button(tr("OK"), click_callback=gui_app.pop_widget, button_style=ButtonStyle.PRIMARY) def _render(self, rect: rl.Rectangle): margin = 50 content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - (margin * 2), rect.height - (margin * 2)) button_height = 160 button_spacing = 20 scrollable_height = content_rect.height - button_height - button_spacing scrollable_rect = rl.Rectangle(content_rect.x, content_rect.y, content_rect.width, scrollable_height) total_height = self._content.get_total_height(int(scrollable_rect.width)) scroll_content_rect = rl.Rectangle(scrollable_rect.x, scrollable_rect.y, scrollable_rect.width, total_height) scroll_offset = self._scroll_panel.update(scrollable_rect, scroll_content_rect) scroll_content_rect.y += scroll_offset rl.begin_scissor_mode(int(scrollable_rect.x), int(scrollable_rect.y), int(scrollable_rect.width), int(scrollable_rect.height)) self._content.render(scroll_content_rect) rl.end_scissor_mode() button_width = (rect.width - 3 * 50) // 3 button_x = content_rect.x + content_rect.width - button_width button_y = content_rect.y + content_rect.height - button_height button_rect = rl.Rectangle(button_x, button_y, button_width, button_height) self._ok_button.render(button_rect) return -1
{ "repo_id": "commaai/openpilot", "file_path": "system/ui/widgets/html_render.py", "license": "MIT License", "lines": 227, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/ui/widgets/ssh_key.py
import pyray as rl import requests import threading import copy from collections.abc import Callable from enum import Enum from openpilot.common.params import Params from openpilot.system.ui.lib.application import gui_app, FontWeight from openpilot.system.ui.lib.multilang import tr, tr_noop from openpilot.system.ui.lib.text_measure import measure_text_cached from openpilot.system.ui.widgets import DialogResult from openpilot.system.ui.widgets.button import Button, ButtonStyle from openpilot.system.ui.widgets.confirm_dialog import alert_dialog from openpilot.system.ui.widgets.keyboard import Keyboard from openpilot.system.ui.widgets.list_view import ( ItemAction, ListItem, BUTTON_HEIGHT, BUTTON_BORDER_RADIUS, BUTTON_FONT_SIZE, BUTTON_WIDTH, ) VALUE_FONT_SIZE = 48 class SshKeyActionState(Enum): LOADING = tr_noop("LOADING") ADD = tr_noop("ADD") REMOVE = tr_noop("REMOVE") class SshKeyAction(ItemAction): HTTP_TIMEOUT = 15 # seconds MAX_WIDTH = 500 def __init__(self): super().__init__(self.MAX_WIDTH, True) self._keyboard = Keyboard(min_text_size=1) self._params = Params() self._error_message: str = "" self._text_font = gui_app.font(FontWeight.NORMAL) self._button = Button("", click_callback=self._handle_button_click, button_style=ButtonStyle.LIST_ACTION, border_radius=BUTTON_BORDER_RADIUS, font_size=BUTTON_FONT_SIZE) self._refresh_state() def set_touch_valid_callback(self, touch_callback: Callable[[], bool]) -> None: super().set_touch_valid_callback(touch_callback) self._button.set_touch_valid_callback(touch_callback) def _refresh_state(self): self._username = self._params.get("GithubUsername") self._state = SshKeyActionState.REMOVE if self._params.get("GithubSshKeys") else SshKeyActionState.ADD def _render(self, rect: rl.Rectangle) -> bool: # Show error dialog if there's an error if self._error_message: message = copy.copy(self._error_message) gui_app.push_widget(alert_dialog(message)) self._username = "" self._error_message = "" # Draw username if exists if self._username: text_size = measure_text_cached(self._text_font, self._username, VALUE_FONT_SIZE) rl.draw_text_ex( self._text_font, self._username, (rect.x + rect.width - BUTTON_WIDTH - text_size.x - 30, rect.y + (rect.height - text_size.y) / 2), VALUE_FONT_SIZE, 1.0, rl.Color(170, 170, 170, 255), ) # Draw button button_rect = rl.Rectangle(rect.x + rect.width - BUTTON_WIDTH, rect.y + (rect.height - BUTTON_HEIGHT) / 2, BUTTON_WIDTH, BUTTON_HEIGHT) self._button.set_rect(button_rect) self._button.set_text(tr(self._state.value)) self._button.set_enabled(self._state != SshKeyActionState.LOADING) self._button.render(button_rect) return False def _handle_button_click(self): if self._state == SshKeyActionState.ADD: self._keyboard.reset() self._keyboard.set_title(tr("Enter your GitHub username")) self._keyboard.set_callback(self._on_username_submit) gui_app.push_widget(self._keyboard) elif self._state == SshKeyActionState.REMOVE: self._params.remove("GithubUsername") self._params.remove("GithubSshKeys") self._refresh_state() def _on_username_submit(self, result: DialogResult): if result != DialogResult.CONFIRM: return username = self._keyboard.text.strip() if not username: return self._state = SshKeyActionState.LOADING threading.Thread(target=lambda: self._fetch_ssh_key(username), daemon=True).start() def _fetch_ssh_key(self, username: str): try: url = f"https://github.com/{username}.keys" response = requests.get(url, timeout=self.HTTP_TIMEOUT) response.raise_for_status() keys = response.text.strip() if not keys: raise requests.exceptions.HTTPError(tr("No SSH keys found")) # Success - save keys self._params.put("GithubUsername", username) self._params.put("GithubSshKeys", keys) self._state = SshKeyActionState.REMOVE self._username = username except requests.exceptions.Timeout: self._error_message = tr("Request timed out") self._state = SshKeyActionState.ADD except Exception: self._error_message = tr("No SSH keys found for user '{}'").format(username) self._state = SshKeyActionState.ADD def ssh_key_item(title: str | Callable[[], str], description: str | Callable[[], str]) -> ListItem: return ListItem(title=title, description=description, action_item=SshKeyAction())
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/widgets/ssh_key.py", "license": "MIT License", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
commaai/openpilot:selfdrive/locationd/test/test_torqued.py
from cereal import car from openpilot.selfdrive.locationd.torqued import TorqueEstimator def test_cal_percent(): est = TorqueEstimator(car.CarParams()) msg = est.get_msg() assert msg.liveTorqueParameters.calPerc == 0 for (low, high), min_pts in zip(est.filtered_points.buckets.keys(), est.filtered_points.buckets_min_points.values(), strict=True): for _ in range(int(min_pts)): est.filtered_points.add_point((low + high) / 2.0, 0.0) # enough bucket points, but not enough total points msg = est.get_msg() assert msg.liveTorqueParameters.calPerc == (len(est.filtered_points) / est.min_points_total * 100 + 100) / 2 # add enough points to bucket with most capacity key = list(est.filtered_points.buckets)[0] for _ in range(est.min_points_total - len(est.filtered_points)): est.filtered_points.add_point((key[0] + key[1]) / 2.0, 0.0) msg = est.get_msg() assert msg.liveTorqueParameters.calPerc == 100
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/locationd/test/test_torqued.py", "license": "MIT License", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
commaai/openpilot:selfdrive/ui/layouts/settings/firehose.py
import pyray as rl from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE from openpilot.system.ui.lib.multilang import tr, trn, tr_noop from openpilot.system.ui.lib.text_measure import measure_text_cached from openpilot.system.ui.lib.scroll_panel import GuiScrollPanel from openpilot.system.ui.lib.wrap_text import wrap_text from openpilot.selfdrive.ui.mici.layouts.settings.firehose import FirehoseLayoutBase TITLE = tr_noop("Firehose Mode") DESCRIPTION = tr_noop( "openpilot 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." ) INSTRUCTIONS = tr_noop( "For maximum effectiveness, bring your device inside and connect to a good USB-C adapter and Wi-Fi weekly.\n\n" + "Firehose Mode can also work while you're driving if connected to a hotspot or unlimited SIM card.\n\n\n" + "Frequently Asked Questions\n\n" + "Does it matter how or where I drive? Nope, just drive as you normally would.\n\n" + "Do all of my segments get pulled in Firehose Mode? No, we selectively pull a subset of your segments.\n\n" + "What's a good USB-C adapter? Any fast phone or laptop charger should be fine.\n\n" + "Does it matter which software I run? Yes, only upstream openpilot (and particular forks) are able to be used for training." ) class FirehoseLayout(FirehoseLayoutBase): def __init__(self): super().__init__() self._scroll_panel = GuiScrollPanel() def _render(self, rect: rl.Rectangle): # Calculate content dimensions content_rect = rl.Rectangle(rect.x, rect.y, rect.width, self._content_height) # Handle scrolling and render with clipping scroll_offset = self._scroll_panel.update(rect, content_rect) rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) self._content_height = self._render_content(rect, scroll_offset) rl.end_scissor_mode() def _render_content(self, rect: rl.Rectangle, scroll_offset: float) -> int: x = int(rect.x + 40) y = int(rect.y + 40 + scroll_offset) w = int(rect.width - 80) # Title (centered) title_text = tr(TITLE) # live translate title_font = gui_app.font(FontWeight.MEDIUM) text_width = measure_text_cached(title_font, title_text, 100).x title_x = rect.x + (rect.width - text_width) / 2 rl.draw_text_ex(title_font, title_text, rl.Vector2(title_x, y), 100, 0, rl.WHITE) y += 200 # Description y = self._draw_wrapped_text(x, y, w, tr(DESCRIPTION), gui_app.font(FontWeight.NORMAL), 45, rl.WHITE) y += 40 + 20 # Separator rl.draw_rectangle(x, y, w, 2, self.GRAY) y += 30 + 20 # Status status_text, status_color = self._get_status() y = self._draw_wrapped_text(x, y, w, status_text, gui_app.font(FontWeight.BOLD), 60, status_color) y += 20 + 20 # Contribution count (if available) if self._segment_count > 0: contrib_text = trn("{} segment of your driving is in the training dataset so far.", "{} segments of your driving is in the training dataset so far.", self._segment_count).format(self._segment_count) y = self._draw_wrapped_text(x, y, w, contrib_text, gui_app.font(FontWeight.BOLD), 52, rl.WHITE) y += 20 + 20 # Separator rl.draw_rectangle(x, y, w, 2, self.GRAY) y += 30 + 20 # Instructions y = self._draw_wrapped_text(x, y, w, tr(INSTRUCTIONS), gui_app.font(FontWeight.NORMAL), 40, self.LIGHT_GRAY) # bottom margin + remove effect of scroll offset return int(round(y - self._scroll_panel.offset + 40)) def _draw_wrapped_text(self, x, y, width, text, font, font_size, color): wrapped = wrap_text(font, text, font_size, width) for line in wrapped: rl.draw_text_ex(font, line, rl.Vector2(x, y), font_size, 0, color) y += font_size * FONT_SCALE return round(y)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/layouts/settings/firehose.py", "license": "MIT License", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/widgets/exp_mode_button.py
import pyray as rl from openpilot.common.params import Params from openpilot.system.ui.lib.application import gui_app, FontWeight, FONT_SCALE from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.widgets import Widget class ExperimentalModeButton(Widget): def __init__(self): super().__init__() self.img_width = 80 self.horizontal_padding = 25 self.button_height = 125 self.params = Params() self.experimental_mode = self.params.get_bool("ExperimentalMode") self.chill_pixmap = gui_app.texture("icons/couch.png", self.img_width, self.img_width) self.experimental_pixmap = gui_app.texture("icons/experimental_grey.png", self.img_width, self.img_width) def show_event(self): self.experimental_mode = self.params.get_bool("ExperimentalMode") def _get_gradient_colors(self): alpha = 0xCC if self.is_pressed else 0xFF if self.experimental_mode: return rl.Color(255, 155, 63, alpha), rl.Color(219, 56, 34, alpha) else: return rl.Color(20, 255, 171, alpha), rl.Color(35, 149, 255, alpha) def _draw_gradient_background(self, rect): start_color, end_color = self._get_gradient_colors() rl.draw_rectangle_gradient_h(int(rect.x), int(rect.y), int(rect.width), int(rect.height), start_color, end_color) def _render(self, rect): rl.begin_scissor_mode(int(rect.x), int(rect.y), int(rect.width), int(rect.height)) self._draw_gradient_background(rect) rl.draw_rectangle_rounded_lines_ex(self._rect, 0.19, 10, 5, rl.BLACK) rl.end_scissor_mode() # Draw vertical separator line line_x = rect.x + rect.width - self.img_width - (2 * self.horizontal_padding) separator_color = rl.Color(0, 0, 0, 77) # 0x4d = 77 rl.draw_line_ex(rl.Vector2(line_x, rect.y), rl.Vector2(line_x, rect.y + rect.height), 3, separator_color) # Draw text label (left aligned) text = tr("EXPERIMENTAL MODE ON") if self.experimental_mode else tr("CHILL MODE ON") text_x = rect.x + self.horizontal_padding text_y = rect.y + rect.height / 2 - 45 * FONT_SCALE // 2 # Center vertically rl.draw_text_ex(gui_app.font(FontWeight.NORMAL), text, rl.Vector2(int(text_x), int(text_y)), 45, 0, rl.BLACK) # Draw icon (right aligned) icon_x = rect.x + rect.width - self.horizontal_padding - self.img_width icon_y = rect.y + (rect.height - self.img_width) / 2 icon_rect = rl.Rectangle(icon_x, icon_y, self.img_width, self.img_width) # Draw current mode icon current_icon = self.experimental_pixmap if self.experimental_mode else self.chill_pixmap source_rect = rl.Rectangle(0, 0, current_icon.width, current_icon.height) rl.draw_texture_pro(current_icon, source_rect, icon_rect, rl.Vector2(0, 0), 0, rl.WHITE)
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/widgets/exp_mode_button.py", "license": "MIT License", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
commaai/openpilot:selfdrive/ui/widgets/pairing_dialog.py
import pyray as rl import qrcode import numpy as np import time from openpilot.common.api import Api from openpilot.common.swaglog import cloudlog from openpilot.common.params import Params from openpilot.system.ui.widgets import Widget from openpilot.system.ui.lib.application import FontWeight, gui_app from openpilot.system.ui.lib.multilang import tr from openpilot.system.ui.lib.wrap_text import wrap_text from openpilot.system.ui.lib.text_measure import measure_text_cached from openpilot.system.ui.widgets.button import IconButton from openpilot.selfdrive.ui.ui_state import ui_state class PairingDialog(Widget): """Dialog for device pairing with QR code.""" QR_REFRESH_INTERVAL = 300 # 5 minutes in seconds def __init__(self): super().__init__() self.params = Params() self.qr_texture: rl.Texture | None = None self.last_qr_generation = float('-inf') self._close_btn = IconButton(gui_app.texture("icons/close.png", 80, 80)) self._close_btn.set_click_callback(gui_app.pop_widget) def _get_pairing_url(self) -> str: try: dongle_id = self.params.get("DongleId") or "" token = Api(dongle_id).get_token({'pair': True}) except Exception: cloudlog.exception("Failed to get pairing token") token = "" return f"https://connect.comma.ai/?pair={token}" def _generate_qr_code(self) -> None: try: qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4) qr.add_data(self._get_pairing_url()) qr.make(fit=True) pil_img = qr.make_image(fill_color="black", back_color="white").convert('RGBA') img_array = np.array(pil_img, dtype=np.uint8) if self.qr_texture and self.qr_texture.id != 0: rl.unload_texture(self.qr_texture) rl_image = rl.Image() rl_image.data = rl.ffi.cast("void *", img_array.ctypes.data) rl_image.width = pil_img.width rl_image.height = pil_img.height rl_image.mipmaps = 1 rl_image.format = rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 self.qr_texture = rl.load_texture_from_image(rl_image) except Exception: cloudlog.exception("QR code generation failed") self.qr_texture = None def _check_qr_refresh(self) -> None: current_time = time.monotonic() if current_time - self.last_qr_generation >= self.QR_REFRESH_INTERVAL: self._generate_qr_code() self.last_qr_generation = current_time def _update_state(self): if ui_state.prime_state.is_paired(): gui_app.pop_widget() def _render(self, rect: rl.Rectangle) -> int: rl.clear_background(rl.Color(224, 224, 224, 255)) self._check_qr_refresh() margin = 70 content_rect = rl.Rectangle(rect.x + margin, rect.y + margin, rect.width - 2 * margin, rect.height - 2 * margin) y = content_rect.y # Close button close_size = 80 pad = 20 close_rect = rl.Rectangle(content_rect.x - pad, y - pad, close_size + pad * 2, close_size + pad * 2) self._close_btn.render(close_rect) y += close_size + 40 # Title title = tr("Pair your device to your comma account") title_font = gui_app.font(FontWeight.NORMAL) left_width = int(content_rect.width * 0.5 - 15) title_wrapped = wrap_text(title_font, title, 75, left_width) rl.draw_text_ex(title_font, "\n".join(title_wrapped), rl.Vector2(content_rect.x, y), 75, 0.0, rl.BLACK) y += len(title_wrapped) * 75 + 60 # Two columns: instructions and QR code remaining_height = content_rect.height - (y - content_rect.y) right_width = content_rect.width // 2 - 20 # Instructions self._render_instructions(rl.Rectangle(content_rect.x, y, left_width, remaining_height)) # QR code qr_size = min(right_width, content_rect.height) - 40 qr_x = content_rect.x + left_width + 40 + (right_width - qr_size) // 2 qr_y = content_rect.y self._render_qr_code(rl.Rectangle(qr_x, qr_y, qr_size, qr_size)) return -1 def _render_instructions(self, rect: rl.Rectangle) -> None: instructions = [ tr("Go to https://connect.comma.ai on your phone"), tr("Click \"add new device\" and scan the QR code on the right"), tr("Bookmark connect.comma.ai to your home screen to use it like an app"), ] font = gui_app.font(FontWeight.BOLD) y = rect.y for i, text in enumerate(instructions): circle_radius = 25 circle_x = rect.x + circle_radius + 15 text_x = rect.x + circle_radius * 2 + 40 text_width = rect.width - (circle_radius * 2 + 40) wrapped = wrap_text(font, text, 47, int(text_width)) text_height = len(wrapped) * 47 circle_y = y + text_height // 2 # Circle and number rl.draw_circle(int(circle_x), int(circle_y), circle_radius, rl.Color(70, 70, 70, 255)) number = str(i + 1) number_size = measure_text_cached(font, number, 30) rl.draw_text_ex(font, number, (int(circle_x - number_size.x // 2), int(circle_y - number_size.y // 2)), 30, 0, rl.WHITE) # Text rl.draw_text_ex(font, "\n".join(wrapped), rl.Vector2(text_x, y), 47, 0.0, rl.BLACK) y += text_height + 50 def _render_qr_code(self, rect: rl.Rectangle) -> None: if not self.qr_texture: rl.draw_rectangle_rounded(rect, 0.1, 20, rl.Color(240, 240, 240, 255)) error_font = gui_app.font(FontWeight.BOLD) rl.draw_text_ex( error_font, tr("QR Code Error"), rl.Vector2(rect.x + 20, rect.y + rect.height // 2 - 15), 30, 0.0, rl.RED ) return source = rl.Rectangle(0, 0, self.qr_texture.width, self.qr_texture.height) rl.draw_texture_pro(self.qr_texture, source, rect, rl.Vector2(0, 0), 0, rl.WHITE) def __del__(self): if self.qr_texture and self.qr_texture.id != 0: rl.unload_texture(self.qr_texture) if __name__ == "__main__": gui_app.init_window("pairing device") pairing = PairingDialog() gui_app.push_widget(pairing) try: for _ in gui_app.render(): pass finally: del pairing
{ "repo_id": "commaai/openpilot", "file_path": "selfdrive/ui/widgets/pairing_dialog.py", "license": "MIT License", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex