code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
#pragma clang diagnostic ignored "-Wexceptions" #include "selfdrive/modeld/runners/snpemodel.h" #include <cstring> #include <memory> #include <string> #include <utility> #include <vector> #include "common/util.h" #include "common/timing.h" void PrintErrorStringAndExit() { std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; std::exit(EXIT_FAILURE); } SNPEModel::SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool _use_tf8, cl_context context) { output = _output; output_size = _output_size; use_tf8 = _use_tf8; #ifdef QCOM2 if (runtime == USE_GPU_RUNTIME) { snpe_runtime = zdl::DlSystem::Runtime_t::GPU; } else if (runtime == USE_DSP_RUNTIME) { snpe_runtime = zdl::DlSystem::Runtime_t::DSP; } else { snpe_runtime = zdl::DlSystem::Runtime_t::CPU; } assert(zdl::SNPE::SNPEFactory::isRuntimeAvailable(snpe_runtime)); #endif model_data = util::read_file(path); assert(model_data.size() > 0); // load model std::unique_ptr<zdl::DlContainer::IDlContainer> container = zdl::DlContainer::IDlContainer::open((uint8_t*)model_data.data(), model_data.size()); if (!container) { PrintErrorStringAndExit(); } LOGW("loaded model with size: %lu", model_data.size()); // create model runner zdl::SNPE::SNPEBuilder snpe_builder(container.get()); while (!snpe) { #ifdef QCOM2 snpe = snpe_builder.setOutputLayers({}) .setRuntimeProcessor(snpe_runtime) .setUseUserSuppliedBuffers(true) .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) .build(); #else snpe = snpe_builder.setOutputLayers({}) .setUseUserSuppliedBuffers(true) .setPerformanceProfile(zdl::DlSystem::PerformanceProfile_t::HIGH_PERFORMANCE) .build(); #endif if (!snpe) std::cerr << zdl::DlSystem::getLastErrorString() << std::endl; } // create output buffer zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float; zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); const auto &output_tensor_names_opt = snpe->getOutputTensorNames(); if (!output_tensor_names_opt) throw std::runtime_error("Error obtaining output tensor names"); const auto &output_tensor_names = *output_tensor_names_opt; assert(output_tensor_names.size() == 1); const char *output_tensor_name = output_tensor_names.at(0); const zdl::DlSystem::TensorShape &buffer_shape = snpe->getInputOutputBufferAttributes(output_tensor_name)->getDims(); if (output_size != 0) { assert(output_size == buffer_shape[1]); } else { output_size = buffer_shape[1]; } std::vector<size_t> output_strides = {output_size * sizeof(float), sizeof(float)}; output_buffer = ub_factory.createUserBuffer(output, output_size * sizeof(float), output_strides, &ub_encoding_float); output_map.add(output_tensor_name, output_buffer.get()); } void SNPEModel::addInput(const std::string name, float *buffer, int size) { const int idx = inputs.size(); const auto &input_tensor_names_opt = snpe->getInputTensorNames(); if (!input_tensor_names_opt) throw std::runtime_error("Error obtaining input tensor names"); const auto &input_tensor_names = *input_tensor_names_opt; const char *input_tensor_name = input_tensor_names.at(idx); const bool input_tf8 = use_tf8 && strcmp(input_tensor_name, "input_img") == 0; // TODO: This is a terrible hack, get rid of this name check both here and in onnx_runner.py LOGW("adding index %d: %s", idx, input_tensor_name); zdl::DlSystem::UserBufferEncodingFloat ub_encoding_float; zdl::DlSystem::UserBufferEncodingTf8 ub_encoding_tf8(0, 1./255); // network takes 0-1 zdl::DlSystem::IUserBufferFactory &ub_factory = zdl::SNPE::SNPEFactory::getUserBufferFactory(); zdl::DlSystem::UserBufferEncoding *input_encoding = input_tf8 ? (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_tf8 : (zdl::DlSystem::UserBufferEncoding*)&ub_encoding_float; const auto &buffer_shape_opt = snpe->getInputDimensions(input_tensor_name); const zdl::DlSystem::TensorShape &buffer_shape = *buffer_shape_opt; size_t size_of_input = input_tf8 ? sizeof(uint8_t) : sizeof(float); std::vector<size_t> strides(buffer_shape.rank()); strides[strides.size() - 1] = size_of_input; size_t product = 1; for (size_t i = 0; i < buffer_shape.rank(); i++) product *= buffer_shape[i]; size_t stride = strides[strides.size() - 1]; for (size_t i = buffer_shape.rank() - 1; i > 0; i--) { stride *= buffer_shape[i]; strides[i-1] = stride; } auto input_buffer = ub_factory.createUserBuffer(buffer, product*size_of_input, strides, input_encoding); input_map.add(input_tensor_name, input_buffer.get()); inputs.push_back(std::unique_ptr<SNPEModelInput>(new SNPEModelInput(name, buffer, size, std::move(input_buffer)))); } void SNPEModel::execute() { if (!snpe->execute(input_map, output_map)) { PrintErrorStringAndExit(); } }
2301_81045437/openpilot
selfdrive/modeld/runners/snpemodel.cc
C++
mit
5,043
#pragma once #pragma clang diagnostic ignored "-Wdeprecated-declarations" #include <memory> #include <string> #include <utility> #include <DlContainer/IDlContainer.hpp> #include <DlSystem/DlError.hpp> #include <DlSystem/ITensor.hpp> #include <DlSystem/ITensorFactory.hpp> #include <DlSystem/IUserBuffer.hpp> #include <DlSystem/IUserBufferFactory.hpp> #include <SNPE/SNPE.hpp> #include <SNPE/SNPEBuilder.hpp> #include <SNPE/SNPEFactory.hpp> #include "selfdrive/modeld/runners/runmodel.h" struct SNPEModelInput : public ModelInput { std::unique_ptr<zdl::DlSystem::IUserBuffer> snpe_buffer; SNPEModelInput(const std::string _name, float *_buffer, int _size, std::unique_ptr<zdl::DlSystem::IUserBuffer> _snpe_buffer) : ModelInput(_name, _buffer, _size), snpe_buffer(std::move(_snpe_buffer)) {} void setBuffer(float *_buffer, int _size) { ModelInput::setBuffer(_buffer, _size); assert(snpe_buffer->setBufferAddress(_buffer) == true); } }; class SNPEModel : public RunModel { public: SNPEModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL); void addInput(const std::string name, float *buffer, int size); void execute(); private: std::string model_data; #ifdef QCOM2 zdl::DlSystem::Runtime_t snpe_runtime; #endif // snpe model stuff std::unique_ptr<zdl::SNPE::SNPE> snpe; zdl::DlSystem::UserBufferMap input_map; zdl::DlSystem::UserBufferMap output_map; std::unique_ptr<zdl::DlSystem::IUserBuffer> output_buffer; bool use_tf8; float *output; size_t output_size; };
2301_81045437/openpilot
selfdrive/modeld/runners/snpemodel.h
C++
mit
1,587
# distutils: language = c++ from libcpp.string cimport string from cereal.visionipc.visionipc cimport cl_context cdef extern from "selfdrive/modeld/runners/snpemodel.h": cdef cppclass SNPEModel: SNPEModel(string, float*, size_t, int, bool, cl_context)
2301_81045437/openpilot
selfdrive/modeld/runners/snpemodel.pxd
Cython
mit
261
# distutils: language = c++ # cython: c_string_encoding=ascii import os from libcpp cimport bool from libcpp.string cimport string from .snpemodel cimport SNPEModel as cppSNPEModel from selfdrive.modeld.models.commonmodel_pyx cimport CLContext from selfdrive.modeld.runners.runmodel_pyx cimport RunModel from selfdrive.modeld.runners.runmodel cimport RunModel as cppRunModel os.environ['ADSP_LIBRARY_PATH'] = "/data/pythonpath/third_party/snpe/dsp/" cdef class SNPEModel(RunModel): def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context): self.model = <cppRunModel *> new cppSNPEModel(path, &output[0], len(output), runtime, use_tf8, context.context)
2301_81045437/openpilot
selfdrive/modeld/runners/snpemodel_pyx.pyx
Cython
mit
701
#include "selfdrive/modeld/runners/thneedmodel.h" #include <string> #include "common/swaglog.h" ThneedModel::ThneedModel(const std::string path, float *_output, size_t _output_size, int runtime, bool luse_tf8, cl_context context) { thneed = new Thneed(true, context); thneed->load(path.c_str()); thneed->clexec(); recorded = false; output = _output; } void* ThneedModel::getCLBuffer(const std::string name) { int index = -1; for (int i = 0; i < inputs.size(); i++) { if (name == inputs[i]->name) { index = i; break; } } if (index == -1) { LOGE("Tried to get CL buffer for input `%s` but no input with this name exists", name.c_str()); assert(false); } if (thneed->input_clmem.size() >= inputs.size()) { return &thneed->input_clmem[inputs.size() - index - 1]; } else { return nullptr; } } void ThneedModel::execute() { if (!recorded) { thneed->record = true; float *input_buffers[inputs.size()]; for (int i = 0; i < inputs.size(); i++) { input_buffers[inputs.size() - i - 1] = inputs[i]->buffer; } thneed->copy_inputs(input_buffers); thneed->clexec(); thneed->copy_output(output); thneed->stop(); recorded = true; } else { float *input_buffers[inputs.size()]; for (int i = 0; i < inputs.size(); i++) { input_buffers[inputs.size() - i - 1] = inputs[i]->buffer; } thneed->execute(input_buffers, output); } }
2301_81045437/openpilot
selfdrive/modeld/runners/thneedmodel.cc
C++
mit
1,447
#pragma once #include <string> #include "selfdrive/modeld/runners/runmodel.h" #include "selfdrive/modeld/thneed/thneed.h" class ThneedModel : public RunModel { public: ThneedModel(const std::string path, float *_output, size_t _output_size, int runtime, bool use_tf8 = false, cl_context context = NULL); void *getCLBuffer(const std::string name); void execute(); private: Thneed *thneed = NULL; bool recorded; float *output; };
2301_81045437/openpilot
selfdrive/modeld/runners/thneedmodel.h
C++
mit
443
# distutils: language = c++ from libcpp.string cimport string from cereal.visionipc.visionipc cimport cl_context cdef extern from "selfdrive/modeld/runners/thneedmodel.h": cdef cppclass ThneedModel: ThneedModel(string, float*, size_t, int, bool, cl_context)
2301_81045437/openpilot
selfdrive/modeld/runners/thneedmodel.pxd
Cython
mit
267
# distutils: language = c++ # cython: c_string_encoding=ascii from libcpp cimport bool from libcpp.string cimport string from .thneedmodel cimport ThneedModel as cppThneedModel from selfdrive.modeld.models.commonmodel_pyx cimport CLContext from selfdrive.modeld.runners.runmodel_pyx cimport RunModel from selfdrive.modeld.runners.runmodel cimport RunModel as cppRunModel cdef class ThneedModel(RunModel): def __cinit__(self, string path, float[:] output, int runtime, bool use_tf8, CLContext context): self.model = <cppRunModel *> new cppThneedModel(path, &output[0], len(output), runtime, use_tf8, context.context)
2301_81045437/openpilot
selfdrive/modeld/runners/thneedmodel_pyx.pyx
Cython
mit
625
// clang++ -O2 repro.cc && ./a.out #include <sched.h> #include <sys/types.h> #include <unistd.h> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> static inline double millis_since_boot() { struct timespec t; clock_gettime(CLOCK_BOOTTIME, &t); return t.tv_sec * 1000.0 + t.tv_nsec * 1e-6; } #define MODEL_WIDTH 320 #define MODEL_HEIGHT 640 // null function still breaks it #define input_lambda(x) x // this is copied from models/dmonitoring.cc, and is the code that triggers the issue void inner(uint8_t *resized_buf, float *net_input_buf) { int resized_width = MODEL_WIDTH; int resized_height = MODEL_HEIGHT; // one shot conversion, O(n) anyway // yuvframe2tensor, normalize for (int r = 0; r < MODEL_HEIGHT/2; r++) { for (int c = 0; c < MODEL_WIDTH/2; c++) { // Y_ul net_input_buf[(c*MODEL_HEIGHT/2) + r] = input_lambda(resized_buf[(2*r*resized_width) + (2*c)]); // Y_ur net_input_buf[(c*MODEL_HEIGHT/2) + r + (2*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width) + (2*c+1)]); // Y_dl net_input_buf[(c*MODEL_HEIGHT/2) + r + ((MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c)]); // Y_dr net_input_buf[(c*MODEL_HEIGHT/2) + r + (3*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(2*r*resized_width+1) + (2*c+1)]); // U net_input_buf[(c*MODEL_HEIGHT/2) + r + (4*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + (r*resized_width/2) + c]); // V net_input_buf[(c*MODEL_HEIGHT/2) + r + (5*(MODEL_WIDTH/2)*(MODEL_HEIGHT/2))] = input_lambda(resized_buf[(resized_width*resized_height) + ((resized_width/2)*(resized_height/2)) + (r*resized_width/2) + c]); } } } float trial() { int resized_width = MODEL_WIDTH; int resized_height = MODEL_HEIGHT; int yuv_buf_len = (MODEL_WIDTH/2) * (MODEL_HEIGHT/2) * 6; // Y|u|v -> y|y|y|y|u|v // allocate the buffers uint8_t *resized_buf = (uint8_t*)malloc(resized_width*resized_height*3/2); float *net_input_buf = (float*)malloc(yuv_buf_len*sizeof(float)); printf("allocate -- %p 0x%x -- %p 0x%lx\n", resized_buf, resized_width*resized_height*3/2, net_input_buf, yuv_buf_len*sizeof(float)); // test for bad buffers static int CNT = 20; float avg = 0.0; for (int i = 0; i < CNT; i++) { double s4 = millis_since_boot(); inner(resized_buf, net_input_buf); double s5 = millis_since_boot(); avg += s5-s4; } avg /= CNT; // once it's bad, it's reliably bad if (avg > 10) { printf("HIT %f\n", avg); printf("BAD\n"); for (int i = 0; i < 200; i++) { double s4 = millis_since_boot(); inner(resized_buf, net_input_buf); double s5 = millis_since_boot(); printf("%.2f ", s5-s4); } printf("\n"); exit(0); } // don't free so we get a different buffer each time //free(resized_buf); //free(net_input_buf); return avg; } int main() { while (true) { float ret = trial(); printf("got %f\n", ret); } }
2301_81045437/openpilot
selfdrive/modeld/tests/dmon_lag/repro.cc
C++
mit
3,116
#include <SNPE/SNPE.hpp> #include <SNPE/SNPEBuilder.hpp> #include <SNPE/SNPEFactory.hpp> #include <DlContainer/IDlContainer.hpp> #include <DlSystem/DlError.hpp> #include <DlSystem/ITensor.hpp> #include <DlSystem/ITensorFactory.hpp> #include <iostream> #include <fstream> #include <sstream> using namespace std; int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p) { return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) - ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec); } void PrintErrorStringAndExit() { cout << "ERROR!" << endl; const char* const errStr = zdl::DlSystem::getLastErrorString(); std::cerr << errStr << std::endl; std::exit(EXIT_FAILURE); } zdl::DlSystem::Runtime_t checkRuntime() { static zdl::DlSystem::Version_t Version = zdl::SNPE::SNPEFactory::getLibraryVersion(); static zdl::DlSystem::Runtime_t Runtime; std::cout << "SNPE Version: " << Version.asString().c_str() << std::endl; //Print Version number if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::DSP)) { std::cout << "Using DSP runtime" << std::endl; Runtime = zdl::DlSystem::Runtime_t::DSP; } else if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(zdl::DlSystem::Runtime_t::GPU)) { std::cout << "Using GPU runtime" << std::endl; Runtime = zdl::DlSystem::Runtime_t::GPU; } else { std::cout << "Using cpu runtime" << std::endl; Runtime = zdl::DlSystem::Runtime_t::CPU; } return Runtime; } void test(char *filename) { static zdl::DlSystem::Runtime_t runtime = checkRuntime(); std::unique_ptr<zdl::DlContainer::IDlContainer> container; container = zdl::DlContainer::IDlContainer::open(filename); if (!container) { PrintErrorStringAndExit(); } cout << "start build" << endl; std::unique_ptr<zdl::SNPE::SNPE> snpe; { snpe = NULL; zdl::SNPE::SNPEBuilder snpeBuilder(container.get()); snpe = snpeBuilder.setOutputLayers({}) .setRuntimeProcessor(runtime) .setUseUserSuppliedBuffers(false) //.setDebugMode(true) .build(); if (!snpe) { cout << "ERROR!" << endl; const char* const errStr = zdl::DlSystem::getLastErrorString(); std::cerr << errStr << std::endl; } cout << "ran snpeBuilder" << endl; } const auto &strList_opt = snpe->getInputTensorNames(); if (!strList_opt) throw std::runtime_error("Error obtaining input tensor names"); cout << "get input tensor names done" << endl; const auto &strList = *strList_opt; static zdl::DlSystem::TensorMap inputTensorMap; static zdl::DlSystem::TensorMap outputTensorMap; vector<std::unique_ptr<zdl::DlSystem::ITensor> > inputs; for (int i = 0; i < strList.size(); i++) { cout << "input name: " << strList.at(i) << endl; const auto &inputDims_opt = snpe->getInputDimensions(strList.at(i)); const auto &inputShape = *inputDims_opt; inputs.push_back(zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape)); inputTensorMap.add(strList.at(i), inputs[i].get()); } struct timespec start, end; cout << "**** starting benchmark ****" << endl; for (int i = 0; i < 50; i++) { clock_gettime(CLOCK_MONOTONIC, &start); int err = snpe->execute(inputTensorMap, outputTensorMap); assert(err == true); clock_gettime(CLOCK_MONOTONIC, &end); uint64_t timeElapsed = timespecDiff(&end, &start); printf("time: %f ms\n", timeElapsed*1.0/1e6); } } void get_testframe(int index, std::unique_ptr<zdl::DlSystem::ITensor> &input) { FILE * pFile; string filepath="/data/ipt/quantize_samples/sample_input_"+std::to_string(index); pFile = fopen(filepath.c_str(), "rb"); int length = 1*6*160*320*4; float * frame_buffer = new float[length/4]; // 32/8 fread(frame_buffer, length, 1, pFile); // std::cout << *(frame_buffer+length/4-1) << std::endl; std::copy(frame_buffer, frame_buffer+(length/4), input->begin()); fclose(pFile); } void SaveITensor(const std::string& path, const zdl::DlSystem::ITensor* tensor) { std::ofstream os(path, std::ofstream::binary); if (!os) { std::cerr << "Failed to open output file for writing: " << path << "\n"; std::exit(EXIT_FAILURE); } for ( auto it = tensor->cbegin(); it != tensor->cend(); ++it ) { float f = *it; if (!os.write(reinterpret_cast<char*>(&f), sizeof(float))) { std::cerr << "Failed to write data to: " << path << "\n"; std::exit(EXIT_FAILURE); } } } void testrun(char* modelfile) { static zdl::DlSystem::Runtime_t runtime = checkRuntime(); std::unique_ptr<zdl::DlContainer::IDlContainer> container; container = zdl::DlContainer::IDlContainer::open(modelfile); if (!container) { PrintErrorStringAndExit(); } cout << "start build" << endl; std::unique_ptr<zdl::SNPE::SNPE> snpe; { snpe = NULL; zdl::SNPE::SNPEBuilder snpeBuilder(container.get()); snpe = snpeBuilder.setOutputLayers({}) .setRuntimeProcessor(runtime) .setUseUserSuppliedBuffers(false) //.setDebugMode(true) .build(); if (!snpe) { cout << "ERROR!" << endl; const char* const errStr = zdl::DlSystem::getLastErrorString(); std::cerr << errStr << std::endl; } cout << "ran snpeBuilder" << endl; } const auto &strList_opt = snpe->getInputTensorNames(); if (!strList_opt) throw std::runtime_error("Error obtaining input tensor names"); cout << "get input tensor names done" << endl; const auto &strList = *strList_opt; static zdl::DlSystem::TensorMap inputTensorMap; static zdl::DlSystem::TensorMap outputTensorMap; assert(strList.size() == 1); const auto &inputDims_opt = snpe->getInputDimensions(strList.at(0)); const auto &inputShape = *inputDims_opt; std::cout << "winkwink" << std::endl; for (int i=0; i<10000; i++) { std::unique_ptr<zdl::DlSystem::ITensor> input; input = zdl::SNPE::SNPEFactory::getTensorFactory().createTensor(inputShape); get_testframe(i, input); snpe->execute(input.get(), outputTensorMap); zdl::DlSystem::StringList tensorNames = outputTensorMap.getTensorNames(); std::for_each(tensorNames.begin(), tensorNames.end(), [&](const char* name) { std::ostringstream path; path << "/data/opt/Result_" << std::to_string(i) << ".raw"; auto tensorPtr = outputTensorMap.getTensor(name); SaveITensor(path.str(), tensorPtr); }); } } int main(int argc, char* argv[]) { if (argc < 2) { printf("usage: %s <filename>\n", argv[0]); return -1; } if (argc == 2) { while (true) test(argv[1]); } else if (argc == 3) { testrun(argv[1]); } return 0; }
2301_81045437/openpilot
selfdrive/modeld/tests/snpe_benchmark/benchmark.cc
C++
mit
6,608
#!/bin/sh -e clang++ -I /data/openpilot/third_party/snpe/include/ -L/data/pythonpath/third_party/snpe/aarch64 -lSNPE benchmark.cc -o benchmark export LD_LIBRARY_PATH="/data/pythonpath/third_party/snpe/aarch64/:$HOME/openpilot/third_party/snpe/x86_64/:$LD_LIBRARY_PATH" exec ./benchmark $1
2301_81045437/openpilot
selfdrive/modeld/tests/snpe_benchmark/benchmark.sh
Shell
mit
289
#!/bin/bash clang++ -I /home/batman/one/external/tensorflow/include/ -L /home/batman/one/external/tensorflow/lib -Wl,-rpath=/home/batman/one/external/tensorflow/lib main.cc -ltensorflow
2301_81045437/openpilot
selfdrive/modeld/tests/tf_test/build.sh
Shell
mit
186
#include <cassert> #include <cstdio> #include <cstdlib> #include "tensorflow/c/c_api.h" void* read_file(const char* path, size_t* out_len) { FILE* f = fopen(path, "r"); if (!f) { return NULL; } fseek(f, 0, SEEK_END); long f_len = ftell(f); rewind(f); char* buf = (char*)calloc(f_len, 1); assert(buf); size_t num_read = fread(buf, f_len, 1, f); fclose(f); if (num_read != 1) { free(buf); return NULL; } if (out_len) { *out_len = f_len; } return buf; } static void DeallocateBuffer(void* data, size_t) { free(data); } int main(int argc, char* argv[]) { TF_Buffer* buf; TF_Graph* graph; TF_Status* status; char *path = argv[1]; // load model { size_t model_size; char tmp[1024]; snprintf(tmp, sizeof(tmp), "%s.pb", path); printf("loading model %s\n", tmp); uint8_t *model_data = (uint8_t *)read_file(tmp, &model_size); buf = TF_NewBuffer(); buf->data = model_data; buf->length = model_size; buf->data_deallocator = DeallocateBuffer; printf("loaded model of size %d\n", model_size); } // import graph status = TF_NewStatus(); graph = TF_NewGraph(); TF_ImportGraphDefOptions *opts = TF_NewImportGraphDefOptions(); TF_GraphImportGraphDef(graph, buf, opts, status); TF_DeleteImportGraphDefOptions(opts); TF_DeleteBuffer(buf); if (TF_GetCode(status) != TF_OK) { printf("FAIL: %s\n", TF_Message(status)); } else { printf("SUCCESS\n"); } }
2301_81045437/openpilot
selfdrive/modeld/tests/tf_test/main.cc
C++
mit
1,470
#!/usr/bin/env python3 import sys import tensorflow as tf with open(sys.argv[1], "rb") as f: graph_def = tf.compat.v1.GraphDef() graph_def.ParseFromString(f.read()) #tf.io.write_graph(graph_def, '', sys.argv[1]+".try")
2301_81045437/openpilot
selfdrive/modeld/tests/tf_test/pb_loader.py
Python
mit
226
#!/usr/bin/env python3 # type: ignore import os import time import numpy as np import cereal.messaging as messaging from openpilot.system.manager.process_config import managed_processes N = int(os.getenv("N", "5")) TIME = int(os.getenv("TIME", "30")) if __name__ == "__main__": sock = messaging.sub_sock('modelV2', conflate=False, timeout=1000) execution_times = [] for _ in range(N): os.environ['LOGPRINT'] = 'debug' managed_processes['modeld'].start() time.sleep(5) t = [] start = time.monotonic() while time.monotonic() - start < TIME: msgs = messaging.drain_sock(sock, wait_for_one=True) for m in msgs: t.append(m.modelV2.modelExecutionTime) execution_times.append(np.array(t[10:]) * 1000) managed_processes['modeld'].stop() print("\n\n") print(f"ran modeld {N} times for {TIME}s each") for _, t in enumerate(execution_times): print(f"\tavg: {sum(t)/len(t):0.2f}ms, min: {min(t):0.2f}ms, max: {max(t):0.2f}ms") print("\n\n")
2301_81045437/openpilot
selfdrive/modeld/tests/timing/benchmark.py
Python
mit
1,009
#include <cassert> #include <set> #include "third_party/json11/json11.hpp" #include "common/util.h" #include "common/clutil.h" #include "common/swaglog.h" #include "selfdrive/modeld/thneed/thneed.h" using namespace json11; extern map<cl_program, string> g_program_source; void Thneed::load(const char *filename) { LOGD("Thneed::load: loading from %s\n", filename); string buf = util::read_file(filename); int jsz = *(int *)buf.data(); string jsonerr; string jj(buf.data() + sizeof(int), jsz); Json jdat = Json::parse(jj, jsonerr); map<cl_mem, cl_mem> real_mem; real_mem[NULL] = NULL; int ptr = sizeof(int)+jsz; for (auto &obj : jdat["objects"].array_items()) { auto mobj = obj.object_items(); int sz = mobj["size"].int_value(); cl_mem clbuf = NULL; if (mobj["buffer_id"].string_value().size() > 0) { // image buffer must already be allocated clbuf = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; assert(mobj["needs_load"].bool_value() == false); } else { if (mobj["needs_load"].bool_value()) { clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, &buf[ptr], NULL); if (debug >= 1) printf("loading %p %d @ 0x%X\n", clbuf, sz, ptr); ptr += sz; } else { // TODO: is there a faster way to init zeroed out buffers? void *host_zeros = calloc(sz, 1); clbuf = clCreateBuffer(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, sz, host_zeros, NULL); free(host_zeros); } } assert(clbuf != NULL); if (mobj["arg_type"] == "image2d_t" || mobj["arg_type"] == "image1d_t") { cl_image_desc desc = {0}; desc.image_type = (mobj["arg_type"] == "image2d_t") ? CL_MEM_OBJECT_IMAGE2D : CL_MEM_OBJECT_IMAGE1D_BUFFER; desc.image_width = mobj["width"].int_value(); desc.image_height = mobj["height"].int_value(); desc.image_row_pitch = mobj["row_pitch"].int_value(); assert(sz == desc.image_height*desc.image_row_pitch); #ifdef QCOM2 desc.buffer = clbuf; #else // TODO: we are creating unused buffers on PC clReleaseMemObject(clbuf); #endif cl_image_format format = {0}; format.image_channel_order = CL_RGBA; format.image_channel_data_type = mobj["float32"].bool_value() ? CL_FLOAT : CL_HALF_FLOAT; cl_int errcode; #ifndef QCOM2 if (mobj["needs_load"].bool_value()) { clbuf = clCreateImage(context, CL_MEM_COPY_HOST_PTR | CL_MEM_READ_WRITE, &format, &desc, &buf[ptr-sz], &errcode); } else { clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); } #else clbuf = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &errcode); #endif if (clbuf == NULL) { LOGE("clError: %s create image %zux%zu rp %zu with buffer %p\n", cl_get_error_string(errcode), desc.image_width, desc.image_height, desc.image_row_pitch, desc.buffer); } assert(clbuf != NULL); } real_mem[*(cl_mem*)(mobj["id"].string_value().data())] = clbuf; } map<string, cl_program> g_programs; for (const auto &[name, source] : jdat["programs"].object_items()) { if (debug >= 1) printf("building %s with size %zu\n", name.c_str(), source.string_value().size()); g_programs[name] = cl_program_from_source(context, device_id, source.string_value()); } for (auto &obj : jdat["inputs"].array_items()) { auto mobj = obj.object_items(); int sz = mobj["size"].int_value(); cl_mem aa = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; input_clmem.push_back(aa); input_sizes.push_back(sz); LOGD("Thneed::load: adding input %s with size %d\n", mobj["name"].string_value().data(), sz); cl_int cl_err; void *ret = clEnqueueMapBuffer(command_queue, aa, CL_TRUE, CL_MAP_WRITE, 0, sz, 0, NULL, NULL, &cl_err); if (cl_err != CL_SUCCESS) LOGE("clError: %s map %p %d\n", cl_get_error_string(cl_err), aa, sz); assert(cl_err == CL_SUCCESS); inputs.push_back(ret); } for (auto &obj : jdat["outputs"].array_items()) { auto mobj = obj.object_items(); int sz = mobj["size"].int_value(); LOGD("Thneed::save: adding output with size %d\n", sz); // TODO: support multiple outputs output = real_mem[*(cl_mem*)(mobj["buffer_id"].string_value().data())]; assert(output != NULL); } for (auto &obj : jdat["binaries"].array_items()) { string name = obj["name"].string_value(); size_t length = obj["length"].int_value(); if (debug >= 1) printf("binary %s with size %zu\n", name.c_str(), length); g_programs[name] = cl_program_from_binary(context, device_id, (const uint8_t*)&buf[ptr], length); ptr += length; } for (auto &obj : jdat["kernels"].array_items()) { auto gws = obj["global_work_size"]; auto lws = obj["local_work_size"]; auto kk = shared_ptr<CLQueuedKernel>(new CLQueuedKernel(this)); kk->name = obj["name"].string_value(); kk->program = g_programs[kk->name]; kk->work_dim = obj["work_dim"].int_value(); for (int i = 0; i < kk->work_dim; i++) { kk->global_work_size[i] = gws[i].int_value(); kk->local_work_size[i] = lws[i].int_value(); } kk->num_args = obj["num_args"].int_value(); for (int i = 0; i < kk->num_args; i++) { string arg = obj["args"].array_items()[i].string_value(); int arg_size = obj["args_size"].array_items()[i].int_value(); kk->args_size.push_back(arg_size); if (arg_size == 8) { cl_mem val = *(cl_mem*)(arg.data()); val = real_mem[val]; kk->args.push_back(string((char*)&val, sizeof(val))); } else { kk->args.push_back(arg); } } kq.push_back(kk); } clFinish(command_queue); }
2301_81045437/openpilot
selfdrive/modeld/thneed/serialize.cc
C++
mit
5,778
#pragma once #ifndef __user #define __user __attribute__(()) #endif #include <cstdint> #include <cstdlib> #include <memory> #include <string> #include <vector> #include <CL/cl.h> #include "third_party/linux/include/msm_kgsl.h" using namespace std; cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value); namespace json11 { class Json; } class Thneed; class GPUMalloc { public: GPUMalloc(int size, int fd); ~GPUMalloc(); void *alloc(int size); private: uint64_t base; int remaining; }; class CLQueuedKernel { public: CLQueuedKernel(Thneed *lthneed) { thneed = lthneed; } CLQueuedKernel(Thneed *lthneed, cl_kernel _kernel, cl_uint _work_dim, const size_t *_global_work_size, const size_t *_local_work_size); cl_int exec(); void debug_print(bool verbose); int get_arg_num(const char *search_arg_name); cl_program program; string name; cl_uint num_args; vector<string> arg_names; vector<string> arg_types; vector<string> args; vector<int> args_size; cl_kernel kernel = NULL; json11::Json to_json() const; cl_uint work_dim; size_t global_work_size[3] = {0}; size_t local_work_size[3] = {0}; private: Thneed *thneed; }; class CachedIoctl { public: virtual void exec() {} }; class CachedSync: public CachedIoctl { public: CachedSync(Thneed *lthneed, string ldata) { thneed = lthneed; data = ldata; } void exec(); private: Thneed *thneed; string data; }; class CachedCommand: public CachedIoctl { public: CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd); void exec(); private: void disassemble(int cmd_index); struct kgsl_gpu_command cache; unique_ptr<kgsl_command_object[]> cmds; unique_ptr<kgsl_command_object[]> objs; Thneed *thneed; vector<shared_ptr<CLQueuedKernel> > kq; }; class Thneed { public: Thneed(bool do_clinit=false, cl_context _context = NULL); void stop(); void execute(float **finputs, float *foutput, bool slow=false); void wait(); vector<cl_mem> input_clmem; vector<void *> inputs; vector<size_t> input_sizes; cl_mem output = NULL; cl_context context = NULL; cl_command_queue command_queue; cl_device_id device_id; int context_id; // protected? bool record = false; int debug; int timestamp; #ifdef QCOM2 unique_ptr<GPUMalloc> ram; vector<unique_ptr<CachedIoctl> > cmds; int fd; #endif // all CL kernels void copy_inputs(float **finputs, bool internal=false); void copy_output(float *foutput); cl_int clexec(); vector<shared_ptr<CLQueuedKernel> > kq; // pending CL kernels vector<shared_ptr<CLQueuedKernel> > ckq; // loading void load(const char *filename); private: void clinit(); };
2301_81045437/openpilot
selfdrive/modeld/thneed/thneed.h
C++
mit
2,942
#include "selfdrive/modeld/thneed/thneed.h" #include <cassert> #include <cstring> #include <map> #include "common/clutil.h" #include "common/timing.h" map<pair<cl_kernel, int>, string> g_args; map<pair<cl_kernel, int>, int> g_args_size; map<cl_program, string> g_program_source; void Thneed::stop() { //printf("Thneed::stop: recorded %lu commands\n", cmds.size()); record = false; } void Thneed::clinit() { device_id = cl_get_device_id(CL_DEVICE_TYPE_DEFAULT); if (context == NULL) context = CL_CHECK_ERR(clCreateContext(NULL, 1, &device_id, NULL, NULL, &err)); //cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, CL_QUEUE_PROFILING_ENABLE, 0}; cl_command_queue_properties props[3] = {CL_QUEUE_PROPERTIES, 0, 0}; command_queue = CL_CHECK_ERR(clCreateCommandQueueWithProperties(context, device_id, props, &err)); printf("Thneed::clinit done\n"); } cl_int Thneed::clexec() { if (debug >= 1) printf("Thneed::clexec: running %lu queued kernels\n", kq.size()); for (auto &k : kq) { if (record) ckq.push_back(k); cl_int ret = k->exec(); assert(ret == CL_SUCCESS); } return clFinish(command_queue); } void Thneed::copy_inputs(float **finputs, bool internal) { for (int idx = 0; idx < inputs.size(); ++idx) { if (debug >= 1) printf("copying %lu -- %p -> %p (cl %p)\n", input_sizes[idx], finputs[idx], inputs[idx], input_clmem[idx]); if (internal) { // if it's internal, using memcpy is fine since the buffer sync is cached in the ioctl layer if (finputs[idx] != NULL) memcpy(inputs[idx], finputs[idx], input_sizes[idx]); } else { if (finputs[idx] != NULL) CL_CHECK(clEnqueueWriteBuffer(command_queue, input_clmem[idx], CL_TRUE, 0, input_sizes[idx], finputs[idx], 0, NULL, NULL)); } } } void Thneed::copy_output(float *foutput) { if (output != NULL) { size_t sz; clGetMemObjectInfo(output, CL_MEM_SIZE, sizeof(sz), &sz, NULL); if (debug >= 1) printf("copying %lu for output %p -> %p\n", sz, output, foutput); CL_CHECK(clEnqueueReadBuffer(command_queue, output, CL_TRUE, 0, sz, foutput, 0, NULL, NULL)); } else { printf("CAUTION: model output is NULL, does it have no outputs?\n"); } } // *********** CLQueuedKernel *********** CLQueuedKernel::CLQueuedKernel(Thneed *lthneed, cl_kernel _kernel, cl_uint _work_dim, const size_t *_global_work_size, const size_t *_local_work_size) { thneed = lthneed; kernel = _kernel; work_dim = _work_dim; assert(work_dim <= 3); for (int i = 0; i < work_dim; i++) { global_work_size[i] = _global_work_size[i]; local_work_size[i] = _local_work_size[i]; } char _name[0x100]; clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME, sizeof(_name), _name, NULL); name = string(_name); clGetKernelInfo(kernel, CL_KERNEL_NUM_ARGS, sizeof(num_args), &num_args, NULL); // get args for (int i = 0; i < num_args; i++) { char arg_name[0x100] = {0}; clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); arg_names.push_back(string(arg_name)); clGetKernelArgInfo(kernel, i, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); arg_types.push_back(string(arg_name)); args.push_back(g_args[make_pair(kernel, i)]); args_size.push_back(g_args_size[make_pair(kernel, i)]); } // get program clGetKernelInfo(kernel, CL_KERNEL_PROGRAM, sizeof(program), &program, NULL); } int CLQueuedKernel::get_arg_num(const char *search_arg_name) { for (int i = 0; i < num_args; i++) { if (arg_names[i] == search_arg_name) return i; } printf("failed to find %s in %s\n", search_arg_name, name.c_str()); assert(false); } cl_int CLQueuedKernel::exec() { if (kernel == NULL) { kernel = clCreateKernel(program, name.c_str(), NULL); arg_names.clear(); arg_types.clear(); for (int j = 0; j < num_args; j++) { char arg_name[0x100] = {0}; clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_NAME, sizeof(arg_name), arg_name, NULL); arg_names.push_back(string(arg_name)); clGetKernelArgInfo(kernel, j, CL_KERNEL_ARG_TYPE_NAME, sizeof(arg_name), arg_name, NULL); arg_types.push_back(string(arg_name)); cl_int ret; if (args[j].size() != 0) { assert(args[j].size() == args_size[j]); ret = thneed_clSetKernelArg(kernel, j, args[j].size(), args[j].data()); } else { ret = thneed_clSetKernelArg(kernel, j, args_size[j], NULL); } assert(ret == CL_SUCCESS); } } if (thneed->debug >= 1) { debug_print(thneed->debug >= 2); } return clEnqueueNDRangeKernel(thneed->command_queue, kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL); } void CLQueuedKernel::debug_print(bool verbose) { printf("%p %56s -- ", kernel, name.c_str()); for (int i = 0; i < work_dim; i++) { printf("%4zu ", global_work_size[i]); } printf(" -- "); for (int i = 0; i < work_dim; i++) { printf("%4zu ", local_work_size[i]); } printf("\n"); if (verbose) { for (int i = 0; i < num_args; i++) { string arg = args[i]; printf(" %s %s", arg_types[i].c_str(), arg_names[i].c_str()); void *arg_value = (void*)arg.data(); int arg_size = arg.size(); if (arg_size == 0) { printf(" (size) %d", args_size[i]); } else if (arg_size == 1) { printf(" = %d", *((char*)arg_value)); } else if (arg_size == 2) { printf(" = %d", *((short*)arg_value)); } else if (arg_size == 4) { if (arg_types[i] == "float") { printf(" = %f", *((float*)arg_value)); } else { printf(" = %d", *((int*)arg_value)); } } else if (arg_size == 8) { cl_mem val = (cl_mem)(*((uintptr_t*)arg_value)); printf(" = %p", val); if (val != NULL) { cl_mem_object_type obj_type; clGetMemObjectInfo(val, CL_MEM_TYPE, sizeof(obj_type), &obj_type, NULL); if (arg_types[i] == "image2d_t" || arg_types[i] == "image1d_t" || obj_type == CL_MEM_OBJECT_IMAGE2D) { cl_image_format format; size_t width, height, depth, array_size, row_pitch, slice_pitch; cl_mem buf; clGetImageInfo(val, CL_IMAGE_FORMAT, sizeof(format), &format, NULL); assert(format.image_channel_order == CL_RGBA); assert(format.image_channel_data_type == CL_HALF_FLOAT || format.image_channel_data_type == CL_FLOAT); clGetImageInfo(val, CL_IMAGE_WIDTH, sizeof(width), &width, NULL); clGetImageInfo(val, CL_IMAGE_HEIGHT, sizeof(height), &height, NULL); clGetImageInfo(val, CL_IMAGE_ROW_PITCH, sizeof(row_pitch), &row_pitch, NULL); clGetImageInfo(val, CL_IMAGE_DEPTH, sizeof(depth), &depth, NULL); clGetImageInfo(val, CL_IMAGE_ARRAY_SIZE, sizeof(array_size), &array_size, NULL); clGetImageInfo(val, CL_IMAGE_SLICE_PITCH, sizeof(slice_pitch), &slice_pitch, NULL); assert(depth == 0); assert(array_size == 0); assert(slice_pitch == 0); clGetImageInfo(val, CL_IMAGE_BUFFER, sizeof(buf), &buf, NULL); size_t sz = 0; if (buf != NULL) clGetMemObjectInfo(buf, CL_MEM_SIZE, sizeof(sz), &sz, NULL); printf(" image %zu x %zu rp %zu @ %p buffer %zu", width, height, row_pitch, buf, sz); } else { size_t sz; clGetMemObjectInfo(val, CL_MEM_SIZE, sizeof(sz), &sz, NULL); printf(" buffer %zu", sz); } } } printf("\n"); } } } cl_int thneed_clSetKernelArg(cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void *arg_value) { g_args_size[make_pair(kernel, arg_index)] = arg_size; if (arg_value != NULL) { g_args[make_pair(kernel, arg_index)] = string((char*)arg_value, arg_size); } else { g_args[make_pair(kernel, arg_index)] = string(""); } cl_int ret = clSetKernelArg(kernel, arg_index, arg_size, arg_value); return ret; }
2301_81045437/openpilot
selfdrive/modeld/thneed/thneed_common.cc
C++
mit
8,095
#include "selfdrive/modeld/thneed/thneed.h" #include <cassert> #include "common/clutil.h" #include "common/timing.h" Thneed::Thneed(bool do_clinit, cl_context _context) { context = _context; if (do_clinit) clinit(); char *thneed_debug_env = getenv("THNEED_DEBUG"); debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; } void Thneed::execute(float **finputs, float *foutput, bool slow) { uint64_t tb, te; if (debug >= 1) tb = nanos_since_boot(); // ****** copy inputs copy_inputs(finputs); // ****** run commands clexec(); // ****** copy outputs copy_output(foutput); if (debug >= 1) { te = nanos_since_boot(); printf("model exec in %lu us\n", (te-tb)/1000); } }
2301_81045437/openpilot
selfdrive/modeld/thneed/thneed_pc.cc
C++
mit
718
#include "selfdrive/modeld/thneed/thneed.h" #include <dlfcn.h> #include <sys/mman.h> #include <cassert> #include <cerrno> #include <cstring> #include <map> #include <string> #include "common/clutil.h" #include "common/timing.h" Thneed *g_thneed = NULL; int g_fd = -1; void hexdump(uint8_t *d, int len) { assert((len%4) == 0); printf(" dumping %p len 0x%x\n", d, len); for (int i = 0; i < len/4; i++) { if (i != 0 && (i%0x10) == 0) printf("\n"); printf("%8x ", d[i]); } printf("\n"); } // *********** ioctl interceptor *********** extern "C" { int (*my_ioctl)(int filedes, unsigned long request, void *argp) = NULL; #undef ioctl int ioctl(int filedes, unsigned long request, void *argp) { request &= 0xFFFFFFFF; // needed on QCOM2 if (my_ioctl == NULL) my_ioctl = reinterpret_cast<decltype(my_ioctl)>(dlsym(RTLD_NEXT, "ioctl")); Thneed *thneed = g_thneed; // save the fd if (request == IOCTL_KGSL_GPUOBJ_ALLOC) g_fd = filedes; // note that this runs always, even without a thneed object if (request == IOCTL_KGSL_DRAWCTXT_CREATE) { struct kgsl_drawctxt_create *create = (struct kgsl_drawctxt_create *)argp; create->flags &= ~KGSL_CONTEXT_PRIORITY_MASK; create->flags |= 6 << KGSL_CONTEXT_PRIORITY_SHIFT; // priority from 1-15, 1 is max priority printf("IOCTL_KGSL_DRAWCTXT_CREATE: creating context with flags 0x%x\n", create->flags); } if (thneed != NULL) { if (request == IOCTL_KGSL_GPU_COMMAND) { struct kgsl_gpu_command *cmd = (struct kgsl_gpu_command *)argp; if (thneed->record) { thneed->timestamp = cmd->timestamp; thneed->context_id = cmd->context_id; thneed->cmds.push_back(unique_ptr<CachedCommand>(new CachedCommand(thneed, cmd))); } if (thneed->debug >= 1) { printf("IOCTL_KGSL_GPU_COMMAND(%2zu): flags: 0x%lx context_id: %u timestamp: %u numcmds: %d numobjs: %d\n", thneed->cmds.size(), cmd->flags, cmd->context_id, cmd->timestamp, cmd->numcmds, cmd->numobjs); } } else if (request == IOCTL_KGSL_GPUOBJ_SYNC) { struct kgsl_gpuobj_sync *cmd = (struct kgsl_gpuobj_sync *)argp; struct kgsl_gpuobj_sync_obj *objs = (struct kgsl_gpuobj_sync_obj *)(cmd->objs); if (thneed->debug >= 2) { printf("IOCTL_KGSL_GPUOBJ_SYNC count:%d ", cmd->count); for (int i = 0; i < cmd->count; i++) { printf(" -- offset:0x%lx len:0x%lx id:%d op:%d ", objs[i].offset, objs[i].length, objs[i].id, objs[i].op); } printf("\n"); } if (thneed->record) { thneed->cmds.push_back(unique_ptr<CachedSync>(new CachedSync(thneed, string((char *)objs, sizeof(struct kgsl_gpuobj_sync_obj)*cmd->count)))); } } else if (request == IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID) { struct kgsl_device_waittimestamp_ctxtid *cmd = (struct kgsl_device_waittimestamp_ctxtid *)argp; if (thneed->debug >= 1) { printf("IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID: context_id: %d timestamp: %d timeout: %d\n", cmd->context_id, cmd->timestamp, cmd->timeout); } } else if (request == IOCTL_KGSL_SETPROPERTY) { if (thneed->debug >= 1) { struct kgsl_device_getproperty *prop = (struct kgsl_device_getproperty *)argp; printf("IOCTL_KGSL_SETPROPERTY: 0x%x sizebytes:%zu\n", prop->type, prop->sizebytes); if (thneed->debug >= 2) { hexdump((uint8_t *)prop->value, prop->sizebytes); if (prop->type == KGSL_PROP_PWR_CONSTRAINT) { struct kgsl_device_constraint *constraint = (struct kgsl_device_constraint *)prop->value; hexdump((uint8_t *)constraint->data, constraint->size); } } } } else if (request == IOCTL_KGSL_DRAWCTXT_CREATE || request == IOCTL_KGSL_DRAWCTXT_DESTROY) { // this happens } else if (request == IOCTL_KGSL_GPUOBJ_ALLOC || request == IOCTL_KGSL_GPUOBJ_FREE) { // this happens } else { if (thneed->debug >= 1) { printf("other ioctl %lx\n", request); } } } int ret = my_ioctl(filedes, request, argp); // NOTE: This error message goes into stdout and messes up pyenv // if (ret != 0) printf("ioctl returned %d with errno %d\n", ret, errno); return ret; } } // *********** GPUMalloc *********** GPUMalloc::GPUMalloc(int size, int fd) { struct kgsl_gpuobj_alloc alloc; memset(&alloc, 0, sizeof(alloc)); alloc.size = size; alloc.flags = 0x10000a00; ioctl(fd, IOCTL_KGSL_GPUOBJ_ALLOC, &alloc); void *addr = mmap64(NULL, alloc.mmapsize, 0x3, 0x1, fd, alloc.id*0x1000); assert(addr != MAP_FAILED); base = (uint64_t)addr; remaining = size; } GPUMalloc::~GPUMalloc() { // TODO: free the GPU malloced area } void *GPUMalloc::alloc(int size) { void *ret = (void*)base; size = (size+0xff) & (~0xFF); assert(size <= remaining); remaining -= size; base += size; return ret; } // *********** CachedSync, at the ioctl layer *********** void CachedSync::exec() { struct kgsl_gpuobj_sync cmd; cmd.objs = (uint64_t)data.data(); cmd.obj_len = data.length(); cmd.count = data.length() / sizeof(struct kgsl_gpuobj_sync_obj); int ret = ioctl(thneed->fd, IOCTL_KGSL_GPUOBJ_SYNC, &cmd); assert(ret == 0); } // *********** CachedCommand, at the ioctl layer *********** CachedCommand::CachedCommand(Thneed *lthneed, struct kgsl_gpu_command *cmd) { thneed = lthneed; assert(cmd->numsyncs == 0); memcpy(&cache, cmd, sizeof(cache)); if (cmd->numcmds > 0) { cmds = make_unique<struct kgsl_command_object[]>(cmd->numcmds); memcpy(cmds.get(), (void *)cmd->cmdlist, sizeof(struct kgsl_command_object)*cmd->numcmds); cache.cmdlist = (uint64_t)cmds.get(); for (int i = 0; i < cmd->numcmds; i++) { void *nn = thneed->ram->alloc(cmds[i].size); memcpy(nn, (void*)cmds[i].gpuaddr, cmds[i].size); cmds[i].gpuaddr = (uint64_t)nn; } } if (cmd->numobjs > 0) { objs = make_unique<struct kgsl_command_object[]>(cmd->numobjs); memcpy(objs.get(), (void *)cmd->objlist, sizeof(struct kgsl_command_object)*cmd->numobjs); cache.objlist = (uint64_t)objs.get(); for (int i = 0; i < cmd->numobjs; i++) { void *nn = thneed->ram->alloc(objs[i].size); memset(nn, 0, objs[i].size); objs[i].gpuaddr = (uint64_t)nn; } } kq = thneed->ckq; thneed->ckq.clear(); } void CachedCommand::exec() { cache.timestamp = ++thneed->timestamp; int ret = ioctl(thneed->fd, IOCTL_KGSL_GPU_COMMAND, &cache); if (thneed->debug >= 1) printf("CachedCommand::exec got %d\n", ret); if (thneed->debug >= 2) { for (auto &it : kq) { it->debug_print(false); } } assert(ret == 0); } // *********** Thneed *********** Thneed::Thneed(bool do_clinit, cl_context _context) { // TODO: QCOM2 actually requires a different context //context = _context; if (do_clinit) clinit(); assert(g_fd != -1); fd = g_fd; ram = make_unique<GPUMalloc>(0x80000, fd); timestamp = -1; g_thneed = this; char *thneed_debug_env = getenv("THNEED_DEBUG"); debug = (thneed_debug_env != NULL) ? atoi(thneed_debug_env) : 0; } void Thneed::wait() { struct kgsl_device_waittimestamp_ctxtid wait; wait.context_id = context_id; wait.timestamp = timestamp; wait.timeout = -1; uint64_t tb = nanos_since_boot(); int wret = ioctl(fd, IOCTL_KGSL_DEVICE_WAITTIMESTAMP_CTXTID, &wait); uint64_t te = nanos_since_boot(); if (debug >= 1) printf("wait %d after %lu us\n", wret, (te-tb)/1000); } void Thneed::execute(float **finputs, float *foutput, bool slow) { uint64_t tb, te; if (debug >= 1) tb = nanos_since_boot(); // ****** copy inputs copy_inputs(finputs, true); // ****** run commands int i = 0; for (auto &it : cmds) { ++i; if (debug >= 1) printf("run %2d @ %7lu us: ", i, (nanos_since_boot()-tb)/1000); it->exec(); if ((i == cmds.size()) || slow) wait(); } // ****** copy outputs copy_output(foutput); if (debug >= 1) { te = nanos_since_boot(); printf("model exec in %lu us\n", (te-tb)/1000); } }
2301_81045437/openpilot
selfdrive/modeld/thneed/thneed_qcom2.cc
C++
mit
8,090
#include "selfdrive/modeld/transforms/loadyuv.h" #include <cassert> #include <cstdio> #include <cstring> void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height) { memset(s, 0, sizeof(*s)); s->width = width; s->height = height; char args[1024]; snprintf(args, sizeof(args), "-cl-fast-relaxed-math -cl-denorms-are-zero " "-DTRANSFORMED_WIDTH=%d -DTRANSFORMED_HEIGHT=%d", width, height); cl_program prg = cl_program_from_file(ctx, device_id, LOADYUV_PATH, args); s->loadys_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loadys", &err)); s->loaduv_krnl = CL_CHECK_ERR(clCreateKernel(prg, "loaduv", &err)); s->copy_krnl = CL_CHECK_ERR(clCreateKernel(prg, "copy", &err)); // done with this CL_CHECK(clReleaseProgram(prg)); } void loadyuv_destroy(LoadYUVState* s) { CL_CHECK(clReleaseKernel(s->loadys_krnl)); CL_CHECK(clReleaseKernel(s->loaduv_krnl)); CL_CHECK(clReleaseKernel(s->copy_krnl)); } void loadyuv_queue(LoadYUVState* s, cl_command_queue q, cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, cl_mem out_cl, bool do_shift) { cl_int global_out_off = 0; if (do_shift) { // shift the image in slot 1 to slot 0, then place the new image in slot 1 global_out_off += (s->width*s->height) + (s->width/2)*(s->height/2)*2; CL_CHECK(clSetKernelArg(s->copy_krnl, 0, sizeof(cl_mem), &out_cl)); CL_CHECK(clSetKernelArg(s->copy_krnl, 1, sizeof(cl_int), &global_out_off)); const size_t copy_work_size = global_out_off/8; CL_CHECK(clEnqueueNDRangeKernel(q, s->copy_krnl, 1, NULL, &copy_work_size, NULL, 0, 0, NULL)); } CL_CHECK(clSetKernelArg(s->loadys_krnl, 0, sizeof(cl_mem), &y_cl)); CL_CHECK(clSetKernelArg(s->loadys_krnl, 1, sizeof(cl_mem), &out_cl)); CL_CHECK(clSetKernelArg(s->loadys_krnl, 2, sizeof(cl_int), &global_out_off)); const size_t loadys_work_size = (s->width*s->height)/8; CL_CHECK(clEnqueueNDRangeKernel(q, s->loadys_krnl, 1, NULL, &loadys_work_size, NULL, 0, 0, NULL)); const size_t loaduv_work_size = ((s->width/2)*(s->height/2))/8; global_out_off += (s->width*s->height); CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &u_cl)); CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, &loaduv_work_size, NULL, 0, 0, NULL)); global_out_off += (s->width/2)*(s->height/2); CL_CHECK(clSetKernelArg(s->loaduv_krnl, 0, sizeof(cl_mem), &v_cl)); CL_CHECK(clSetKernelArg(s->loaduv_krnl, 1, sizeof(cl_mem), &out_cl)); CL_CHECK(clSetKernelArg(s->loaduv_krnl, 2, sizeof(cl_int), &global_out_off)); CL_CHECK(clEnqueueNDRangeKernel(q, s->loaduv_krnl, 1, NULL, &loaduv_work_size, NULL, 0, 0, NULL)); }
2301_81045437/openpilot
selfdrive/modeld/transforms/loadyuv.cc
C++
mit
2,984
#define UV_SIZE ((TRANSFORMED_WIDTH/2)*(TRANSFORMED_HEIGHT/2)) __kernel void loadys(__global uchar8 const * const Y, __global float * out, int out_offset) { const int gid = get_global_id(0); const int ois = gid * 8; const int oy = ois / TRANSFORMED_WIDTH; const int ox = ois % TRANSFORMED_WIDTH; const uchar8 ys = Y[gid]; const float8 ysf = convert_float8(ys); // 02 // 13 __global float* outy0; __global float* outy1; if ((oy & 1) == 0) { outy0 = out + out_offset; //y0 outy1 = out + out_offset + UV_SIZE*2; //y2 } else { outy0 = out + out_offset + UV_SIZE; //y1 outy1 = out + out_offset + UV_SIZE*3; //y3 } vstore4(ysf.s0246, 0, outy0 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); vstore4(ysf.s1357, 0, outy1 + (oy/2) * (TRANSFORMED_WIDTH/2) + ox/2); } __kernel void loaduv(__global uchar8 const * const in, __global float8 * out, int out_offset) { const int gid = get_global_id(0); const uchar8 inv = in[gid]; const float8 outv = convert_float8(inv); out[gid + out_offset / 8] = outv; } __kernel void copy(__global float8 * inout, int in_offset) { const int gid = get_global_id(0); inout[gid] = inout[gid + in_offset / 8]; }
2301_81045437/openpilot
selfdrive/modeld/transforms/loadyuv.cl
OpenCL
mit
1,331
#pragma once #include "common/clutil.h" typedef struct { int width, height; cl_kernel loadys_krnl, loaduv_krnl, copy_krnl; } LoadYUVState; void loadyuv_init(LoadYUVState* s, cl_context ctx, cl_device_id device_id, int width, int height); void loadyuv_destroy(LoadYUVState* s); void loadyuv_queue(LoadYUVState* s, cl_command_queue q, cl_mem y_cl, cl_mem u_cl, cl_mem v_cl, cl_mem out_cl, bool do_shift = false);
2301_81045437/openpilot
selfdrive/modeld/transforms/loadyuv.h
C
mit
458
#include "selfdrive/modeld/transforms/transform.h" #include <cassert> #include <cstring> #include "common/clutil.h" void transform_init(Transform* s, cl_context ctx, cl_device_id device_id) { memset(s, 0, sizeof(*s)); cl_program prg = cl_program_from_file(ctx, device_id, TRANSFORM_PATH, ""); s->krnl = CL_CHECK_ERR(clCreateKernel(prg, "warpPerspective", &err)); // done with this CL_CHECK(clReleaseProgram(prg)); s->m_y_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); s->m_uv_cl = CL_CHECK_ERR(clCreateBuffer(ctx, CL_MEM_READ_WRITE, 3*3*sizeof(float), NULL, &err)); } void transform_destroy(Transform* s) { CL_CHECK(clReleaseMemObject(s->m_y_cl)); CL_CHECK(clReleaseMemObject(s->m_uv_cl)); CL_CHECK(clReleaseKernel(s->krnl)); } void transform_queue(Transform* s, cl_command_queue q, cl_mem in_yuv, int in_width, int in_height, int in_stride, int in_uv_offset, cl_mem out_y, cl_mem out_u, cl_mem out_v, int out_width, int out_height, const mat3& projection) { const int zero = 0; // sampled using pixel center origin // (because that's how fastcv and opencv does it) mat3 projection_y = projection; // in and out uv is half the size of y. mat3 projection_uv = transform_scale_buffer(projection, 0.5); CL_CHECK(clEnqueueWriteBuffer(q, s->m_y_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_y.v, 0, NULL, NULL)); CL_CHECK(clEnqueueWriteBuffer(q, s->m_uv_cl, CL_TRUE, 0, 3*3*sizeof(float), (void*)projection_uv.v, 0, NULL, NULL)); const int in_y_width = in_width; const int in_y_height = in_height; const int in_y_px_stride = 1; const int in_uv_width = in_width/2; const int in_uv_height = in_height/2; const int in_uv_px_stride = 2; const int in_u_offset = in_uv_offset; const int in_v_offset = in_uv_offset + 1; const int out_y_width = out_width; const int out_y_height = out_height; const int out_uv_width = out_width/2; const int out_uv_height = out_height/2; CL_CHECK(clSetKernelArg(s->krnl, 0, sizeof(cl_mem), &in_yuv)); // src CL_CHECK(clSetKernelArg(s->krnl, 1, sizeof(cl_int), &in_stride)); // src_row_stride CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_y_px_stride)); // src_px_stride CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &zero)); // src_offset CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_y_height)); // src_rows CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_y_width)); // src_cols CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_y)); // dst CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_y_width)); // dst_row_stride CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_y_height)); // dst_rows CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_y_width)); // dst_cols CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_y_cl)); // M const size_t work_size_y[2] = {(size_t)out_y_width, (size_t)out_y_height}; CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, (const size_t*)&work_size_y, NULL, 0, 0, NULL)); const size_t work_size_uv[2] = {(size_t)out_uv_width, (size_t)out_uv_height}; CL_CHECK(clSetKernelArg(s->krnl, 2, sizeof(cl_int), &in_uv_px_stride)); // src_px_stride CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_u_offset)); // src_offset CL_CHECK(clSetKernelArg(s->krnl, 4, sizeof(cl_int), &in_uv_height)); // src_rows CL_CHECK(clSetKernelArg(s->krnl, 5, sizeof(cl_int), &in_uv_width)); // src_cols CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_u)); // dst CL_CHECK(clSetKernelArg(s->krnl, 7, sizeof(cl_int), &out_uv_width)); // dst_row_stride CL_CHECK(clSetKernelArg(s->krnl, 8, sizeof(cl_int), &zero)); // dst_offset CL_CHECK(clSetKernelArg(s->krnl, 9, sizeof(cl_int), &out_uv_height)); // dst_rows CL_CHECK(clSetKernelArg(s->krnl, 10, sizeof(cl_int), &out_uv_width)); // dst_cols CL_CHECK(clSetKernelArg(s->krnl, 11, sizeof(cl_mem), &s->m_uv_cl)); // M CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); CL_CHECK(clSetKernelArg(s->krnl, 3, sizeof(cl_int), &in_v_offset)); // src_ofset CL_CHECK(clSetKernelArg(s->krnl, 6, sizeof(cl_mem), &out_v)); // dst CL_CHECK(clEnqueueNDRangeKernel(q, s->krnl, 2, NULL, (const size_t*)&work_size_uv, NULL, 0, 0, NULL)); }
2301_81045437/openpilot
selfdrive/modeld/transforms/transform.cc
C++
mit
4,618
#define INTER_BITS 5 #define INTER_TAB_SIZE (1 << INTER_BITS) #define INTER_SCALE 1.f / INTER_TAB_SIZE #define INTER_REMAP_COEF_BITS 15 #define INTER_REMAP_COEF_SCALE (1 << INTER_REMAP_COEF_BITS) __kernel void warpPerspective(__global const uchar * src, int src_row_stride, int src_px_stride, int src_offset, int src_rows, int src_cols, __global uchar * dst, int dst_row_stride, int dst_offset, int dst_rows, int dst_cols, __constant float * M) { int dx = get_global_id(0); int dy = get_global_id(1); if (dx < dst_cols && dy < dst_rows) { float X0 = M[0] * dx + M[1] * dy + M[2]; float Y0 = M[3] * dx + M[4] * dy + M[5]; float W = M[6] * dx + M[7] * dy + M[8]; W = W != 0.0f ? INTER_TAB_SIZE / W : 0.0f; int X = rint(X0 * W), Y = rint(Y0 * W); int sx = convert_short_sat(X >> INTER_BITS); int sy = convert_short_sat(Y >> INTER_BITS); short sx_clamp = clamp(sx, 0, src_cols - 1); short sx_p1_clamp = clamp(sx + 1, 0, src_cols - 1); short sy_clamp = clamp(sy, 0, src_rows - 1); short sy_p1_clamp = clamp(sy + 1, 0, src_rows - 1); int v0 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); int v1 = convert_int(src[mad24(sy_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); int v2 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_clamp*src_px_stride)]); int v3 = convert_int(src[mad24(sy_p1_clamp, src_row_stride, src_offset + sx_p1_clamp*src_px_stride)]); short ay = (short)(Y & (INTER_TAB_SIZE - 1)); short ax = (short)(X & (INTER_TAB_SIZE - 1)); float taby = 1.f/INTER_TAB_SIZE*ay; float tabx = 1.f/INTER_TAB_SIZE*ax; int dst_index = mad24(dy, dst_row_stride, dst_offset + dx); int itab0 = convert_short_sat_rte( (1.0f-taby)*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); int itab1 = convert_short_sat_rte( (1.0f-taby)*tabx * INTER_REMAP_COEF_SCALE ); int itab2 = convert_short_sat_rte( taby*(1.0f-tabx) * INTER_REMAP_COEF_SCALE ); int itab3 = convert_short_sat_rte( taby*tabx * INTER_REMAP_COEF_SCALE ); int val = v0 * itab0 + v1 * itab1 + v2 * itab2 + v3 * itab3; uchar pix = convert_uchar_sat((val + (1 << (INTER_REMAP_COEF_BITS-1))) >> INTER_REMAP_COEF_BITS); dst[dst_index] = pix; } }
2301_81045437/openpilot
selfdrive/modeld/transforms/transform.cl
OpenCL
mit
2,524
#pragma once #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #ifdef __APPLE__ #include <OpenCL/cl.h> #else #include <CL/cl.h> #endif #include "common/mat.h" typedef struct { cl_kernel krnl; cl_mem m_y_cl, m_uv_cl; } Transform; void transform_init(Transform* s, cl_context ctx, cl_device_id device_id); void transform_destroy(Transform* transform); void transform_queue(Transform* s, cl_command_queue q, cl_mem yuv, int in_width, int in_height, int in_stride, int in_uv_offset, cl_mem out_y, cl_mem out_u, cl_mem out_v, int out_width, int out_height, const mat3& projection);
2301_81045437/openpilot
selfdrive/modeld/transforms/transform.h
C
mit
663
#!/usr/bin/env python3 import gc import cereal.messaging as messaging from openpilot.common.params import Params from openpilot.common.realtime import set_realtime_priority from openpilot.selfdrive.monitoring.helpers import DriverMonitoring def dmonitoringd_thread(): gc.disable() set_realtime_priority(2) params = Params() pm = messaging.PubMaster(['driverMonitoringState']) sm = messaging.SubMaster(['driverStateV2', 'liveCalibration', 'carState', 'controlsState', 'modelV2'], poll='driverStateV2') DM = DriverMonitoring(rhd_saved=params.get_bool("IsRhdDetected"), always_on=params.get_bool("AlwaysOnDM")) # 20Hz <- dmonitoringmodeld while True: sm.update() if not sm.updated['driverStateV2']: # iterate when model has new output continue valid = sm.all_checks() if valid: DM.run_step(sm) # publish dat = DM.get_state_packet(valid=valid) pm.send('driverMonitoringState', dat) # load live always-on toggle if sm['driverStateV2'].frameId % 40 == 1: DM.always_on = params.get_bool("AlwaysOnDM") # save rhd virtual toggle every 5 mins if (sm['driverStateV2'].frameId % 6000 == 0 and DM.wheelpos_learner.filtered_stat.n > DM.settings._WHEELPOS_FILTER_MIN_COUNT and DM.wheel_on_right == (DM.wheelpos_learner.filtered_stat.M > DM.settings._WHEELPOS_THRESHOLD)): params.put_bool_nonblocking("IsRhdDetected", DM.wheel_on_right) def main(): dmonitoringd_thread() if __name__ == '__main__': main()
2301_81045437/openpilot
selfdrive/monitoring/dmonitoringd.py
Python
mit
1,506
from math import atan2 from cereal import car import cereal.messaging as messaging from openpilot.selfdrive.controls.lib.events import Events from openpilot.common.numpy_fast import interp from openpilot.common.realtime import DT_DMON from openpilot.common.filter_simple import FirstOrderFilter from openpilot.common.stat_live import RunningStatFilter from openpilot.common.transformations.camera import DEVICE_CAMERAS EventName = car.CarEvent.EventName # ****************************************************************************************** # NOTE: To fork maintainers. # Disabling or nerfing safety features will get you and your users banned from our servers. # We recommend that you do not change these numbers from the defaults. # ****************************************************************************************** class DRIVER_MONITOR_SETTINGS: def __init__(self): self._DT_DMON = DT_DMON # ref (page15-16): https://eur-lex.europa.eu/legal-content/EN/TXT/PDF/?uri=CELEX:42018X1947&rid=2 self._AWARENESS_TIME = 30. # passive wheeltouch total timeout self._AWARENESS_PRE_TIME_TILL_TERMINAL = 15. self._AWARENESS_PROMPT_TIME_TILL_TERMINAL = 6. self._DISTRACTED_TIME = 11. # active monitoring total timeout self._DISTRACTED_PRE_TIME_TILL_TERMINAL = 8. self._DISTRACTED_PROMPT_TIME_TILL_TERMINAL = 6. self._FACE_THRESHOLD = 0.7 self._EYE_THRESHOLD = 0.65 self._SG_THRESHOLD = 0.9 self._BLINK_THRESHOLD = 0.865 self._EE_THRESH11 = 0.25 self._EE_THRESH12 = 7.5 self._EE_MAX_OFFSET1 = 0.06 self._EE_MIN_OFFSET1 = 0.025 self._EE_THRESH21 = 0.01 self._EE_THRESH22 = 0.35 self._POSE_PITCH_THRESHOLD = 0.3133 self._POSE_PITCH_THRESHOLD_SLACK = 0.3237 self._POSE_PITCH_THRESHOLD_STRICT = self._POSE_PITCH_THRESHOLD self._POSE_YAW_THRESHOLD = 0.4020 self._POSE_YAW_THRESHOLD_SLACK = 0.5042 self._POSE_YAW_THRESHOLD_STRICT = self._POSE_YAW_THRESHOLD self._PITCH_NATURAL_OFFSET = 0.029 # initial value before offset is learned self._PITCH_NATURAL_THRESHOLD = 0.449 self._YAW_NATURAL_OFFSET = 0.097 # initial value before offset is learned self._PITCH_MAX_OFFSET = 0.124 self._PITCH_MIN_OFFSET = -0.0881 self._YAW_MAX_OFFSET = 0.289 self._YAW_MIN_OFFSET = -0.0246 self._POSESTD_THRESHOLD = 0.3 self._HI_STD_FALLBACK_TIME = int(10 / self._DT_DMON) # fall back to wheel touch if model is uncertain for 10s self._DISTRACTED_FILTER_TS = 0.25 # 0.6Hz self._ALWAYS_ON_ALERT_MIN_SPEED = 7 self._POSE_CALIB_MIN_SPEED = 13 # 30 mph self._POSE_OFFSET_MIN_COUNT = int(60 / self._DT_DMON) # valid data counts before calibration completes, 1min cumulative self._POSE_OFFSET_MAX_COUNT = int(360 / self._DT_DMON) # stop deweighting new data after 6 min, aka "short term memory" self._WHEELPOS_CALIB_MIN_SPEED = 11 self._WHEELPOS_THRESHOLD = 0.5 self._WHEELPOS_FILTER_MIN_COUNT = int(15 / self._DT_DMON) # allow 15 seconds to converge wheel side self._RECOVERY_FACTOR_MAX = 5. # relative to minus step change self._RECOVERY_FACTOR_MIN = 1.25 # relative to minus step change self._MAX_TERMINAL_ALERTS = 3 # not allowed to engage after 3 terminal alerts self._MAX_TERMINAL_DURATION = int(30 / self._DT_DMON) # not allowed to engage after 30s of terminal alerts class DistractedType: NOT_DISTRACTED = 0 DISTRACTED_POSE = 1 << 0 DISTRACTED_BLINK = 1 << 1 DISTRACTED_E2E = 1 << 2 class DriverPose: def __init__(self, max_trackable): self.yaw = 0. self.pitch = 0. self.roll = 0. self.yaw_std = 0. self.pitch_std = 0. self.roll_std = 0. self.pitch_offseter = RunningStatFilter(max_trackable=max_trackable) self.yaw_offseter = RunningStatFilter(max_trackable=max_trackable) self.calibrated = False self.low_std = True self.cfactor_pitch = 1. self.cfactor_yaw = 1. class DriverBlink: def __init__(self): self.left = 0. self.right = 0. # model output refers to center of undistorted+leveled image EFL = 598.0 # focal length in K cam = DEVICE_CAMERAS[("tici", "ar0231")] # corrected image has same size as raw W, H = (cam.dcam.width, cam.dcam.height) # corrected image has same size as raw def face_orientation_from_net(angles_desc, pos_desc, rpy_calib): # the output of these angles are in device frame # so from driver's perspective, pitch is up and yaw is right pitch_net, yaw_net, roll_net = angles_desc face_pixel_position = ((pos_desc[0]+0.5)*W, (pos_desc[1]+0.5)*H) yaw_focal_angle = atan2(face_pixel_position[0] - W//2, EFL) pitch_focal_angle = atan2(face_pixel_position[1] - H//2, EFL) pitch = pitch_net + pitch_focal_angle yaw = -yaw_net + yaw_focal_angle # no calib for roll pitch -= rpy_calib[1] yaw -= rpy_calib[2] return roll_net, pitch, yaw class DriverMonitoring: def __init__(self, rhd_saved=False, settings=None, always_on=False): if settings is None: settings = DRIVER_MONITOR_SETTINGS() # init policy settings self.settings = settings # init driver status self.wheelpos_learner = RunningStatFilter() self.pose = DriverPose(self.settings._POSE_OFFSET_MAX_COUNT) self.blink = DriverBlink() self.eev1 = 0. self.eev2 = 1. self.ee1_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) self.ee2_offseter = RunningStatFilter(max_trackable=self.settings._POSE_OFFSET_MAX_COUNT) self.ee1_calibrated = False self.ee2_calibrated = False self.always_on = always_on self.distracted_types = [] self.driver_distracted = False self.driver_distraction_filter = FirstOrderFilter(0., self.settings._DISTRACTED_FILTER_TS, self.settings._DT_DMON) self.wheel_on_right = False self.wheel_on_right_last = None self.wheel_on_right_default = rhd_saved self.face_detected = False self.terminal_alert_cnt = 0 self.terminal_time = 0 self.step_change = 0. self.active_monitoring_mode = True self.is_model_uncertain = False self.hi_stds = 0 self.threshold_pre = self.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME self.threshold_prompt = self.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME self._reset_awareness() self._set_timers(active_monitoring=True) self._reset_events() def _reset_awareness(self): self.awareness = 1. self.awareness_active = 1. self.awareness_passive = 1. def _reset_events(self): self.current_events = Events() def _set_timers(self, active_monitoring): if self.active_monitoring_mode and self.awareness <= self.threshold_prompt: if active_monitoring: self.step_change = self.settings._DT_DMON / self.settings._DISTRACTED_TIME else: self.step_change = 0. return # no exploit after orange alert elif self.awareness <= 0.: return if active_monitoring: # when falling back from passive mode to active mode, reset awareness to avoid false alert if not self.active_monitoring_mode: self.awareness_passive = self.awareness self.awareness = self.awareness_active self.threshold_pre = self.settings._DISTRACTED_PRE_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME self.threshold_prompt = self.settings._DISTRACTED_PROMPT_TIME_TILL_TERMINAL / self.settings._DISTRACTED_TIME self.step_change = self.settings._DT_DMON / self.settings._DISTRACTED_TIME self.active_monitoring_mode = True else: if self.active_monitoring_mode: self.awareness_active = self.awareness self.awareness = self.awareness_passive self.threshold_pre = self.settings._AWARENESS_PRE_TIME_TILL_TERMINAL / self.settings._AWARENESS_TIME self.threshold_prompt = self.settings._AWARENESS_PROMPT_TIME_TILL_TERMINAL / self.settings._AWARENESS_TIME self.step_change = self.settings._DT_DMON / self.settings._AWARENESS_TIME self.active_monitoring_mode = False def _set_policy(self, model_data, car_speed): bp = model_data.meta.disengagePredictions.brakeDisengageProbs[0] # brake disengage prob in next 2s k1 = max(-0.00156*((car_speed-16)**2)+0.6, 0.2) bp_normal = max(min(bp / k1, 0.5),0) self.pose.cfactor_pitch = interp(bp_normal, [0, 0.5], [self.settings._POSE_PITCH_THRESHOLD_SLACK, self.settings._POSE_PITCH_THRESHOLD_STRICT]) / self.settings._POSE_PITCH_THRESHOLD self.pose.cfactor_yaw = interp(bp_normal, [0, 0.5], [self.settings._POSE_YAW_THRESHOLD_SLACK, self.settings._POSE_YAW_THRESHOLD_STRICT]) / self.settings._POSE_YAW_THRESHOLD def _get_distracted_types(self): distracted_types = [] if not self.pose.calibrated: pitch_error = self.pose.pitch - self.settings._PITCH_NATURAL_OFFSET yaw_error = self.pose.yaw - self.settings._YAW_NATURAL_OFFSET else: pitch_error = self.pose.pitch - min(max(self.pose.pitch_offseter.filtered_stat.mean(), self.settings._PITCH_MIN_OFFSET), self.settings._PITCH_MAX_OFFSET) yaw_error = self.pose.yaw - min(max(self.pose.yaw_offseter.filtered_stat.mean(), self.settings._YAW_MIN_OFFSET), self.settings._YAW_MAX_OFFSET) pitch_error = 0 if pitch_error > 0 else abs(pitch_error) # no positive pitch limit yaw_error = abs(yaw_error) if pitch_error > (self.settings._POSE_PITCH_THRESHOLD*self.pose.cfactor_pitch if self.pose.calibrated else self.settings._PITCH_NATURAL_THRESHOLD) or \ yaw_error > self.settings._POSE_YAW_THRESHOLD*self.pose.cfactor_yaw: distracted_types.append(DistractedType.DISTRACTED_POSE) if (self.blink.left + self.blink.right)*0.5 > self.settings._BLINK_THRESHOLD: distracted_types.append(DistractedType.DISTRACTED_BLINK) if self.ee1_calibrated: ee1_dist = self.eev1 > max(min(self.ee1_offseter.filtered_stat.M, self.settings._EE_MAX_OFFSET1), self.settings._EE_MIN_OFFSET1) \ * self.settings._EE_THRESH12 else: ee1_dist = self.eev1 > self.settings._EE_THRESH11 if ee1_dist: distracted_types.append(DistractedType.DISTRACTED_E2E) return distracted_types def _update_states(self, driver_state, cal_rpy, car_speed, op_engaged): rhd_pred = driver_state.wheelOnRightProb # calibrates only when there's movement and either face detected if car_speed > self.settings._WHEELPOS_CALIB_MIN_SPEED and (driver_state.leftDriverData.faceProb > self.settings._FACE_THRESHOLD or driver_state.rightDriverData.faceProb > self.settings._FACE_THRESHOLD): self.wheelpos_learner.push_and_update(rhd_pred) if self.wheelpos_learner.filtered_stat.n > self.settings._WHEELPOS_FILTER_MIN_COUNT: self.wheel_on_right = self.wheelpos_learner.filtered_stat.M > self.settings._WHEELPOS_THRESHOLD else: self.wheel_on_right = self.wheel_on_right_default # use default/saved if calibration is unfinished # make sure no switching when engaged if op_engaged and self.wheel_on_right_last is not None and self.wheel_on_right_last != self.wheel_on_right: self.wheel_on_right = self.wheel_on_right_last driver_data = driver_state.rightDriverData if self.wheel_on_right else driver_state.leftDriverData if not all(len(x) > 0 for x in (driver_data.faceOrientation, driver_data.facePosition, driver_data.faceOrientationStd, driver_data.facePositionStd, driver_data.readyProb, driver_data.notReadyProb)): return self.face_detected = driver_data.faceProb > self.settings._FACE_THRESHOLD self.pose.roll, self.pose.pitch, self.pose.yaw = face_orientation_from_net(driver_data.faceOrientation, driver_data.facePosition, cal_rpy) if self.wheel_on_right: self.pose.yaw *= -1 self.wheel_on_right_last = self.wheel_on_right self.pose.pitch_std = driver_data.faceOrientationStd[0] self.pose.yaw_std = driver_data.faceOrientationStd[1] model_std_max = max(self.pose.pitch_std, self.pose.yaw_std) self.pose.low_std = model_std_max < self.settings._POSESTD_THRESHOLD self.blink.left = driver_data.leftBlinkProb * (driver_data.leftEyeProb > self.settings._EYE_THRESHOLD) \ * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) self.blink.right = driver_data.rightBlinkProb * (driver_data.rightEyeProb > self.settings._EYE_THRESHOLD) \ * (driver_data.sunglassesProb < self.settings._SG_THRESHOLD) self.eev1 = driver_data.notReadyProb[0] self.eev2 = driver_data.readyProb[0] self.distracted_types = self._get_distracted_types() self.driver_distracted = (DistractedType.DISTRACTED_E2E in self.distracted_types or DistractedType.DISTRACTED_POSE in self.distracted_types or DistractedType.DISTRACTED_BLINK in self.distracted_types) \ and driver_data.faceProb > self.settings._FACE_THRESHOLD and self.pose.low_std self.driver_distraction_filter.update(self.driver_distracted) # update offseter # only update when driver is actively driving the car above a certain speed if self.face_detected and car_speed > self.settings._POSE_CALIB_MIN_SPEED and self.pose.low_std and (not op_engaged or not self.driver_distracted): self.pose.pitch_offseter.push_and_update(self.pose.pitch) self.pose.yaw_offseter.push_and_update(self.pose.yaw) self.ee1_offseter.push_and_update(self.eev1) self.ee2_offseter.push_and_update(self.eev2) self.pose.calibrated = self.pose.pitch_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT and \ self.pose.yaw_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT self.ee1_calibrated = self.ee1_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT self.ee2_calibrated = self.ee2_offseter.filtered_stat.n > self.settings._POSE_OFFSET_MIN_COUNT self.is_model_uncertain = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME self._set_timers(self.face_detected and not self.is_model_uncertain) if self.face_detected and not self.pose.low_std and not self.driver_distracted: self.hi_stds += 1 elif self.face_detected and self.pose.low_std: self.hi_stds = 0 def _update_events(self, driver_engaged, op_engaged, standstill, wrong_gear, car_speed): self._reset_events() # Block engaging after max number of distrations or when alert active if self.terminal_alert_cnt >= self.settings._MAX_TERMINAL_ALERTS or \ self.terminal_time >= self.settings._MAX_TERMINAL_DURATION or \ self.always_on and self.awareness <= self.threshold_prompt: self.current_events.add(EventName.tooDistracted) always_on_valid = self.always_on and not wrong_gear if (driver_engaged and self.awareness > 0 and not self.active_monitoring_mode) or \ (not always_on_valid and not op_engaged) or \ (always_on_valid and not op_engaged and self.awareness <= 0): # always reset on disengage with normal mode; disengage resets only on red if always on self._reset_awareness() return driver_attentive = self.driver_distraction_filter.x < 0.37 awareness_prev = self.awareness if (driver_attentive and self.face_detected and self.pose.low_std and self.awareness > 0): if driver_engaged: self._reset_awareness() return # only restore awareness when paying attention and alert is not red self.awareness = min(self.awareness + ((self.settings._RECOVERY_FACTOR_MAX-self.settings._RECOVERY_FACTOR_MIN)* (1.-self.awareness)+self.settings._RECOVERY_FACTOR_MIN)*self.step_change, 1.) if self.awareness == 1.: self.awareness_passive = min(self.awareness_passive + self.step_change, 1.) # don't display alert banner when awareness is recovering and has cleared orange if self.awareness > self.threshold_prompt: return _reaching_audible = self.awareness - self.step_change <= self.threshold_prompt _reaching_terminal = self.awareness - self.step_change <= 0 standstill_exemption = standstill and _reaching_audible always_on_red_exemption = always_on_valid and not op_engaged and _reaching_terminal always_on_lowspeed_exemption = always_on_valid and not op_engaged and car_speed < self.settings._ALWAYS_ON_ALERT_MIN_SPEED and _reaching_audible certainly_distracted = self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected maybe_distracted = self.hi_stds > self.settings._HI_STD_FALLBACK_TIME or not self.face_detected if certainly_distracted or maybe_distracted: # should always be counting if distracted unless at standstill (lowspeed for always-on) and reaching orange # also will not be reaching 0 if DM is active when not engaged if not (standstill_exemption or always_on_red_exemption or always_on_lowspeed_exemption): self.awareness = max(self.awareness - self.step_change, -0.1) alert = None if self.awareness <= 0.: # terminal red alert: disengagement required alert = EventName.driverDistracted if self.active_monitoring_mode else EventName.driverUnresponsive self.terminal_time += 1 if awareness_prev > 0.: self.terminal_alert_cnt += 1 elif self.awareness <= self.threshold_prompt: # prompt orange alert alert = EventName.promptDriverDistracted if self.active_monitoring_mode else EventName.promptDriverUnresponsive elif self.awareness <= self.threshold_pre: # pre green alert alert = EventName.preDriverDistracted if self.active_monitoring_mode else EventName.preDriverUnresponsive if alert is not None: self.current_events.add(alert) def get_state_packet(self, valid=True): # build driverMonitoringState packet dat = messaging.new_message('driverMonitoringState', valid=valid) dat.driverMonitoringState = { "events": self.current_events.to_msg(), "faceDetected": self.face_detected, "isDistracted": self.driver_distracted, "distractedType": sum(self.distracted_types), "awarenessStatus": self.awareness, "posePitchOffset": self.pose.pitch_offseter.filtered_stat.mean(), "posePitchValidCount": self.pose.pitch_offseter.filtered_stat.n, "poseYawOffset": self.pose.yaw_offseter.filtered_stat.mean(), "poseYawValidCount": self.pose.yaw_offseter.filtered_stat.n, "stepChange": self.step_change, "awarenessActive": self.awareness_active, "awarenessPassive": self.awareness_passive, "isLowStd": self.pose.low_std, "hiStdCount": self.hi_stds, "isActiveMode": self.active_monitoring_mode, "isRHD": self.wheel_on_right, } return dat def run_step(self, sm): # Set strictness self._set_policy( model_data=sm['modelV2'], car_speed=sm['carState'].vEgo ) # Parse data from dmonitoringmodeld self._update_states( driver_state=sm['driverStateV2'], cal_rpy=sm['liveCalibration'].rpyCalib, car_speed=sm['carState'].vEgo, op_engaged=sm['controlsState'].enabled ) # Update distraction events self._update_events( driver_engaged=sm['carState'].steeringPressed or sm['carState'].gasPressed, op_engaged=sm['controlsState'].enabled, standstill=sm['carState'].standstill, wrong_gear=sm['carState'].gearShifter in [car.CarState.GearShifter.reverse, car.CarState.GearShifter.park], car_speed=sm['carState'].vEgo )
2301_81045437/openpilot
selfdrive/monitoring/helpers.py
Python
mit
19,980
Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'transformations') map_env = qt_env.Clone() libs = ['qt_widgets', 'qt_util', 'QMapLibre', common, messaging, cereal, visionipc, transformations, 'zmq', 'capnp', 'kj', 'm', 'OpenCL', 'ssl', 'crypto', 'pthread', 'json11'] + map_env["LIBS"] if arch == 'larch64': libs.append(':libEGL_mesa.so.0') if arch in ['larch64', 'aarch64', 'x86_64']: if arch == 'x86_64': rpath = Dir(f"#third_party/maplibre-native-qt/{arch}/lib").srcnode().abspath map_env["RPATH"] += [rpath, ] style_path = File("style.json").abspath map_env['CXXFLAGS'].append(f'-DSTYLE_PATH=\\"{style_path}\\"') map_env["RPATH"].append(Dir('.').abspath) map_env["LIBPATH"].append(Dir('.').abspath) maplib = map_env.SharedLibrary("maprender", ["map_renderer.cc"], LIBS=libs) # map_env.Program("mapsd", ["main.cc", ], LIBS=[maplib[0].get_path(), ] + libs)
2301_81045437/openpilot
selfdrive/navd/SConscript
Python
mit
918
from __future__ import annotations import json import math from typing import Any, cast from openpilot.common.conversions import Conversions from openpilot.common.numpy_fast import clip from openpilot.common.params import Params DIRECTIONS = ('left', 'right', 'straight') MODIFIABLE_DIRECTIONS = ('left', 'right') EARTH_MEAN_RADIUS = 6371007.2 SPEED_CONVERSIONS = { 'km/h': Conversions.KPH_TO_MS, 'mph': Conversions.MPH_TO_MS, } class Coordinate: def __init__(self, latitude: float, longitude: float) -> None: self.latitude = latitude self.longitude = longitude self.annotations: dict[str, float] = {} @classmethod def from_mapbox_tuple(cls, t: tuple[float, float]) -> Coordinate: return cls(t[1], t[0]) def as_dict(self) -> dict[str, float]: return {'latitude': self.latitude, 'longitude': self.longitude} def __str__(self) -> str: return f'Coordinate({self.latitude}, {self.longitude})' def __repr__(self) -> str: return self.__str__() def __eq__(self, other) -> bool: if not isinstance(other, Coordinate): return False return (self.latitude == other.latitude) and (self.longitude == other.longitude) def __sub__(self, other: Coordinate) -> Coordinate: return Coordinate(self.latitude - other.latitude, self.longitude - other.longitude) def __add__(self, other: Coordinate) -> Coordinate: return Coordinate(self.latitude + other.latitude, self.longitude + other.longitude) def __mul__(self, c: float) -> Coordinate: return Coordinate(self.latitude * c, self.longitude * c) def dot(self, other: Coordinate) -> float: return self.latitude * other.latitude + self.longitude * other.longitude def distance_to(self, other: Coordinate) -> float: # Haversine formula dlat = math.radians(other.latitude - self.latitude) dlon = math.radians(other.longitude - self.longitude) haversine_dlat = math.sin(dlat / 2.0) haversine_dlat *= haversine_dlat haversine_dlon = math.sin(dlon / 2.0) haversine_dlon *= haversine_dlon y = haversine_dlat \ + math.cos(math.radians(self.latitude)) \ * math.cos(math.radians(other.latitude)) \ * haversine_dlon x = 2 * math.asin(math.sqrt(y)) return x * EARTH_MEAN_RADIUS def minimum_distance(a: Coordinate, b: Coordinate, p: Coordinate): if a.distance_to(b) < 0.01: return a.distance_to(p) ap = p - a ab = b - a t = clip(ap.dot(ab) / ab.dot(ab), 0.0, 1.0) projection = a + ab * t return projection.distance_to(p) def distance_along_geometry(geometry: list[Coordinate], pos: Coordinate) -> float: if len(geometry) <= 2: return geometry[0].distance_to(pos) # 1. Find segment that is closest to current position # 2. Total distance is sum of distance to start of closest segment # + all previous segments total_distance = 0.0 total_distance_closest = 0.0 closest_distance = 1e9 for i in range(len(geometry) - 1): d = minimum_distance(geometry[i], geometry[i + 1], pos) if d < closest_distance: closest_distance = d total_distance_closest = total_distance + geometry[i].distance_to(pos) total_distance += geometry[i].distance_to(geometry[i + 1]) return total_distance_closest def coordinate_from_param(param: str, params: Params = None) -> Coordinate | None: if params is None: params = Params() json_str = params.get(param) if json_str is None: return None pos = json.loads(json_str) if 'latitude' not in pos or 'longitude' not in pos: return None return Coordinate(pos['latitude'], pos['longitude']) def string_to_direction(direction: str) -> str: for d in DIRECTIONS: if d in direction: if 'slight' in direction and d in MODIFIABLE_DIRECTIONS: return 'slight' + d.capitalize() return d return 'none' def maxspeed_to_ms(maxspeed: dict[str, str | float]) -> float: unit = cast(str, maxspeed['unit']) speed = cast(float, maxspeed['speed']) return SPEED_CONVERSIONS[unit] * speed def field_valid(dat: dict, field: str) -> bool: return field in dat and dat[field] is not None def parse_banner_instructions(banners: Any, distance_to_maneuver: float = 0.0) -> dict[str, Any] | None: if not len(banners): return None instruction = {} # A segment can contain multiple banners, find one that we need to show now current_banner = banners[0] for banner in banners: if distance_to_maneuver < banner['distanceAlongGeometry']: current_banner = banner # Only show banner when close enough to maneuver instruction['showFull'] = distance_to_maneuver < current_banner['distanceAlongGeometry'] # Primary p = current_banner['primary'] if field_valid(p, 'text'): instruction['maneuverPrimaryText'] = p['text'] if field_valid(p, 'type'): instruction['maneuverType'] = p['type'] if field_valid(p, 'modifier'): instruction['maneuverModifier'] = p['modifier'] # Secondary if field_valid(current_banner, 'secondary'): instruction['maneuverSecondaryText'] = current_banner['secondary']['text'] # Lane lines if field_valid(current_banner, 'sub'): lanes = [] for component in current_banner['sub']['components']: if component['type'] != 'lane': continue lane = { 'active': component['active'], 'directions': [string_to_direction(d) for d in component['directions']], } if field_valid(component, 'active_direction'): lane['activeDirection'] = string_to_direction(component['active_direction']) lanes.append(lane) instruction['lanes'] = lanes return instruction
2301_81045437/openpilot
selfdrive/navd/helpers.py
Python
mit
5,637
#include <csignal> #include <sys/resource.h> #include <QApplication> #include <QDebug> #include "common/util.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/maps/map_helpers.h" #include "selfdrive/navd/map_renderer.h" #include "system/hardware/hw.h" int main(int argc, char *argv[]) { Hardware::config_cpu_rendering(true); qInstallMessageHandler(swagLogMessageHandler); setpriority(PRIO_PROCESS, 0, -20); int ret = util::set_core_affinity({0, 1, 2, 3}); assert(ret == 0); QApplication app(argc, argv); std::signal(SIGINT, sigTermHandler); std::signal(SIGTERM, sigTermHandler); MapRenderer * m = new MapRenderer(get_mapbox_settings()); assert(m); return app.exec(); }
2301_81045437/openpilot
selfdrive/navd/main.cc
C++
mit
711
#include "selfdrive/navd/map_renderer.h" #include <cmath> #include <string> #include <QApplication> #include <QBuffer> #include "common/util.h" #include "common/timing.h" #include "common/swaglog.h" #include "selfdrive/ui/qt/maps/map_helpers.h" const float DEFAULT_ZOOM = 13.5; // Don't go below 13 or features will start to disappear const int HEIGHT = 256, WIDTH = 256; const int NUM_VIPC_BUFFERS = 4; const int EARTH_CIRCUMFERENCE_METERS = 40075000; const int EARTH_RADIUS_METERS = 6378137; const int PIXELS_PER_TILE = 256; const int MAP_OFFSET = 128; const bool TEST_MODE = getenv("MAP_RENDER_TEST_MODE"); const int LLK_DECIMATION = TEST_MODE ? 1 : 10; float get_zoom_level_for_scale(float lat, float meters_per_pixel) { float meters_per_tile = meters_per_pixel * PIXELS_PER_TILE; float num_tiles = cos(DEG2RAD(lat)) * EARTH_CIRCUMFERENCE_METERS / meters_per_tile; return log2(num_tiles) - 1; } QMapLibre::Coordinate get_point_along_line(float lat, float lon, float bearing, float dist) { float ang_dist = dist / EARTH_RADIUS_METERS; float lat1 = DEG2RAD(lat), lon1 = DEG2RAD(lon), bearing1 = DEG2RAD(bearing); float lat2 = asin(sin(lat1)*cos(ang_dist) + cos(lat1)*sin(ang_dist)*cos(bearing1)); float lon2 = lon1 + atan2(sin(bearing1)*sin(ang_dist)*cos(lat1), cos(ang_dist)-sin(lat1)*sin(lat2)); return QMapLibre::Coordinate(RAD2DEG(lat2), RAD2DEG(lon2)); } MapRenderer::MapRenderer(const QMapLibre::Settings &settings, bool online) : m_settings(settings) { QSurfaceFormat fmt; fmt.setRenderableType(QSurfaceFormat::OpenGLES); m_settings.setMapMode(QMapLibre::Settings::MapMode::Static); ctx = std::make_unique<QOpenGLContext>(); ctx->setFormat(fmt); ctx->create(); assert(ctx->isValid()); surface = std::make_unique<QOffscreenSurface>(); surface->setFormat(ctx->format()); surface->create(); ctx->makeCurrent(surface.get()); assert(QOpenGLContext::currentContext() == ctx.get()); gl_functions.reset(ctx->functions()); gl_functions->initializeOpenGLFunctions(); QOpenGLFramebufferObjectFormat fbo_format; fbo.reset(new QOpenGLFramebufferObject(WIDTH, HEIGHT, fbo_format)); std::string style = util::read_file(STYLE_PATH); m_map.reset(new QMapLibre::Map(nullptr, m_settings, fbo->size(), 1)); m_map->setCoordinateZoom(QMapLibre::Coordinate(0, 0), DEFAULT_ZOOM); m_map->setStyleJson(style.c_str()); m_map->createRenderer(); ever_loaded = false; m_map->resize(fbo->size()); m_map->setFramebufferObject(fbo->handle(), fbo->size()); gl_functions->glViewport(0, 0, WIDTH, HEIGHT); QObject::connect(m_map.data(), &QMapLibre::Map::mapChanged, [=](QMapLibre::Map::MapChange change) { // Ignore expected signals // https://github.com/mapbox/mapbox-gl-native/blob/cf734a2fec960025350d8de0d01ad38aeae155a0/platform/qt/include/qmapboxgl.hpp#L116 if (ever_loaded) { if (change != QMapLibre::Map::MapChange::MapChangeRegionWillChange && change != QMapLibre::Map::MapChange::MapChangeRegionDidChange && change != QMapLibre::Map::MapChange::MapChangeWillStartRenderingFrame && change != QMapLibre::Map::MapChange::MapChangeDidFinishRenderingFrameFullyRendered) { LOGD("New map state: %d", change); } } }); QObject::connect(m_map.data(), &QMapLibre::Map::mapLoadingFailed, [=](QMapLibre::Map::MapLoadingFailure err_code, const QString &reason) { LOGE("Map loading failed with %d: '%s'\n", err_code, reason.toStdString().c_str()); }); QObject::connect(m_map.data(), &QMapLibre::Map::staticRenderFinished, [=](const QString &error) { rendering = false; if (!error.isEmpty()) { LOGE("Static map rendering failed with error: '%s'\n", error.toStdString().c_str()); } else if (vipc_server != nullptr) { double end_render_t = millis_since_boot(); publish((end_render_t - start_render_t) / 1000.0, true); last_llk_rendered = (*sm)["liveLocationKalman"].getLogMonoTime(); } }); if (online) { vipc_server.reset(new VisionIpcServer("navd")); vipc_server->create_buffers(VisionStreamType::VISION_STREAM_MAP, NUM_VIPC_BUFFERS, false, WIDTH, HEIGHT); vipc_server->start_listener(); pm.reset(new PubMaster({"navThumbnail", "mapRenderState"})); sm.reset(new SubMaster({"liveLocationKalman", "navRoute"}, {"liveLocationKalman"})); timer = new QTimer(this); timer->setSingleShot(true); QObject::connect(timer, SIGNAL(timeout()), this, SLOT(msgUpdate())); timer->start(0); } } void MapRenderer::msgUpdate() { sm->update(1000); if (sm->updated("liveLocationKalman")) { auto location = (*sm)["liveLocationKalman"].getLiveLocationKalman(); auto pos = location.getPositionGeodetic(); auto orientation = location.getCalibratedOrientationNED(); if ((sm->rcv_frame("liveLocationKalman") % LLK_DECIMATION) == 0) { float bearing = RAD2DEG(orientation.getValue()[2]); updatePosition(get_point_along_line(pos.getValue()[0], pos.getValue()[1], bearing, MAP_OFFSET), bearing); if (!rendering) { update(); } if (!rendered()) { publish(0, false); } } } if (sm->updated("navRoute")) { QList<QGeoCoordinate> route; auto coords = (*sm)["navRoute"].getNavRoute().getCoordinates(); for (auto const &c : coords) { route.push_back(QGeoCoordinate(c.getLatitude(), c.getLongitude())); } updateRoute(route); } // schedule next update timer->start(0); } void MapRenderer::updatePosition(QMapLibre::Coordinate position, float bearing) { if (m_map.isNull()) { return; } // Choose a scale that ensures above 13 zoom level up to and above 75deg of lat float meters_per_pixel = 2; float zoom = get_zoom_level_for_scale(position.first, meters_per_pixel); m_map->setCoordinate(position); m_map->setBearing(bearing); m_map->setZoom(zoom); if (!rendering) { update(); } } bool MapRenderer::loaded() { return m_map->isFullyLoaded(); } void MapRenderer::update() { rendering = true; gl_functions->glClear(GL_COLOR_BUFFER_BIT); start_render_t = millis_since_boot(); m_map->startStaticRender(); } void MapRenderer::sendThumbnail(const uint64_t ts, const kj::Array<capnp::byte> &buf) { MessageBuilder msg; auto thumbnaild = msg.initEvent().initNavThumbnail(); thumbnaild.setFrameId(frame_id); thumbnaild.setTimestampEof(ts); thumbnaild.setThumbnail(buf); pm->send("navThumbnail", msg); } void MapRenderer::publish(const double render_time, const bool loaded) { QImage cap = fbo->toImage().convertToFormat(QImage::Format_RGB888, Qt::AutoColor); auto location = (*sm)["liveLocationKalman"].getLiveLocationKalman(); bool valid = loaded && (location.getStatus() == cereal::LiveLocationKalman::Status::VALID) && location.getPositionGeodetic().getValid(); ever_loaded = ever_loaded || loaded; uint64_t ts = nanos_since_boot(); VisionBuf* buf = vipc_server->get_buffer(VisionStreamType::VISION_STREAM_MAP); VisionIpcBufExtra extra = { .frame_id = frame_id, .timestamp_sof = (*sm)["liveLocationKalman"].getLogMonoTime(), .timestamp_eof = ts, .valid = valid, }; assert(cap.sizeInBytes() >= buf->len); uint8_t* dst = (uint8_t*)buf->addr; uint8_t* src = cap.bits(); // RGB to greyscale memset(dst, 128, buf->len); for (int i = 0; i < WIDTH * HEIGHT; i++) { dst[i] = src[i * 3]; } vipc_server->send(buf, &extra); // Send thumbnail if (TEST_MODE) { // Full image in thumbnails in test mode kj::Array<capnp::byte> buffer_kj = kj::heapArray<capnp::byte>((const capnp::byte*)cap.bits(), cap.sizeInBytes()); sendThumbnail(ts, buffer_kj); } else if (frame_id % 100 == 0) { // Write jpeg into buffer QByteArray buffer_bytes; QBuffer buffer(&buffer_bytes); buffer.open(QIODevice::WriteOnly); cap.save(&buffer, "JPG", 50); kj::Array<capnp::byte> buffer_kj = kj::heapArray<capnp::byte>((const capnp::byte*)buffer_bytes.constData(), buffer_bytes.size()); sendThumbnail(ts, buffer_kj); } // Send state msg MessageBuilder msg; auto evt = msg.initEvent(); auto state = evt.initMapRenderState(); evt.setValid(valid); state.setLocationMonoTime((*sm)["liveLocationKalman"].getLogMonoTime()); state.setRenderTime(render_time); state.setFrameId(frame_id); pm->send("mapRenderState", msg); frame_id++; } uint8_t* MapRenderer::getImage() { QImage cap = fbo->toImage().convertToFormat(QImage::Format_RGB888, Qt::AutoColor); uint8_t* src = cap.bits(); uint8_t* dst = new uint8_t[WIDTH * HEIGHT]; // RGB to greyscale for (int i = 0; i < WIDTH * HEIGHT; i++) { dst[i] = src[i * 3]; } return dst; } void MapRenderer::updateRoute(QList<QGeoCoordinate> coordinates) { if (m_map.isNull()) return; initLayers(); auto route_points = coordinate_list_to_collection(coordinates); QMapLibre::Feature feature(QMapLibre::Feature::LineStringType, route_points, {}, {}); QVariantMap navSource; navSource["type"] = "geojson"; navSource["data"] = QVariant::fromValue<QMapLibre::Feature>(feature); m_map->updateSource("navSource", navSource); m_map->setLayoutProperty("navLayer", "visibility", "visible"); } void MapRenderer::initLayers() { if (!m_map->layerExists("navLayer")) { LOGD("Initializing navLayer"); QVariantMap nav; nav["type"] = "line"; nav["source"] = "navSource"; m_map->addLayer("navLayer", nav, "road-intersection"); m_map->setPaintProperty("navLayer", "line-color", QColor("grey")); m_map->setPaintProperty("navLayer", "line-width", 5); m_map->setLayoutProperty("navLayer", "line-cap", "round"); } } MapRenderer::~MapRenderer() { } extern "C" { MapRenderer* map_renderer_init(char *maps_host = nullptr, char *token = nullptr) { char *argv[] = { (char*)"navd", nullptr }; int argc = 0; QApplication *app = new QApplication(argc, argv); assert(app); QMapLibre::Settings settings; settings.setProviderTemplate(QMapLibre::Settings::ProviderTemplate::MapboxProvider); settings.setApiBaseUrl(maps_host == nullptr ? MAPS_HOST : maps_host); settings.setApiKey(token == nullptr ? get_mapbox_token() : token); return new MapRenderer(settings, false); } void map_renderer_update_position(MapRenderer *inst, float lat, float lon, float bearing) { inst->updatePosition({lat, lon}, bearing); QApplication::processEvents(); } void map_renderer_update_route(MapRenderer *inst, char* polyline) { inst->updateRoute(polyline_to_coordinate_list(QString::fromUtf8(polyline))); } void map_renderer_update(MapRenderer *inst) { inst->update(); } void map_renderer_process(MapRenderer *inst) { QApplication::processEvents(); } bool map_renderer_loaded(MapRenderer *inst) { return inst->loaded(); } uint8_t * map_renderer_get_image(MapRenderer *inst) { return inst->getImage(); } void map_renderer_free_image(MapRenderer *inst, uint8_t * buf) { delete[] buf; } }
2301_81045437/openpilot
selfdrive/navd/map_renderer.cc
C++
mit
10,992
#pragma once #include <memory> #include <QOpenGLContext> #include <QMapLibre/Map> #include <QMapLibre/Settings> #include <QTimer> #include <QGeoCoordinate> #include <QOpenGLBuffer> #include <QOffscreenSurface> #include <QOpenGLFunctions> #include <QOpenGLFramebufferObject> #include "cereal/visionipc/visionipc_server.h" #include "cereal/messaging/messaging.h" class MapRenderer : public QObject { Q_OBJECT public: MapRenderer(const QMapLibre::Settings &, bool online=true); uint8_t* getImage(); void update(); bool loaded(); ~MapRenderer(); private: std::unique_ptr<QOpenGLContext> ctx; std::unique_ptr<QOffscreenSurface> surface; std::unique_ptr<QOpenGLFunctions> gl_functions; std::unique_ptr<QOpenGLFramebufferObject> fbo; std::unique_ptr<VisionIpcServer> vipc_server; std::unique_ptr<PubMaster> pm; std::unique_ptr<SubMaster> sm; void publish(const double render_time, const bool loaded); void sendThumbnail(const uint64_t ts, const kj::Array<capnp::byte> &buf); QMapLibre::Settings m_settings; QScopedPointer<QMapLibre::Map> m_map; void initLayers(); double start_render_t; uint32_t frame_id = 0; uint64_t last_llk_rendered = 0; bool rendering = false; bool rendered() { return last_llk_rendered == (*sm)["liveLocationKalman"].getLogMonoTime(); } QTimer* timer; bool ever_loaded = false; public slots: void updatePosition(QMapLibre::Coordinate position, float bearing); void updateRoute(QList<QGeoCoordinate> coordinates); void msgUpdate(); };
2301_81045437/openpilot
selfdrive/navd/map_renderer.h
C++
mit
1,525
#!/usr/bin/env python3 # You might need to uninstall the PyQt5 pip package to avoid conflicts import os import time import numpy as np import polyline from cffi import FFI from openpilot.common.ffi_wrapper import suffix from openpilot.common.basedir import BASEDIR HEIGHT = WIDTH = SIZE = 256 METERS_PER_PIXEL = 2 def get_ffi(): lib = os.path.join(BASEDIR, "selfdrive", "navd", "libmaprender" + suffix()) ffi = FFI() ffi.cdef(""" void* map_renderer_init(char *maps_host, char *token); void map_renderer_update_position(void *inst, float lat, float lon, float bearing); void map_renderer_update_route(void *inst, char *polyline); void map_renderer_update(void *inst); void map_renderer_process(void *inst); bool map_renderer_loaded(void *inst); uint8_t* map_renderer_get_image(void *inst); void map_renderer_free_image(void *inst, uint8_t *buf); """) return ffi, ffi.dlopen(lib) def wait_ready(lib, renderer, timeout=None): st = time.time() while not lib.map_renderer_loaded(renderer): lib.map_renderer_update(renderer) # The main qt app is not execed, so we need to periodically process events for e.g. network requests lib.map_renderer_process(renderer) time.sleep(0.01) if timeout is not None and time.time() - st > timeout: raise TimeoutError("Timeout waiting for map renderer to be ready") def get_image(lib, renderer): buf = lib.map_renderer_get_image(renderer) r = list(buf[0:WIDTH * HEIGHT]) lib.map_renderer_free_image(renderer, buf) # Convert to numpy r = np.asarray(r) return r.reshape((WIDTH, HEIGHT)) def navRoute_to_polyline(nr): coords = [(m.latitude, m.longitude) for m in nr.navRoute.coordinates] return coords_to_polyline(coords) def coords_to_polyline(coords): # TODO: where does this factor of 10 come from? return polyline.encode([(lat * 10., lon * 10.) for lat, lon in coords]) def polyline_to_coords(p): coords = polyline.decode(p) return [(lat / 10., lon / 10.) for lat, lon in coords] if __name__ == "__main__": import matplotlib.pyplot as plt ffi, lib = get_ffi() renderer = lib.map_renderer_init(ffi.NULL, ffi.NULL) wait_ready(lib, renderer) geometry = r"{yxk}@|obn~Eg@@eCFqc@J{RFw@?kA@gA?q|@Riu@NuJBgi@ZqVNcRBaPBkG@iSD{I@_H@cH?gG@mG@gG?aD@{LDgDDkVVyQLiGDgX@q_@@qI@qKhS{R~[}NtYaDbGoIvLwNfP_b@|f@oFnF_JxHel@bf@{JlIuxAlpAkNnLmZrWqFhFoh@jd@kX|TkJxH_RnPy^|[uKtHoZ~Um`DlkCorC``CuShQogCtwB_ThQcr@fk@sVrWgRhVmSb\\oj@jxA{Qvg@u]tbAyHzSos@xjBeKbWszAbgEc~@~jCuTrl@cYfo@mRn\\_m@v}@ij@jp@om@lk@y|A`pAiXbVmWzUod@xj@wNlTw}@|uAwSn\\kRfYqOdS_IdJuK`KmKvJoOhLuLbHaMzGwO~GoOzFiSrEsOhD}PhCqw@vJmnAxSczA`Vyb@bHk[fFgl@pJeoDdl@}}@zIyr@hG}X`BmUdBcM^aRR}Oe@iZc@mR_@{FScHxAn_@vz@zCzH~GjPxAhDlB~DhEdJlIbMhFfG|F~GlHrGjNjItLnGvQ~EhLnBfOn@p`@AzAAvn@CfC?fc@`@lUrArStCfSxEtSzGxM|ElFlBrOzJlEbDnC~BfDtCnHjHlLvMdTnZzHpObOf^pKla@~G|a@dErg@rCbj@zArYlj@ttJ~AfZh@r]LzYg@`TkDbj@gIdv@oE|i@kKzhA{CdNsEfOiGlPsEvMiDpLgBpHyB`MkB|MmArPg@|N?|P^rUvFz~AWpOCdAkB|PuB`KeFfHkCfGy@tAqC~AsBPkDs@uAiAcJwMe@s@eKkPMoXQux@EuuCoH?eI?Kas@}Dy@wAUkMOgDL" # noqa: E501 lib.map_renderer_update_route(renderer, geometry.encode()) POSITIONS = [ (32.71569271952601, -117.16384270868463, 0), (32.71569271952601, -117.16384270868463, 45), # San Diego (52.378641991483136, 4.902623379456488, 0), (52.378641991483136, 4.902623379456488, 45), # Amsterdam ] plt.figure() for i, pos in enumerate(POSITIONS): t = time.time() lib.map_renderer_update_position(renderer, *pos) wait_ready(lib, renderer) print(f"{pos} took {time.time() - t:.2f} s") plt.subplot(2, 2, i + 1) plt.imshow(get_image(lib, renderer), cmap='gray') plt.show()
2301_81045437/openpilot
selfdrive/navd/map_renderer.py
Python
mit
3,629
#!/usr/bin/env python3 import json import math import os import threading import requests import cereal.messaging as messaging from cereal import log from openpilot.common.api import Api from openpilot.common.params import Params from openpilot.common.realtime import Ratekeeper from openpilot.selfdrive.navd.helpers import (Coordinate, coordinate_from_param, distance_along_geometry, maxspeed_to_ms, minimum_distance, parse_banner_instructions) from openpilot.common.swaglog import cloudlog REROUTE_DISTANCE = 25 MANEUVER_TRANSITION_THRESHOLD = 10 REROUTE_COUNTER_MIN = 3 class RouteEngine: def __init__(self, sm, pm): self.sm = sm self.pm = pm self.params = Params() # Get last gps position from params self.last_position = coordinate_from_param("LastGPSPosition", self.params) self.last_bearing = None self.gps_ok = False self.localizer_valid = False self.nav_destination = None self.step_idx = None self.route = None self.route_geometry = None self.recompute_backoff = 0 self.recompute_countdown = 0 self.ui_pid = None self.reroute_counter = 0 self.api = None self.mapbox_token = None if "MAPBOX_TOKEN" in os.environ: self.mapbox_token = os.environ["MAPBOX_TOKEN"] self.mapbox_host = "https://api.mapbox.com" else: self.api = Api(self.params.get("DongleId", encoding='utf8')) self.mapbox_host = "https://maps.comma.ai" def update(self): self.sm.update(0) if self.sm.updated["managerState"]: ui_pid = [p.pid for p in self.sm["managerState"].processes if p.name == "ui" and p.running] if ui_pid: if self.ui_pid and self.ui_pid != ui_pid[0]: cloudlog.warning("UI restarting, sending route") threading.Timer(5.0, self.send_route).start() self.ui_pid = ui_pid[0] self.update_location() try: self.recompute_route() self.send_instruction() except Exception: cloudlog.exception("navd.failed_to_compute") def update_location(self): location = self.sm['liveLocationKalman'] self.gps_ok = location.gpsOK self.localizer_valid = (location.status == log.LiveLocationKalman.Status.valid) and location.positionGeodetic.valid if self.localizer_valid: self.last_bearing = math.degrees(location.calibratedOrientationNED.value[2]) self.last_position = Coordinate(location.positionGeodetic.value[0], location.positionGeodetic.value[1]) def recompute_route(self): if self.last_position is None: return new_destination = coordinate_from_param("NavDestination", self.params) if new_destination is None: self.clear_route() self.reset_recompute_limits() return should_recompute = self.should_recompute() if new_destination != self.nav_destination: cloudlog.warning(f"Got new destination from NavDestination param {new_destination}") should_recompute = True # Don't recompute when GPS drifts in tunnels if not self.gps_ok and self.step_idx is not None: return if self.recompute_countdown == 0 and should_recompute: self.recompute_countdown = 2**self.recompute_backoff self.recompute_backoff = min(6, self.recompute_backoff + 1) self.calculate_route(new_destination) self.reroute_counter = 0 else: self.recompute_countdown = max(0, self.recompute_countdown - 1) def calculate_route(self, destination): cloudlog.warning(f"Calculating route {self.last_position} -> {destination}") self.nav_destination = destination lang = self.params.get('LanguageSetting', encoding='utf8') if lang is not None: lang = lang.replace('main_', '') token = self.mapbox_token if token is None: token = self.api.get_token() params = { 'access_token': token, 'annotations': 'maxspeed', 'geometries': 'geojson', 'overview': 'full', 'steps': 'true', 'banner_instructions': 'true', 'alternatives': 'false', 'language': lang, } # TODO: move waypoints into NavDestination param? waypoints = self.params.get('NavDestinationWaypoints', encoding='utf8') waypoint_coords = [] if waypoints is not None and len(waypoints) > 0: waypoint_coords = json.loads(waypoints) coords = [ (self.last_position.longitude, self.last_position.latitude), *waypoint_coords, (destination.longitude, destination.latitude) ] params['waypoints'] = f'0;{len(coords)-1}' if self.last_bearing is not None: params['bearings'] = f"{(self.last_bearing + 360) % 360:.0f},90" + (';'*(len(coords)-1)) coords_str = ';'.join([f'{lon},{lat}' for lon, lat in coords]) url = self.mapbox_host + '/directions/v5/mapbox/driving-traffic/' + coords_str try: resp = requests.get(url, params=params, timeout=10) if resp.status_code != 200: cloudlog.event("API request failed", status_code=resp.status_code, text=resp.text, error=True) resp.raise_for_status() r = resp.json() if len(r['routes']): self.route = r['routes'][0]['legs'][0]['steps'] self.route_geometry = [] maxspeed_idx = 0 maxspeeds = r['routes'][0]['legs'][0]['annotation']['maxspeed'] # Convert coordinates for step in self.route: coords = [] for c in step['geometry']['coordinates']: coord = Coordinate.from_mapbox_tuple(c) # Last step does not have maxspeed if (maxspeed_idx < len(maxspeeds)): maxspeed = maxspeeds[maxspeed_idx] if ('unknown' not in maxspeed) and ('none' not in maxspeed): coord.annotations['maxspeed'] = maxspeed_to_ms(maxspeed) coords.append(coord) maxspeed_idx += 1 self.route_geometry.append(coords) maxspeed_idx -= 1 # Every segment ends with the same coordinate as the start of the next self.step_idx = 0 else: cloudlog.warning("Got empty route response") self.clear_route() # clear waypoints to avoid a re-route including past waypoints # TODO: only clear once we're past a waypoint self.params.remove('NavDestinationWaypoints') except requests.exceptions.RequestException: cloudlog.exception("failed to get route") self.clear_route() self.send_route() def send_instruction(self): msg = messaging.new_message('navInstruction', valid=True) if self.step_idx is None: msg.valid = False self.pm.send('navInstruction', msg) return step = self.route[self.step_idx] geometry = self.route_geometry[self.step_idx] along_geometry = distance_along_geometry(geometry, self.last_position) distance_to_maneuver_along_geometry = step['distance'] - along_geometry # Banner instructions are for the following maneuver step, don't use empty last step banner_step = step if not len(banner_step['bannerInstructions']) and self.step_idx == len(self.route) - 1: banner_step = self.route[max(self.step_idx - 1, 0)] # Current instruction msg.navInstruction.maneuverDistance = distance_to_maneuver_along_geometry instruction = parse_banner_instructions(banner_step['bannerInstructions'], distance_to_maneuver_along_geometry) if instruction is not None: for k,v in instruction.items(): setattr(msg.navInstruction, k, v) # All instructions maneuvers = [] for i, step_i in enumerate(self.route): if i < self.step_idx: distance_to_maneuver = -sum(self.route[j]['distance'] for j in range(i+1, self.step_idx)) - along_geometry elif i == self.step_idx: distance_to_maneuver = distance_to_maneuver_along_geometry else: distance_to_maneuver = distance_to_maneuver_along_geometry + sum(self.route[j]['distance'] for j in range(self.step_idx+1, i+1)) instruction = parse_banner_instructions(step_i['bannerInstructions'], distance_to_maneuver) if instruction is None: continue maneuver = {'distance': distance_to_maneuver} if 'maneuverType' in instruction: maneuver['type'] = instruction['maneuverType'] if 'maneuverModifier' in instruction: maneuver['modifier'] = instruction['maneuverModifier'] maneuvers.append(maneuver) msg.navInstruction.allManeuvers = maneuvers # Compute total remaining time and distance remaining = 1.0 - along_geometry / max(step['distance'], 1) total_distance = step['distance'] * remaining total_time = step['duration'] * remaining if step['duration_typical'] is None: total_time_typical = total_time else: total_time_typical = step['duration_typical'] * remaining # Add up totals for future steps for i in range(self.step_idx + 1, len(self.route)): total_distance += self.route[i]['distance'] total_time += self.route[i]['duration'] if self.route[i]['duration_typical'] is None: total_time_typical += self.route[i]['duration'] else: total_time_typical += self.route[i]['duration_typical'] msg.navInstruction.distanceRemaining = total_distance msg.navInstruction.timeRemaining = total_time msg.navInstruction.timeRemainingTypical = total_time_typical # Speed limit closest_idx, closest = min(enumerate(geometry), key=lambda p: p[1].distance_to(self.last_position)) if closest_idx > 0: # If we are not past the closest point, show previous if along_geometry < distance_along_geometry(geometry, geometry[closest_idx]): closest = geometry[closest_idx - 1] if ('maxspeed' in closest.annotations) and self.localizer_valid: msg.navInstruction.speedLimit = closest.annotations['maxspeed'] # Speed limit sign type if 'speedLimitSign' in step: if step['speedLimitSign'] == 'mutcd': msg.navInstruction.speedLimitSign = log.NavInstruction.SpeedLimitSign.mutcd elif step['speedLimitSign'] == 'vienna': msg.navInstruction.speedLimitSign = log.NavInstruction.SpeedLimitSign.vienna self.pm.send('navInstruction', msg) # Transition to next route segment if distance_to_maneuver_along_geometry < -MANEUVER_TRANSITION_THRESHOLD: if self.step_idx + 1 < len(self.route): self.step_idx += 1 self.reset_recompute_limits() else: cloudlog.warning("Destination reached") # Clear route if driving away from destination dist = self.nav_destination.distance_to(self.last_position) if dist > REROUTE_DISTANCE: self.params.remove("NavDestination") self.clear_route() def send_route(self): coords = [] if self.route is not None: for path in self.route_geometry: coords += [c.as_dict() for c in path] msg = messaging.new_message('navRoute', valid=True) msg.navRoute.coordinates = coords self.pm.send('navRoute', msg) def clear_route(self): self.route = None self.route_geometry = None self.step_idx = None self.nav_destination = None def reset_recompute_limits(self): self.recompute_backoff = 0 self.recompute_countdown = 0 def should_recompute(self): if self.step_idx is None or self.route is None: return True # Don't recompute in last segment, assume destination is reached if self.step_idx == len(self.route) - 1: return False # Compute closest distance to all line segments in the current path min_d = REROUTE_DISTANCE + 1 path = self.route_geometry[self.step_idx] for i in range(len(path) - 1): a = path[i] b = path[i + 1] if a.distance_to(b) < 1.0: continue min_d = min(min_d, minimum_distance(a, b, self.last_position)) if min_d > REROUTE_DISTANCE: self.reroute_counter += 1 else: self.reroute_counter = 0 return self.reroute_counter > REROUTE_COUNTER_MIN # TODO: Check for going wrong way in segment def main(): pm = messaging.PubMaster(['navInstruction', 'navRoute']) sm = messaging.SubMaster(['liveLocationKalman', 'managerState']) rk = Ratekeeper(1.0) route_engine = RouteEngine(sm, pm) while True: route_engine.update() rk.keep_time() if __name__ == "__main__": main()
2301_81045437/openpilot
selfdrive/navd/navd.py
Python
mit
12,379
#!/usr/bin/env python3 import json import sys from openpilot.common.params import Params if __name__ == "__main__": params = Params() # set from google maps url if len(sys.argv) > 1: coords = sys.argv[1].split("/@")[-1].split("/")[0].split(",") dest = { "latitude": float(coords[0]), "longitude": float(coords[1]) } params.put("NavDestination", json.dumps(dest)) params.remove("NavDestinationWaypoints") else: print("Setting to Taco Bell") dest = { "latitude": 32.71160109904473, "longitude": -117.12556569985693, } params.put("NavDestination", json.dumps(dest)) waypoints = [ (-117.16020713111648, 32.71997612490662), ] params.put("NavDestinationWaypoints", json.dumps(waypoints)) print(dest) print(waypoints)
2301_81045437/openpilot
selfdrive/navd/set_destination.py
Python
mit
810
#!/bin/bash -e DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null && pwd)" OP_ROOT="$DIR/../../" if [ -z "$BUILD" ]; then docker pull ghcr.io/commaai/openpilot-base:latest else docker build --cache-from ghcr.io/commaai/openpilot-base:latest -t ghcr.io/commaai/openpilot-base:latest -f $OP_ROOT/Dockerfile.openpilot_base . fi docker run \ -it \ --rm \ --volume $OP_ROOT:$OP_ROOT \ --workdir $PWD \ --env PYTHONPATH=$OP_ROOT \ ghcr.io/commaai/openpilot-base:latest \ /bin/bash
2301_81045437/openpilot
selfdrive/test/ci_shell.sh
Shell
mit
534
#!/usr/bin/env python3 import signal import subprocess signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGTERM, signal.SIG_DFL) from PyQt5.QtCore import QTimer from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel from openpilot.selfdrive.ui.qt.python_helpers import set_main_window class Window(QWidget): def __init__(self, parent=None): super().__init__(parent) layout = QVBoxLayout() self.setLayout(layout) self.l = QLabel("jenkins runner") layout.addWidget(self.l) layout.addStretch(1) layout.setContentsMargins(20, 20, 20, 20) cmds = [ "cat /etc/hostname", "echo AGNOS v$(cat /VERSION)", "uptime -p", ] self.labels = {} for c in cmds: self.labels[c] = QLabel(c) layout.addWidget(self.labels[c]) self.setStyleSheet(""" * { color: white; font-size: 55px; background-color: black; font-family: "JetBrains Mono"; } """) self.timer = QTimer() self.timer.timeout.connect(self.update) self.timer.start(10 * 1000) self.update() def update(self): for cmd, label in self.labels.items(): out = subprocess.run(cmd, capture_output=True, shell=True, check=False, encoding='utf8').stdout label.setText(out.strip()) if __name__ == "__main__": app = QApplication([]) w = Window() set_main_window(w) app.exec_()
2301_81045437/openpilot
selfdrive/test/ciui.py
Python
mit
1,441
#!/usr/bin/env python3 import subprocess import sys from openpilot.common.prefix import OpenpilotPrefix with OpenpilotPrefix(): ret = subprocess.call(sys.argv[1:]) exit(ret)
2301_81045437/openpilot
selfdrive/test/cpp_harness.py
Python
mit
180
#!/usr/bin/env bash set -e # To build sim and docs, you can run the following to mount the scons cache to the same place as in CI: # mkdir -p .ci_cache/scons_cache # sudo mount --bind /tmp/scons_cache/ .ci_cache/scons_cache SCRIPT_DIR=$(dirname "$0") OPENPILOT_DIR=$SCRIPT_DIR/../../ if [ -n "$TARGET_ARCHITECTURE" ]; then PLATFORM="linux/$TARGET_ARCHITECTURE" TAG_SUFFIX="-$TARGET_ARCHITECTURE" else PLATFORM="linux/$(uname -m)" TAG_SUFFIX="" fi source $SCRIPT_DIR/docker_common.sh $1 "$TAG_SUFFIX" DOCKER_BUILDKIT=1 docker buildx build --provenance false --pull --platform $PLATFORM --load --cache-to type=inline --cache-from type=registry,ref=$REMOTE_TAG -t $DOCKER_IMAGE:latest -t $REMOTE_TAG -t $LOCAL_TAG -f $OPENPILOT_DIR/$DOCKER_FILE $OPENPILOT_DIR if [ -n "$PUSH_IMAGE" ]; then docker push $REMOTE_TAG docker tag $REMOTE_TAG $REMOTE_SHA_TAG docker push $REMOTE_SHA_TAG fi
2301_81045437/openpilot
selfdrive/test/docker_build.sh
Shell
mit
900
if [ "$1" = "base" ]; then export DOCKER_IMAGE=openpilot-base export DOCKER_FILE=Dockerfile.openpilot_base elif [ "$1" = "sim" ]; then export DOCKER_IMAGE=openpilot-sim export DOCKER_FILE=tools/sim/Dockerfile.sim elif [ "$1" = "prebuilt" ]; then export DOCKER_IMAGE=openpilot-prebuilt export DOCKER_FILE=Dockerfile.openpilot else echo "Invalid docker build image: '$1'" exit 1 fi export DOCKER_REGISTRY=ghcr.io/commaai export COMMIT_SHA=$(git rev-parse HEAD) TAG_SUFFIX=$2 LOCAL_TAG=$DOCKER_IMAGE$TAG_SUFFIX REMOTE_TAG=$DOCKER_REGISTRY/$LOCAL_TAG REMOTE_SHA_TAG=$DOCKER_REGISTRY/$LOCAL_TAG:$COMMIT_SHA
2301_81045437/openpilot
selfdrive/test/docker_common.sh
Shell
mit
620
#!/usr/bin/env bash set -e if [ $# -lt 2 ]; then echo "Usage: $0 <base|docs|sim|prebuilt|cl> <arch1> <arch2> ..." exit 1 fi SCRIPT_DIR=$(dirname "$0") ARCHS=("${@:2}") source $SCRIPT_DIR/docker_common.sh $1 MANIFEST_AMENDS="" for ARCH in ${ARCHS[@]}; do MANIFEST_AMENDS="$MANIFEST_AMENDS --amend $REMOTE_TAG-$ARCH:$COMMIT_SHA" done docker manifest create $REMOTE_TAG $MANIFEST_AMENDS docker manifest create $REMOTE_SHA_TAG $MANIFEST_AMENDS if [[ -n "$PUSH_IMAGE" ]]; then docker manifest push $REMOTE_TAG docker manifest push $REMOTE_SHA_TAG fi
2301_81045437/openpilot
selfdrive/test/docker_tag_multiarch.sh
Shell
mit
561
import capnp import hypothesis.strategies as st from typing import Any from collections.abc import Callable from cereal import log DrawType = Callable[[st.SearchStrategy], Any] class FuzzyGenerator: def __init__(self, draw: DrawType, real_floats: bool): self.draw = draw self.real_floats = real_floats def generate_native_type(self, field: str) -> st.SearchStrategy[bool | int | float | str | bytes]: def floats(**kwargs) -> st.SearchStrategy[float]: allow_nan = not self.real_floats allow_infinity = not self.real_floats return st.floats(**kwargs, allow_nan=allow_nan, allow_infinity=allow_infinity) if field == 'bool': return st.booleans() elif field == 'int8': return st.integers(min_value=-2**7, max_value=2**7-1) elif field == 'int16': return st.integers(min_value=-2**15, max_value=2**15-1) elif field == 'int32': return st.integers(min_value=-2**31, max_value=2**31-1) elif field == 'int64': return st.integers(min_value=-2**63, max_value=2**63-1) elif field == 'uint8': return st.integers(min_value=0, max_value=2**8-1) elif field == 'uint16': return st.integers(min_value=0, max_value=2**16-1) elif field == 'uint32': return st.integers(min_value=0, max_value=2**32-1) elif field == 'uint64': return st.integers(min_value=0, max_value=2**64-1) elif field == 'float32': return floats(width=32) elif field == 'float64': return floats(width=64) elif field == 'text': return st.text(max_size=1000) elif field == 'data': return st.binary(max_size=1000) elif field == 'anyPointer': return st.text() else: raise NotImplementedError(f'Invalid type : {field}') def generate_field(self, field: capnp.lib.capnp._StructSchemaField) -> st.SearchStrategy: def rec(field_type: capnp.lib.capnp._DynamicStructReader) -> st.SearchStrategy: if field_type.which() == 'struct': return self.generate_struct(field.schema.elementType if base_type == 'list' else field.schema) elif field_type.which() == 'list': return st.lists(rec(field_type.list.elementType)) elif field_type.which() == 'enum': schema = field.schema.elementType if base_type == 'list' else field.schema return st.sampled_from(list(schema.enumerants.keys())) else: return self.generate_native_type(field_type.which()) if 'slot' in field.proto.to_dict(): base_type = field.proto.slot.type.which() return rec(field.proto.slot.type) else: return self.generate_struct(field.schema) def generate_struct(self, schema: capnp.lib.capnp._StructSchema, event: str = None) -> st.SearchStrategy[dict[str, Any]]: full_fill: list[str] = list(schema.non_union_fields) single_fill: list[str] = [event] if event else [self.draw(st.sampled_from(schema.union_fields))] if schema.union_fields else [] return st.fixed_dictionaries({field: self.generate_field(schema.fields[field]) for field in full_fill + single_fill}) @classmethod def get_random_msg(cls, draw: DrawType, struct: capnp.lib.capnp._StructModule, real_floats: bool = False) -> dict[str, Any]: fg = cls(draw, real_floats=real_floats) data: dict[str, Any] = draw(fg.generate_struct(struct.schema)) return data @classmethod def get_random_event_msg(cls, draw: DrawType, events: list[str], real_floats: bool = False) -> list[dict[str, Any]]: fg = cls(draw, real_floats=real_floats) return [draw(fg.generate_struct(log.Event.schema, e)) for e in sorted(events)]
2301_81045437/openpilot
selfdrive/test/fuzzy_generation.py
Python
mit
3,586
import contextlib import http.server import os import threading import time import pytest from functools import wraps import cereal.messaging as messaging from openpilot.common.params import Params from openpilot.system.manager.process_config import managed_processes from openpilot.system.hardware import PC from openpilot.system.version import training_version, terms_version def set_params_enabled(): os.environ['FINGERPRINT'] = "TOYOTA_COROLLA_TSS2" os.environ['LOGPRINT'] = "debug" params = Params() params.put("HasAcceptedTerms", terms_version) params.put("CompletedTrainingVersion", training_version) params.put_bool("OpenpilotEnabledToggle", True) # valid calib msg = messaging.new_message('liveCalibration') msg.liveCalibration.validBlocks = 20 msg.liveCalibration.rpyCalib = [0.0, 0.0, 0.0] params.put("CalibrationParams", msg.to_bytes()) def phone_only(f): @wraps(f) def wrap(self, *args, **kwargs): if PC: pytest.skip("This test is not meant to run on PC") return f(self, *args, **kwargs) return wrap def release_only(f): @wraps(f) def wrap(self, *args, **kwargs): if "RELEASE" not in os.environ: pytest.skip("This test is only for release branches") f(self, *args, **kwargs) return wrap @contextlib.contextmanager def processes_context(processes, init_time=0, ignore_stopped=None): ignore_stopped = [] if ignore_stopped is None else ignore_stopped # start and assert started for n, p in enumerate(processes): managed_processes[p].start() if n < len(processes) - 1: time.sleep(init_time) assert all(managed_processes[name].proc.exitcode is None for name in processes) try: yield [managed_processes[name] for name in processes] # assert processes are still started assert all(managed_processes[name].proc.exitcode is None for name in processes if name not in ignore_stopped) finally: for p in processes: managed_processes[p].stop() def with_processes(processes, init_time=0, ignore_stopped=None): def wrapper(func): @wraps(func) def wrap(*args, **kwargs): with processes_context(processes, init_time, ignore_stopped): return func(*args, **kwargs) return wrap return wrapper def noop(*args, **kwargs): pass def read_segment_list(segment_list_path): with open(segment_list_path) as f: seg_list = f.read().splitlines() return [(platform[2:], segment) for platform, segment in zip(seg_list[::2], seg_list[1::2], strict=True)] @contextlib.contextmanager def http_server_context(handler, setup=None): host = '127.0.0.1' server = http.server.HTTPServer((host, 0), handler) port = server.server_port t = threading.Thread(target=server.serve_forever) t.start() if setup is not None: setup(host, port) try: yield (host, port) finally: server.shutdown() server.server_close() t.join() def with_http_server(func, handler=http.server.BaseHTTPRequestHandler, setup=None): @wraps(func) def inner(*args, **kwargs): with http_server_context(handler, setup) as (host, port): return func(*args, f"http://{host}:{port}", **kwargs) return inner def DirectoryHttpServer(directory) -> type[http.server.SimpleHTTPRequestHandler]: # creates an http server that serves files from directory class Handler(http.server.SimpleHTTPRequestHandler): API_NO_RESPONSE = False API_BAD_RESPONSE = False def do_GET(self): if self.API_NO_RESPONSE: return if self.API_BAD_RESPONSE: self.send_response(500, "") return super().do_GET() def __init__(self, *args, **kwargs): super().__init__(*args, directory=str(directory), **kwargs) return Handler
2301_81045437/openpilot
selfdrive/test/helpers.py
Python
mit
3,722
import numpy as np from openpilot.selfdrive.test.longitudinal_maneuvers.plant import Plant class Maneuver: def __init__(self, title, duration, **kwargs): # Was tempted to make a builder class self.distance_lead = kwargs.get("initial_distance_lead", 200.0) self.speed = kwargs.get("initial_speed", 0.0) self.lead_relevancy = kwargs.get("lead_relevancy", 0) self.breakpoints = kwargs.get("breakpoints", [0.0, duration]) self.speed_lead_values = kwargs.get("speed_lead_values", [0.0 for i in range(len(self.breakpoints))]) self.prob_lead_values = kwargs.get("prob_lead_values", [1.0 for i in range(len(self.breakpoints))]) self.cruise_values = kwargs.get("cruise_values", [50.0 for i in range(len(self.breakpoints))]) self.only_lead2 = kwargs.get("only_lead2", False) self.only_radar = kwargs.get("only_radar", False) self.ensure_start = kwargs.get("ensure_start", False) self.enabled = kwargs.get("enabled", True) self.e2e = kwargs.get("e2e", False) self.personality = kwargs.get("personality", 0) self.force_decel = kwargs.get("force_decel", False) self.duration = duration self.title = title def evaluate(self): plant = Plant( lead_relevancy=self.lead_relevancy, speed=self.speed, distance_lead=self.distance_lead, enabled=self.enabled, only_lead2=self.only_lead2, only_radar=self.only_radar, e2e=self.e2e, personality=self.personality, force_decel=self.force_decel, ) valid = True logs = [] while plant.current_time < self.duration: speed_lead = np.interp(plant.current_time, self.breakpoints, self.speed_lead_values) prob = np.interp(plant.current_time, self.breakpoints, self.prob_lead_values) cruise = np.interp(plant.current_time, self.breakpoints, self.cruise_values) log = plant.step(speed_lead, prob, cruise) d_rel = log['distance_lead'] - log['distance'] if self.lead_relevancy else 200. v_rel = speed_lead - log['speed'] if self.lead_relevancy else 0. log['d_rel'] = d_rel log['v_rel'] = v_rel logs.append(np.array([plant.current_time, log['distance'], log['distance_lead'], log['speed'], speed_lead, log['acceleration']])) if d_rel < .4 and (self.only_radar or prob > 0.5): print("Crashed!!!!") valid = False if self.ensure_start and log['v_rel'] > 0 and log['speeds'][-1] <= 0.1: print('LongitudinalPlanner not starting!') valid = False if self.force_decel and log['speed'] > 1e-1 and log['acceleration'] > -0.04: print('Not stopping with force decel') valid = False print("maneuver end", valid) return valid, np.array(logs)
2301_81045437/openpilot
selfdrive/test/longitudinal_maneuvers/maneuver.py
Python
mit
2,857
#!/usr/bin/env python3 import time import numpy as np from cereal import log import cereal.messaging as messaging from openpilot.common.realtime import Ratekeeper, DT_MDL from openpilot.selfdrive.controls.lib.longcontrol import LongCtrlState from openpilot.selfdrive.modeld.constants import ModelConstants from openpilot.selfdrive.controls.lib.longitudinal_planner import LongitudinalPlanner from openpilot.selfdrive.controls.radard import _LEAD_ACCEL_TAU class Plant: messaging_initialized = False def __init__(self, lead_relevancy=False, speed=0.0, distance_lead=2.0, enabled=True, only_lead2=False, only_radar=False, e2e=False, personality=0, force_decel=False): self.rate = 1. / DT_MDL if not Plant.messaging_initialized: Plant.radar = messaging.pub_sock('radarState') Plant.controls_state = messaging.pub_sock('controlsState') Plant.car_state = messaging.pub_sock('carState') Plant.plan = messaging.sub_sock('longitudinalPlan') Plant.messaging_initialized = True self.v_lead_prev = 0.0 self.distance = 0. self.speed = speed self.acceleration = 0.0 self.speeds = [] # lead car self.lead_relevancy = lead_relevancy self.distance_lead = distance_lead self.enabled = enabled self.only_lead2 = only_lead2 self.only_radar = only_radar self.e2e = e2e self.personality = personality self.force_decel = force_decel self.rk = Ratekeeper(self.rate, print_delay_threshold=100.0) self.ts = 1. / self.rate time.sleep(0.1) self.sm = messaging.SubMaster(['longitudinalPlan']) from openpilot.selfdrive.car.honda.values import CAR from openpilot.selfdrive.car.honda.interface import CarInterface self.planner = LongitudinalPlanner(CarInterface.get_non_essential_params(CAR.HONDA_CIVIC), init_v=self.speed) @property def current_time(self): return float(self.rk.frame) / self.rate def step(self, v_lead=0.0, prob=1.0, v_cruise=50.): # ******** publish a fake model going straight and fake calibration ******** # note that this is worst case for MPC, since model will delay long mpc by one time step radar = messaging.new_message('radarState') control = messaging.new_message('controlsState') car_state = messaging.new_message('carState') model = messaging.new_message('modelV2') a_lead = (v_lead - self.v_lead_prev)/self.ts self.v_lead_prev = v_lead if self.lead_relevancy: d_rel = np.maximum(0., self.distance_lead - self.distance) v_rel = v_lead - self.speed if self.only_radar: status = True elif prob > .5: status = True else: status = False else: d_rel = 200. v_rel = 0. prob = 0.0 status = False lead = log.RadarState.LeadData.new_message() lead.dRel = float(d_rel) lead.yRel = 0.0 lead.vRel = float(v_rel) lead.aRel = float(a_lead - self.acceleration) lead.vLead = float(v_lead) lead.vLeadK = float(v_lead) lead.aLeadK = float(a_lead) # TODO use real radard logic for this lead.aLeadTau = float(_LEAD_ACCEL_TAU) lead.status = status lead.modelProb = float(prob) if not self.only_lead2: radar.radarState.leadOne = lead radar.radarState.leadTwo = lead # Simulate model predicting slightly faster speed # this is to ensure lead policy is effective when model # does not predict slowdown in e2e mode position = log.XYZTData.new_message() position.x = [float(x) for x in (self.speed + 0.5) * np.array(ModelConstants.T_IDXS)] model.modelV2.position = position velocity = log.XYZTData.new_message() velocity.x = [float(x) for x in (self.speed + 0.5) * np.ones_like(ModelConstants.T_IDXS)] model.modelV2.velocity = velocity acceleration = log.XYZTData.new_message() acceleration.x = [float(x) for x in np.zeros_like(ModelConstants.T_IDXS)] model.modelV2.acceleration = acceleration control.controlsState.longControlState = LongCtrlState.pid if self.enabled else LongCtrlState.off control.controlsState.vCruise = float(v_cruise * 3.6) control.controlsState.experimentalMode = self.e2e control.controlsState.personality = self.personality control.controlsState.forceDecel = self.force_decel car_state.carState.vEgo = float(self.speed) car_state.carState.standstill = self.speed < 0.01 # ******** get controlsState messages for plotting *** sm = {'radarState': radar.radarState, 'carState': car_state.carState, 'controlsState': control.controlsState, 'modelV2': model.modelV2} self.planner.update(sm) self.speed = self.planner.v_desired_filter.x self.acceleration = self.planner.a_desired self.speeds = self.planner.v_desired_trajectory.tolist() fcw = self.planner.fcw self.distance_lead = self.distance_lead + v_lead * self.ts # ******** run the car ******** #print(self.distance, speed) if self.speed <= 0: self.speed = 0 self.acceleration = 0 self.distance = self.distance + self.speed * self.ts # *** radar model *** if self.lead_relevancy: d_rel = np.maximum(0., self.distance_lead - self.distance) v_rel = v_lead - self.speed else: d_rel = 200. v_rel = 0. # print at 5hz # if (self.rk.frame % (self.rate // 5)) == 0: # print("%2.2f sec %6.2f m %6.2f m/s %6.2f m/s2 lead_rel: %6.2f m %6.2f m/s" # % (self.current_time, self.distance, self.speed, self.acceleration, d_rel, v_rel)) # ******** update prevs ******** self.rk.monitor_time() return { "distance": self.distance, "speed": self.speed, "acceleration": self.acceleration, "speeds": self.speeds, "distance_lead": self.distance_lead, "fcw": fcw, } # simple engage in standalone mode def plant_thread(): plant = Plant() while 1: plant.step() if __name__ == "__main__": plant_thread()
2301_81045437/openpilot
selfdrive/test/longitudinal_maneuvers/plant.py
Python
mit
5,979
#!/usr/bin/env bash set -e # Loop something forever until it fails, for verifying new tests while true; do $@ done
2301_81045437/openpilot
selfdrive/test/loop_until_fail.sh
Shell
mit
119
from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, get_process_config, get_custom_params_from_lr, \ replay_process, replay_process_with_name # noqa: F401
2301_81045437/openpilot
selfdrive/test/process_replay/__init__.py
Python
mit
246
import os import sys from typing import no_type_check class FdRedirect: def __init__(self, file_prefix: str, fd: int): fname = os.path.join("/tmp", f"{file_prefix}.{fd}") if os.path.exists(fname): os.unlink(fname) self.dest_fd = os.open(fname, os.O_WRONLY | os.O_CREAT) self.dest_fname = fname self.source_fd = fd os.set_inheritable(self.dest_fd, True) def __del__(self): os.close(self.dest_fd) def purge(self) -> None: os.unlink(self.dest_fname) def read(self) -> bytes: with open(self.dest_fname, "rb") as f: return f.read() or b"" def link(self) -> None: os.dup2(self.dest_fd, self.source_fd) class ProcessOutputCapture: def __init__(self, proc_name: str, prefix: str): prefix = f"{proc_name}_{prefix}" self.stdout_redirect = FdRedirect(prefix, 1) self.stderr_redirect = FdRedirect(prefix, 2) def __del__(self): self.stdout_redirect.purge() self.stderr_redirect.purge() @no_type_check # ipython classes have incompatible signatures def link_with_current_proc(self) -> None: try: # prevent ipykernel from redirecting stdout/stderr of python subprocesses from ipykernel.iostream import OutStream if isinstance(sys.stdout, OutStream): sys.stdout = sys.__stdout__ if isinstance(sys.stderr, OutStream): sys.stderr = sys.__stderr__ except ImportError: pass # link stdout/stderr to the fifo self.stdout_redirect.link() self.stderr_redirect.link() def read_outerr(self) -> tuple[str, str]: out_str = self.stdout_redirect.read().decode() err_str = self.stderr_redirect.read().decode() return out_str, err_str
2301_81045437/openpilot
selfdrive/test/process_replay/capture.py
Python
mit
1,685
#!/usr/bin/env python3 import sys import math import capnp import numbers import dictdiffer from collections import Counter from openpilot.tools.lib.logreader import LogReader EPSILON = sys.float_info.epsilon def remove_ignored_fields(msg, ignore): msg = msg.as_builder() for key in ignore: attr = msg keys = key.split(".") if msg.which() != keys[0] and len(keys) > 1: continue for k in keys[:-1]: # indexing into list if k.isdigit(): attr = attr[int(k)] else: attr = getattr(attr, k) v = getattr(attr, keys[-1]) if isinstance(v, bool): val = False elif isinstance(v, numbers.Number): val = 0 elif isinstance(v, (list, capnp.lib.capnp._DynamicListBuilder)): val = [] else: raise NotImplementedError(f"Unknown type: {type(v)}") setattr(attr, keys[-1], val) return msg def compare_logs(log1, log2, ignore_fields=None, ignore_msgs=None, tolerance=None,): if ignore_fields is None: ignore_fields = [] if ignore_msgs is None: ignore_msgs = [] tolerance = EPSILON if tolerance is None else tolerance log1, log2 = ( [m for m in log if m.which() not in ignore_msgs] for log in (log1, log2) ) if len(log1) != len(log2): cnt1 = Counter(m.which() for m in log1) cnt2 = Counter(m.which() for m in log2) raise Exception(f"logs are not same length: {len(log1)} VS {len(log2)}\n\t\t{cnt1}\n\t\t{cnt2}") diff = [] for msg1, msg2 in zip(log1, log2, strict=True): if msg1.which() != msg2.which(): raise Exception("msgs not aligned between logs") msg1 = remove_ignored_fields(msg1, ignore_fields) msg2 = remove_ignored_fields(msg2, ignore_fields) if msg1.to_bytes() != msg2.to_bytes(): msg1_dict = msg1.as_reader().to_dict(verbose=True) msg2_dict = msg2.as_reader().to_dict(verbose=True) dd = dictdiffer.diff(msg1_dict, msg2_dict, ignore=ignore_fields) # Dictdiffer only supports relative tolerance, we also want to check for absolute # TODO: add this to dictdiffer def outside_tolerance(diff): try: if diff[0] == "change": a, b = diff[2] finite = math.isfinite(a) and math.isfinite(b) if finite and isinstance(a, numbers.Number) and isinstance(b, numbers.Number): return abs(a - b) > max(tolerance, tolerance * max(abs(a), abs(b))) except TypeError: pass return True dd = list(filter(outside_tolerance, dd)) diff.extend(dd) return diff def format_process_diff(diff): diff_short, diff_long = "", "" if isinstance(diff, str): diff_short += f" {diff}\n" diff_long += f"\t{diff}\n" else: cnt: dict[str, int] = {} for d in diff: diff_long += f"\t{str(d)}\n" k = str(d[1]) cnt[k] = 1 if k not in cnt else cnt[k] + 1 for k, v in sorted(cnt.items()): diff_short += f" {k}: {v}\n" return diff_short, diff_long def format_diff(results, log_paths, ref_commit): diff_short, diff_long = "", "" diff_long += f"***** tested against commit {ref_commit} *****\n" failed = False for segment, result in list(results.items()): diff_short += f"***** results for segment {segment} *****\n" diff_long += f"***** differences for segment {segment} *****\n" for proc, diff in list(result.items()): diff_long += f"*** process: {proc} ***\n" diff_long += f"\tref: {log_paths[segment][proc]['ref']}\n" diff_long += f"\tnew: {log_paths[segment][proc]['new']}\n\n" diff_short += f" {proc}\n" if isinstance(diff, str) or len(diff): diff_short += f" ref: {log_paths[segment][proc]['ref']}\n" diff_short += f" new: {log_paths[segment][proc]['new']}\n\n" failed = True proc_diff_short, proc_diff_long = format_process_diff(diff) diff_long += proc_diff_long diff_short += proc_diff_short return diff_short, diff_long, failed if __name__ == "__main__": log1 = list(LogReader(sys.argv[1])) log2 = list(LogReader(sys.argv[2])) ignore_fields = sys.argv[3:] or ["logMonoTime", "controlsState.startMonoTime", "controlsState.cumLagMs"] results = {"segment": {"proc": compare_logs(log1, log2, ignore_fields)}} log_paths = {"segment": {"proc": {"ref": sys.argv[1], "new": sys.argv[2]}}} diff_short, diff_long, failed = format_diff(results, log_paths, None) print(diff_long) print(diff_short)
2301_81045437/openpilot
selfdrive/test/process_replay/compare_logs.py
Python
mit
4,483
from collections import defaultdict from cereal import messaging from openpilot.selfdrive.car.fingerprints import MIGRATION from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_encode_index from openpilot.selfdrive.car.toyota.values import EPS_SCALE from openpilot.system.manager.process_config import managed_processes from panda import Panda # TODO: message migration should happen in-place def migrate_all(lr, old_logtime=False, manager_states=False, panda_states=False, camera_states=False): msgs = migrate_sensorEvents(lr, old_logtime) msgs = migrate_carParams(msgs, old_logtime) msgs = migrate_gpsLocation(msgs) msgs = migrate_deviceState(msgs) msgs = migrate_carOutput(msgs) if manager_states: msgs = migrate_managerState(msgs) if panda_states: msgs = migrate_pandaStates(msgs) msgs = migrate_peripheralState(msgs) if camera_states: msgs = migrate_cameraStates(msgs) return msgs def migrate_managerState(lr): all_msgs = [] for msg in lr: if msg.which() != "managerState": all_msgs.append(msg) continue new_msg = msg.as_builder() new_msg.managerState.processes = [{'name': name, 'running': True} for name in managed_processes] all_msgs.append(new_msg.as_reader()) return all_msgs def migrate_gpsLocation(lr): all_msgs = [] for msg in lr: if msg.which() in ('gpsLocation', 'gpsLocationExternal'): new_msg = msg.as_builder() g = getattr(new_msg, new_msg.which()) # hasFix is a newer field if not g.hasFix and g.flags == 1: g.hasFix = True all_msgs.append(new_msg.as_reader()) else: all_msgs.append(msg) return all_msgs def migrate_deviceState(lr): all_msgs = [] dt = None for msg in lr: if msg.which() == 'initData': dt = msg.initData.deviceType if msg.which() == 'deviceState': n = msg.as_builder() n.deviceState.deviceType = dt all_msgs.append(n.as_reader()) else: all_msgs.append(msg) return all_msgs def migrate_carOutput(lr): # migration needed only for routes before carOutput if any(msg.which() == 'carOutput' for msg in lr): return lr all_msgs = [] for msg in lr: if msg.which() == 'carControl': co = messaging.new_message('carOutput') co.valid = msg.valid co.logMonoTime = msg.logMonoTime co.carOutput.actuatorsOutput = msg.carControl.actuatorsOutputDEPRECATED all_msgs.append(co.as_reader()) all_msgs.append(msg) return all_msgs def migrate_pandaStates(lr): all_msgs = [] # TODO: safety param migration should be handled automatically safety_param_migration = { "TOYOTA_PRIUS": EPS_SCALE["TOYOTA_PRIUS"] | Panda.FLAG_TOYOTA_STOCK_LONGITUDINAL, "TOYOTA_RAV4": EPS_SCALE["TOYOTA_RAV4"] | Panda.FLAG_TOYOTA_ALT_BRAKE, "KIA_EV6": Panda.FLAG_HYUNDAI_EV_GAS | Panda.FLAG_HYUNDAI_CANFD_HDA2, } # Migrate safety param base on carState CP = next((m.carParams for m in lr if m.which() == 'carParams'), None) assert CP is not None, "carParams message not found" if CP.carFingerprint in safety_param_migration: safety_param = safety_param_migration[CP.carFingerprint] elif len(CP.safetyConfigs): safety_param = CP.safetyConfigs[0].safetyParam if CP.safetyConfigs[0].safetyParamDEPRECATED != 0: safety_param = CP.safetyConfigs[0].safetyParamDEPRECATED else: safety_param = CP.safetyParamDEPRECATED for msg in lr: if msg.which() == 'pandaStateDEPRECATED': new_msg = messaging.new_message('pandaStates', 1) new_msg.valid = msg.valid new_msg.logMonoTime = msg.logMonoTime new_msg.pandaStates[0] = msg.pandaStateDEPRECATED new_msg.pandaStates[0].safetyParam = safety_param all_msgs.append(new_msg.as_reader()) elif msg.which() == 'pandaStates': new_msg = msg.as_builder() new_msg.pandaStates[-1].safetyParam = safety_param all_msgs.append(new_msg.as_reader()) else: all_msgs.append(msg) return all_msgs def migrate_peripheralState(lr): if any(msg.which() == "peripheralState" for msg in lr): return lr all_msg = [] for msg in lr: all_msg.append(msg) if msg.which() not in ["pandaStates", "pandaStateDEPRECATED"]: continue new_msg = messaging.new_message("peripheralState") new_msg.valid = msg.valid new_msg.logMonoTime = msg.logMonoTime all_msg.append(new_msg.as_reader()) return all_msg def migrate_cameraStates(lr): all_msgs = [] frame_to_encode_id = defaultdict(dict) # just for encodeId fallback mechanism min_frame_id = defaultdict(lambda: float('inf')) for msg in lr: if msg.which() not in ["roadEncodeIdx", "wideRoadEncodeIdx", "driverEncodeIdx"]: continue encode_index = getattr(msg, msg.which()) meta = meta_from_encode_index(msg.which()) assert encode_index.segmentId < 1200, f"Encoder index segmentId greater that 1200: {msg.which()} {encode_index.segmentId}" frame_to_encode_id[meta.camera_state][encode_index.frameId] = encode_index.segmentId for msg in lr: if msg.which() not in ["roadCameraState", "wideRoadCameraState", "driverCameraState"]: all_msgs.append(msg) continue camera_state = getattr(msg, msg.which()) min_frame_id[msg.which()] = min(min_frame_id[msg.which()], camera_state.frameId) encode_id = frame_to_encode_id[msg.which()].get(camera_state.frameId) if encode_id is None: print(f"Missing encoded frame for camera feed {msg.which()} with frameId: {camera_state.frameId}") if len(frame_to_encode_id[msg.which()]) != 0: continue # fallback mechanism for logs without encodeIdx (e.g. logs from before 2022 with dcamera recording disabled) # try to fake encode_id by subtracting lowest frameId encode_id = camera_state.frameId - min_frame_id[msg.which()] print(f"Faking encodeId to {encode_id} for camera feed {msg.which()} with frameId: {camera_state.frameId}") new_msg = messaging.new_message(msg.which()) new_camera_state = getattr(new_msg, new_msg.which()) new_camera_state.frameId = encode_id new_camera_state.encodeId = encode_id # timestampSof was added later so it might be missing on some old segments if camera_state.timestampSof == 0 and camera_state.timestampEof > 25000000: new_camera_state.timestampSof = camera_state.timestampEof - 18000000 else: new_camera_state.timestampSof = camera_state.timestampSof new_camera_state.timestampEof = camera_state.timestampEof new_msg.logMonoTime = msg.logMonoTime new_msg.valid = msg.valid all_msgs.append(new_msg.as_reader()) return all_msgs def migrate_carParams(lr, old_logtime=False): all_msgs = [] for msg in lr: if msg.which() == 'carParams': CP = msg.as_builder() CP.carParams.carFingerprint = MIGRATION.get(CP.carParams.carFingerprint, CP.carParams.carFingerprint) for car_fw in CP.carParams.carFw: car_fw.brand = CP.carParams.carName if old_logtime: CP.logMonoTime = msg.logMonoTime msg = CP.as_reader() all_msgs.append(msg) return all_msgs def migrate_sensorEvents(lr, old_logtime=False): all_msgs = [] for msg in lr: if msg.which() != 'sensorEventsDEPRECATED': all_msgs.append(msg) continue # migrate to split sensor events for evt in msg.sensorEventsDEPRECATED: # build new message for each sensor type sensor_service = '' if evt.which() == 'acceleration': sensor_service = 'accelerometer' elif evt.which() == 'gyro' or evt.which() == 'gyroUncalibrated': sensor_service = 'gyroscope' elif evt.which() == 'light' or evt.which() == 'proximity': sensor_service = 'lightSensor' elif evt.which() == 'magnetic' or evt.which() == 'magneticUncalibrated': sensor_service = 'magnetometer' elif evt.which() == 'temperature': sensor_service = 'temperatureSensor' m = messaging.new_message(sensor_service) m.valid = True if old_logtime: m.logMonoTime = msg.logMonoTime m_dat = getattr(m, sensor_service) m_dat.version = evt.version m_dat.sensor = evt.sensor m_dat.type = evt.type m_dat.source = evt.source if old_logtime: m_dat.timestamp = evt.timestamp setattr(m_dat, evt.which(), getattr(evt, evt.which())) all_msgs.append(m.as_reader()) return all_msgs
2301_81045437/openpilot
selfdrive/test/process_replay/migration.py
Python
mit
8,423
#!/usr/bin/env python3 import os import sys from collections import defaultdict from typing import Any from openpilot.common.git import get_commit from openpilot.system.hardware import PC from openpilot.tools.lib.openpilotci import BASE_URL, get_url from openpilot.selfdrive.test.process_replay.compare_logs import compare_logs, format_diff from openpilot.selfdrive.test.process_replay.process_replay import get_process_config, replay_process from openpilot.tools.lib.framereader import FrameReader from openpilot.tools.lib.logreader import LogReader from openpilot.tools.lib.helpers import save_log TEST_ROUTE = "2f4452b03ccb98f0|2022-12-03--13-45-30" SEGMENT = 6 MAX_FRAMES = 100 if PC else 600 NO_MODEL = "NO_MODEL" in os.environ SEND_EXTRA_INPUTS = bool(int(os.getenv("SEND_EXTRA_INPUTS", "0"))) def get_log_fn(ref_commit, test_route): return f"{test_route}_model_tici_{ref_commit}.bz2" def trim_logs_to_max_frames(logs, max_frames, frs_types, include_all_types): all_msgs = [] cam_state_counts = defaultdict(int) # keep adding messages until cam states are equal to MAX_FRAMES for msg in sorted(logs, key=lambda m: m.logMonoTime): all_msgs.append(msg) if msg.which() in frs_types: cam_state_counts[msg.which()] += 1 if all(cam_state_counts[state] == max_frames for state in frs_types): break if len(include_all_types) != 0: other_msgs = [m for m in logs if m.which() in include_all_types] all_msgs.extend(other_msgs) return all_msgs def model_replay(lr, frs): # modeld is using frame pairs modeld_logs = trim_logs_to_max_frames(lr, MAX_FRAMES, {"roadCameraState", "wideRoadCameraState"}, {"roadEncodeIdx", "wideRoadEncodeIdx", "carParams"}) dmodeld_logs = trim_logs_to_max_frames(lr, MAX_FRAMES, {"driverCameraState"}, {"driverEncodeIdx", "carParams"}) if not SEND_EXTRA_INPUTS: modeld_logs = [msg for msg in modeld_logs if msg.which() != 'liveCalibration'] dmodeld_logs = [msg for msg in dmodeld_logs if msg.which() != 'liveCalibration'] # initial setup for s in ('liveCalibration', 'deviceState'): msg = next(msg for msg in lr if msg.which() == s).as_builder() msg.logMonoTime = lr[0].logMonoTime modeld_logs.insert(1, msg.as_reader()) dmodeld_logs.insert(1, msg.as_reader()) modeld = get_process_config("modeld") dmonitoringmodeld = get_process_config("dmonitoringmodeld") modeld_msgs = replay_process(modeld, modeld_logs, frs) dmonitoringmodeld_msgs = replay_process(dmonitoringmodeld, dmodeld_logs, frs) return modeld_msgs + dmonitoringmodeld_msgs if __name__ == "__main__": update = "--update" in sys.argv replay_dir = os.path.dirname(os.path.abspath(__file__)) ref_commit_fn = os.path.join(replay_dir, "model_replay_ref_commit") # load logs lr = list(LogReader(get_url(TEST_ROUTE, SEGMENT))) frs = { 'roadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="fcamera"), readahead=True), 'driverCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="dcamera"), readahead=True), 'wideRoadCameraState': FrameReader(get_url(TEST_ROUTE, SEGMENT, log_type="ecamera"), readahead=True) } # Update tile refs if update: import urllib import requests import threading import http.server from openpilot.tools.lib.openpilotci import upload_bytes os.environ['MAPS_HOST'] = 'http://localhost:5000' class HTTPRequestHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): assert len(self.path) > 10 # Sanity check on path length r = requests.get(f'https://api.mapbox.com{self.path}', timeout=30) upload_bytes(r.content, urllib.parse.urlparse(self.path).path.lstrip('/')) self.send_response(r.status_code) self.send_header('Content-type','text/html') self.end_headers() self.wfile.write(r.content) server = http.server.HTTPServer(("127.0.0.1", 5000), HTTPRequestHandler) thread = threading.Thread(None, server.serve_forever, daemon=True) thread.start() else: os.environ['MAPS_HOST'] = BASE_URL.rstrip('/') log_msgs = [] # run replays if not NO_MODEL: log_msgs += model_replay(lr, frs) # get diff failed = False if not update: with open(ref_commit_fn) as f: ref_commit = f.read().strip() log_fn = get_log_fn(ref_commit, TEST_ROUTE) try: all_logs = list(LogReader(BASE_URL + log_fn)) cmp_log = [] # logs are ordered based on type: modelV2, driverStateV2 if not NO_MODEL: model_start_index = next(i for i, m in enumerate(all_logs) if m.which() in ("modelV2", "cameraOdometry")) cmp_log += all_logs[model_start_index:model_start_index + MAX_FRAMES*2] dmon_start_index = next(i for i, m in enumerate(all_logs) if m.which() == "driverStateV2") cmp_log += all_logs[dmon_start_index:dmon_start_index + MAX_FRAMES] ignore = [ 'logMonoTime', 'modelV2.frameDropPerc', 'modelV2.modelExecutionTime', 'driverStateV2.modelExecutionTime', 'driverStateV2.dspExecutionTime' ] if PC: ignore += [ 'modelV2.laneLines.0.t', 'modelV2.laneLines.1.t', 'modelV2.laneLines.2.t', 'modelV2.laneLines.3.t', 'modelV2.roadEdges.0.t', 'modelV2.roadEdges.1.t', ] # TODO this tolerance is absurdly large tolerance = 2.0 if PC else None results: Any = {TEST_ROUTE: {}} log_paths: Any = {TEST_ROUTE: {"models": {'ref': BASE_URL + log_fn, 'new': log_fn}}} results[TEST_ROUTE]["models"] = compare_logs(cmp_log, log_msgs, tolerance=tolerance, ignore_fields=ignore) diff_short, diff_long, failed = format_diff(results, log_paths, ref_commit) if "CI" in os.environ: print(diff_long) print('-------------\n'*5) print(diff_short) with open("model_diff.txt", "w") as f: f.write(diff_long) except Exception as e: print(str(e)) failed = True # upload new refs if (update or failed) and not PC: from openpilot.tools.lib.openpilotci import upload_file print("Uploading new refs") new_commit = get_commit() log_fn = get_log_fn(new_commit, TEST_ROUTE) save_log(log_fn, log_msgs) try: upload_file(log_fn, os.path.basename(log_fn)) except Exception as e: print("failed to upload", e) with open(ref_commit_fn, 'w') as f: f.write(str(new_commit)) print("\n\nNew ref commit: ", new_commit) sys.exit(int(failed))
2301_81045437/openpilot
selfdrive/test/process_replay/model_replay.py
Python
mit
6,519
#!/usr/bin/env python3 import os import time import copy import json import heapq import signal import platform from collections import Counter, OrderedDict from dataclasses import dataclass, field from typing import Any from collections.abc import Callable, Iterable from tqdm import tqdm import capnp import cereal.messaging as messaging from cereal import car from cereal.services import SERVICE_LIST from cereal.visionipc import VisionIpcServer, get_endpoint_name as vipc_get_endpoint_name from openpilot.common.params import Params from openpilot.common.prefix import OpenpilotPrefix from openpilot.common.timeout import Timeout from openpilot.common.realtime import DT_CTRL from panda.python import ALTERNATIVE_EXPERIENCE from openpilot.selfdrive.car.car_helpers import get_car, interfaces from openpilot.system.manager.process_config import managed_processes from openpilot.selfdrive.test.process_replay.vision_meta import meta_from_camera_state, available_streams from openpilot.selfdrive.test.process_replay.migration import migrate_all from openpilot.selfdrive.test.process_replay.capture import ProcessOutputCapture from openpilot.tools.lib.logreader import LogIterable from openpilot.tools.lib.framereader import BaseFrameReader # Numpy gives different results based on CPU features after version 19 NUMPY_TOLERANCE = 1e-7 PROC_REPLAY_DIR = os.path.dirname(os.path.abspath(__file__)) FAKEDATA = os.path.join(PROC_REPLAY_DIR, "fakedata/") class DummySocket: def __init__(self): self.data: list[bytes] = [] def receive(self, non_blocking: bool = False) -> bytes | None: if non_blocking: return None return self.data.pop() def send(self, data: bytes): self.data.append(data) class LauncherWithCapture: def __init__(self, capture: ProcessOutputCapture, launcher: Callable): self.capture = capture self.launcher = launcher def __call__(self, *args, **kwargs): self.capture.link_with_current_proc() self.launcher(*args, **kwargs) class ReplayContext: def __init__(self, cfg): self.proc_name = cfg.proc_name self.pubs = cfg.pubs self.main_pub = cfg.main_pub self.main_pub_drained = cfg.main_pub_drained self.unlocked_pubs = cfg.unlocked_pubs assert(len(self.pubs) != 0 or self.main_pub is not None) def __enter__(self): self.open_context() return self def __exit__(self, exc_type, exc_obj, exc_tb): self.close_context() def open_context(self): messaging.toggle_fake_events(True) messaging.set_fake_prefix(self.proc_name) if self.main_pub is None: self.events = OrderedDict() pubs_with_events = [pub for pub in self.pubs if pub not in self.unlocked_pubs] for pub in pubs_with_events: self.events[pub] = messaging.fake_event_handle(pub, enable=True) else: self.events = {self.main_pub: messaging.fake_event_handle(self.main_pub, enable=True)} def close_context(self): del self.events messaging.toggle_fake_events(False) messaging.delete_fake_prefix() @property def all_recv_called_events(self): return [man.recv_called_event for man in self.events.values()] @property def all_recv_ready_events(self): return [man.recv_ready_event for man in self.events.values()] def send_sync(self, pm, endpoint, dat): self.events[endpoint].recv_called_event.wait() self.events[endpoint].recv_called_event.clear() pm.send(endpoint, dat) self.events[endpoint].recv_ready_event.set() def unlock_sockets(self): expected_sets = len(self.events) while expected_sets > 0: index = messaging.wait_for_one_event(self.all_recv_called_events) self.all_recv_called_events[index].clear() self.all_recv_ready_events[index].set() expected_sets -= 1 def wait_for_recv_called(self): messaging.wait_for_one_event(self.all_recv_called_events) def wait_for_next_recv(self, trigger_empty_recv): index = messaging.wait_for_one_event(self.all_recv_called_events) if self.main_pub is not None and self.main_pub_drained and trigger_empty_recv: self.all_recv_called_events[index].clear() self.all_recv_ready_events[index].set() self.all_recv_called_events[index].wait() @dataclass class ProcessConfig: proc_name: str pubs: list[str] subs: list[str] ignore: list[str] config_callback: Callable | None = None init_callback: Callable | None = None should_recv_callback: Callable | None = None tolerance: float | None = None processing_time: float = 0.001 timeout: int = 30 simulation: bool = True main_pub: str | None = None main_pub_drained: bool = True vision_pubs: list[str] = field(default_factory=list) ignore_alive_pubs: list[str] = field(default_factory=list) unlocked_pubs: list[str] = field(default_factory=list) class ProcessContainer: def __init__(self, cfg: ProcessConfig): self.prefix = OpenpilotPrefix(clean_dirs_on_exit=False) self.cfg = copy.deepcopy(cfg) self.process = copy.deepcopy(managed_processes[cfg.proc_name]) self.msg_queue: list[capnp._DynamicStructReader] = [] self.cnt = 0 self.pm: messaging.PubMaster | None = None self.sockets: list[messaging.SubSocket] | None = None self.rc: ReplayContext | None = None self.vipc_server: VisionIpcServer | None = None self.environ_config: dict[str, Any] | None = None self.capture: ProcessOutputCapture | None = None @property def has_empty_queue(self) -> bool: return len(self.msg_queue) == 0 @property def pubs(self) -> list[str]: return self.cfg.pubs @property def subs(self) -> list[str]: return self.cfg.subs def _clean_env(self): for k in self.environ_config.keys(): if k in os.environ: del os.environ[k] for k in ["PROC_NAME", "SIMULATION"]: if k in os.environ: del os.environ[k] def _setup_env(self, params_config: dict[str, Any], environ_config: dict[str, Any]): for k, v in environ_config.items(): if len(v) != 0: os.environ[k] = v elif k in os.environ: del os.environ[k] os.environ["PROC_NAME"] = self.cfg.proc_name if self.cfg.simulation: os.environ["SIMULATION"] = "1" elif "SIMULATION" in os.environ: del os.environ["SIMULATION"] params = Params() for k, v in params_config.items(): if isinstance(v, bool): params.put_bool(k, v) else: params.put(k, v) self.environ_config = environ_config def _setup_vision_ipc(self, all_msgs: LogIterable, frs: dict[str, Any]): assert len(self.cfg.vision_pubs) != 0 vipc_server = VisionIpcServer("camerad") streams_metas = available_streams(all_msgs) for meta in streams_metas: if meta.camera_state in self.cfg.vision_pubs: frame_size = (frs[meta.camera_state].w, frs[meta.camera_state].h) vipc_server.create_buffers(meta.stream, 2, False, *frame_size) vipc_server.start_listener() self.vipc_server = vipc_server self.cfg.vision_pubs = [meta.camera_state for meta in streams_metas if meta.camera_state in self.cfg.vision_pubs] def _start_process(self): if self.capture is not None: self.process.launcher = LauncherWithCapture(self.capture, self.process.launcher) self.process.prepare() self.process.start() def start( self, params_config: dict[str, Any], environ_config: dict[str, Any], all_msgs: LogIterable, frs: dict[str, BaseFrameReader] | None, fingerprint: str | None, capture_output: bool ): with self.prefix as p: self._setup_env(params_config, environ_config) if self.cfg.config_callback is not None: params = Params() self.cfg.config_callback(params, self.cfg, all_msgs) self.rc = ReplayContext(self.cfg) self.rc.open_context() self.pm = messaging.PubMaster(self.cfg.pubs) self.sockets = [messaging.sub_sock(s, timeout=100) for s in self.cfg.subs] if len(self.cfg.vision_pubs) != 0: assert frs is not None self._setup_vision_ipc(all_msgs, frs) assert self.vipc_server is not None if capture_output: self.capture = ProcessOutputCapture(self.cfg.proc_name, p.prefix) self._start_process() if self.cfg.init_callback is not None: self.cfg.init_callback(self.rc, self.pm, all_msgs, fingerprint) # wait for process to startup with Timeout(10, error_msg=f"timed out waiting for process to start: {repr(self.cfg.proc_name)}"): while not all(self.pm.all_readers_updated(s) for s in self.cfg.pubs if s not in self.cfg.ignore_alive_pubs): time.sleep(0) def stop(self): with self.prefix: self.process.signal(signal.SIGKILL) self.process.stop() self.rc.close_context() self.prefix.clean_dirs() self._clean_env() def run_step(self, msg: capnp._DynamicStructReader, frs: dict[str, BaseFrameReader] | None) -> list[capnp._DynamicStructReader]: assert self.rc and self.pm and self.sockets and self.process.proc output_msgs = [] with self.prefix, Timeout(self.cfg.timeout, error_msg=f"timed out testing process {repr(self.cfg.proc_name)}"): end_of_cycle = True if self.cfg.should_recv_callback is not None: end_of_cycle = self.cfg.should_recv_callback(msg, self.cfg, self.cnt) self.msg_queue.append(msg) if end_of_cycle: self.rc.wait_for_recv_called() # call recv to let sub-sockets reconnect, after we know the process is ready if self.cnt == 0: for s in self.sockets: messaging.recv_one_or_none(s) # empty recv on drained pub indicates the end of messages, only do that if there're any trigger_empty_recv = False if self.cfg.main_pub and self.cfg.main_pub_drained: trigger_empty_recv = next((True for m in self.msg_queue if m.which() == self.cfg.main_pub), False) for m in self.msg_queue: self.pm.send(m.which(), m.as_builder()) # send frames if needed if self.vipc_server is not None and m.which() in self.cfg.vision_pubs: camera_state = getattr(m, m.which()) camera_meta = meta_from_camera_state(m.which()) assert frs is not None img = frs[m.which()].get(camera_state.frameId, pix_fmt="nv12")[0] self.vipc_server.send(camera_meta.stream, img.flatten().tobytes(), camera_state.frameId, camera_state.timestampSof, camera_state.timestampEof) self.msg_queue = [] self.rc.unlock_sockets() self.rc.wait_for_next_recv(trigger_empty_recv) for socket in self.sockets: ms = messaging.drain_sock(socket) for m in ms: m = m.as_builder() m.logMonoTime = msg.logMonoTime + int(self.cfg.processing_time * 1e9) output_msgs.append(m.as_reader()) self.cnt += 1 assert self.process.proc.is_alive() return output_msgs def card_fingerprint_callback(rc, pm, msgs, fingerprint): print("start fingerprinting") params = Params() canmsgs = [msg for msg in msgs if msg.which() == "can"][:300] # card expects one arbitrary can and pandaState rc.send_sync(pm, "can", messaging.new_message("can", 1)) pm.send("pandaStates", messaging.new_message("pandaStates", 1)) rc.send_sync(pm, "can", messaging.new_message("can", 1)) rc.wait_for_next_recv(True) # fingerprinting is done, when CarParams is set while params.get("CarParams") is None: if len(canmsgs) == 0: raise ValueError("Fingerprinting failed. Run out of can msgs") m = canmsgs.pop(0) rc.send_sync(pm, "can", m.as_builder().to_bytes()) rc.wait_for_next_recv(False) def get_car_params_callback(rc, pm, msgs, fingerprint): params = Params() if fingerprint: CarInterface, _, _ = interfaces[fingerprint] CP = CarInterface.get_non_essential_params(fingerprint) else: can = DummySocket() sendcan = DummySocket() canmsgs = [msg for msg in msgs if msg.which() == "can"] has_cached_cp = params.get("CarParamsCache") is not None assert len(canmsgs) != 0, "CAN messages are required for fingerprinting" assert os.environ.get("SKIP_FW_QUERY", False) or has_cached_cp, \ "CarParamsCache is required for fingerprinting. Make sure to keep carParams msgs in the logs." for m in canmsgs[:300]: can.send(m.as_builder().to_bytes()) _, CP = get_car(can, sendcan, Params().get_bool("ExperimentalLongitudinalEnabled")) if not params.get_bool("DisengageOnAccelerator"): CP.alternativeExperience |= ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS params.put("CarParams", CP.to_bytes()) return CP def controlsd_rcv_callback(msg, cfg, frame): return (frame - 1) == 0 or msg.which() == 'carState' def card_rcv_callback(msg, cfg, frame): # no sendcan until card is initialized if msg.which() != "can": return False socks = [ s for s in cfg.subs if frame % int(SERVICE_LIST[msg.which()].frequency / SERVICE_LIST[s].frequency) == 0 ] if "sendcan" in socks and (frame - 1) < 2000: socks.remove("sendcan") return len(socks) > 0 def calibration_rcv_callback(msg, cfg, frame): # calibrationd publishes 1 calibrationData every 5 cameraOdometry packets. # should_recv always true to increment frame return (frame - 1) == 0 or msg.which() == 'cameraOdometry' def torqued_rcv_callback(msg, cfg, frame): # should_recv always true to increment frame return (frame - 1) == 0 or msg.which() == 'liveLocationKalman' def dmonitoringmodeld_rcv_callback(msg, cfg, frame): return msg.which() == "driverCameraState" class ModeldCameraSyncRcvCallback: def __init__(self): self.road_present = False self.wide_road_present = False self.is_dual_camera = True def __call__(self, msg, cfg, frame): self.is_dual_camera = len(cfg.vision_pubs) == 2 if msg.which() == "roadCameraState": self.road_present = True elif msg.which() == "wideRoadCameraState": self.wide_road_present = True if self.road_present and self.wide_road_present: self.road_present, self.wide_road_present = False, False return True elif self.road_present and not self.is_dual_camera: self.road_present = False return True else: return False class MessageBasedRcvCallback: def __init__(self, trigger_msg_type): self.trigger_msg_type = trigger_msg_type def __call__(self, msg, cfg, frame): return msg.which() == self.trigger_msg_type class FrequencyBasedRcvCallback: def __init__(self, trigger_msg_type): self.trigger_msg_type = trigger_msg_type def __call__(self, msg, cfg, frame): if msg.which() != self.trigger_msg_type: return False resp_sockets = [ s for s in cfg.subs if frame % max(1, int(SERVICE_LIST[msg.which()].frequency / SERVICE_LIST[s].frequency)) == 0 ] return bool(len(resp_sockets)) def controlsd_config_callback(params, cfg, lr): controlsState = None initialized = False for msg in lr: if msg.which() == "controlsState": controlsState = msg.controlsState if initialized: break elif msg.which() == "onroadEvents": initialized = car.CarEvent.EventName.controlsInitializing not in [e.name for e in msg.onroadEvents] assert controlsState is not None and initialized, "controlsState never initialized" params.put("ReplayControlsState", controlsState.as_builder().to_bytes()) def locationd_config_pubsub_callback(params, cfg, lr): ublox = params.get_bool("UbloxAvailable") sub_keys = ({"gpsLocation", } if ublox else {"gpsLocationExternal", }) cfg.pubs = set(cfg.pubs) - sub_keys CONFIGS = [ ProcessConfig( proc_name="controlsd", pubs=[ "carState", "deviceState", "pandaStates", "peripheralState", "liveCalibration", "driverMonitoringState", "longitudinalPlan", "liveLocationKalman", "liveParameters", "radarState", "modelV2", "driverCameraState", "roadCameraState", "wideRoadCameraState", "managerState", "testJoystick", "liveTorqueParameters", "accelerometer", "gyroscope", "carOutput" ], subs=["controlsState", "carControl", "onroadEvents"], ignore=["logMonoTime", "controlsState.startMonoTime", "controlsState.cumLagMs"], config_callback=controlsd_config_callback, init_callback=get_car_params_callback, should_recv_callback=controlsd_rcv_callback, tolerance=NUMPY_TOLERANCE, processing_time=0.004, ), ProcessConfig( proc_name="card", pubs=["pandaStates", "carControl", "onroadEvents", "can"], subs=["sendcan", "carState", "carParams", "carOutput"], ignore=["logMonoTime", "carState.cumLagMs"], init_callback=card_fingerprint_callback, should_recv_callback=card_rcv_callback, tolerance=NUMPY_TOLERANCE, processing_time=0.004, main_pub="can", ), ProcessConfig( proc_name="radard", pubs=["can", "carState", "modelV2"], subs=["radarState", "liveTracks"], ignore=["logMonoTime", "radarState.cumLagMs"], init_callback=get_car_params_callback, should_recv_callback=MessageBasedRcvCallback("can"), main_pub="can", ), ProcessConfig( proc_name="plannerd", pubs=["modelV2", "carControl", "carState", "controlsState", "radarState"], subs=["longitudinalPlan", "uiPlan"], ignore=["logMonoTime", "longitudinalPlan.processingDelay", "longitudinalPlan.solverExecutionTime"], init_callback=get_car_params_callback, should_recv_callback=FrequencyBasedRcvCallback("modelV2"), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="calibrationd", pubs=["carState", "cameraOdometry", "carParams"], subs=["liveCalibration"], ignore=["logMonoTime"], should_recv_callback=calibration_rcv_callback, ), ProcessConfig( proc_name="dmonitoringd", pubs=["driverStateV2", "liveCalibration", "carState", "modelV2", "controlsState"], subs=["driverMonitoringState"], ignore=["logMonoTime"], should_recv_callback=FrequencyBasedRcvCallback("driverStateV2"), tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="locationd", pubs=[ "cameraOdometry", "accelerometer", "gyroscope", "gpsLocationExternal", "liveCalibration", "carState", "gpsLocation" ], subs=["liveLocationKalman"], ignore=["logMonoTime"], config_callback=locationd_config_pubsub_callback, tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="paramsd", pubs=["liveLocationKalman", "carState"], subs=["liveParameters"], ignore=["logMonoTime"], init_callback=get_car_params_callback, should_recv_callback=FrequencyBasedRcvCallback("liveLocationKalman"), tolerance=NUMPY_TOLERANCE, processing_time=0.004, ), ProcessConfig( proc_name="ubloxd", pubs=["ubloxRaw"], subs=["ubloxGnss", "gpsLocationExternal"], ignore=["logMonoTime"], ), ProcessConfig( proc_name="torqued", pubs=["liveLocationKalman", "carState", "carControl", "carOutput"], subs=["liveTorqueParameters"], ignore=["logMonoTime"], init_callback=get_car_params_callback, should_recv_callback=torqued_rcv_callback, tolerance=NUMPY_TOLERANCE, ), ProcessConfig( proc_name="modeld", pubs=["deviceState", "roadCameraState", "wideRoadCameraState", "liveCalibration", "driverMonitoringState"], subs=["modelV2", "cameraOdometry"], ignore=["logMonoTime", "modelV2.frameDropPerc", "modelV2.modelExecutionTime"], should_recv_callback=ModeldCameraSyncRcvCallback(), tolerance=NUMPY_TOLERANCE, processing_time=0.020, main_pub=vipc_get_endpoint_name("camerad", meta_from_camera_state("roadCameraState").stream), main_pub_drained=False, vision_pubs=["roadCameraState", "wideRoadCameraState"], ignore_alive_pubs=["wideRoadCameraState"], init_callback=get_car_params_callback, ), ProcessConfig( proc_name="dmonitoringmodeld", pubs=["liveCalibration", "driverCameraState"], subs=["driverStateV2"], ignore=["logMonoTime", "driverStateV2.modelExecutionTime", "driverStateV2.dspExecutionTime"], should_recv_callback=dmonitoringmodeld_rcv_callback, tolerance=NUMPY_TOLERANCE, processing_time=0.020, main_pub=vipc_get_endpoint_name("camerad", meta_from_camera_state("driverCameraState").stream), main_pub_drained=False, vision_pubs=["driverCameraState"], ignore_alive_pubs=["driverCameraState"], ), ] def get_process_config(name: str) -> ProcessConfig: try: return copy.deepcopy(next(c for c in CONFIGS if c.proc_name == name)) except StopIteration as ex: raise Exception(f"Cannot find process config with name: {name}") from ex def get_custom_params_from_lr(lr: LogIterable, initial_state: str = "first") -> dict[str, Any]: """ Use this to get custom params dict based on provided logs. Useful when replaying following processes: calibrationd, paramsd, torqued The params may be based on first or last message of given type (carParams, liveCalibration, liveParameters, liveTorqueParameters) in the logs. """ car_params = [m for m in lr if m.which() == "carParams"] live_calibration = [m for m in lr if m.which() == "liveCalibration"] live_parameters = [m for m in lr if m.which() == "liveParameters"] live_torque_parameters = [m for m in lr if m.which() == "liveTorqueParameters"] assert initial_state in ["first", "last"] msg_index = 0 if initial_state == "first" else -1 assert len(car_params) > 0, "carParams required for initial state of liveParameters and CarParamsPrevRoute" CP = car_params[msg_index].carParams custom_params = { "CarParamsPrevRoute": CP.as_builder().to_bytes() } if len(live_calibration) > 0: custom_params["CalibrationParams"] = live_calibration[msg_index].as_builder().to_bytes() if len(live_parameters) > 0: lp_dict = live_parameters[msg_index].to_dict() lp_dict["carFingerprint"] = CP.carFingerprint custom_params["LiveParameters"] = json.dumps(lp_dict) if len(live_torque_parameters) > 0: custom_params["LiveTorqueParameters"] = live_torque_parameters[msg_index].as_builder().to_bytes() return custom_params def replay_process_with_name(name: str | Iterable[str], lr: LogIterable, *args, **kwargs) -> list[capnp._DynamicStructReader]: if isinstance(name, str): cfgs = [get_process_config(name)] elif isinstance(name, Iterable): cfgs = [get_process_config(n) for n in name] else: raise ValueError("name must be str or collections of strings") return replay_process(cfgs, lr, *args, **kwargs) def replay_process( cfg: ProcessConfig | Iterable[ProcessConfig], lr: LogIterable, frs: dict[str, BaseFrameReader] = None, fingerprint: str = None, return_all_logs: bool = False, custom_params: dict[str, Any] = None, captured_output_store: dict[str, dict[str, str]] = None, disable_progress: bool = False ) -> list[capnp._DynamicStructReader]: if isinstance(cfg, Iterable): cfgs = list(cfg) else: cfgs = [cfg] all_msgs = migrate_all(lr, old_logtime=True, manager_states=True, panda_states=any("pandaStates" in cfg.pubs for cfg in cfgs), camera_states=any(len(cfg.vision_pubs) != 0 for cfg in cfgs)) process_logs = _replay_multi_process(cfgs, all_msgs, frs, fingerprint, custom_params, captured_output_store, disable_progress) if return_all_logs: keys = {m.which() for m in process_logs} modified_logs = [m for m in all_msgs if m.which() not in keys] modified_logs.extend(process_logs) modified_logs.sort(key=lambda m: int(m.logMonoTime)) log_msgs = modified_logs else: log_msgs = process_logs return log_msgs def _replay_multi_process( cfgs: list[ProcessConfig], lr: LogIterable, frs: dict[str, BaseFrameReader] | None, fingerprint: str | None, custom_params: dict[str, Any] | None, captured_output_store: dict[str, dict[str, str]] | None, disable_progress: bool ) -> list[capnp._DynamicStructReader]: if fingerprint is not None: params_config = generate_params_config(lr=lr, fingerprint=fingerprint, custom_params=custom_params) env_config = generate_environ_config(fingerprint=fingerprint) else: CP = next((m.carParams for m in lr if m.which() == "carParams"), None) params_config = generate_params_config(lr=lr, CP=CP, custom_params=custom_params) env_config = generate_environ_config(CP=CP) # validate frs and vision pubs all_vision_pubs = [pub for cfg in cfgs for pub in cfg.vision_pubs] if len(all_vision_pubs) != 0: assert frs is not None, "frs must be provided when replaying process using vision streams" assert all(meta_from_camera_state(st) is not None for st in all_vision_pubs), \ f"undefined vision stream spotted, probably misconfigured process: (vision pubs: {all_vision_pubs})" required_vision_pubs = {m.camera_state for m in available_streams(lr)} & set(all_vision_pubs) assert all(st in frs for st in required_vision_pubs), f"frs for this process must contain following vision streams: {required_vision_pubs}" all_msgs = sorted(lr, key=lambda msg: msg.logMonoTime) log_msgs = [] try: containers = [] for cfg in cfgs: container = ProcessContainer(cfg) containers.append(container) container.start(params_config, env_config, all_msgs, frs, fingerprint, captured_output_store is not None) all_pubs = {pub for container in containers for pub in container.pubs} all_subs = {sub for container in containers for sub in container.subs} lr_pubs = all_pubs - all_subs pubs_to_containers = {pub: [container for container in containers if pub in container.pubs] for pub in all_pubs} pub_msgs = [msg for msg in all_msgs if msg.which() in lr_pubs] # external queue for messages taken from logs; internal queue for messages generated by processes, which will be republished external_pub_queue: list[capnp._DynamicStructReader] = pub_msgs.copy() internal_pub_queue: list[capnp._DynamicStructReader] = [] # heap for maintaining the order of messages generated by processes, where each element: (logMonoTime, index in internal_pub_queue) internal_pub_index_heap: list[tuple[int, int]] = [] pbar = tqdm(total=len(external_pub_queue), disable=disable_progress) while len(external_pub_queue) != 0 or (len(internal_pub_index_heap) != 0 and not all(c.has_empty_queue for c in containers)): if len(internal_pub_index_heap) == 0 or (len(external_pub_queue) != 0 and external_pub_queue[0].logMonoTime < internal_pub_index_heap[0][0]): msg = external_pub_queue.pop(0) pbar.update(1) else: _, index = heapq.heappop(internal_pub_index_heap) msg = internal_pub_queue[index] target_containers = pubs_to_containers[msg.which()] for container in target_containers: output_msgs = container.run_step(msg, frs) for m in output_msgs: if m.which() in all_pubs: internal_pub_queue.append(m) heapq.heappush(internal_pub_index_heap, (m.logMonoTime, len(internal_pub_queue) - 1)) log_msgs.extend(output_msgs) finally: for container in containers: container.stop() if captured_output_store is not None: assert container.capture is not None out, err = container.capture.read_outerr() captured_output_store[container.cfg.proc_name] = {"out": out, "err": err} return log_msgs def generate_params_config(lr=None, CP=None, fingerprint=None, custom_params=None) -> dict[str, Any]: params_dict = { "OpenpilotEnabledToggle": True, "DisengageOnAccelerator": True, "DisableLogging": False, } if custom_params is not None: params_dict.update(custom_params) if lr is not None: has_ublox = any(msg.which() == "ubloxGnss" for msg in lr) params_dict["UbloxAvailable"] = has_ublox is_rhd = next((msg.driverMonitoringState.isRHD for msg in lr if msg.which() == "driverMonitoringState"), False) params_dict["IsRhdDetected"] = is_rhd if CP is not None: if CP.alternativeExperience == ALTERNATIVE_EXPERIENCE.DISABLE_DISENGAGE_ON_GAS: params_dict["DisengageOnAccelerator"] = False if fingerprint is None: if CP.fingerprintSource == "fw": params_dict["CarParamsCache"] = CP.as_builder().to_bytes() if CP.openpilotLongitudinalControl: params_dict["ExperimentalLongitudinalEnabled"] = True if CP.notCar: params_dict["JoystickDebugMode"] = True return params_dict def generate_environ_config(CP=None, fingerprint=None, log_dir=None) -> dict[str, Any]: environ_dict = {} if platform.system() != "Darwin": environ_dict["PARAMS_ROOT"] = "/dev/shm/params" if log_dir is not None: environ_dict["LOG_ROOT"] = log_dir environ_dict["REPLAY"] = "1" # Regen or python process if CP is not None and fingerprint is None: if CP.fingerprintSource == "fw": environ_dict['SKIP_FW_QUERY'] = "" environ_dict['FINGERPRINT'] = "" else: environ_dict['SKIP_FW_QUERY'] = "1" environ_dict['FINGERPRINT'] = CP.carFingerprint elif fingerprint is not None: environ_dict['SKIP_FW_QUERY'] = "1" environ_dict['FINGERPRINT'] = fingerprint else: environ_dict["SKIP_FW_QUERY"] = "" environ_dict["FINGERPRINT"] = "" return environ_dict def check_openpilot_enabled(msgs: LogIterable) -> bool: cur_enabled_count = 0 max_enabled_count = 0 for msg in msgs: if msg.which() == "carParams": if msg.carParams.notCar: return True elif msg.which() == "controlsState": if msg.controlsState.active: cur_enabled_count += 1 else: cur_enabled_count = 0 max_enabled_count = max(max_enabled_count, cur_enabled_count) return max_enabled_count > int(10. / DT_CTRL) def check_most_messages_valid(msgs: LogIterable, threshold: float = 0.9) -> bool: msgs_counts = Counter(msg.which() for msg in msgs) msgs_valid_counts = Counter(msg.which() for msg in msgs if msg.valid) most_valid_for_service = {} for msg_type in msgs_counts.keys(): valid_share = msgs_valid_counts.get(msg_type, 0) / msgs_counts[msg_type] ok = valid_share >= threshold if not ok: print(f"WARNING: Service {msg_type} has {valid_share * 100:.2f}% valid messages, which is below threshold of {threshold * 100:.2f}%") most_valid_for_service[msg_type] = ok return all(most_valid_for_service.values())
2301_81045437/openpilot
selfdrive/test/process_replay/process_replay.py
Python
mit
30,478
#!/usr/bin/env python3 import os import argparse import time import capnp import numpy as np from typing import Any from collections.abc import Iterable from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS, FAKEDATA, ProcessConfig, replay_process, get_process_config, \ check_openpilot_enabled, check_most_messages_valid, get_custom_params_from_lr from openpilot.selfdrive.test.process_replay.vision_meta import DRIVER_CAMERA_FRAME_SIZES from openpilot.selfdrive.test.update_ci_routes import upload_route from openpilot.tools.lib.route import Route from openpilot.tools.lib.framereader import FrameReader, BaseFrameReader, FrameType from openpilot.tools.lib.logreader import LogReader, LogIterable from openpilot.tools.lib.helpers import save_log class DummyFrameReader(BaseFrameReader): def __init__(self, w: int, h: int, frame_count: int, pix_val: int): self.pix_val = pix_val self.w, self.h = w, h self.frame_count = frame_count self.frame_type = FrameType.raw def get(self, idx, count=1, pix_fmt="yuv420p"): if pix_fmt == "rgb24": shape = (self.h, self.w, 3) elif pix_fmt == "nv12" or pix_fmt == "yuv420p": shape = (int((self.h * self.w) * 3 / 2),) else: raise NotImplementedError return [np.full(shape, self.pix_val, dtype=np.uint8) for _ in range(count)] @staticmethod def zero_dcamera(): return DummyFrameReader(*DRIVER_CAMERA_FRAME_SIZES[("tici", "ar0231")], 1200, 0) def regen_segment( lr: LogIterable, frs: dict[str, Any] = None, processes: Iterable[ProcessConfig] = CONFIGS, disable_tqdm: bool = False ) -> list[capnp._DynamicStructReader]: all_msgs = sorted(lr, key=lambda m: m.logMonoTime) custom_params = get_custom_params_from_lr(all_msgs) print("Replayed processes:", [p.proc_name for p in processes]) print("\n\n", "*"*30, "\n\n", sep="") output_logs = replay_process(processes, all_msgs, frs, return_all_logs=True, custom_params=custom_params, disable_progress=disable_tqdm) return output_logs def setup_data_readers( route: str, sidx: int, use_route_meta: bool, needs_driver_cam: bool = True, needs_road_cam: bool = True, dummy_driver_cam: bool = False ) -> tuple[LogReader, dict[str, Any]]: if use_route_meta: r = Route(route) lr = LogReader(r.log_paths()[sidx]) frs = {} if needs_road_cam and len(r.camera_paths()) > sidx and r.camera_paths()[sidx] is not None: frs['roadCameraState'] = FrameReader(r.camera_paths()[sidx]) if needs_road_cam and len(r.ecamera_paths()) > sidx and r.ecamera_paths()[sidx] is not None: frs['wideRoadCameraState'] = FrameReader(r.ecamera_paths()[sidx]) if needs_driver_cam: if dummy_driver_cam: frs['driverCameraState'] = DummyFrameReader.zero_dcamera() elif len(r.dcamera_paths()) > sidx and r.dcamera_paths()[sidx] is not None: device_type = next(str(msg.initData.deviceType) for msg in lr if msg.which() == "initData") assert device_type != "neo", "Driver camera not supported on neo segments. Use dummy dcamera." frs['driverCameraState'] = FrameReader(r.dcamera_paths()[sidx]) else: lr = LogReader(f"cd:/{route.replace('|', '/')}/{sidx}/rlog.bz2") frs = {} if needs_road_cam: frs['roadCameraState'] = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/fcamera.hevc") if next((True for m in lr if m.which() == "wideRoadCameraState"), False): frs['wideRoadCameraState'] = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/ecamera.hevc") if needs_driver_cam: if dummy_driver_cam: frs['driverCameraState'] = DummyFrameReader.zero_dcamera() else: device_type = next(str(msg.initData.deviceType) for msg in lr if msg.which() == "initData") assert device_type != "neo", "Driver camera not supported on neo segments. Use dummy dcamera." frs['driverCameraState'] = FrameReader(f"cd:/{route.replace('|', '/')}/{sidx}/dcamera.hevc") return lr, frs def regen_and_save( route: str, sidx: int, processes: str | Iterable[str] = "all", outdir: str = FAKEDATA, upload: bool = False, use_route_meta: bool = False, disable_tqdm: bool = False, dummy_driver_cam: bool = False ) -> str: if not isinstance(processes, str) and not hasattr(processes, "__iter__"): raise ValueError("whitelist_proc must be a string or iterable") if processes != "all": if isinstance(processes, str): raise ValueError(f"Invalid value for processes: {processes}") replayed_processes = [] for d in processes: cfg = get_process_config(d) replayed_processes.append(cfg) else: replayed_processes = CONFIGS all_vision_pubs = {pub for cfg in replayed_processes for pub in cfg.vision_pubs} lr, frs = setup_data_readers(route, sidx, use_route_meta, needs_driver_cam="driverCameraState" in all_vision_pubs, needs_road_cam="roadCameraState" in all_vision_pubs or "wideRoadCameraState" in all_vision_pubs, dummy_driver_cam=dummy_driver_cam) output_logs = regen_segment(lr, frs, replayed_processes, disable_tqdm=disable_tqdm) log_dir = os.path.join(outdir, time.strftime("%Y-%m-%d--%H-%M-%S--0", time.gmtime())) rel_log_dir = os.path.relpath(log_dir) rpath = os.path.join(log_dir, "rlog.bz2") os.makedirs(log_dir) save_log(rpath, output_logs, compress=True) print("\n\n", "*"*30, "\n\n", sep="") print("New route:", rel_log_dir, "\n") if not check_openpilot_enabled(output_logs): raise Exception("Route did not engage for long enough") if not check_most_messages_valid(output_logs): raise Exception("Route has too many invalid messages") if upload: upload_route(rel_log_dir) return rel_log_dir if __name__ == "__main__": def comma_separated_list(string): return string.split(",") all_procs = [p.proc_name for p in CONFIGS] parser = argparse.ArgumentParser(description="Generate new segments from old ones") parser.add_argument("--upload", action="store_true", help="Upload the new segment to the CI bucket") parser.add_argument("--outdir", help="log output dir", default=FAKEDATA) parser.add_argument("--dummy-dcamera", action='store_true', help="Use dummy blank driver camera") parser.add_argument("--whitelist-procs", type=comma_separated_list, default=all_procs, help="Comma-separated whitelist of processes to regen (e.g. controlsd,radard)") parser.add_argument("--blacklist-procs", type=comma_separated_list, default=[], help="Comma-separated blacklist of processes to regen (e.g. controlsd,radard)") parser.add_argument("route", type=str, help="The source route") parser.add_argument("seg", type=int, help="Segment in source route") args = parser.parse_args() blacklist_set = set(args.blacklist_procs) processes = [p for p in args.whitelist_procs if p not in blacklist_set] regen_and_save(args.route, args.seg, processes=processes, upload=args.upload, outdir=args.outdir, dummy_driver_cam=args.dummy_dcamera)
2301_81045437/openpilot
selfdrive/test/process_replay/regen.py
Python
mit
7,142
#!/usr/bin/env python3 import argparse import concurrent.futures import os import random import traceback from tqdm import tqdm from openpilot.common.prefix import OpenpilotPrefix from openpilot.selfdrive.test.process_replay.regen import regen_and_save from openpilot.selfdrive.test.process_replay.test_processes import FAKEDATA, source_segments as segments from openpilot.tools.lib.route import SegmentName def regen_job(segment, upload, disable_tqdm): with OpenpilotPrefix(): sn = SegmentName(segment[1]) fake_dongle_id = 'regen' + ''.join(random.choice('0123456789ABCDEF') for _ in range(11)) try: relr = regen_and_save(sn.route_name.canonical_name, sn.segment_num, upload=upload, use_route_meta=False, outdir=os.path.join(FAKEDATA, fake_dongle_id), disable_tqdm=disable_tqdm, dummy_driver_cam=True) relr = '|'.join(relr.split('/')[-2:]) return f' ("{segment[0]}", "{relr}"), ' except Exception as e: err = f" {segment} failed: {str(e)}" err += traceback.format_exc() err += "\n\n" return err if __name__ == "__main__": all_cars = {car for car, _ in segments} parser = argparse.ArgumentParser(description="Generate new segments from old ones") parser.add_argument("-j", "--jobs", type=int, default=1) parser.add_argument("--no-upload", action="store_true") parser.add_argument("--whitelist-cars", type=str, nargs="*", default=all_cars, help="Whitelist given cars from the test (e.g. HONDA)") parser.add_argument("--blacklist-cars", type=str, nargs="*", default=[], help="Blacklist given cars from the test (e.g. HONDA)") args = parser.parse_args() tested_cars = set(args.whitelist_cars) - set(args.blacklist_cars) tested_cars = {c.upper() for c in tested_cars} tested_segments = [(car, segment) for car, segment in segments if car in tested_cars] with concurrent.futures.ProcessPoolExecutor(max_workers=args.jobs) as pool: p = pool.map(regen_job, tested_segments, [not args.no_upload] * len(tested_segments), [args.jobs > 1] * len(tested_segments)) msg = "Copy these new segments into test_processes.py:" for seg in tqdm(p, desc="Generating segments", total=len(tested_segments)): msg += "\n" + str(seg) print() print() print(msg)
2301_81045437/openpilot
selfdrive/test/process_replay/regen_all.py
Python
mit
2,328
from collections import namedtuple from cereal.visionipc import VisionStreamType from openpilot.common.realtime import DT_MDL, DT_DMON from openpilot.common.transformations.camera import DEVICE_CAMERAS VideoStreamMeta = namedtuple("VideoStreamMeta", ["camera_state", "encode_index", "stream", "dt", "frame_sizes"]) ROAD_CAMERA_FRAME_SIZES = {k: (v.dcam.width, v.dcam.height) for k, v in DEVICE_CAMERAS.items()} WIDE_ROAD_CAMERA_FRAME_SIZES = {k: (v.ecam.width, v.ecam.height) for k, v in DEVICE_CAMERAS.items() if v.ecam is not None} DRIVER_CAMERA_FRAME_SIZES = {k: (v.dcam.width, v.dcam.height) for k, v in DEVICE_CAMERAS.items()} VIPC_STREAM_METADATA = [ # metadata: (state_msg_type, encode_msg_type, stream_type, dt, frame_sizes) ("roadCameraState", "roadEncodeIdx", VisionStreamType.VISION_STREAM_ROAD, DT_MDL, ROAD_CAMERA_FRAME_SIZES), ("wideRoadCameraState", "wideRoadEncodeIdx", VisionStreamType.VISION_STREAM_WIDE_ROAD, DT_MDL, WIDE_ROAD_CAMERA_FRAME_SIZES), ("driverCameraState", "driverEncodeIdx", VisionStreamType.VISION_STREAM_DRIVER, DT_DMON, DRIVER_CAMERA_FRAME_SIZES), ] def meta_from_camera_state(state): meta = next((VideoStreamMeta(*meta) for meta in VIPC_STREAM_METADATA if meta[0] == state), None) return meta def meta_from_encode_index(encode_index): meta = next((VideoStreamMeta(*meta) for meta in VIPC_STREAM_METADATA if meta[1] == encode_index), None) return meta def meta_from_stream_type(stream_type): meta = next((VideoStreamMeta(*meta) for meta in VIPC_STREAM_METADATA if meta[2] == stream_type), None) return meta def available_streams(lr=None): if lr is None: return [VideoStreamMeta(*meta) for meta in VIPC_STREAM_METADATA] result = [] for meta in VIPC_STREAM_METADATA: has_cam_state = next((True for m in lr if m.which() == meta[0]), False) if has_cam_state: result.append(VideoStreamMeta(*meta)) return result
2301_81045437/openpilot
selfdrive/test/process_replay/vision_meta.py
Python
mit
1,900
from collections import defaultdict, deque from cereal.services import SERVICE_LIST import cereal.messaging as messaging import capnp class ReplayDone(Exception): pass class SubSocket: def __init__(self, msgs, trigger): self.i = 0 self.trigger = trigger self.msgs = [m.as_builder().to_bytes() for m in msgs if m.which() == trigger] self.max_i = len(self.msgs) - 1 def receive(self, non_blocking=False): if non_blocking: return None if self.i == self.max_i: raise ReplayDone while True: msg = self.msgs[self.i] self.i += 1 return msg class PubSocket: def send(self, data): pass class SubMaster(messaging.SubMaster): def __init__(self, msgs, trigger, services, check_averag_freq=False): self.frame = 0 self.data = {} self.ignore_alive = [] self.alive = {s: True for s in services} self.updated = {s: False for s in services} self.rcv_time = {s: 0. for s in services} self.rcv_frame = {s: 0 for s in services} self.valid = {s: True for s in services} self.freq_ok = {s: True for s in services} self.recv_dts = {s: deque([0.0] * messaging.AVG_FREQ_HISTORY, maxlen=messaging.AVG_FREQ_HISTORY) for s in services} self.logMonoTime = {} self.sock = {} self.freq = {} self.check_average_freq = check_averag_freq self.non_polled_services = [] self.ignore_average_freq = [] # TODO: specify multiple triggers for service like plannerd that poll on more than one service cur_msgs = [] self.msgs = [] msgs = [m for m in msgs if m.which() in services] for msg in msgs: cur_msgs.append(msg) if msg.which() == trigger: self.msgs.append(cur_msgs) cur_msgs = [] self.msgs = list(reversed(self.msgs)) for s in services: self.freq[s] = SERVICE_LIST[s].frequency try: data = messaging.new_message(s) except capnp.lib.capnp.KjException: # lists data = messaging.new_message(s, 0) self.data[s] = getattr(data, s) self.logMonoTime[s] = 0 self.sock[s] = SubSocket(msgs, s) def update(self, timeout=None): if not len(self.msgs): raise ReplayDone cur_msgs = self.msgs.pop() self.update_msgs(cur_msgs[0].logMonoTime, self.msgs.pop()) class PubMaster(messaging.PubMaster): def __init__(self): self.sock = defaultdict(PubSocket)
2301_81045437/openpilot
selfdrive/test/profiling/lib.py
Python
mit
2,397
#!/usr/bin/env python3 import os import sys import cProfile import pprofile import pyprof2calltree from openpilot.common.params import Params from openpilot.tools.lib.logreader import LogReader from openpilot.selfdrive.test.profiling.lib import SubMaster, PubMaster, SubSocket, ReplayDone from openpilot.selfdrive.test.process_replay.process_replay import CONFIGS from openpilot.selfdrive.car.toyota.values import CAR as TOYOTA from openpilot.selfdrive.car.honda.values import CAR as HONDA from openpilot.selfdrive.car.volkswagen.values import CAR as VW BASE_URL = "https://commadataci.blob.core.windows.net/openpilotci/" CARS = { 'toyota': ("0982d79ebb0de295|2021-01-03--20-03-36/6", TOYOTA.TOYOTA_RAV4), 'honda': ("0982d79ebb0de295|2021-01-08--10-13-10/6", HONDA.HONDA_CIVIC), "vw": ("ef895f46af5fd73f|2021-05-22--14-06-35/6", VW.AUDI_A3_MK3), } def get_inputs(msgs, process, fingerprint): for config in CONFIGS: if config.proc_name == process: sub_socks = list(config.pubs) trigger = sub_socks[0] break # some procs block on CarParams for msg in msgs: if msg.which() == 'carParams': m = msg.as_builder() m.carParams.carFingerprint = fingerprint Params().put("CarParams", m.carParams.copy().to_bytes()) break sm = SubMaster(msgs, trigger, sub_socks) pm = PubMaster() if 'can' in sub_socks: can_sock = SubSocket(msgs, 'can') else: can_sock = None return sm, pm, can_sock def profile(proc, func, car='toyota'): segment, fingerprint = CARS[car] segment = segment.replace('|', '/') rlog_url = f"{BASE_URL}{segment}/rlog.bz2" msgs = list(LogReader(rlog_url)) * int(os.getenv("LOOP", "1")) os.environ['FINGERPRINT'] = fingerprint os.environ['SKIP_FW_QUERY'] = "1" os.environ['REPLAY'] = "1" def run(sm, pm, can_sock): try: if can_sock is not None: func(sm, pm, can_sock) else: func(sm, pm) except ReplayDone: pass # Statistical sm, pm, can_sock = get_inputs(msgs, proc, fingerprint) with pprofile.StatisticalProfile()(period=0.00001) as pr: run(sm, pm, can_sock) pr.dump_stats(f'cachegrind.out.{proc}_statistical') # Deterministic sm, pm, can_sock = get_inputs(msgs, proc, fingerprint) with cProfile.Profile() as pr: run(sm, pm, can_sock) pyprof2calltree.convert(pr.getstats(), f'cachegrind.out.{proc}_deterministic') if __name__ == '__main__': from openpilot.selfdrive.controls.controlsd import main as controlsd_thread from openpilot.selfdrive.locationd.paramsd import main as paramsd_thread from openpilot.selfdrive.controls.plannerd import main as plannerd_thread procs = { 'controlsd': controlsd_thread, 'paramsd': paramsd_thread, 'plannerd': plannerd_thread, } proc = sys.argv[1] if proc not in procs: print(f"{proc} not available") sys.exit(0) else: profile(proc, procs[proc])
2301_81045437/openpilot
selfdrive/test/profiling/profiler.py
Python
mit
2,899
#!/bin/bash SCRIPT_DIR=$(dirname "$0") BASEDIR=$(realpath "$SCRIPT_DIR/../../") cd $BASEDIR # tests that our build system's dependencies are configured properly, # needs a machine with lots of cores scons --clean scons --no-cache --random -j$(nproc)
2301_81045437/openpilot
selfdrive/test/scons_build_test.sh
Shell
mit
252
#!/usr/bin/bash set -e if [ -z "$SOURCE_DIR" ]; then echo "SOURCE_DIR must be set" exit 1 fi if [ -z "$GIT_COMMIT" ]; then echo "GIT_COMMIT must be set" exit 1 fi if [ -z "$TEST_DIR" ]; then echo "TEST_DIR must be set" exit 1 fi umount /data/safe_staging/merged/ || true sudo umount /data/safe_staging/merged/ || true rm -rf /data/safe_staging/* || true CONTINUE_PATH="/data/continue.sh" tee $CONTINUE_PATH << EOF #!/usr/bin/bash sudo abctl --set_success # patch sshd config sudo mount -o rw,remount / sudo sed -i "s,/data/params/d/GithubSshKeys,/usr/comma/setup_keys," /etc/ssh/sshd_config sudo systemctl daemon-reload sudo systemctl restart ssh sudo systemctl restart NetworkManager sudo systemctl disable ssh-param-watcher.path sudo systemctl disable ssh-param-watcher.service sudo mount -o ro,remount / while true; do if ! sudo systemctl is-active -q ssh; then sudo systemctl start ssh fi #if ! pgrep -f 'ciui.py' > /dev/null 2>&1; then # echo 'starting UI' # cp $SOURCE_DIR/selfdrive/test/ciui.py /data/ # /data/ciui.py & #fi sleep 5s done sleep infinity EOF chmod +x $CONTINUE_PATH safe_checkout() { # completely clean TEST_DIR cd $SOURCE_DIR # cleanup orphaned locks find .git -type f -name "*.lock" -exec rm {} + git reset --hard git fetch --no-tags --no-recurse-submodules -j4 --verbose --depth 1 origin $GIT_COMMIT find . -maxdepth 1 -not -path './.git' -not -name '.' -not -name '..' -exec rm -rf '{}' \; git reset --hard $GIT_COMMIT git checkout $GIT_COMMIT git clean -xdff git submodule sync git submodule update --init --recursive git submodule foreach --recursive "git reset --hard && git clean -xdff" git lfs pull (ulimit -n 65535 && git lfs prune) echo "git checkout done, t=$SECONDS" du -hs $SOURCE_DIR $SOURCE_DIR/.git rsync -a --delete $SOURCE_DIR $TEST_DIR } unsafe_checkout() { # checkout directly in test dir, leave old build products cd $TEST_DIR # cleanup orphaned locks find .git -type f -name "*.lock" -exec rm {} + git fetch --no-tags --no-recurse-submodules -j8 --verbose --depth 1 origin $GIT_COMMIT git checkout --force --no-recurse-submodules $GIT_COMMIT git reset --hard $GIT_COMMIT git clean -df git submodule sync git submodule update --init --recursive git submodule foreach --recursive "git reset --hard && git clean -df" git lfs pull (ulimit -n 65535 && git lfs prune) } export GIT_PACK_THREADS=8 # set up environment if [ ! -d "$SOURCE_DIR" ]; then git clone https://github.com/commaai/openpilot.git $SOURCE_DIR fi if [ ! -z "$UNSAFE" ]; then echo "doing unsafe checkout" unsafe_checkout else echo "doing safe checkout" safe_checkout fi echo "$TEST_DIR synced with $GIT_COMMIT, t=$SECONDS"
2301_81045437/openpilot
selfdrive/test/setup_device_ci.sh
Shell
mit
2,764
#!/bin/bash { #start pulseaudio daemon sudo pulseaudio -D # create a virtual null audio and set it to default device sudo pactl load-module module-null-sink sink_name=virtual_audio sudo pactl set-default-sink virtual_audio } > /dev/null 2>&1
2301_81045437/openpilot
selfdrive/test/setup_vsound.sh
Shell
mit
254
#!/usr/bin/env bash # Sets up a virtual display for running map renderer and simulator without an X11 display DISP_ID=99 export DISPLAY=:$DISP_ID sudo Xvfb $DISPLAY -screen 0 2160x1080x24 2>/dev/null & # check for x11 socket for the specified display ID while [ ! -S /tmp/.X11-unix/X$DISP_ID ] do echo "Waiting for Xvfb..." sleep 1 done touch ~/.Xauthority export XDG_SESSION_TYPE="x11" xset -q
2301_81045437/openpilot
selfdrive/test/setup_xvfb.sh
Shell
mit
403
#!/usr/bin/env python3 import os import re import subprocess import sys from collections.abc import Iterable from tqdm import tqdm from openpilot.selfdrive.car.tests.routes import routes as test_car_models_routes from openpilot.selfdrive.test.process_replay.test_processes import source_segments as replay_segments from openpilot.tools.lib.azure_container import AzureContainer from openpilot.tools.lib.openpilotcontainers import DataCIContainer, DataProdContainer, OpenpilotCIContainer SOURCES: list[AzureContainer] = [ DataProdContainer, DataCIContainer ] DEST = OpenpilotCIContainer def upload_route(path: str, exclude_patterns: Iterable[str] = None) -> None: if exclude_patterns is None: exclude_patterns = [r'dcamera\.hevc'] r, n = path.rsplit("--", 1) r = '/'.join(r.split('/')[-2:]) # strip out anything extra in the path destpath = f"{r}/{n}" for file in os.listdir(path): if any(re.search(pattern, file) for pattern in exclude_patterns): continue DEST.upload_file(os.path.join(path, file), f"{destpath}/{file}") def sync_to_ci_public(route: str) -> bool: dest_container, dest_key = DEST.get_client_and_key() key_prefix = route.replace('|', '/') dongle_id = key_prefix.split('/')[0] if next(dest_container.list_blob_names(name_starts_with=key_prefix), None) is not None: return True print(f"Uploading {route}") for source_container in SOURCES: # assumes az login has been run print(f"Trying {source_container.ACCOUNT}/{source_container.CONTAINER}") _, source_key = source_container.get_client_and_key() cmd = [ "azcopy", "copy", f"{source_container.BASE_URL}{key_prefix}?{source_key}", f"{DEST.BASE_URL}{dongle_id}?{dest_key}", "--recursive=true", "--overwrite=false", "--exclude-pattern=*/dcamera.hevc", ] try: result = subprocess.call(cmd, stdout=subprocess.DEVNULL) if result == 0: print("Success") return True except subprocess.CalledProcessError: print("Failed") return False if __name__ == "__main__": failed_routes = [] to_sync = sys.argv[1:] if not len(to_sync): # sync routes from the car tests routes and process replay to_sync.extend([rt.route for rt in test_car_models_routes]) to_sync.extend([s[1].rsplit('--', 1)[0] for s in replay_segments]) for r in tqdm(to_sync): if not sync_to_ci_public(r): failed_routes.append(r) if len(failed_routes): print("failed routes:", failed_routes)
2301_81045437/openpilot
selfdrive/test/update_ci_routes.py
Python
mit
2,513
import os import json Import('qt_env', 'arch', 'common', 'messaging', 'visionipc', 'cereal', 'transformations') base_libs = [common, messaging, cereal, visionipc, transformations, 'zmq', 'capnp', 'kj', 'm', 'OpenCL', 'ssl', 'crypto', 'pthread'] + qt_env["LIBS"] if arch == 'larch64': base_libs.append('EGL') maps = arch in ['larch64', 'aarch64', 'x86_64'] if arch == "Darwin": del base_libs[base_libs.index('OpenCL')] qt_env['FRAMEWORKS'] += ['OpenCL'] # FIXME: remove this once we're on 5.15 (24.04) qt_env['CXXFLAGS'] += ["-Wno-deprecated-declarations"] qt_util = qt_env.Library("qt_util", ["#selfdrive/ui/qt/api.cc", "#selfdrive/ui/qt/util.cc"], LIBS=base_libs) widgets_src = ["ui.cc", "qt/widgets/input.cc", "qt/widgets/wifi.cc", "qt/widgets/ssh_keys.cc", "qt/widgets/toggle.cc", "qt/widgets/controls.cc", "qt/widgets/offroad_alerts.cc", "qt/widgets/prime.cc", "qt/widgets/keyboard.cc", "qt/widgets/scrollview.cc", "qt/widgets/cameraview.cc", "#third_party/qrcode/QrCode.cc", "qt/request_repeater.cc", "qt/qt_window.cc", "qt/network/networking.cc", "qt/network/wifi_manager.cc"] qt_env['CPPDEFINES'] = [] if maps: base_libs += ['QMapLibre'] widgets_src += ["qt/maps/map_helpers.cc", "qt/maps/map_settings.cc", "qt/maps/map.cc", "qt/maps/map_panel.cc", "qt/maps/map_eta.cc", "qt/maps/map_instructions.cc"] qt_env['CPPDEFINES'] += ["ENABLE_MAPS"] widgets = qt_env.Library("qt_widgets", widgets_src, LIBS=base_libs) Export('widgets') qt_libs = [widgets, qt_util] + base_libs qt_src = ["main.cc", "qt/sidebar.cc", "qt/body.cc", "qt/window.cc", "qt/home.cc", "qt/offroad/settings.cc", "qt/offroad/software_settings.cc", "qt/offroad/onboarding.cc", "qt/offroad/driverview.cc", "qt/offroad/experimental_mode.cc", "qt/onroad/onroad_home.cc", "qt/onroad/annotated_camera.cc", "qt/onroad/buttons.cc", "qt/onroad/alerts.cc"] # build translation files with open(File("translations/languages.json").abspath) as f: languages = json.loads(f.read()) translation_sources = [f"#selfdrive/ui/translations/{l}.ts" for l in languages.values()] translation_targets = [src.replace(".ts", ".qm") for src in translation_sources] lrelease_bin = 'third_party/qt5/larch64/bin/lrelease' if arch == 'larch64' else 'lrelease' lupdate = qt_env.Command(translation_sources, qt_src + widgets_src, "selfdrive/ui/update_translations.py") lrelease = qt_env.Command(translation_targets, translation_sources, f"{lrelease_bin} $SOURCES") qt_env.Depends(lrelease, lupdate) qt_env.NoClean(translation_sources) qt_env.Precious(translation_sources) qt_env.NoCache(lupdate) # create qrc file for compiled translations to include with assets translations_assets_src = "#selfdrive/assets/translations_assets.qrc" with open(File(translations_assets_src).abspath, 'w') as f: f.write('<!DOCTYPE RCC><RCC version="1.0">\n<qresource>\n') f.write('\n'.join([f'<file alias="{l}">../ui/translations/{l}.qm</file>' for l in languages.values()])) f.write('\n</qresource>\n</RCC>') # build assets assets = "#selfdrive/assets/assets.cc" assets_src = "#selfdrive/assets/assets.qrc" qt_env.Command(assets, [assets_src, translations_assets_src], f"rcc $SOURCES -o $TARGET") qt_env.Depends(assets, Glob('#selfdrive/assets/*', exclude=[assets, assets_src, translations_assets_src, "#selfdrive/assets/assets.o"]) + [lrelease]) asset_obj = qt_env.Object("assets", assets) qt_env.SharedLibrary("qt/python_helpers", ["qt/qt_window.cc"], LIBS=qt_libs) # spinner and text window qt_env.Program("_text", ["qt/text.cc"], LIBS=qt_libs) qt_env.Program("_spinner", ["qt/spinner.cc"], LIBS=qt_libs) # build main UI qt_env.Program("ui", qt_src + [asset_obj], LIBS=qt_libs) if GetOption('extras'): qt_src.remove("main.cc") # replaced by test_runner qt_env.Program('tests/test_translations', [asset_obj, 'tests/test_runner.cc', 'tests/test_translations.cc'] + qt_src, LIBS=qt_libs) qt_env.Program('tests/ui_snapshot', [asset_obj, "tests/ui_snapshot.cc"] + qt_src, LIBS=qt_libs) if GetOption('extras') and arch != "Darwin": # setup and factory resetter qt_env.Program("qt/setup/reset", ["qt/setup/reset.cc"], LIBS=qt_libs) qt_env.Program("qt/setup/setup", ["qt/setup/setup.cc", asset_obj], LIBS=qt_libs + ['curl', 'common', 'json11']) # build updater UI qt_env.Program("qt/setup/updater", ["qt/setup/updater.cc", asset_obj], LIBS=qt_libs) # build mui qt_env.Program("mui", ["mui.cc"], LIBS=qt_libs) # build installers senv = qt_env.Clone() senv['LINKFLAGS'].append('-Wl,-strip-debug') release = "release3" installers = [ ("openpilot", release), ("openpilot_test", f"{release}-staging"), ("openpilot_nightly", "nightly"), ("openpilot_internal", "master"), ] cont = senv.Command(f"installer/continue_openpilot.o", f"installer/continue_openpilot.sh", "ld -r -b binary -o $TARGET $SOURCE") for name, branch in installers: d = {'BRANCH': f"'\"{branch}\"'"} if "internal" in name: d['INTERNAL'] = "1" import requests r = requests.get("https://github.com/commaci2.keys") r.raise_for_status() d['SSH_KEYS'] = f'\\"{r.text.strip()}\\"' obj = senv.Object(f"installer/installers/installer_{name}.o", ["installer/installer.cc"], CPPDEFINES=d) f = senv.Program(f"installer/installers/installer_{name}", [obj, cont], LIBS=qt_libs) # keep installers small assert f[0].get_size() < 350*1e3 # build watch3 if arch in ['x86_64', 'aarch64', 'Darwin'] or GetOption('extras'): qt_env.Program("watch3", ["watch3.cc"], LIBS=qt_libs + ['common', 'json11', 'zmq', 'visionipc', 'messaging'])
2301_81045437/openpilot
selfdrive/ui/SConscript
Python
mit
5,731
#!/usr/bin/bash cd /data/openpilot exec ./launch_openpilot.sh
2301_81045437/openpilot
selfdrive/ui/installer/continue_openpilot.sh
Shell
mit
63
#include <time.h> #include <unistd.h> #include <cstdlib> #include <fstream> #include <map> #include <string> #include <QDebug> #include <QDir> #include <QTimer> #include <QVBoxLayout> #include "selfdrive/ui/installer/installer.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/qt_window.h" std::string get_str(std::string const s) { std::string::size_type pos = s.find('?'); assert(pos != std::string::npos); return s.substr(0, pos); } // Leave some extra space for the fork installer const std::string GIT_URL = get_str("https://github.com/commaai/openpilot.git" "? "); const std::string BRANCH_STR = get_str(BRANCH "? "); #define GIT_SSH_URL "git@github.com:commaai/openpilot.git" #define CONTINUE_PATH "/data/continue.sh" const QString CACHE_PATH = "/data/openpilot.cache"; #define INSTALL_PATH "/data/openpilot" #define TMP_INSTALL_PATH "/data/tmppilot" extern const uint8_t str_continue[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_start"); extern const uint8_t str_continue_end[] asm("_binary_selfdrive_ui_installer_continue_openpilot_sh_end"); bool time_valid() { time_t rawtime; time(&rawtime); struct tm * sys_time = gmtime(&rawtime); return (1900 + sys_time->tm_year) >= 2020; } void run(const char* cmd) { int err = std::system(cmd); assert(err == 0); } Installer::Installer(QWidget *parent) : QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(this); layout->setContentsMargins(150, 290, 150, 150); layout->setSpacing(0); QLabel *title = new QLabel(tr("Installing...")); title->setStyleSheet("font-size: 90px; font-weight: 600;"); layout->addWidget(title, 0, Qt::AlignTop); layout->addSpacing(170); bar = new QProgressBar(); bar->setRange(0, 100); bar->setTextVisible(false); bar->setFixedHeight(72); layout->addWidget(bar, 0, Qt::AlignTop); layout->addSpacing(30); val = new QLabel("0%"); val->setStyleSheet("font-size: 70px; font-weight: 300;"); layout->addWidget(val, 0, Qt::AlignTop); layout->addStretch(); QObject::connect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &Installer::cloneFinished); QObject::connect(&proc, &QProcess::readyReadStandardError, this, &Installer::readProgress); QTimer::singleShot(100, this, &Installer::doInstall); setStyleSheet(R"( * { font-family: Inter; color: white; background-color: black; } QProgressBar { border: none; background-color: #292929; } QProgressBar::chunk { background-color: #364DEF; } )"); } void Installer::updateProgress(int percent) { bar->setValue(percent); val->setText(QString("%1%").arg(percent)); update(); } void Installer::doInstall() { // wait for valid time while (!time_valid()) { usleep(500 * 1000); qDebug() << "Waiting for valid time"; } // cleanup previous install attempts run("rm -rf " TMP_INSTALL_PATH " " INSTALL_PATH); // do the install if (QDir(CACHE_PATH).exists()) { cachedFetch(CACHE_PATH); } else { freshClone(); } } void Installer::freshClone() { qDebug() << "Doing fresh clone"; proc.start("git", {"clone", "--progress", GIT_URL.c_str(), "-b", BRANCH_STR.c_str(), "--depth=1", "--recurse-submodules", TMP_INSTALL_PATH}); } void Installer::cachedFetch(const QString &cache) { qDebug() << "Fetching with cache: " << cache; run(QString("cp -rp %1 %2").arg(cache, TMP_INSTALL_PATH).toStdString().c_str()); int err = chdir(TMP_INSTALL_PATH); assert(err == 0); run(("git remote set-branches --add origin " + BRANCH_STR).c_str()); updateProgress(10); proc.setWorkingDirectory(TMP_INSTALL_PATH); proc.start("git", {"fetch", "--progress", "origin", BRANCH_STR.c_str()}); } void Installer::readProgress() { const QVector<QPair<QString, int>> stages = { // prefix, weight in percentage {"Receiving objects: ", 91}, {"Resolving deltas: ", 2}, {"Updating files: ", 7}, }; auto line = QString(proc.readAllStandardError()); int base = 0; for (const QPair kv : stages) { if (line.startsWith(kv.first)) { auto perc = line.split(kv.first)[1].split("%")[0]; int p = base + int(perc.toFloat() / 100. * kv.second); updateProgress(p); break; } base += kv.second; } } void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) { qDebug() << "git finished with " << exitCode; assert(exitCode == 0); updateProgress(100); // ensure correct branch is checked out int err = chdir(TMP_INSTALL_PATH); assert(err == 0); run(("git checkout " + BRANCH_STR).c_str()); run(("git reset --hard origin/" + BRANCH_STR).c_str()); run("git submodule update --init"); // move into place run("mv " TMP_INSTALL_PATH " " INSTALL_PATH); #ifdef INTERNAL run("mkdir -p /data/params/d/"); std::map<std::string, std::string> params = { {"SshEnabled", "1"}, {"RecordFrontLock", "1"}, {"GithubSshKeys", SSH_KEYS}, }; for (const auto& [key, value] : params) { std::ofstream param; param.open("/data/params/d/" + key); param << value; param.close(); } run("cd " INSTALL_PATH " && " "git remote set-url origin --push " GIT_SSH_URL " && " "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\""); #endif // write continue.sh FILE *of = fopen("/data/continue.sh.new", "wb"); assert(of != NULL); size_t num = str_continue_end - str_continue; size_t num_written = fwrite(str_continue, 1, num, of); assert(num == num_written); fclose(of); run("chmod +x /data/continue.sh.new"); run("mv /data/continue.sh.new " CONTINUE_PATH); // wait for the installed software's UI to take over QTimer::singleShot(60 * 1000, &QCoreApplication::quit); } int main(int argc, char *argv[]) { initApp(argc, argv); QApplication a(argc, argv); Installer installer; setMainWindow(&installer); return a.exec(); }
2301_81045437/openpilot
selfdrive/ui/installer/installer.cc
C++
mit
6,080
#pragma once #include <QLabel> #include <QProcess> #include <QProgressBar> #include <QWidget> class Installer : public QWidget { Q_OBJECT public: explicit Installer(QWidget *parent = 0); private slots: void updateProgress(int percent); void readProgress(); void cloneFinished(int exitCode, QProcess::ExitStatus exitStatus); private: QLabel *val; QProgressBar *bar; QProcess proc; void doInstall(); void freshClone(); void cachedFetch(const QString &cache); };
2301_81045437/openpilot
selfdrive/ui/installer/installer.h
C++
mit
489
#include <sys/resource.h> #include <QApplication> #include <QTranslator> #include "system/hardware/hw.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/window.h" int main(int argc, char *argv[]) { setpriority(PRIO_PROCESS, 0, -20); qInstallMessageHandler(swagLogMessageHandler); initApp(argc, argv); QTranslator translator; QString translation_file = QString::fromStdString(Params().get("LanguageSetting")); if (!translator.load(QString(":/%1").arg(translation_file)) && translation_file.length()) { qCritical() << "Failed to load translation file:" << translation_file; } QApplication a(argc, argv); a.installTranslator(&translator); MainWindow w; setMainWindow(&w); a.installEventFilter(&w); return a.exec(); }
2301_81045437/openpilot
selfdrive/ui/main.cc
C++
mit
802
#include <QApplication> #include <QtWidgets> #include <QTimer> #include "cereal/messaging/messaging.h" #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/qt_window.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget w; setMainWindow(&w); w.setStyleSheet("background-color: black;"); // our beautiful UI QVBoxLayout *layout = new QVBoxLayout(&w); QLabel *label = new QLabel("〇"); layout->addWidget(label, 0, Qt::AlignCenter); QTimer timer; QObject::connect(&timer, &QTimer::timeout, [=]() { static SubMaster sm({"deviceState", "controlsState"}); bool onroad_prev = sm.allAliveAndValid({"deviceState"}) && sm["deviceState"].getDeviceState().getStarted(); sm.update(0); bool onroad = sm.allAliveAndValid({"deviceState"}) && sm["deviceState"].getDeviceState().getStarted(); if (onroad) { label->setText("〇"); auto cs = sm["controlsState"].getControlsState(); UIStatus status = cs.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; label->setStyleSheet(QString("color: %1; font-size: 250px;").arg(bg_colors[status].name())); } else { label->setText("offroad"); label->setStyleSheet("color: grey; font-size: 40px;"); } if ((onroad != onroad_prev) || sm.frame < 2) { Hardware::set_brightness(50); Hardware::set_display_power(onroad); } }); timer.start(50); return a.exec(); }
2301_81045437/openpilot
selfdrive/ui/mui.cc
C++
mit
1,460
#include "selfdrive/ui/qt/api.h" #include <openssl/pem.h> #include <openssl/rsa.h> #include <QApplication> #include <QCryptographicHash> #include <QDateTime> #include <QDebug> #include <QJsonDocument> #include <QNetworkRequest> #include <memory> #include <string> #include "common/util.h" #include "system/hardware/hw.h" #include "selfdrive/ui/qt/util.h" namespace CommaApi { RSA *get_rsa_private_key() { static std::unique_ptr<RSA, decltype(&RSA_free)> rsa_private(nullptr, RSA_free); if (!rsa_private) { FILE *fp = fopen(Path::rsa_file().c_str(), "rb"); if (!fp) { qDebug() << "No RSA private key found, please run manager.py or registration.py"; return nullptr; } rsa_private.reset(PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)); fclose(fp); } return rsa_private.get(); } QByteArray rsa_sign(const QByteArray &data) { RSA *rsa_private = get_rsa_private_key(); if (!rsa_private) return {}; QByteArray sig(RSA_size(rsa_private), Qt::Uninitialized); unsigned int sig_len; int ret = RSA_sign(NID_sha256, (unsigned char*)data.data(), data.size(), (unsigned char*)sig.data(), &sig_len, rsa_private); assert(ret == 1); assert(sig.size() == sig_len); return sig; } QString create_jwt(const QJsonObject &payloads, int expiry) { QJsonObject header = {{"alg", "RS256"}}; auto t = QDateTime::currentSecsSinceEpoch(); QJsonObject payload = {{"identity", getDongleId().value_or("")}, {"nbf", t}, {"iat", t}, {"exp", t + expiry}}; for (auto it = payloads.begin(); it != payloads.end(); ++it) { payload.insert(it.key(), it.value()); } auto b64_opts = QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals; QString jwt = QJsonDocument(header).toJson(QJsonDocument::Compact).toBase64(b64_opts) + '.' + QJsonDocument(payload).toJson(QJsonDocument::Compact).toBase64(b64_opts); auto hash = QCryptographicHash::hash(jwt.toUtf8(), QCryptographicHash::Sha256); return jwt + "." + rsa_sign(hash).toBase64(b64_opts); } } // namespace CommaApi HttpRequest::HttpRequest(QObject *parent, bool create_jwt, int timeout) : create_jwt(create_jwt), QObject(parent) { networkTimer = new QTimer(this); networkTimer->setSingleShot(true); networkTimer->setInterval(timeout); connect(networkTimer, &QTimer::timeout, this, &HttpRequest::requestTimeout); } bool HttpRequest::active() const { return reply != nullptr; } bool HttpRequest::timeout() const { return reply && reply->error() == QNetworkReply::OperationCanceledError; } void HttpRequest::sendRequest(const QString &requestURL, const HttpRequest::Method method) { if (active()) { qDebug() << "HttpRequest is active"; return; } QString token; if (create_jwt) { token = CommaApi::create_jwt(); } else { QString token_json = QString::fromStdString(util::read_file(util::getenv("HOME") + "/.comma/auth.json")); QJsonDocument json_d = QJsonDocument::fromJson(token_json.toUtf8()); token = json_d["access_token"].toString(); } QNetworkRequest request; request.setUrl(QUrl(requestURL)); request.setRawHeader("User-Agent", getUserAgent().toUtf8()); if (!token.isEmpty()) { request.setRawHeader(QByteArray("Authorization"), ("JWT " + token).toUtf8()); } if (method == HttpRequest::Method::GET) { reply = nam()->get(request); } else if (method == HttpRequest::Method::DELETE) { reply = nam()->deleteResource(request); } networkTimer->start(); connect(reply, &QNetworkReply::finished, this, &HttpRequest::requestFinished); } void HttpRequest::requestTimeout() { reply->abort(); } void HttpRequest::requestFinished() { networkTimer->stop(); if (reply->error() == QNetworkReply::NoError) { emit requestDone(reply->readAll(), true, reply->error()); } else { QString error; if (reply->error() == QNetworkReply::OperationCanceledError) { nam()->clearAccessCache(); nam()->clearConnectionCache(); error = "Request timed out"; } else { error = reply->errorString(); } emit requestDone(error, false, reply->error()); } reply->deleteLater(); reply = nullptr; } QNetworkAccessManager *HttpRequest::nam() { static QNetworkAccessManager *networkAccessManager = new QNetworkAccessManager(qApp); return networkAccessManager; }
2301_81045437/openpilot
selfdrive/ui/qt/api.cc
C++
mit
4,299
#pragma once #include <QJsonObject> #include <QNetworkReply> #include <QString> #include <QTimer> #include "common/util.h" namespace CommaApi { const QString BASE_URL = util::getenv("API_HOST", "https://api.commadotai.com").c_str(); QByteArray rsa_sign(const QByteArray &data); QString create_jwt(const QJsonObject &payloads = {}, int expiry = 3600); } // namespace CommaApi /** * Makes a request to the request endpoint. */ class HttpRequest : public QObject { Q_OBJECT public: enum class Method {GET, DELETE}; explicit HttpRequest(QObject* parent, bool create_jwt = true, int timeout = 20000); void sendRequest(const QString &requestURL, const Method method = Method::GET); bool active() const; bool timeout() const; signals: void requestDone(const QString &response, bool success, QNetworkReply::NetworkError error); protected: QNetworkReply *reply = nullptr; private: static QNetworkAccessManager *nam(); QTimer *networkTimer = nullptr; bool create_jwt; private slots: void requestTimeout(); void requestFinished(); };
2301_81045437/openpilot
selfdrive/ui/qt/api.h
C++
mit
1,065
#include "selfdrive/ui/qt/body.h" #include <cmath> #include <algorithm> #include <QPainter> #include <QStackedLayout> #include "common/params.h" #include "common/timing.h" RecordButton::RecordButton(QWidget *parent) : QPushButton(parent) { setCheckable(true); setChecked(false); setFixedSize(148, 148); QObject::connect(this, &QPushButton::toggled, [=]() { setEnabled(false); }); } void RecordButton::paintEvent(QPaintEvent *event) { QPainter p(this); p.setRenderHint(QPainter::Antialiasing); QPoint center(width() / 2, height() / 2); QColor bg(isChecked() ? "#FFFFFF" : "#737373"); QColor accent(isChecked() ? "#FF0000" : "#FFFFFF"); if (!isEnabled()) { bg = QColor("#404040"); accent = QColor("#FFFFFF"); } if (isDown()) { accent.setAlphaF(0.7); } p.setPen(Qt::NoPen); p.setBrush(bg); p.drawEllipse(center, 74, 74); p.setPen(QPen(accent, 6)); p.setBrush(Qt::NoBrush); p.drawEllipse(center, 42, 42); p.setPen(Qt::NoPen); p.setBrush(accent); p.drawEllipse(center, 22, 22); } BodyWindow::BodyWindow(QWidget *parent) : fuel_filter(1.0, 5., 1. / UI_FREQ), QWidget(parent) { QStackedLayout *layout = new QStackedLayout(this); layout->setStackingMode(QStackedLayout::StackAll); QWidget *w = new QWidget; QVBoxLayout *vlayout = new QVBoxLayout(w); vlayout->setMargin(45); layout->addWidget(w); // face face = new QLabel(); face->setAlignment(Qt::AlignCenter); layout->addWidget(face); awake = new QMovie("../assets/body/awake.gif", {}, this); awake->setCacheMode(QMovie::CacheAll); sleep = new QMovie("../assets/body/sleep.gif", {}, this); sleep->setCacheMode(QMovie::CacheAll); // record button btn = new RecordButton(this); vlayout->addWidget(btn, 0, Qt::AlignBottom | Qt::AlignRight); QObject::connect(btn, &QPushButton::clicked, [=](bool checked) { btn->setEnabled(false); Params().putBool("DisableLogging", !checked); last_button = nanos_since_boot(); }); w->raise(); QObject::connect(uiState(), &UIState::uiUpdate, this, &BodyWindow::updateState); } void BodyWindow::paintEvent(QPaintEvent *event) { QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.fillRect(rect(), QColor(0, 0, 0)); // battery outline + detail p.translate(width() - 136, 16); const QColor gray = QColor("#737373"); p.setBrush(Qt::NoBrush); p.setPen(QPen(gray, 4, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); p.drawRoundedRect(2, 2, 78, 36, 8, 8); p.setPen(Qt::NoPen); p.setBrush(gray); p.drawRoundedRect(84, 12, 6, 16, 4, 4); p.drawRect(84, 12, 3, 16); // battery level double fuel = std::clamp(fuel_filter.x(), 0.2f, 1.0f); const int m = 5; // manual margin since we can't do an inner border p.setPen(Qt::NoPen); p.setBrush(fuel > 0.25 ? QColor("#32D74B") : QColor("#FF453A")); p.drawRoundedRect(2 + m, 2 + m, (78 - 2*m)*fuel, 36 - 2*m, 4, 4); // charging status if (charging) { p.setPen(Qt::NoPen); p.setBrush(Qt::white); const QPolygonF charger({ QPointF(12.31, 0), QPointF(12.31, 16.92), QPointF(18.46, 16.92), QPointF(6.15, 40), QPointF(6.15, 23.08), QPointF(0, 23.08), }); p.drawPolygon(charger.translated(98, 0)); } } void BodyWindow::offroadTransition(bool offroad) { btn->setChecked(true); btn->setEnabled(true); fuel_filter.reset(1.0); } void BodyWindow::updateState(const UIState &s) { if (!isVisible()) { return; } const SubMaster &sm = *(s.sm); auto cs = sm["carState"].getCarState(); charging = cs.getCharging(); fuel_filter.update(cs.getFuelGauge()); // TODO: use carState.standstill when that's fixed const bool standstill = std::abs(cs.getVEgo()) < 0.01; QMovie *m = standstill ? sleep : awake; if (m != face->movie()) { face->setMovie(m); face->movie()->start(); } // update record button state if (sm.updated("managerState") && (sm.rcv_time("managerState") - last_button)*1e-9 > 0.5) { for (auto proc : sm["managerState"].getManagerState().getProcesses()) { if (proc.getName() == "loggerd") { btn->setEnabled(true); btn->setChecked(proc.getRunning()); } } } update(); }
2301_81045437/openpilot
selfdrive/ui/qt/body.cc
C++
mit
4,201
#pragma once #include <QMovie> #include <QLabel> #include <QPushButton> #include "common/util.h" #include "selfdrive/ui/ui.h" class RecordButton : public QPushButton { Q_OBJECT public: RecordButton(QWidget* parent = 0); private: void paintEvent(QPaintEvent*) override; }; class BodyWindow : public QWidget { Q_OBJECT public: BodyWindow(QWidget* parent = 0); private: bool charging = false; uint64_t last_button = 0; FirstOrderFilter fuel_filter; QLabel *face; QMovie *awake, *sleep; RecordButton *btn; void paintEvent(QPaintEvent*) override; private slots: void updateState(const UIState &s); void offroadTransition(bool onroad); };
2301_81045437/openpilot
selfdrive/ui/qt/body.h
C++
mit
670
#include "selfdrive/ui/qt/home.h" #include <QHBoxLayout> #include <QMouseEvent> #include <QStackedWidget> #include <QVBoxLayout> #include "selfdrive/ui/qt/offroad/experimental_mode.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/prime.h" #ifdef ENABLE_MAPS #include "selfdrive/ui/qt/maps/map_settings.h" #endif // HomeWindow: the container for the offroad and onroad UIs HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) { QHBoxLayout *main_layout = new QHBoxLayout(this); main_layout->setMargin(0); main_layout->setSpacing(0); sidebar = new Sidebar(this); main_layout->addWidget(sidebar); QObject::connect(sidebar, &Sidebar::openSettings, this, &HomeWindow::openSettings); slayout = new QStackedLayout(); main_layout->addLayout(slayout); home = new OffroadHome(this); QObject::connect(home, &OffroadHome::openSettings, this, &HomeWindow::openSettings); slayout->addWidget(home); onroad = new OnroadWindow(this); QObject::connect(onroad, &OnroadWindow::mapPanelRequested, this, [=] { sidebar->hide(); }); slayout->addWidget(onroad); body = new BodyWindow(this); slayout->addWidget(body); driver_view = new DriverViewWindow(this); connect(driver_view, &DriverViewWindow::done, [=] { showDriverView(false); }); slayout->addWidget(driver_view); setAttribute(Qt::WA_NoSystemBackground); QObject::connect(uiState(), &UIState::uiUpdate, this, &HomeWindow::updateState); QObject::connect(uiState(), &UIState::offroadTransition, this, &HomeWindow::offroadTransition); QObject::connect(uiState(), &UIState::offroadTransition, sidebar, &Sidebar::offroadTransition); } void HomeWindow::showSidebar(bool show) { sidebar->setVisible(show); } void HomeWindow::showMapPanel(bool show) { onroad->showMapPanel(show); } void HomeWindow::updateState(const UIState &s) { const SubMaster &sm = *(s.sm); // switch to the generic robot UI if (onroad->isVisible() && !body->isEnabled() && sm["carParams"].getCarParams().getNotCar()) { body->setEnabled(true); slayout->setCurrentWidget(body); } } void HomeWindow::offroadTransition(bool offroad) { body->setEnabled(false); sidebar->setVisible(offroad); if (offroad) { slayout->setCurrentWidget(home); } else { slayout->setCurrentWidget(onroad); } } void HomeWindow::showDriverView(bool show) { if (show) { emit closeSettings(); slayout->setCurrentWidget(driver_view); } else { slayout->setCurrentWidget(home); } sidebar->setVisible(show == false); } void HomeWindow::mousePressEvent(QMouseEvent* e) { // Handle sidebar collapsing if ((onroad->isVisible() || body->isVisible()) && (!sidebar->isVisible() || e->x() > sidebar->width())) { sidebar->setVisible(!sidebar->isVisible() && !onroad->isMapVisible()); } } void HomeWindow::mouseDoubleClickEvent(QMouseEvent* e) { HomeWindow::mousePressEvent(e); const SubMaster &sm = *(uiState()->sm); if (sm["carParams"].getCarParams().getNotCar()) { if (onroad->isVisible()) { slayout->setCurrentWidget(body); } else if (body->isVisible()) { slayout->setCurrentWidget(onroad); } showSidebar(false); } } // OffroadHome: the offroad home page OffroadHome::OffroadHome(QWidget* parent) : QFrame(parent) { QVBoxLayout* main_layout = new QVBoxLayout(this); main_layout->setContentsMargins(40, 40, 40, 40); // top header QHBoxLayout* header_layout = new QHBoxLayout(); header_layout->setContentsMargins(0, 0, 0, 0); header_layout->setSpacing(16); update_notif = new QPushButton(tr("UPDATE")); update_notif->setVisible(false); update_notif->setStyleSheet("background-color: #364DEF;"); QObject::connect(update_notif, &QPushButton::clicked, [=]() { center_layout->setCurrentIndex(1); }); header_layout->addWidget(update_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); alert_notif = new QPushButton(); alert_notif->setVisible(false); alert_notif->setStyleSheet("background-color: #E22C2C;"); QObject::connect(alert_notif, &QPushButton::clicked, [=] { center_layout->setCurrentIndex(2); }); header_layout->addWidget(alert_notif, 0, Qt::AlignHCenter | Qt::AlignLeft); version = new ElidedLabel(); header_layout->addWidget(version, 0, Qt::AlignHCenter | Qt::AlignRight); main_layout->addLayout(header_layout); // main content main_layout->addSpacing(25); center_layout = new QStackedLayout(); QWidget *home_widget = new QWidget(this); { QHBoxLayout *home_layout = new QHBoxLayout(home_widget); home_layout->setContentsMargins(0, 0, 0, 0); home_layout->setSpacing(30); // left: MapSettings/PrimeAdWidget QStackedWidget *left_widget = new QStackedWidget(this); #ifdef ENABLE_MAPS left_widget->addWidget(new MapSettings); #else left_widget->addWidget(new QWidget); #endif left_widget->addWidget(new PrimeAdWidget); left_widget->setStyleSheet("border-radius: 10px;"); left_widget->setCurrentIndex(uiState()->hasPrime() ? 0 : 1); connect(uiState(), &UIState::primeChanged, [=](bool prime) { left_widget->setCurrentIndex(prime ? 0 : 1); }); home_layout->addWidget(left_widget, 1); // right: ExperimentalModeButton, SetupWidget QWidget* right_widget = new QWidget(this); QVBoxLayout* right_column = new QVBoxLayout(right_widget); right_column->setContentsMargins(0, 0, 0, 0); right_widget->setFixedWidth(750); right_column->setSpacing(30); ExperimentalModeButton *experimental_mode = new ExperimentalModeButton(this); QObject::connect(experimental_mode, &ExperimentalModeButton::openSettings, this, &OffroadHome::openSettings); right_column->addWidget(experimental_mode, 1); SetupWidget *setup_widget = new SetupWidget; QObject::connect(setup_widget, &SetupWidget::openSettings, this, &OffroadHome::openSettings); right_column->addWidget(setup_widget, 1); home_layout->addWidget(right_widget, 1); } center_layout->addWidget(home_widget); // add update & alerts widgets update_widget = new UpdateAlert(); QObject::connect(update_widget, &UpdateAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); center_layout->addWidget(update_widget); alerts_widget = new OffroadAlert(); QObject::connect(alerts_widget, &OffroadAlert::dismiss, [=]() { center_layout->setCurrentIndex(0); }); center_layout->addWidget(alerts_widget); main_layout->addLayout(center_layout, 1); // set up refresh timer timer = new QTimer(this); timer->callOnTimeout(this, &OffroadHome::refresh); setStyleSheet(R"( * { color: white; } OffroadHome { background-color: black; } OffroadHome > QPushButton { padding: 15px 30px; border-radius: 5px; font-size: 40px; font-weight: 500; } OffroadHome > QLabel { font-size: 55px; } )"); } void OffroadHome::showEvent(QShowEvent *event) { refresh(); timer->start(10 * 1000); } void OffroadHome::hideEvent(QHideEvent *event) { timer->stop(); } void OffroadHome::refresh() { version->setText(getBrand() + " " + QString::fromStdString(params.get("UpdaterCurrentDescription"))); bool updateAvailable = update_widget->refresh(); int alerts = alerts_widget->refresh(); // pop-up new notification int idx = center_layout->currentIndex(); if (!updateAvailable && !alerts) { idx = 0; } else if (updateAvailable && (!update_notif->isVisible() || (!alerts && idx == 2))) { idx = 1; } else if (alerts && (!alert_notif->isVisible() || (!updateAvailable && idx == 1))) { idx = 2; } center_layout->setCurrentIndex(idx); update_notif->setVisible(updateAvailable); alert_notif->setVisible(alerts); if (alerts) { alert_notif->setText(QString::number(alerts) + (alerts > 1 ? tr(" ALERTS") : tr(" ALERT"))); } }
2301_81045437/openpilot
selfdrive/ui/qt/home.cc
C++
mit
7,793
#pragma once #include <QFrame> #include <QLabel> #include <QPushButton> #include <QStackedLayout> #include <QTimer> #include <QWidget> #include "common/params.h" #include "selfdrive/ui/qt/offroad/driverview.h" #include "selfdrive/ui/qt/body.h" #include "selfdrive/ui/qt/onroad/onroad_home.h" #include "selfdrive/ui/qt/sidebar.h" #include "selfdrive/ui/qt/widgets/controls.h" #include "selfdrive/ui/qt/widgets/offroad_alerts.h" #include "selfdrive/ui/ui.h" class OffroadHome : public QFrame { Q_OBJECT public: explicit OffroadHome(QWidget* parent = 0); signals: void openSettings(int index = 0, const QString &param = ""); private: void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; void refresh(); Params params; QTimer* timer; ElidedLabel* version; QStackedLayout* center_layout; UpdateAlert *update_widget; OffroadAlert* alerts_widget; QPushButton* alert_notif; QPushButton* update_notif; }; class HomeWindow : public QWidget { Q_OBJECT public: explicit HomeWindow(QWidget* parent = 0); signals: void openSettings(int index = 0, const QString &param = ""); void closeSettings(); public slots: void offroadTransition(bool offroad); void showDriverView(bool show); void showSidebar(bool show); void showMapPanel(bool show); protected: void mousePressEvent(QMouseEvent* e) override; void mouseDoubleClickEvent(QMouseEvent* e) override; private: Sidebar *sidebar; OffroadHome *home; OnroadWindow *onroad; BodyWindow *body; DriverViewWindow *driver_view; QStackedLayout *slayout; private slots: void updateState(const UIState &s); };
2301_81045437/openpilot
selfdrive/ui/qt/home.h
C++
mit
1,645
#include "selfdrive/ui/qt/maps/map.h" #include <algorithm> #include <eigen3/Eigen/Dense> #include <QDebug> #include "common/swaglog.h" #include "selfdrive/ui/qt/maps/map_helpers.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/ui.h" const int INTERACTION_TIMEOUT = 100; const float MAX_ZOOM = 17; const float MIN_ZOOM = 14; const float MAX_PITCH = 50; const float MIN_PITCH = 0; const float MAP_SCALE = 2; MapWindow::MapWindow(const QMapLibre::Settings &settings) : m_settings(settings), velocity_filter(0, 10, 0.05, false) { QObject::connect(uiState(), &UIState::uiUpdate, this, &MapWindow::updateState); map_overlay = new QWidget (this); map_overlay->setAttribute(Qt::WA_TranslucentBackground, true); QVBoxLayout *overlay_layout = new QVBoxLayout(map_overlay); overlay_layout->setContentsMargins(0, 0, 0, 0); // Instructions map_instructions = new MapInstructions(this); map_instructions->setVisible(false); map_eta = new MapETA(this); map_eta->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); map_eta->setFixedHeight(120); error = new QLabel(this); error->setStyleSheet(R"(color:white;padding:50px 11px;font-size: 90px; background-color:rgba(0, 0, 0, 150);)"); error->setAlignment(Qt::AlignCenter); overlay_layout->addWidget(error); overlay_layout->addWidget(map_instructions); overlay_layout->addStretch(1); overlay_layout->addWidget(map_eta); last_position = coordinate_from_param("LastGPSPosition"); grabGesture(Qt::GestureType::PinchGesture); qDebug() << "MapWindow initialized"; } MapWindow::~MapWindow() { makeCurrent(); } void MapWindow::initLayers() { // This doesn't work from initializeGL if (!m_map->layerExists("modelPathLayer")) { qDebug() << "Initializing modelPathLayer"; QVariantMap modelPath; //modelPath["id"] = "modelPathLayer"; modelPath["type"] = "line"; modelPath["source"] = "modelPathSource"; m_map->addLayer("modelPathLayer", modelPath); m_map->setPaintProperty("modelPathLayer", "line-color", QColor("red")); m_map->setPaintProperty("modelPathLayer", "line-width", 5.0); m_map->setLayoutProperty("modelPathLayer", "line-cap", "round"); } if (!m_map->layerExists("navLayer")) { qDebug() << "Initializing navLayer"; QVariantMap nav; nav["type"] = "line"; nav["source"] = "navSource"; m_map->addLayer("navLayer", nav, "road-intersection"); QVariantMap transition; transition["duration"] = 400; // ms m_map->setPaintProperty("navLayer", "line-color", QColor("#31a1ee")); m_map->setPaintProperty("navLayer", "line-color-transition", transition); m_map->setPaintProperty("navLayer", "line-width", 7.5); m_map->setLayoutProperty("navLayer", "line-cap", "round"); } if (!m_map->layerExists("pinLayer")) { qDebug() << "Initializing pinLayer"; m_map->addImage("default_marker", QImage("../assets/navigation/default_marker.svg")); QVariantMap pin; pin["type"] = "symbol"; pin["source"] = "pinSource"; m_map->addLayer("pinLayer", pin); m_map->setLayoutProperty("pinLayer", "icon-pitch-alignment", "viewport"); m_map->setLayoutProperty("pinLayer", "icon-image", "default_marker"); m_map->setLayoutProperty("pinLayer", "icon-ignore-placement", true); m_map->setLayoutProperty("pinLayer", "icon-allow-overlap", true); m_map->setLayoutProperty("pinLayer", "symbol-sort-key", 0); m_map->setLayoutProperty("pinLayer", "icon-anchor", "bottom"); } if (!m_map->layerExists("carPosLayer")) { qDebug() << "Initializing carPosLayer"; m_map->addImage("label-arrow", QImage("../assets/images/triangle.svg")); QVariantMap carPos; carPos["type"] = "symbol"; carPos["source"] = "carPosSource"; m_map->addLayer("carPosLayer", carPos); m_map->setLayoutProperty("carPosLayer", "icon-pitch-alignment", "map"); m_map->setLayoutProperty("carPosLayer", "icon-image", "label-arrow"); m_map->setLayoutProperty("carPosLayer", "icon-size", 0.5); m_map->setLayoutProperty("carPosLayer", "icon-ignore-placement", true); m_map->setLayoutProperty("carPosLayer", "icon-allow-overlap", true); // TODO: remove, symbol-sort-key does not seem to matter outside of each layer m_map->setLayoutProperty("carPosLayer", "symbol-sort-key", 0); } } void MapWindow::updateState(const UIState &s) { if (!uiState()->scene.started) { return; } const SubMaster &sm = *(s.sm); update(); // on rising edge of a valid system time, reinitialize the map to set a new token if (sm.valid("clocks") && !prev_time_valid) { LOGW("Time is now valid, reinitializing map"); m_settings.setApiKey(get_mapbox_token()); initializeGL(); } prev_time_valid = sm.valid("clocks"); if (sm.updated("liveLocationKalman")) { auto locationd_location = sm["liveLocationKalman"].getLiveLocationKalman(); auto locationd_pos = locationd_location.getPositionGeodetic(); auto locationd_orientation = locationd_location.getCalibratedOrientationNED(); auto locationd_velocity = locationd_location.getVelocityCalibrated(); auto locationd_ecef = locationd_location.getPositionECEF(); locationd_valid = (locationd_pos.getValid() && locationd_orientation.getValid() && locationd_velocity.getValid() && locationd_ecef.getValid()); if (locationd_valid) { // Check std norm auto pos_ecef_std = locationd_ecef.getStd(); bool pos_accurate_enough = sqrt(pow(pos_ecef_std[0], 2) + pow(pos_ecef_std[1], 2) + pow(pos_ecef_std[2], 2)) < 100; locationd_valid = pos_accurate_enough; } if (locationd_valid) { last_position = QMapLibre::Coordinate(locationd_pos.getValue()[0], locationd_pos.getValue()[1]); last_bearing = RAD2DEG(locationd_orientation.getValue()[2]); velocity_filter.update(std::max(10.0, locationd_velocity.getValue()[0])); } } if (sm.updated("navRoute") && sm["navRoute"].getNavRoute().getCoordinates().size()) { auto nav_dest = coordinate_from_param("NavDestination"); bool allow_open = std::exchange(last_valid_nav_dest, nav_dest) != nav_dest && nav_dest && !isVisible(); qWarning() << "Got new navRoute from navd. Opening map:" << allow_open; // Show map on destination set/change if (allow_open) { emit requestSettings(false); emit requestVisible(true); } } loaded_once = loaded_once || (m_map && m_map->isFullyLoaded()); if (!loaded_once) { setError(tr("Map Loading")); return; } initLayers(); if (!locationd_valid) { setError(tr("Waiting for GPS")); } else if (routing_problem) { setError(tr("Waiting for route")); } else { setError(""); } if (locationd_valid) { // Update current location marker auto point = coordinate_to_collection(*last_position); QMapLibre::Feature feature1(QMapLibre::Feature::PointType, point, {}, {}); QVariantMap carPosSource; carPosSource["type"] = "geojson"; carPosSource["data"] = QVariant::fromValue<QMapLibre::Feature>(feature1); m_map->updateSource("carPosSource", carPosSource); // Map bearing isn't updated when interacting, keep location marker up to date if (last_bearing) { m_map->setLayoutProperty("carPosLayer", "icon-rotate", *last_bearing - m_map->bearing()); } } if (interaction_counter == 0) { if (last_position) m_map->setCoordinate(*last_position); if (last_bearing) m_map->setBearing(*last_bearing); m_map->setZoom(util::map_val<float>(velocity_filter.x(), 0, 30, MAX_ZOOM, MIN_ZOOM)); } else { interaction_counter--; } if (sm.updated("navInstruction")) { // an invalid navInstruction packet with a nav destination is only possible if: // - API exception/no internet // - route response is empty // - any time navd is waiting for recompute_countdown routing_problem = !sm.valid("navInstruction") && coordinate_from_param("NavDestination").has_value(); if (sm.valid("navInstruction")) { auto i = sm["navInstruction"].getNavInstruction(); map_eta->updateETA(i.getTimeRemaining(), i.getTimeRemainingTypical(), i.getDistanceRemaining()); if (locationd_valid) { m_map->setPitch(MAX_PITCH); // TODO: smooth pitching based on maneuver distance map_instructions->updateInstructions(i); } } else { clearRoute(); } } if (sm.rcv_frame("navRoute") != route_rcv_frame) { qWarning() << "Updating navLayer with new route"; auto route = sm["navRoute"].getNavRoute(); auto route_points = capnp_coordinate_list_to_collection(route.getCoordinates()); QMapLibre::Feature feature(QMapLibre::Feature::LineStringType, route_points, {}, {}); QVariantMap navSource; navSource["type"] = "geojson"; navSource["data"] = QVariant::fromValue<QMapLibre::Feature>(feature); m_map->updateSource("navSource", navSource); m_map->setLayoutProperty("navLayer", "visibility", "visible"); route_rcv_frame = sm.rcv_frame("navRoute"); updateDestinationMarker(); } } void MapWindow::setError(const QString &err_str) { if (err_str != error->text()) { error->setText(err_str); error->setVisible(!err_str.isEmpty()); if (!err_str.isEmpty()) map_instructions->setVisible(false); } } void MapWindow::resizeGL(int w, int h) { m_map->resize(size() / MAP_SCALE); map_overlay->setFixedSize(width(), height()); } void MapWindow::initializeGL() { m_map.reset(new QMapLibre::Map(this, m_settings, size(), 1)); if (last_position) { m_map->setCoordinateZoom(*last_position, MAX_ZOOM); } else { m_map->setCoordinateZoom(QMapLibre::Coordinate(64.31990695292795, -149.79038934046247), MIN_ZOOM); } m_map->setMargins({0, 350, 0, 50}); m_map->setPitch(MIN_PITCH); m_map->setStyleUrl("mapbox://styles/commaai/clkqztk0f00ou01qyhsa5bzpj"); QObject::connect(m_map.data(), &QMapLibre::Map::mapChanged, [=](QMapLibre::Map::MapChange change) { // set global animation duration to 0 ms so visibility changes are instant if (change == QMapLibre::Map::MapChange::MapChangeDidFinishLoadingStyle) { m_map->setTransitionOptions(0, 0); } if (change == QMapLibre::Map::MapChange::MapChangeDidFinishLoadingMap) { loaded_once = true; } }); QObject::connect(m_map.data(), &QMapLibre::Map::mapLoadingFailed, [=](QMapLibre::Map::MapLoadingFailure err_code, const QString &reason) { LOGE("Map loading failed with %d: '%s'\n", err_code, reason.toStdString().c_str()); }); } void MapWindow::paintGL() { if (!isVisible() || m_map.isNull()) return; m_map->render(); } void MapWindow::clearRoute() { if (!m_map.isNull()) { m_map->setLayoutProperty("navLayer", "visibility", "none"); m_map->setPitch(MIN_PITCH); updateDestinationMarker(); } map_instructions->setVisible(false); map_eta->setVisible(false); last_valid_nav_dest = std::nullopt; } void MapWindow::mousePressEvent(QMouseEvent *ev) { m_lastPos = ev->localPos(); ev->accept(); } void MapWindow::mouseDoubleClickEvent(QMouseEvent *ev) { if (last_position) m_map->setCoordinate(*last_position); if (last_bearing) m_map->setBearing(*last_bearing); m_map->setZoom(util::map_val<float>(velocity_filter.x(), 0, 30, MAX_ZOOM, MIN_ZOOM)); update(); interaction_counter = 0; } void MapWindow::mouseMoveEvent(QMouseEvent *ev) { QPointF delta = ev->localPos() - m_lastPos; if (!delta.isNull()) { interaction_counter = INTERACTION_TIMEOUT; m_map->moveBy(delta / MAP_SCALE); update(); } m_lastPos = ev->localPos(); ev->accept(); } void MapWindow::wheelEvent(QWheelEvent *ev) { if (ev->orientation() == Qt::Horizontal) { return; } float factor = ev->delta() / 1200.; if (ev->delta() < 0) { factor = factor > -1 ? factor : 1 / factor; } m_map->scaleBy(1 + factor, ev->pos() / MAP_SCALE); update(); interaction_counter = INTERACTION_TIMEOUT; ev->accept(); } bool MapWindow::event(QEvent *event) { if (event->type() == QEvent::Gesture) { return gestureEvent(static_cast<QGestureEvent*>(event)); } return QWidget::event(event); } bool MapWindow::gestureEvent(QGestureEvent *event) { if (QGesture *pinch = event->gesture(Qt::PinchGesture)) { pinchTriggered(static_cast<QPinchGesture *>(pinch)); } return true; } void MapWindow::pinchTriggered(QPinchGesture *gesture) { QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags(); if (changeFlags & QPinchGesture::ScaleFactorChanged) { // TODO: figure out why gesture centerPoint doesn't work m_map->scaleBy(gesture->scaleFactor(), {width() / 2.0 / MAP_SCALE, height() / 2.0 / MAP_SCALE}); update(); interaction_counter = INTERACTION_TIMEOUT; } } void MapWindow::offroadTransition(bool offroad) { if (offroad) { clearRoute(); routing_problem = false; } else { auto dest = coordinate_from_param("NavDestination"); emit requestVisible(dest.has_value()); } last_bearing = {}; } void MapWindow::updateDestinationMarker() { auto nav_dest = coordinate_from_param("NavDestination"); if (nav_dest.has_value()) { auto point = coordinate_to_collection(*nav_dest); QMapLibre::Feature feature(QMapLibre::Feature::PointType, point, {}, {}); QVariantMap pinSource; pinSource["type"] = "geojson"; pinSource["data"] = QVariant::fromValue<QMapLibre::Feature>(feature); m_map->updateSource("pinSource", pinSource); m_map->setPaintProperty("pinLayer", "visibility", "visible"); } else { m_map->setPaintProperty("pinLayer", "visibility", "none"); } }
2301_81045437/openpilot
selfdrive/ui/qt/maps/map.cc
C++
mit
13,549
#pragma once #include <optional> #include <QGeoCoordinate> #include <QGestureEvent> #include <QLabel> #include <QMap> #include <QMapLibre/Map> #include <QMapLibre/Settings> #include <QMouseEvent> #include <QOpenGLWidget> #include <QPixmap> #include <QPushButton> #include <QScopedPointer> #include <QString> #include <QVBoxLayout> #include <QWheelEvent> #include "cereal/messaging/messaging.h" #include "common/params.h" #include "common/util.h" #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/maps/map_eta.h" #include "selfdrive/ui/qt/maps/map_instructions.h" class MapWindow : public QOpenGLWidget { Q_OBJECT public: MapWindow(const QMapLibre::Settings &); ~MapWindow(); private: void initializeGL() final; void paintGL() final; void resizeGL(int w, int h) override; QMapLibre::Settings m_settings; QScopedPointer<QMapLibre::Map> m_map; void initLayers(); void mousePressEvent(QMouseEvent *ev) final; void mouseDoubleClickEvent(QMouseEvent *ev) final; void mouseMoveEvent(QMouseEvent *ev) final; void wheelEvent(QWheelEvent *ev) final; bool event(QEvent *event) final; bool gestureEvent(QGestureEvent *event); void pinchTriggered(QPinchGesture *gesture); void setError(const QString &err_str); bool loaded_once = false; bool prev_time_valid = true; // Panning QPointF m_lastPos; int interaction_counter = 0; // Position std::optional<QMapLibre::Coordinate> last_valid_nav_dest; std::optional<QMapLibre::Coordinate> last_position; std::optional<float> last_bearing; FirstOrderFilter velocity_filter; bool locationd_valid = false; bool routing_problem = false; QWidget *map_overlay; QLabel *error; MapInstructions* map_instructions; MapETA* map_eta; void clearRoute(); void updateDestinationMarker(); uint64_t route_rcv_frame = 0; private slots: void updateState(const UIState &s); public slots: void offroadTransition(bool offroad); signals: void requestVisible(bool visible); void requestSettings(bool settings); };
2301_81045437/openpilot
selfdrive/ui/qt/maps/map.h
C++
mit
2,022
#include "selfdrive/ui/qt/maps/map_eta.h" #include <QDateTime> #include <QPainter> #include "selfdrive/ui/qt/maps/map_helpers.h" #include "selfdrive/ui/ui.h" const float MANEUVER_TRANSITION_THRESHOLD = 10; MapETA::MapETA(QWidget *parent) : QWidget(parent) { setVisible(false); setAttribute(Qt::WA_TranslucentBackground); eta_doc.setUndoRedoEnabled(false); eta_doc.setDefaultStyleSheet("body {font-family:Inter;font-size:70px;color:white;} b{font-weight:600;} td{padding:0 3px;}"); } void MapETA::paintEvent(QPaintEvent *event) { if (!eta_doc.isEmpty()) { QPainter p(this); p.setRenderHint(QPainter::Antialiasing); p.setPen(Qt::NoPen); p.setBrush(QColor(0, 0, 0, 255)); QSizeF txt_size = eta_doc.size(); p.drawRoundedRect((width() - txt_size.width()) / 2 - UI_BORDER_SIZE, 0, txt_size.width() + UI_BORDER_SIZE * 2, height() + 25, 25, 25); p.translate((width() - txt_size.width()) / 2, (height() - txt_size.height()) / 2); eta_doc.drawContents(&p); } } void MapETA::updateETA(float s, float s_typical, float d) { // ETA auto eta_t = QDateTime::currentDateTime().addSecs(s).time(); auto eta = format_24h ? std::pair{eta_t.toString("HH:mm"), tr("eta")} : std::pair{eta_t.toString("h:mm a").split(' ')[0], eta_t.toString("a")}; // Remaining time auto remaining = s < 3600 ? std::pair{QString::number(int(s / 60)), tr("min")} : std::pair{QString("%1:%2").arg((int)s / 3600).arg(((int)s % 3600) / 60, 2, 10, QLatin1Char('0')), tr("hr")}; QString color = "#25DA6E"; if (std::abs(s_typical) > 1e-5) { if (s / s_typical > 1.5) { color = "#DA3025"; } else if (s / s_typical > 1.2) { color = "#DAA725"; } } // Distance auto distance = map_format_distance(d, uiState()->scene.is_metric); eta_doc.setHtml(QString(R"(<body><table><tr style="vertical-align:bottom;"><td><b>%1</b></td><td>%2</td> <td style="padding-left:40px;color:%3;"><b>%4</b></td><td style="padding-right:40px;color:%3;">%5</td> <td><b>%6</b></td><td>%7</td></tr></body>)") .arg(eta.first, eta.second, color, remaining.first, remaining.second, distance.first, distance.second)); setVisible(d >= MANEUVER_TRANSITION_THRESHOLD); update(); }
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_eta.cc
C++
mit
2,329
#pragma once #include <QPaintEvent> #include <QTextDocument> #include <QWidget> #include "common/params.h" class MapETA : public QWidget { Q_OBJECT public: MapETA(QWidget * parent=nullptr); void updateETA(float seconds, float seconds_typical, float distance); private: void paintEvent(QPaintEvent *event) override; void showEvent(QShowEvent *event) override { format_24h = param.getBool("NavSettingTime24h"); } bool format_24h = false; QTextDocument eta_doc; Params param; };
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_eta.h
C++
mit
498
#include "selfdrive/ui/qt/maps/map_helpers.h" #include <algorithm> #include <string> #include <utility> #include <QJsonDocument> #include <QJsonObject> #include "common/params.h" #include "system/hardware/hw.h" #include "selfdrive/ui/qt/api.h" QString get_mapbox_token() { // Valid for 4 weeks since we can't swap tokens on the fly return MAPBOX_TOKEN.isEmpty() ? CommaApi::create_jwt({}, 4 * 7 * 24 * 3600) : MAPBOX_TOKEN; } QMapLibre::Settings get_mapbox_settings() { QMapLibre::Settings settings; settings.setProviderTemplate(QMapLibre::Settings::ProviderTemplate::MapboxProvider); if (!Hardware::PC()) { settings.setCacheDatabasePath(MAPS_CACHE_PATH); settings.setCacheDatabaseMaximumSize(100 * 1024 * 1024); } settings.setApiBaseUrl(MAPS_HOST); settings.setApiKey(get_mapbox_token()); return settings; } QGeoCoordinate to_QGeoCoordinate(const QMapLibre::Coordinate &in) { return QGeoCoordinate(in.first, in.second); } QMapLibre::CoordinatesCollections model_to_collection( const cereal::LiveLocationKalman::Measurement::Reader &calibratedOrientationECEF, const cereal::LiveLocationKalman::Measurement::Reader &positionECEF, const cereal::XYZTData::Reader &line){ Eigen::Vector3d ecef(positionECEF.getValue()[0], positionECEF.getValue()[1], positionECEF.getValue()[2]); Eigen::Vector3d orient(calibratedOrientationECEF.getValue()[0], calibratedOrientationECEF.getValue()[1], calibratedOrientationECEF.getValue()[2]); Eigen::Matrix3d ecef_from_local = euler2rot(orient); QMapLibre::Coordinates coordinates; auto x = line.getX(); auto y = line.getY(); auto z = line.getZ(); for (int i = 0; i < x.size(); i++) { Eigen::Vector3d point_ecef = ecef_from_local * Eigen::Vector3d(x[i], y[i], z[i]) + ecef; Geodetic point_geodetic = ecef2geodetic((ECEF){.x = point_ecef[0], .y = point_ecef[1], .z = point_ecef[2]}); coordinates.push_back({point_geodetic.lat, point_geodetic.lon}); } return {QMapLibre::CoordinatesCollection{coordinates}}; } QMapLibre::CoordinatesCollections coordinate_to_collection(const QMapLibre::Coordinate &c) { QMapLibre::Coordinates coordinates{c}; return {QMapLibre::CoordinatesCollection{coordinates}}; } QMapLibre::CoordinatesCollections capnp_coordinate_list_to_collection(const capnp::List<cereal::NavRoute::Coordinate>::Reader& coordinate_list) { QMapLibre::Coordinates coordinates; for (auto const &c : coordinate_list) { coordinates.push_back({c.getLatitude(), c.getLongitude()}); } return {QMapLibre::CoordinatesCollection{coordinates}}; } QMapLibre::CoordinatesCollections coordinate_list_to_collection(const QList<QGeoCoordinate> &coordinate_list) { QMapLibre::Coordinates coordinates; for (auto &c : coordinate_list) { coordinates.push_back({c.latitude(), c.longitude()}); } return {QMapLibre::CoordinatesCollection{coordinates}}; } QList<QGeoCoordinate> polyline_to_coordinate_list(const QString &polylineString) { QList<QGeoCoordinate> path; if (polylineString.isEmpty()) return path; QByteArray data = polylineString.toLatin1(); bool parsingLatitude = true; int shift = 0; int value = 0; QGeoCoordinate coord(0, 0); for (int i = 0; i < data.length(); ++i) { unsigned char c = data.at(i) - 63; value |= (c & 0x1f) << shift; shift += 5; // another chunk if (c & 0x20) continue; int diff = (value & 1) ? ~(value >> 1) : (value >> 1); if (parsingLatitude) { coord.setLatitude(coord.latitude() + (double)diff/1e6); } else { coord.setLongitude(coord.longitude() + (double)diff/1e6); path.append(coord); } parsingLatitude = !parsingLatitude; value = 0; shift = 0; } return path; } std::optional<QMapLibre::Coordinate> coordinate_from_param(const std::string &param) { QString json_str = QString::fromStdString(Params().get(param)); if (json_str.isEmpty()) return {}; QJsonDocument doc = QJsonDocument::fromJson(json_str.toUtf8()); if (doc.isNull()) return {}; QJsonObject json = doc.object(); if (json["latitude"].isDouble() && json["longitude"].isDouble()) { QMapLibre::Coordinate coord(json["latitude"].toDouble(), json["longitude"].toDouble()); return coord; } else { return {}; } } // return {distance, unit} std::pair<QString, QString> map_format_distance(float d, bool is_metric) { auto round_distance = [](float d) -> QString { return (d > 10) ? QString::number(std::nearbyint(d)) : QString::number(std::nearbyint(d * 10) / 10.0, 'f', 1); }; d = std::max(d, 0.0f); if (is_metric) { return (d > 500) ? std::pair{round_distance(d / 1000), QObject::tr("km")} : std::pair{QString::number(50 * std::nearbyint(d / 50)), QObject::tr("m")}; } else { float feet = d * METER_TO_FOOT; return (feet > 500) ? std::pair{round_distance(d * METER_TO_MILE), QObject::tr("mi")} : std::pair{QString::number(50 * std::nearbyint(d / 50)), QObject::tr("ft")}; } }
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_helpers.cc
C++
mit
5,042
#pragma once #include <optional> #include <string> #include <utility> #include <QMapLibre/Map> #include <QMapLibre/Settings> #include <eigen3/Eigen/Dense> #include <QGeoCoordinate> #include "common/util.h" #include "common/transformations/coordinates.hpp" #include "common/transformations/orientation.hpp" #include "cereal/messaging/messaging.h" const QString MAPBOX_TOKEN = util::getenv("MAPBOX_TOKEN").c_str(); const QString MAPS_HOST = util::getenv("MAPS_HOST", MAPBOX_TOKEN.isEmpty() ? "https://maps.comma.ai" : "https://api.mapbox.com").c_str(); const QString MAPS_CACHE_PATH = "/data/mbgl-cache-navd.db"; QString get_mapbox_token(); QMapLibre::Settings get_mapbox_settings(); QGeoCoordinate to_QGeoCoordinate(const QMapLibre::Coordinate &in); QMapLibre::CoordinatesCollections model_to_collection( const cereal::LiveLocationKalman::Measurement::Reader &calibratedOrientationECEF, const cereal::LiveLocationKalman::Measurement::Reader &positionECEF, const cereal::XYZTData::Reader &line); QMapLibre::CoordinatesCollections coordinate_to_collection(const QMapLibre::Coordinate &c); QMapLibre::CoordinatesCollections capnp_coordinate_list_to_collection(const capnp::List<cereal::NavRoute::Coordinate>::Reader &coordinate_list); QMapLibre::CoordinatesCollections coordinate_list_to_collection(const QList<QGeoCoordinate> &coordinate_list); QList<QGeoCoordinate> polyline_to_coordinate_list(const QString &polylineString); std::optional<QMapLibre::Coordinate> coordinate_from_param(const std::string &param); std::pair<QString, QString> map_format_distance(float d, bool is_metric);
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_helpers.h
C++
mit
1,594
#include "selfdrive/ui/qt/maps/map_instructions.h" #include <QDir> #include <QVBoxLayout> #include "selfdrive/ui/qt/maps/map_helpers.h" #include "selfdrive/ui/ui.h" const QString ICON_SUFFIX = ".png"; MapInstructions::MapInstructions(QWidget *parent) : QWidget(parent) { is_rhd = Params().getBool("IsRhdDetected"); QVBoxLayout *main_layout = new QVBoxLayout(this); main_layout->setContentsMargins(11, UI_BORDER_SIZE, 11, 20); QHBoxLayout *top_layout = new QHBoxLayout; top_layout->addWidget(icon_01 = new QLabel, 0, Qt::AlignTop); QVBoxLayout *right_layout = new QVBoxLayout; right_layout->setContentsMargins(9, 9, 9, 0); right_layout->addWidget(distance = new QLabel); distance->setStyleSheet(R"(font-size: 90px;)"); right_layout->addWidget(primary = new QLabel); primary->setStyleSheet(R"(font-size: 60px;)"); primary->setWordWrap(true); right_layout->addWidget(secondary = new QLabel); secondary->setStyleSheet(R"(font-size: 50px;)"); secondary->setWordWrap(true); top_layout->addLayout(right_layout); main_layout->addLayout(top_layout); main_layout->addLayout(lane_layout = new QHBoxLayout); lane_layout->setAlignment(Qt::AlignHCenter); lane_layout->setSpacing(10); setStyleSheet("color:white"); QPalette pal = palette(); pal.setColor(QPalette::Background, QColor(0, 0, 0, 150)); setAutoFillBackground(true); setPalette(pal); buildPixmapCache(); } void MapInstructions::buildPixmapCache() { QDir dir("../assets/navigation"); for (QString fn : dir.entryList({"*" + ICON_SUFFIX}, QDir::Files)) { QPixmap pm(dir.filePath(fn)); QString key = fn.left(fn.size() - ICON_SUFFIX.length()); pm = pm.scaledToWidth(200, Qt::SmoothTransformation); // Maneuver icons pixmap_cache[key] = pm; // lane direction icons if (key.contains("turn_")) { pixmap_cache["lane_" + key] = pm.scaled({125, 125}, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); } // for rhd, reflect direction and then flip if (key.contains("_left")) { pixmap_cache["rhd_" + key.replace("_left", "_right")] = pm.transformed(QTransform().scale(-1, 1)); } else if (key.contains("_right")) { pixmap_cache["rhd_" + key.replace("_right", "_left")] = pm.transformed(QTransform().scale(-1, 1)); } } } void MapInstructions::updateInstructions(cereal::NavInstruction::Reader instruction) { setUpdatesEnabled(false); // Show instruction text QString primary_str = QString::fromStdString(instruction.getManeuverPrimaryText()); QString secondary_str = QString::fromStdString(instruction.getManeuverSecondaryText()); primary->setText(primary_str); secondary->setVisible(secondary_str.length() > 0); secondary->setText(secondary_str); auto distance_str_pair = map_format_distance(instruction.getManeuverDistance(), uiState()->scene.is_metric); distance->setText(QString("%1 %2").arg(distance_str_pair.first, distance_str_pair.second)); // Show arrow with direction QString type = QString::fromStdString(instruction.getManeuverType()); QString modifier = QString::fromStdString(instruction.getManeuverModifier()); if (!type.isEmpty()) { QString fn = "direction_" + type; if (!modifier.isEmpty()) { fn += "_" + modifier; } fn = fn.replace(' ', '_'); bool rhd = is_rhd && (fn.contains("_left") || fn.contains("_right")); icon_01->setPixmap(pixmap_cache[!rhd ? fn : "rhd_" + fn]); icon_01->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); icon_01->setVisible(true); } else { icon_01->setVisible(false); } // Hide distance after arrival distance->setVisible(type != "arrive" || instruction.getManeuverDistance() > 0); // Show lanes auto lanes = instruction.getLanes(); for (int i = 0; i < lanes.size(); ++i) { bool active = lanes[i].getActive(); const auto active_direction = lanes[i].getActiveDirection(); // TODO: Make more images based on active direction and combined directions QString fn = "lane_direction_"; // active direction has precedence if (active && active_direction != cereal::NavInstruction::Direction::NONE) { fn += "turn_" + DIRECTIONS[active_direction]; } else { for (auto const &direction : lanes[i].getDirections()) { if (direction != cereal::NavInstruction::Direction::NONE) { fn += "turn_" + DIRECTIONS[direction]; break; } } } if (!active) { fn += "_inactive"; } QLabel *label = (i < lane_labels.size()) ? lane_labels[i] : lane_labels.emplace_back(new QLabel); if (!label->parentWidget()) { lane_layout->addWidget(label); } label->setPixmap(pixmap_cache[fn]); label->setVisible(true); } for (int i = lanes.size(); i < lane_labels.size(); ++i) { lane_labels[i]->setVisible(false); } setUpdatesEnabled(true); setVisible(true); }
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_instructions.cc
C++
mit
4,883
#pragma once #include <map> #include <vector> #include <QHash> #include <QHBoxLayout> #include <QLabel> #include "cereal/gen/cpp/log.capnp.h" static std::map<cereal::NavInstruction::Direction, QString> DIRECTIONS = { {cereal::NavInstruction::Direction::NONE, "none"}, {cereal::NavInstruction::Direction::LEFT, "left"}, {cereal::NavInstruction::Direction::RIGHT, "right"}, {cereal::NavInstruction::Direction::STRAIGHT, "straight"}, {cereal::NavInstruction::Direction::SLIGHT_LEFT, "slight_left"}, {cereal::NavInstruction::Direction::SLIGHT_RIGHT, "slight_right"}, }; class MapInstructions : public QWidget { Q_OBJECT private: QLabel *distance; QLabel *primary; QLabel *secondary; QLabel *icon_01; QHBoxLayout *lane_layout; bool is_rhd = false; std::vector<QLabel *> lane_labels; QHash<QString, QPixmap> pixmap_cache; public: MapInstructions(QWidget * parent=nullptr); void buildPixmapCache(); void updateInstructions(cereal::NavInstruction::Reader instruction); };
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_instructions.h
C++
mit
1,007
#include "selfdrive/ui/qt/maps/map_panel.h" #include <QHBoxLayout> #include <QWidget> #include "selfdrive/ui/qt/maps/map.h" #include "selfdrive/ui/qt/maps/map_settings.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/ui.h" MapPanel::MapPanel(const QMapLibre::Settings &mapboxSettings, QWidget *parent) : QFrame(parent) { content_stack = new QStackedLayout(this); content_stack->setContentsMargins(0, 0, 0, 0); auto map = new MapWindow(mapboxSettings); QObject::connect(uiState(), &UIState::offroadTransition, map, &MapWindow::offroadTransition); QObject::connect(device(), &Device::interactiveTimeout, this, [=]() { content_stack->setCurrentIndex(0); }); QObject::connect(map, &MapWindow::requestVisible, this, [=](bool visible) { // when we show the map for a new route, signal HomeWindow to hide the sidebar if (visible) { emit mapPanelRequested(); } setVisible(visible); }); QObject::connect(map, &MapWindow::requestSettings, this, [=](bool settings) { content_stack->setCurrentIndex(settings ? 1 : 0); }); content_stack->addWidget(map); auto settings = new MapSettings(true, parent); QObject::connect(settings, &MapSettings::closeSettings, this, [=]() { content_stack->setCurrentIndex(0); }); content_stack->addWidget(settings); } void MapPanel::toggleMapSettings() { // show settings if not visible, then toggle between map and settings int new_index = isVisible() ? (1 - content_stack->currentIndex()) : 1; content_stack->setCurrentIndex(new_index); emit mapPanelRequested(); show(); }
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_panel.cc
C++
mit
1,573
#pragma once #include <QFrame> #include <QMapLibre/Settings> #include <QStackedLayout> class MapPanel : public QFrame { Q_OBJECT public: explicit MapPanel(const QMapLibre::Settings &settings, QWidget *parent = nullptr); signals: void mapPanelRequested(); public slots: void toggleMapSettings(); private: QStackedLayout *content_stack; };
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_panel.h
C++
mit
354
#include "selfdrive/ui/qt/maps/map_settings.h" #include <utility> #include <QApplication> #include <QDebug> #include "common/util.h" #include "selfdrive/ui/qt/request_repeater.h" #include "selfdrive/ui/qt/widgets/scrollview.h" static void swap(QJsonValueRef v1, QJsonValueRef v2) { std::swap(v1, v2); } static bool locationEqual(const QJsonValue &v1, const QJsonValue &v2) { return v1["latitude"] == v2["latitude"] && v1["longitude"] == v2["longitude"]; } static qint64 convertTimestampToEpoch(const QString &timestamp) { QDateTime dt = QDateTime::fromString(timestamp, Qt::ISODate); return dt.isValid() ? dt.toSecsSinceEpoch() : 0; } MapSettings::MapSettings(bool closeable, QWidget *parent) : QFrame(parent) { setContentsMargins(0, 0, 0, 0); setAttribute(Qt::WA_NoMousePropagation); auto *frame = new QVBoxLayout(this); frame->setContentsMargins(40, 40, 40, 0); frame->setSpacing(0); auto *heading_frame = new QHBoxLayout; heading_frame->setContentsMargins(0, 0, 0, 0); heading_frame->setSpacing(32); { if (closeable) { auto *close_btn = new QPushButton("←"); close_btn->setStyleSheet(R"( QPushButton { color: #FFFFFF; font-size: 100px; padding-bottom: 8px; border 1px grey solid; border-radius: 70px; background-color: #292929; font-weight: 500; } QPushButton:pressed { background-color: #3B3B3B; } )"); close_btn->setFixedSize(140, 140); QObject::connect(close_btn, &QPushButton::clicked, [=]() { emit closeSettings(); }); // TODO: read map_on_left from ui state heading_frame->addWidget(close_btn); } auto *heading = new QVBoxLayout; heading->setContentsMargins(0, 0, 0, 0); heading->setSpacing(16); { auto *title = new QLabel(tr("NAVIGATION"), this); title->setStyleSheet("color: #FFFFFF; font-size: 54px; font-weight: 600;"); heading->addWidget(title); auto *subtitle = new QLabel(tr("Manage at connect.comma.ai"), this); subtitle->setStyleSheet("color: #A0A0A0; font-size: 40px; font-weight: 300;"); heading->addWidget(subtitle); } heading_frame->addLayout(heading, 1); } frame->addLayout(heading_frame); frame->addSpacing(32); current_widget = new DestinationWidget(this); QObject::connect(current_widget, &DestinationWidget::actionClicked, []() { NavManager::instance()->setCurrentDestination({}); }); frame->addWidget(current_widget); frame->addSpacing(32); QWidget *destinations_container = new QWidget(this); destinations_layout = new QVBoxLayout(destinations_container); destinations_layout->setContentsMargins(0, 32, 0, 32); destinations_layout->setSpacing(20); destinations_layout->addWidget(home_widget = new DestinationWidget(this)); destinations_layout->addWidget(work_widget = new DestinationWidget(this)); QObject::connect(home_widget, &DestinationWidget::navigateTo, this, &MapSettings::navigateTo); QObject::connect(work_widget, &DestinationWidget::navigateTo, this, &MapSettings::navigateTo); destinations_layout->addStretch(); ScrollView *destinations_scroller = new ScrollView(destinations_container, this); destinations_scroller->setFrameShape(QFrame::NoFrame); frame->addWidget(destinations_scroller); setStyleSheet("MapSettings { background-color: #333333; }"); QObject::connect(NavManager::instance(), &NavManager::updated, this, &MapSettings::refresh); } void MapSettings::showEvent(QShowEvent *event) { refresh(); } void MapSettings::refresh() { if (!isVisible()) return; setUpdatesEnabled(false); auto get_w = [this](int i) { auto w = i < widgets.size() ? widgets[i] : widgets.emplace_back(new DestinationWidget); if (!w->parentWidget()) { destinations_layout->insertWidget(destinations_layout->count() - 1, w); QObject::connect(w, &DestinationWidget::navigateTo, this, &MapSettings::navigateTo); } return w; }; const auto current_dest = NavManager::instance()->currentDestination(); if (!current_dest.isEmpty()) { current_widget->set(current_dest, true); } else { current_widget->unset("", true); } home_widget->unset(NAV_FAVORITE_LABEL_HOME); work_widget->unset(NAV_FAVORITE_LABEL_WORK); int n = 0; for (auto location : NavManager::instance()->currentLocations()) { DestinationWidget *w = nullptr; auto dest = location.toObject(); if (dest["save_type"].toString() == NAV_TYPE_FAVORITE) { auto label = dest["label"].toString(); if (label == NAV_FAVORITE_LABEL_HOME) w = home_widget; if (label == NAV_FAVORITE_LABEL_WORK) w = work_widget; } w = w ? w : get_w(n++); w->set(dest, false); w->setVisible(!locationEqual(dest, current_dest)); } for (; n < widgets.size(); ++n) widgets[n]->setVisible(false); setUpdatesEnabled(true); } void MapSettings::navigateTo(const QJsonObject &place) { NavManager::instance()->setCurrentDestination(place); emit closeSettings(); } DestinationWidget::DestinationWidget(QWidget *parent) : QPushButton(parent) { setContentsMargins(0, 0, 0, 0); auto *frame = new QHBoxLayout(this); frame->setContentsMargins(32, 24, 32, 24); frame->setSpacing(32); icon = new QLabel(this); icon->setAlignment(Qt::AlignCenter); icon->setFixedSize(96, 96); icon->setObjectName("icon"); frame->addWidget(icon); auto *inner_frame = new QVBoxLayout; inner_frame->setContentsMargins(0, 0, 0, 0); inner_frame->setSpacing(0); { title = new ElidedLabel(this); title->setAttribute(Qt::WA_TransparentForMouseEvents); inner_frame->addWidget(title); subtitle = new ElidedLabel(this); subtitle->setAttribute(Qt::WA_TransparentForMouseEvents); subtitle->setObjectName("subtitle"); inner_frame->addWidget(subtitle); } frame->addLayout(inner_frame, 1); action = new QPushButton(this); action->setFixedSize(96, 96); action->setObjectName("action"); action->setStyleSheet("font-size: 65px; font-weight: 600;"); QObject::connect(action, &QPushButton::clicked, this, &QPushButton::clicked); QObject::connect(action, &QPushButton::clicked, this, &DestinationWidget::actionClicked); frame->addWidget(action); setFixedHeight(164); setStyleSheet(R"( DestinationWidget { background-color: #202123; border-radius: 10px; } QLabel { color: #FFFFFF; font-size: 48px; font-weight: 400; } #icon { background-color: #3B4356; border-radius: 48px; } #subtitle { color: #9BA0A5; } #action { border: none; border-radius: 48px; color: #FFFFFF; padding-bottom: 4px; } /* current destination */ [current="true"] { background-color: #E8E8E8; } [current="true"] QLabel { color: #000000; } [current="true"] #icon { background-color: #42906B; } [current="true"] #subtitle { color: #333333; } [current="true"] #action { color: #202123; } /* no saved destination */ [set="false"] QLabel { color: #9BA0A5; } [current="true"][set="false"] QLabel { color: #A0000000; } /* pressed */ [current="false"]:pressed { background-color: #18191B; } [current="true"] #action:pressed { background-color: #D6D6D6; } )"); QObject::connect(this, &QPushButton::clicked, [this]() { if (!dest.isEmpty()) emit navigateTo(dest); }); } void DestinationWidget::set(const QJsonObject &destination, bool current) { if (dest == destination) return; dest = destination; setProperty("current", current); setProperty("set", true); auto icon_pixmap = current ? icons().directions : icons().recent; auto title_text = destination["place_name"].toString(); auto subtitle_text = destination["place_details"].toString(); if (destination["save_type"] == NAV_TYPE_FAVORITE) { if (destination["label"] == NAV_FAVORITE_LABEL_HOME) { icon_pixmap = icons().home; subtitle_text = title_text + ", " + subtitle_text; title_text = tr("Home"); } else if (destination["label"] == NAV_FAVORITE_LABEL_WORK) { icon_pixmap = icons().work; subtitle_text = title_text + ", " + subtitle_text; title_text = tr("Work"); } else { icon_pixmap = icons().favorite; } } icon->setPixmap(icon_pixmap); title->setText(title_text); subtitle->setText(subtitle_text); subtitle->setVisible(true); // TODO: use pixmap action->setAttribute(Qt::WA_TransparentForMouseEvents, !current); action->setText(current ? "×" : "→"); action->setVisible(true); setStyleSheet(styleSheet()); } void DestinationWidget::unset(const QString &label, bool current) { dest = {}; setProperty("current", current); setProperty("set", false); if (label.isEmpty()) { icon->setPixmap(icons().directions); title->setText(tr("No destination set")); } else { QString title_text = label == NAV_FAVORITE_LABEL_HOME ? tr("home") : tr("work"); icon->setPixmap(label == NAV_FAVORITE_LABEL_HOME ? icons().home : icons().work); title->setText(tr("No %1 location set").arg(title_text)); } subtitle->setVisible(false); action->setVisible(false); setStyleSheet(styleSheet()); setVisible(true); } // singleton NavManager NavManager *NavManager::instance() { static NavManager *request = new NavManager(qApp); return request; } NavManager::NavManager(QObject *parent) : QObject(parent) { locations = QJsonDocument::fromJson(params.get("NavPastDestinations").c_str()).array(); current_dest = QJsonDocument::fromJson(params.get("NavDestination").c_str()).object(); if (auto dongle_id = getDongleId()) { { // Fetch favorite and recent locations QString url = CommaApi::BASE_URL + "/v1/navigation/" + *dongle_id + "/locations"; RequestRepeater *repeater = new RequestRepeater(this, url, "ApiCache_NavDestinations", 30, true); QObject::connect(repeater, &RequestRepeater::requestDone, this, &NavManager::parseLocationsResponse); } { auto param_watcher = new ParamWatcher(this); QObject::connect(param_watcher, &ParamWatcher::paramChanged, this, &NavManager::updated); // Destination set while offline QString url = CommaApi::BASE_URL + "/v1/navigation/" + *dongle_id + "/next"; HttpRequest *deleter = new HttpRequest(this); RequestRepeater *repeater = new RequestRepeater(this, url, "", 10, true); QObject::connect(repeater, &RequestRepeater::requestDone, [=](const QString &resp, bool success) { if (success && resp != "null") { if (params.get("NavDestination").empty()) { qWarning() << "Setting NavDestination from /next" << resp; params.put("NavDestination", resp.toStdString()); } else { qWarning() << "Got location from /next, but NavDestination already set"; } // Send DELETE to clear destination server side deleter->sendRequest(url, HttpRequest::Method::DELETE); } // athena can set destination at any time param_watcher->addParam("NavDestination"); current_dest = QJsonDocument::fromJson(params.get("NavDestination").c_str()).object(); emit updated(); }); } } } void NavManager::parseLocationsResponse(const QString &response, bool success) { if (!success || response == prev_response) return; prev_response = response; QJsonDocument doc = QJsonDocument::fromJson(response.trimmed().toUtf8()); if (doc.isNull()) { qWarning() << "JSON Parse failed on navigation locations" << response; return; } // set last activity time. auto remote_locations = doc.array(); for (QJsonValueRef loc : remote_locations) { auto obj = loc.toObject(); auto serverTime = convertTimestampToEpoch(obj["modified"].toString()); obj.insert("time", qMax(serverTime, getLastActivity(obj))); loc = obj; } locations = remote_locations; sortLocations(); emit updated(); } void NavManager::sortLocations() { // Sort: alphabetical FAVORITES, and then most recent. // We don't need to care about the ordering of HOME and WORK. DestinationWidget always displays them at the top. std::stable_sort(locations.begin(), locations.end(), [](const QJsonValue &a, const QJsonValue &b) { if (a["save_type"] == NAV_TYPE_FAVORITE || b["save_type"] == NAV_TYPE_FAVORITE) { return (std::tuple(a["save_type"].toString(), a["place_name"].toString()) < std::tuple(b["save_type"].toString(), b["place_name"].toString())); } else { return a["time"].toVariant().toLongLong() > b["time"].toVariant().toLongLong(); } }); write_param_future = std::async(std::launch::async, [destinations = QJsonArray(locations)]() { Params().put("NavPastDestinations", QJsonDocument(destinations).toJson().toStdString()); }); } qint64 NavManager::getLastActivity(const QJsonObject &loc) const { qint64 last_activity = 0; auto it = std::find_if(locations.begin(), locations.end(), [&loc](const QJsonValue &l) { return locationEqual(loc, l); }); if (it != locations.end()) { auto tm = it->toObject().value("time"); if (!tm.isUndefined() && !tm.isNull()) { last_activity = tm.toVariant().toLongLong(); } } return last_activity; } void NavManager::setCurrentDestination(const QJsonObject &loc) { current_dest = loc; if (!current_dest.isEmpty()) { current_dest["time"] = QDateTime::currentSecsSinceEpoch(); auto it = std::find_if(locations.begin(), locations.end(), [&loc](const QJsonValue &l) { return locationEqual(loc, l); }); if (it != locations.end()) { *it = current_dest; sortLocations(); } params.put("NavDestination", QJsonDocument(current_dest).toJson().toStdString()); } else { params.remove("NavDestination"); } emit updated(); }
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_settings.cc
C++
mit
13,787
#pragma once #include <future> #include <vector> #include <QFrame> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> #include "common/params.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/controls.h" const QString NAV_TYPE_FAVORITE = "favorite"; const QString NAV_TYPE_RECENT = "recent"; const QString NAV_FAVORITE_LABEL_HOME = "home"; const QString NAV_FAVORITE_LABEL_WORK = "work"; class DestinationWidget; class NavManager : public QObject { Q_OBJECT public: static NavManager *instance(); QJsonArray currentLocations() const { return locations; } QJsonObject currentDestination() const { return current_dest; } void setCurrentDestination(const QJsonObject &loc); qint64 getLastActivity(const QJsonObject &loc) const; signals: void updated(); private: NavManager(QObject *parent); void parseLocationsResponse(const QString &response, bool success); void sortLocations(); Params params; QString prev_response; QJsonArray locations; QJsonObject current_dest; std::future<void> write_param_future; }; class MapSettings : public QFrame { Q_OBJECT public: explicit MapSettings(bool closeable = false, QWidget *parent = nullptr); void navigateTo(const QJsonObject &place); private: void showEvent(QShowEvent *event) override; void refresh(); QVBoxLayout *destinations_layout; DestinationWidget *current_widget; DestinationWidget *home_widget; DestinationWidget *work_widget; std::vector<DestinationWidget *> widgets; signals: void closeSettings(); }; class DestinationWidget : public QPushButton { Q_OBJECT public: explicit DestinationWidget(QWidget *parent = nullptr); void set(const QJsonObject &location, bool current = false); void unset(const QString &label, bool current = false); signals: void actionClicked(); void navigateTo(const QJsonObject &destination); private: struct NavIcons { QPixmap home, work, favorite, recent, directions; }; static NavIcons icons() { static NavIcons nav_icons { loadPixmap("../assets/navigation/icon_home.svg", {48, 48}), loadPixmap("../assets/navigation/icon_work.svg", {48, 48}), loadPixmap("../assets/navigation/icon_favorite.svg", {48, 48}), loadPixmap("../assets/navigation/icon_recent.svg", {48, 48}), loadPixmap("../assets/navigation/icon_directions.svg", {48, 48}), }; return nav_icons; } private: QLabel *icon, *title, *subtitle; QPushButton *action; QJsonObject dest; };
2301_81045437/openpilot
selfdrive/ui/qt/maps/map_settings.h
C++
mit
2,569
#include "selfdrive/ui/qt/network/networking.h" #include <algorithm> #include <QHBoxLayout> #include <QScrollBar> #include <QStyle> #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/controls.h" #include "selfdrive/ui/qt/widgets/scrollview.h" static const int ICON_WIDTH = 49; // Networking functions Networking::Networking(QWidget* parent, bool show_advanced) : QFrame(parent) { main_layout = new QStackedLayout(this); wifi = new WifiManager(this); connect(wifi, &WifiManager::refreshSignal, this, &Networking::refresh); connect(wifi, &WifiManager::wrongPassword, this, &Networking::wrongPassword); wifiScreen = new QWidget(this); QVBoxLayout* vlayout = new QVBoxLayout(wifiScreen); vlayout->setContentsMargins(20, 20, 20, 20); if (show_advanced) { QPushButton* advancedSettings = new QPushButton(tr("Advanced")); advancedSettings->setObjectName("advanced_btn"); advancedSettings->setStyleSheet("margin-right: 30px;"); advancedSettings->setFixedSize(400, 100); connect(advancedSettings, &QPushButton::clicked, [=]() { main_layout->setCurrentWidget(an); }); vlayout->addSpacing(10); vlayout->addWidget(advancedSettings, 0, Qt::AlignRight); vlayout->addSpacing(10); } wifiWidget = new WifiUI(this, wifi); wifiWidget->setObjectName("wifiWidget"); connect(wifiWidget, &WifiUI::connectToNetwork, this, &Networking::connectToNetwork); ScrollView *wifiScroller = new ScrollView(wifiWidget, this); wifiScroller->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); vlayout->addWidget(wifiScroller, 1); main_layout->addWidget(wifiScreen); an = new AdvancedNetworking(this, wifi); connect(an, &AdvancedNetworking::backPress, [=]() { main_layout->setCurrentWidget(wifiScreen); }); connect(an, &AdvancedNetworking::requestWifiScreen, [=]() { main_layout->setCurrentWidget(wifiScreen); }); main_layout->addWidget(an); QPalette pal = palette(); pal.setColor(QPalette::Window, QColor(0x29, 0x29, 0x29)); setAutoFillBackground(true); setPalette(pal); setStyleSheet(R"( #wifiWidget > QPushButton, #back_btn, #advanced_btn { font-size: 50px; margin: 0px; padding: 15px; border-width: 0; border-radius: 30px; color: #dddddd; background-color: #393939; } #back_btn:pressed, #advanced_btn:pressed { background-color: #4a4a4a; } )"); main_layout->setCurrentWidget(wifiScreen); } void Networking::refresh() { wifiWidget->refresh(); an->refresh(); } void Networking::connectToNetwork(const Network n) { if (wifi->isKnownConnection(n.ssid)) { wifi->activateWifiConnection(n.ssid); } else if (n.security_type == SecurityType::OPEN) { wifi->connect(n, false); } else if (n.security_type == SecurityType::WPA) { QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); if (!pass.isEmpty()) { wifi->connect(n, false, pass); } } } void Networking::wrongPassword(const QString &ssid) { if (wifi->seenNetworks.contains(ssid)) { const Network &n = wifi->seenNetworks.value(ssid); QString pass = InputDialog::getText(tr("Wrong password"), this, tr("for \"%1\"").arg(QString::fromUtf8(n.ssid)), true, 8); if (!pass.isEmpty()) { wifi->connect(n, false, pass); } } } void Networking::showEvent(QShowEvent *event) { wifi->start(); } void Networking::hideEvent(QHideEvent *event) { main_layout->setCurrentWidget(wifiScreen); wifi->stop(); } // AdvancedNetworking functions AdvancedNetworking::AdvancedNetworking(QWidget* parent, WifiManager* wifi): QWidget(parent), wifi(wifi) { QVBoxLayout* main_layout = new QVBoxLayout(this); main_layout->setMargin(40); main_layout->setSpacing(20); // Back button QPushButton* back = new QPushButton(tr("Back")); back->setObjectName("back_btn"); back->setFixedSize(400, 100); connect(back, &QPushButton::clicked, [=]() { emit backPress(); }); main_layout->addWidget(back, 0, Qt::AlignLeft); ListWidget *list = new ListWidget(this); // Enable tethering layout tetheringToggle = new ToggleControl(tr("Enable Tethering"), "", "", wifi->isTetheringEnabled()); list->addItem(tetheringToggle); QObject::connect(tetheringToggle, &ToggleControl::toggleFlipped, this, &AdvancedNetworking::toggleTethering); // Change tethering password ButtonControl *editPasswordButton = new ButtonControl(tr("Tethering Password"), tr("EDIT")); connect(editPasswordButton, &ButtonControl::clicked, [=]() { QString pass = InputDialog::getText(tr("Enter new tethering password"), this, "", true, 8, wifi->getTetheringPassword()); if (!pass.isEmpty()) { wifi->changeTetheringPassword(pass); } }); list->addItem(editPasswordButton); // IP address ipLabel = new LabelControl(tr("IP Address"), wifi->ipv4_address); list->addItem(ipLabel); // SSH keys list->addItem(new SshToggle()); list->addItem(new SshControl()); // Roaming toggle const bool roamingEnabled = params.getBool("GsmRoaming"); roamingToggle = new ToggleControl(tr("Enable Roaming"), "", "", roamingEnabled); QObject::connect(roamingToggle, &ToggleControl::toggleFlipped, [=](bool state) { params.putBool("GsmRoaming", state); wifi->updateGsmSettings(state, QString::fromStdString(params.get("GsmApn")), params.getBool("GsmMetered")); }); list->addItem(roamingToggle); // APN settings editApnButton = new ButtonControl(tr("APN Setting"), tr("EDIT")); connect(editApnButton, &ButtonControl::clicked, [=]() { const QString cur_apn = QString::fromStdString(params.get("GsmApn")); QString apn = InputDialog::getText(tr("Enter APN"), this, tr("leave blank for automatic configuration"), false, -1, cur_apn).trimmed(); if (apn.isEmpty()) { params.remove("GsmApn"); } else { params.put("GsmApn", apn.toStdString()); } wifi->updateGsmSettings(params.getBool("GsmRoaming"), apn, params.getBool("GsmMetered")); }); list->addItem(editApnButton); // Metered toggle const bool metered = params.getBool("GsmMetered"); meteredToggle = new ToggleControl(tr("Cellular Metered"), tr("Prevent large data uploads when on a metered connection"), "", metered); QObject::connect(meteredToggle, &SshToggle::toggleFlipped, [=](bool state) { params.putBool("GsmMetered", state); wifi->updateGsmSettings(params.getBool("GsmRoaming"), QString::fromStdString(params.get("GsmApn")), state); }); list->addItem(meteredToggle); // Hidden Network hiddenNetworkButton = new ButtonControl(tr("Hidden Network"), tr("CONNECT")); connect(hiddenNetworkButton, &ButtonControl::clicked, [=]() { QString ssid = InputDialog::getText(tr("Enter SSID"), this, "", false, 1); if (!ssid.isEmpty()) { QString pass = InputDialog::getText(tr("Enter password"), this, tr("for \"%1\"").arg(ssid), true, -1); Network hidden_network; hidden_network.ssid = ssid.toUtf8(); if (!pass.isEmpty()) { hidden_network.security_type = SecurityType::WPA; wifi->connect(hidden_network, true, pass); } else { wifi->connect(hidden_network, true); } emit requestWifiScreen(); } }); list->addItem(hiddenNetworkButton); // Set initial config wifi->updateGsmSettings(roamingEnabled, QString::fromStdString(params.get("GsmApn")), metered); connect(uiState(), &UIState::primeTypeChanged, this, [=](PrimeType prime_type) { bool gsmVisible = prime_type == PrimeType::NONE || prime_type == PrimeType::LITE; roamingToggle->setVisible(gsmVisible); editApnButton->setVisible(gsmVisible); meteredToggle->setVisible(gsmVisible); }); main_layout->addWidget(new ScrollView(list, this)); main_layout->addStretch(1); } void AdvancedNetworking::refresh() { ipLabel->setText(wifi->ipv4_address); tetheringToggle->setEnabled(true); update(); } void AdvancedNetworking::toggleTethering(bool enabled) { wifi->setTetheringEnabled(enabled); tetheringToggle->setEnabled(false); } // WifiUI functions WifiUI::WifiUI(QWidget *parent, WifiManager* wifi) : QWidget(parent), wifi(wifi) { QVBoxLayout *main_layout = new QVBoxLayout(this); main_layout->setContentsMargins(0, 0, 0, 0); main_layout->setSpacing(0); // load imgs for (const auto &s : {"low", "medium", "high", "full"}) { QPixmap pix(ASSET_PATH + "/offroad/icon_wifi_strength_" + s + ".svg"); strengths.push_back(pix.scaledToHeight(68, Qt::SmoothTransformation)); } lock = QPixmap(ASSET_PATH + "offroad/icon_lock_closed.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); checkmark = QPixmap(ASSET_PATH + "offroad/icon_checkmark.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); circled_slash = QPixmap(ASSET_PATH + "img_circled_slash.svg").scaledToWidth(ICON_WIDTH, Qt::SmoothTransformation); scanningLabel = new QLabel(tr("Scanning for networks...")); scanningLabel->setStyleSheet("font-size: 65px;"); main_layout->addWidget(scanningLabel, 0, Qt::AlignCenter); wifi_list_widget = new ListWidget(this); wifi_list_widget->setVisible(false); main_layout->addWidget(wifi_list_widget); setStyleSheet(R"( QScrollBar::handle:vertical { min-height: 0px; border-radius: 4px; background-color: #8A8A8A; } #forgetBtn { font-size: 32px; font-weight: 600; color: #292929; background-color: #BDBDBD; border-width: 1px solid #828282; border-radius: 5px; padding: 40px; padding-bottom: 16px; padding-top: 16px; } #forgetBtn:pressed { background-color: #828282; } #connecting { font-size: 32px; font-weight: 600; color: white; border-radius: 0; padding: 27px; padding-left: 43px; padding-right: 43px; background-color: black; } #ssidLabel { text-align: left; border: none; padding-top: 50px; padding-bottom: 50px; } #ssidLabel:disabled { color: #696969; } )"); } void WifiUI::refresh() { bool is_empty = wifi->seenNetworks.isEmpty(); scanningLabel->setVisible(is_empty); wifi_list_widget->setVisible(!is_empty); if (is_empty) return; setUpdatesEnabled(false); const bool is_tethering_enabled = wifi->isTetheringEnabled(); QList<Network> sortedNetworks = wifi->seenNetworks.values(); std::sort(sortedNetworks.begin(), sortedNetworks.end(), compare_by_strength); int n = 0; for (Network &network : sortedNetworks) { QPixmap status_icon; if (network.connected == ConnectedType::CONNECTED) { status_icon = checkmark; } else if (network.security_type == SecurityType::UNSUPPORTED) { status_icon = circled_slash; } else if (network.security_type == SecurityType::WPA) { status_icon = lock; } bool show_forget_btn = wifi->isKnownConnection(network.ssid) && !is_tethering_enabled; QPixmap strength = strengths[strengthLevel(network.strength)]; auto item = getItem(n++); item->setItem(network, status_icon, show_forget_btn, strength); item->setVisible(true); } for (; n < wifi_items.size(); ++n) wifi_items[n]->setVisible(false); setUpdatesEnabled(true); } WifiItem *WifiUI::getItem(int n) { auto item = n < wifi_items.size() ? wifi_items[n] : wifi_items.emplace_back(new WifiItem(tr("CONNECTING..."), tr("FORGET"))); if (!item->parentWidget()) { QObject::connect(item, &WifiItem::connectToNetwork, this, &WifiUI::connectToNetwork); QObject::connect(item, &WifiItem::forgotNetwork, [this](const Network n) { if (ConfirmationDialog::confirm(tr("Forget Wi-Fi Network \"%1\"?").arg(QString::fromUtf8(n.ssid)), tr("Forget"), this)) wifi->forgetConnection(n.ssid); }); wifi_list_widget->addItem(item); } return item; } // WifiItem WifiItem::WifiItem(const QString &connecting_text, const QString &forget_text, QWidget *parent) : QWidget(parent) { QHBoxLayout *hlayout = new QHBoxLayout(this); hlayout->setContentsMargins(44, 0, 73, 0); hlayout->setSpacing(50); hlayout->addWidget(ssidLabel = new ElidedLabel()); ssidLabel->setObjectName("ssidLabel"); ssidLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); hlayout->addWidget(connecting = new QPushButton(connecting_text), 0, Qt::AlignRight); connecting->setObjectName("connecting"); hlayout->addWidget(forgetBtn = new QPushButton(forget_text), 0, Qt::AlignRight); forgetBtn->setObjectName("forgetBtn"); hlayout->addWidget(iconLabel = new QLabel(), 0, Qt::AlignRight); hlayout->addWidget(strengthLabel = new QLabel(), 0, Qt::AlignRight); iconLabel->setFixedWidth(ICON_WIDTH); QObject::connect(forgetBtn, &QPushButton::clicked, [this]() { emit forgotNetwork(network); }); QObject::connect(ssidLabel, &ElidedLabel::clicked, [this]() { if (network.connected == ConnectedType::DISCONNECTED) emit connectToNetwork(network); }); } void WifiItem::setItem(const Network &n, const QPixmap &status_icon, bool show_forget_btn, const QPixmap &strength_icon) { network = n; ssidLabel->setText(n.ssid); ssidLabel->setEnabled(n.security_type != SecurityType::UNSUPPORTED); ssidLabel->setFont(InterFont(55, network.connected == ConnectedType::DISCONNECTED ? QFont::Normal : QFont::Bold)); connecting->setVisible(n.connected == ConnectedType::CONNECTING); forgetBtn->setVisible(show_forget_btn); iconLabel->setPixmap(status_icon); strengthLabel->setPixmap(strength_icon); }
2301_81045437/openpilot
selfdrive/ui/qt/network/networking.cc
C++
mit
13,530
#pragma once #include <vector> #include "selfdrive/ui/qt/network/wifi_manager.h" #include "selfdrive/ui/qt/widgets/input.h" #include "selfdrive/ui/qt/widgets/ssh_keys.h" #include "selfdrive/ui/qt/widgets/toggle.h" class WifiItem : public QWidget { Q_OBJECT public: explicit WifiItem(const QString &connecting_text, const QString &forget_text, QWidget* parent = nullptr); void setItem(const Network& n, const QPixmap &icon, bool show_forget_btn, const QPixmap &strength); signals: // Cannot pass Network by reference. it may change after the signal is sent. void connectToNetwork(const Network n); void forgotNetwork(const Network n); protected: ElidedLabel* ssidLabel; QPushButton* connecting; QPushButton* forgetBtn; QLabel* iconLabel; QLabel* strengthLabel; Network network; }; class WifiUI : public QWidget { Q_OBJECT public: explicit WifiUI(QWidget *parent = 0, WifiManager* wifi = 0); private: WifiItem *getItem(int n); WifiManager *wifi = nullptr; QLabel *scanningLabel = nullptr; QPixmap lock; QPixmap checkmark; QPixmap circled_slash; QVector<QPixmap> strengths; ListWidget *wifi_list_widget = nullptr; std::vector<WifiItem*> wifi_items; signals: void connectToNetwork(const Network n); public slots: void refresh(); }; class AdvancedNetworking : public QWidget { Q_OBJECT public: explicit AdvancedNetworking(QWidget* parent = 0, WifiManager* wifi = 0); private: LabelControl* ipLabel; ToggleControl* tetheringToggle; ToggleControl* roamingToggle; ButtonControl* editApnButton; ButtonControl* hiddenNetworkButton; ToggleControl* meteredToggle; WifiManager* wifi = nullptr; Params params; signals: void backPress(); void requestWifiScreen(); public slots: void toggleTethering(bool enabled); void refresh(); }; class Networking : public QFrame { Q_OBJECT public: explicit Networking(QWidget* parent = 0, bool show_advanced = true); WifiManager* wifi = nullptr; private: QStackedLayout* main_layout = nullptr; QWidget* wifiScreen = nullptr; AdvancedNetworking* an = nullptr; WifiUI* wifiWidget; void showEvent(QShowEvent* event) override; void hideEvent(QHideEvent* event) override; public slots: void refresh(); private slots: void connectToNetwork(const Network n); void wrongPassword(const QString &ssid); };
2301_81045437/openpilot
selfdrive/ui/qt/network/networking.h
C++
mit
2,341
#pragma once /** * We are using a NetworkManager DBUS API : https://developer.gnome.org/NetworkManager/1.26/spec.html * */ // https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApFlags const int NM_802_11_AP_FLAGS_NONE = 0x00000000; const int NM_802_11_AP_FLAGS_PRIVACY = 0x00000001; const int NM_802_11_AP_FLAGS_WPS = 0x00000002; // https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NM80211ApSecurityFlags const int NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001; const int NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002; const int NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010; const int NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020; const int NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100; const int NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200; const QString NM_DBUS_PATH = "/org/freedesktop/NetworkManager"; const QString NM_DBUS_PATH_SETTINGS = "/org/freedesktop/NetworkManager/Settings"; const QString NM_DBUS_INTERFACE = "org.freedesktop.NetworkManager"; const QString NM_DBUS_INTERFACE_PROPERTIES = "org.freedesktop.DBus.Properties"; const QString NM_DBUS_INTERFACE_SETTINGS = "org.freedesktop.NetworkManager.Settings"; const QString NM_DBUS_INTERFACE_SETTINGS_CONNECTION = "org.freedesktop.NetworkManager.Settings.Connection"; const QString NM_DBUS_INTERFACE_DEVICE = "org.freedesktop.NetworkManager.Device"; const QString NM_DBUS_INTERFACE_DEVICE_WIRELESS = "org.freedesktop.NetworkManager.Device.Wireless"; const QString NM_DBUS_INTERFACE_ACCESS_POINT = "org.freedesktop.NetworkManager.AccessPoint"; const QString NM_DBUS_INTERFACE_ACTIVE_CONNECTION = "org.freedesktop.NetworkManager.Connection.Active"; const QString NM_DBUS_INTERFACE_IP4_CONFIG = "org.freedesktop.NetworkManager.IP4Config"; const QString NM_DBUS_SERVICE = "org.freedesktop.NetworkManager"; const int NM_DEVICE_STATE_UNKNOWN = 0; const int NM_DEVICE_STATE_ACTIVATED = 100; const int NM_DEVICE_STATE_NEED_AUTH = 60; const int NM_DEVICE_TYPE_WIFI = 2; const int NM_DEVICE_TYPE_MODEM = 8; const int NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8; const int DBUS_TIMEOUT = 100; // https://developer-old.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMMetered const int NM_METERED_UNKNOWN = 0; const int NM_METERED_YES = 1; const int NM_METERED_NO = 2; const int NM_METERED_GUESS_YES = 3; const int NM_METERED_GUESS_NO = 4;
2301_81045437/openpilot
selfdrive/ui/qt/network/networkmanager.h
C
mit
2,509
#include "selfdrive/ui/qt/network/wifi_manager.h" #include <utility> #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/widgets/prime.h" #include "common/params.h" #include "common/swaglog.h" #include "selfdrive/ui/qt/util.h" bool compare_by_strength(const Network &a, const Network &b) { return std::tuple(a.connected, strengthLevel(a.strength), b.ssid) > std::tuple(b.connected, strengthLevel(b.strength), a.ssid); } template <typename T = QDBusMessage, typename... Args> T call(const QString &path, const QString &interface, const QString &method, Args &&...args) { QDBusInterface nm(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); nm.setTimeout(DBUS_TIMEOUT); QDBusMessage response = nm.call(method, std::forward<Args>(args)...); if (response.type() == QDBusMessage::ErrorMessage) { qCritical() << "DBus call error:" << response.errorMessage(); return T(); } if constexpr (std::is_same_v<T, QDBusMessage>) { return response; } else if (response.arguments().count() >= 1) { QVariant vFirst = response.arguments().at(0).value<QDBusVariant>().variant(); if (vFirst.canConvert<T>()) { return vFirst.value<T>(); } QDebug critical = qCritical(); critical << "Variant unpacking failure :" << method << ','; (critical << ... << args); } return T(); } template <typename... Args> QDBusPendingCall asyncCall(const QString &path, const QString &interface, const QString &method, Args &&...args) { QDBusInterface nm = QDBusInterface(NM_DBUS_SERVICE, path, interface, QDBusConnection::systemBus()); return nm.asyncCall(method, args...); } bool emptyPath(const QString &path) { return path == "" || path == "/"; } WifiManager::WifiManager(QObject *parent) : QObject(parent) { qDBusRegisterMetaType<Connection>(); qDBusRegisterMetaType<IpConfig>(); // Set tethering ssid as "weedle" + first 4 characters of a dongle id tethering_ssid = "weedle"; if (auto dongle_id = getDongleId()) { tethering_ssid += "-" + dongle_id->left(4); } adapter = getAdapter(); if (!adapter.isEmpty()) { setup(); } else { QDBusConnection::systemBus().connect(NM_DBUS_SERVICE, NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeviceAdded", this, SLOT(deviceAdded(QDBusObjectPath))); } timer.callOnTimeout(this, &WifiManager::requestScan); initConnections(); } void WifiManager::setup() { auto bus = QDBusConnection::systemBus(); bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_DEVICE, "StateChanged", this, SLOT(stateChange(unsigned int, unsigned int, unsigned int))); bus.connect(NM_DBUS_SERVICE, adapter, NM_DBUS_INTERFACE_PROPERTIES, "PropertiesChanged", this, SLOT(propertyChange(QString, QVariantMap, QStringList))); bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ConnectionRemoved", this, SLOT(connectionRemoved(QDBusObjectPath))); bus.connect(NM_DBUS_SERVICE, NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "NewConnection", this, SLOT(newConnection(QDBusObjectPath))); raw_adapter_state = call<uint>(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "State"); activeAp = call<QDBusObjectPath>(adapter, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE_WIRELESS, "ActiveAccessPoint").path(); requestScan(); } void WifiManager::start() { timer.start(5000); refreshNetworks(); } void WifiManager::stop() { timer.stop(); } void WifiManager::refreshNetworks() { if (adapter.isEmpty() || !timer.isActive()) return; QDBusPendingCall pending_call = asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "GetAllAccessPoints"); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pending_call); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::refreshFinished); } void WifiManager::refreshFinished(QDBusPendingCallWatcher *watcher) { ipv4_address = getIp4Address(); seenNetworks.clear(); const QDBusReply<QList<QDBusObjectPath>> watcher_reply = *watcher; if (!watcher_reply.isValid()) { qCritical() << "Failed to refresh"; watcher->deleteLater(); return; } for (const QDBusObjectPath &path : watcher_reply.value()) { QDBusReply<QVariantMap> reply = call(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "GetAll", NM_DBUS_INTERFACE_ACCESS_POINT); if (!reply.isValid()) { qCritical() << "Failed to retrieve properties for path:" << path.path(); continue; } auto properties = reply.value(); const QByteArray ssid = properties["Ssid"].toByteArray(); if (ssid.isEmpty()) continue; // May be multiple access points for each SSID. // Use first for ssid and security type, then update connected status and strength using all if (!seenNetworks.contains(ssid)) { seenNetworks[ssid] = {ssid, 0U, ConnectedType::DISCONNECTED, getSecurityType(properties)}; } if (path.path() == activeAp) { seenNetworks[ssid].connected = (ssid == connecting_to_network) ? ConnectedType::CONNECTING : ConnectedType::CONNECTED; } uint32_t strength = properties["Strength"].toUInt(); if (seenNetworks[ssid].strength < strength) { seenNetworks[ssid].strength = strength; } } emit refreshSignal(); watcher->deleteLater(); } QString WifiManager::getIp4Address() { if (raw_adapter_state != NM_DEVICE_STATE_ACTIVATED) return ""; for (const auto &p : getActiveConnections()) { QString type = call<QString>(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); if (type == "802-11-wireless") { auto ip4config = call<QDBusObjectPath>(p.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Ip4Config"); const auto &arr = call<QDBusArgument>(ip4config.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_IP4_CONFIG, "AddressData"); QVariantMap path; arr.beginArray(); while (!arr.atEnd()) { arr >> path; arr.endArray(); return path.value("address").value<QString>(); } arr.endArray(); } } return ""; } SecurityType WifiManager::getSecurityType(const QVariantMap &properties) { int sflag = properties["Flags"].toUInt(); int wpaflag = properties["WpaFlags"].toUInt(); int rsnflag = properties["RsnFlags"].toUInt(); int wpa_props = wpaflag | rsnflag; // obtained by looking at flags of networks in the office as reported by an Android phone const int supports_wpa = NM_802_11_AP_SEC_PAIR_WEP40 | NM_802_11_AP_SEC_PAIR_WEP104 | NM_802_11_AP_SEC_GROUP_WEP40 | NM_802_11_AP_SEC_GROUP_WEP104 | NM_802_11_AP_SEC_KEY_MGMT_PSK; if ((sflag == NM_802_11_AP_FLAGS_NONE) || ((sflag & NM_802_11_AP_FLAGS_WPS) && !(wpa_props & supports_wpa))) { return SecurityType::OPEN; } else if ((sflag & NM_802_11_AP_FLAGS_PRIVACY) && (wpa_props & supports_wpa) && !(wpa_props & NM_802_11_AP_SEC_KEY_MGMT_802_1X)) { return SecurityType::WPA; } else { LOGW("Unsupported network! sflag: %d, wpaflag: %d, rsnflag: %d", sflag, wpaflag, rsnflag); return SecurityType::UNSUPPORTED; } } void WifiManager::connect(const Network &n, const bool is_hidden, const QString &password, const QString &username) { setCurrentConnecting(n.ssid); forgetConnection(n.ssid); // Clear all connections that may already exist to the network we are connecting Connection connection; connection["connection"]["type"] = "802-11-wireless"; connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); connection["connection"]["id"] = "openpilot connection " + QString::fromStdString(n.ssid.toStdString()); connection["connection"]["autoconnect-retries"] = 0; connection["802-11-wireless"]["ssid"] = n.ssid; connection["802-11-wireless"]["hidden"] = is_hidden; connection["802-11-wireless"]["mode"] = "infrastructure"; if (n.security_type == SecurityType::WPA) { connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; connection["802-11-wireless-security"]["auth-alg"] = "open"; connection["802-11-wireless-security"]["psk"] = password; } connection["ipv4"]["method"] = "auto"; connection["ipv4"]["dns-priority"] = 600; connection["ipv6"]["method"] = "ignore"; call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); } void WifiManager::deactivateConnectionBySsid(const QString &ssid) { for (QDBusObjectPath active_connection : getActiveConnections()) { auto pth = call<QDBusObjectPath>(active_connection.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "SpecificObject"); if (!emptyPath(pth.path())) { QString Ssid = get_property(pth.path(), "Ssid"); if (Ssid == ssid) { deactivateConnection(active_connection); return; } } } } void WifiManager::deactivateConnection(const QDBusObjectPath &path) { asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "DeactivateConnection", QVariant::fromValue(path)); } QVector<QDBusObjectPath> WifiManager::getActiveConnections() { auto result = call<QDBusArgument>(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "ActiveConnections"); return qdbus_cast<QVector<QDBusObjectPath>>(result); } bool WifiManager::isKnownConnection(const QString &ssid) { return !getConnectionPath(ssid).path().isEmpty(); } void WifiManager::forgetConnection(const QString &ssid) { const QDBusObjectPath &path = getConnectionPath(ssid); if (!path.path().isEmpty()) { call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Delete"); } } void WifiManager::setCurrentConnecting(const QString &ssid) { connecting_to_network = ssid; for (auto &network : seenNetworks) { network.connected = (network.ssid == ssid) ? ConnectedType::CONNECTING : ConnectedType::DISCONNECTED; } emit refreshSignal(); } uint WifiManager::getAdapterType(const QDBusObjectPath &path) { return call<uint>(path.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_DEVICE, "DeviceType"); } void WifiManager::requestScan() { if (!adapter.isEmpty()) { asyncCall(adapter, NM_DBUS_INTERFACE_DEVICE_WIRELESS, "RequestScan", QVariantMap()); } } QByteArray WifiManager::get_property(const QString &network_path , const QString &property) { return call<QByteArray>(network_path, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACCESS_POINT, property); } QString WifiManager::getAdapter(const uint adapter_type) { QDBusReply<QList<QDBusObjectPath>> response = call(NM_DBUS_PATH, NM_DBUS_INTERFACE, "GetDevices"); for (const QDBusObjectPath &path : response.value()) { if (getAdapterType(path) == adapter_type) { return path.path(); } } return ""; } void WifiManager::stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason) { raw_adapter_state = new_state; if (new_state == NM_DEVICE_STATE_NEED_AUTH && change_reason == NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT && !connecting_to_network.isEmpty()) { forgetConnection(connecting_to_network); emit wrongPassword(connecting_to_network); } else if (new_state == NM_DEVICE_STATE_ACTIVATED) { connecting_to_network = ""; refreshNetworks(); } } // https://developer.gnome.org/NetworkManager/stable/gdbus-org.freedesktop.NetworkManager.Device.Wireless.html void WifiManager::propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props) { if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("LastScan")) { refreshNetworks(); } else if (interface == NM_DBUS_INTERFACE_DEVICE_WIRELESS && props.contains("ActiveAccessPoint")) { activeAp = props.value("ActiveAccessPoint").value<QDBusObjectPath>().path(); } } void WifiManager::deviceAdded(const QDBusObjectPath &path) { if (getAdapterType(path) == NM_DEVICE_TYPE_WIFI && emptyPath(adapter)) { adapter = path.path(); setup(); } } void WifiManager::connectionRemoved(const QDBusObjectPath &path) { knownConnections.remove(path); } void WifiManager::newConnection(const QDBusObjectPath &path) { Connection settings = getConnectionSettings(path); if (settings.value("connection").value("type") == "802-11-wireless") { knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); if (knownConnections[path] != tethering_ssid) { activateWifiConnection(knownConnections[path]); } } } QDBusObjectPath WifiManager::getConnectionPath(const QString &ssid) { return knownConnections.key(ssid); } Connection WifiManager::getConnectionSettings(const QDBusObjectPath &path) { return QDBusReply<Connection>(call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSettings")).value(); } void WifiManager::initConnections() { const QDBusReply<QList<QDBusObjectPath>> response = call(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "ListConnections"); for (const QDBusObjectPath &path : response.value()) { const Connection settings = getConnectionSettings(path); if (settings.value("connection").value("type") == "802-11-wireless") { knownConnections[path] = settings.value("802-11-wireless").value("ssid").toString(); } else if (settings.value("connection").value("id") == "lte") { lteConnectionPath = path; } } } std::optional<QDBusPendingCall> WifiManager::activateWifiConnection(const QString &ssid) { const QDBusObjectPath &path = getConnectionPath(ssid); if (!path.path().isEmpty()) { setCurrentConnecting(ssid); return asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(adapter)), QVariant::fromValue(QDBusObjectPath("/"))); } return std::nullopt; } void WifiManager::activateModemConnection(const QDBusObjectPath &path) { QString modem = getAdapter(NM_DEVICE_TYPE_MODEM); if (!path.path().isEmpty() && !modem.isEmpty()) { asyncCall(NM_DBUS_PATH, NM_DBUS_INTERFACE, "ActivateConnection", QVariant::fromValue(path), QVariant::fromValue(QDBusObjectPath(modem)), QVariant::fromValue(QDBusObjectPath("/"))); } } // function matches tici/hardware.py NetworkType WifiManager::currentNetworkType() { auto primary_conn = call<QDBusObjectPath>(NM_DBUS_PATH, NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE, "PrimaryConnection"); auto primary_type = call<QString>(primary_conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); if (primary_type == "802-3-ethernet") { return NetworkType::ETHERNET; } else if (primary_type == "802-11-wireless" && !isTetheringEnabled()) { return NetworkType::WIFI; } else { for (const QDBusObjectPath &conn : getActiveConnections()) { auto type = call<QString>(conn.path(), NM_DBUS_INTERFACE_PROPERTIES, "Get", NM_DBUS_INTERFACE_ACTIVE_CONNECTION, "Type"); if (type == "gsm") { return NetworkType::CELL; } } } return NetworkType::NONE; } void WifiManager::updateGsmSettings(bool roaming, QString apn, bool metered) { if (!lteConnectionPath.path().isEmpty()) { bool changes = false; bool auto_config = apn.isEmpty(); Connection settings = getConnectionSettings(lteConnectionPath); if (settings.value("gsm").value("auto-config").toBool() != auto_config) { qWarning() << "Changing gsm.auto-config to" << auto_config; settings["gsm"]["auto-config"] = auto_config; changes = true; } if (settings.value("gsm").value("apn").toString() != apn) { qWarning() << "Changing gsm.apn to" << apn; settings["gsm"]["apn"] = apn; changes = true; } if (settings.value("gsm").value("home-only").toBool() == roaming) { qWarning() << "Changing gsm.home-only to" << !roaming; settings["gsm"]["home-only"] = !roaming; changes = true; } int meteredInt = metered ? NM_METERED_UNKNOWN : NM_METERED_NO; if (settings.value("connection").value("metered").toInt() != meteredInt) { qWarning() << "Changing connection.metered to" << meteredInt; settings["connection"]["metered"] = meteredInt; changes = true; } if (changes) { call(lteConnectionPath.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "UpdateUnsaved", QVariant::fromValue(settings)); // update is temporary deactivateConnection(lteConnectionPath); activateModemConnection(lteConnectionPath); } } } // Functions for tethering void WifiManager::addTetheringConnection() { Connection connection; connection["connection"]["id"] = "Hotspot"; connection["connection"]["uuid"] = QUuid::createUuid().toString().remove('{').remove('}'); connection["connection"]["type"] = "802-11-wireless"; connection["connection"]["interface-name"] = "wlan0"; connection["connection"]["autoconnect"] = false; connection["802-11-wireless"]["band"] = "bg"; connection["802-11-wireless"]["mode"] = "ap"; connection["802-11-wireless"]["ssid"] = tethering_ssid.toUtf8(); connection["802-11-wireless-security"]["group"] = QStringList("ccmp"); connection["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"; connection["802-11-wireless-security"]["pairwise"] = QStringList("ccmp"); connection["802-11-wireless-security"]["proto"] = QStringList("rsn"); connection["802-11-wireless-security"]["psk"] = defaultTetheringPassword; connection["ipv4"]["method"] = "shared"; QVariantMap address; address["address"] = "192.168.43.1"; address["prefix"] = 24u; connection["ipv4"]["address-data"] = QVariant::fromValue(IpConfig() << address); connection["ipv4"]["gateway"] = "192.168.43.1"; connection["ipv4"]["route-metric"] = 1100; connection["ipv6"]["method"] = "ignore"; auto path = call<QDBusObjectPath>(NM_DBUS_PATH_SETTINGS, NM_DBUS_INTERFACE_SETTINGS, "AddConnection", QVariant::fromValue(connection)); if (!path.path().isEmpty()) { knownConnections[path] = tethering_ssid; } } void WifiManager::tetheringActivated(QDBusPendingCallWatcher *call) { int prime_type = uiState()->primeType(); int ipv4_forward = (prime_type == PrimeType::NONE || prime_type == PrimeType::LITE); if (!ipv4_forward) { QTimer::singleShot(5000, this, [=] { qWarning() << "net.ipv4.ip_forward = 0"; std::system("sudo sysctl net.ipv4.ip_forward=0"); }); } call->deleteLater(); } void WifiManager::setTetheringEnabled(bool enabled) { if (enabled) { if (!isKnownConnection(tethering_ssid)) { addTetheringConnection(); } auto pending_call = activateWifiConnection(tethering_ssid); if (pending_call) { QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(*pending_call); QObject::connect(watcher, &QDBusPendingCallWatcher::finished, this, &WifiManager::tetheringActivated); } } else { deactivateConnectionBySsid(tethering_ssid); } } bool WifiManager::isTetheringEnabled() { if (!emptyPath(activeAp)) { return get_property(activeAp, "Ssid") == tethering_ssid; } return false; } QString WifiManager::getTetheringPassword() { if (!isKnownConnection(tethering_ssid)) { addTetheringConnection(); } const QDBusObjectPath &path = getConnectionPath(tethering_ssid); if (!path.path().isEmpty()) { QDBusReply<QMap<QString, QVariantMap>> response = call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "GetSecrets", "802-11-wireless-security"); return response.value().value("802-11-wireless-security").value("psk").toString(); } return ""; } void WifiManager::changeTetheringPassword(const QString &newPassword) { const QDBusObjectPath &path = getConnectionPath(tethering_ssid); if (!path.path().isEmpty()) { Connection settings = getConnectionSettings(path); settings["802-11-wireless-security"]["psk"] = newPassword; call(path.path(), NM_DBUS_INTERFACE_SETTINGS_CONNECTION, "Update", QVariant::fromValue(settings)); if (isTetheringEnabled()) { activateWifiConnection(tethering_ssid); } } }
2301_81045437/openpilot
selfdrive/ui/qt/network/wifi_manager.cc
C++
mit
19,978
#pragma once #include <optional> #include <QtDBus> #include <QTimer> #include "selfdrive/ui/qt/network/networkmanager.h" enum class SecurityType { OPEN, WPA, UNSUPPORTED }; enum class ConnectedType { DISCONNECTED, CONNECTING, CONNECTED }; enum class NetworkType { NONE, WIFI, CELL, ETHERNET }; typedef QMap<QString, QVariantMap> Connection; typedef QVector<QVariantMap> IpConfig; struct Network { QByteArray ssid; unsigned int strength; ConnectedType connected; SecurityType security_type; }; bool compare_by_strength(const Network &a, const Network &b); inline int strengthLevel(unsigned int strength) { return std::clamp((int)round(strength / 33.), 0, 3); } class WifiManager : public QObject { Q_OBJECT public: QMap<QString, Network> seenNetworks; QMap<QDBusObjectPath, QString> knownConnections; QString ipv4_address; explicit WifiManager(QObject* parent); void start(); void stop(); void requestScan(); void forgetConnection(const QString &ssid); bool isKnownConnection(const QString &ssid); std::optional<QDBusPendingCall> activateWifiConnection(const QString &ssid); NetworkType currentNetworkType(); void updateGsmSettings(bool roaming, QString apn, bool metered); void connect(const Network &ssid, const bool is_hidden = false, const QString &password = {}, const QString &username = {}); // Tethering functions void setTetheringEnabled(bool enabled); bool isTetheringEnabled(); void changeTetheringPassword(const QString &newPassword); QString getTetheringPassword(); private: QString adapter; // Path to network manager wifi-device QTimer timer; unsigned int raw_adapter_state = NM_DEVICE_STATE_UNKNOWN; // Connection status https://developer.gnome.org/NetworkManager/1.26/nm-dbus-types.html#NMDeviceState QString connecting_to_network; QString tethering_ssid; const QString defaultTetheringPassword = "swagswagcomma"; QString activeAp; QDBusObjectPath lteConnectionPath; QString getAdapter(const uint = NM_DEVICE_TYPE_WIFI); uint getAdapterType(const QDBusObjectPath &path); QString getIp4Address(); void deactivateConnectionBySsid(const QString &ssid); void deactivateConnection(const QDBusObjectPath &path); QVector<QDBusObjectPath> getActiveConnections(); QByteArray get_property(const QString &network_path, const QString &property); SecurityType getSecurityType(const QVariantMap &properties); QDBusObjectPath getConnectionPath(const QString &ssid); Connection getConnectionSettings(const QDBusObjectPath &path); void initConnections(); void setup(); void refreshNetworks(); void activateModemConnection(const QDBusObjectPath &path); void addTetheringConnection(); void setCurrentConnecting(const QString &ssid); signals: void wrongPassword(const QString &ssid); void refreshSignal(); private slots: void stateChange(unsigned int new_state, unsigned int previous_state, unsigned int change_reason); void propertyChange(const QString &interface, const QVariantMap &props, const QStringList &invalidated_props); void deviceAdded(const QDBusObjectPath &path); void connectionRemoved(const QDBusObjectPath &path); void newConnection(const QDBusObjectPath &path); void refreshFinished(QDBusPendingCallWatcher *call); void tetheringActivated(QDBusPendingCallWatcher *call); };
2301_81045437/openpilot
selfdrive/ui/qt/network/wifi_manager.h
C++
mit
3,335
#include "selfdrive/ui/qt/offroad/driverview.h" #include <algorithm> #include <QPainter> #include "selfdrive/ui/qt/util.h" const int FACE_IMG_SIZE = 130; DriverViewWindow::DriverViewWindow(QWidget* parent) : CameraWidget("camerad", VISION_STREAM_DRIVER, true, parent) { face_img = loadPixmap("../assets/img_driver_face_static.png", {FACE_IMG_SIZE, FACE_IMG_SIZE}); QObject::connect(this, &CameraWidget::clicked, this, &DriverViewWindow::done); QObject::connect(device(), &Device::interactiveTimeout, this, [this]() { if (isVisible()) { emit done(); } }); } void DriverViewWindow::showEvent(QShowEvent* event) { params.putBool("IsDriverViewEnabled", true); device()->resetInteractiveTimeout(60); CameraWidget::showEvent(event); } void DriverViewWindow::hideEvent(QHideEvent* event) { params.putBool("IsDriverViewEnabled", false); stopVipcThread(); CameraWidget::hideEvent(event); } void DriverViewWindow::paintGL() { CameraWidget::paintGL(); std::lock_guard lk(frame_lock); QPainter p(this); // startup msg if (frames.empty()) { p.setPen(Qt::white); p.setRenderHint(QPainter::TextAntialiasing); p.setFont(InterFont(100, QFont::Bold)); p.drawText(geometry(), Qt::AlignCenter, tr("camera starting")); return; } const auto &sm = *(uiState()->sm); cereal::DriverStateV2::Reader driver_state = sm["driverStateV2"].getDriverStateV2(); bool is_rhd = driver_state.getWheelOnRightProb() > 0.5; auto driver_data = is_rhd ? driver_state.getRightDriverData() : driver_state.getLeftDriverData(); bool face_detected = driver_data.getFaceProb() > 0.7; if (face_detected) { auto fxy_list = driver_data.getFacePosition(); auto std_list = driver_data.getFaceOrientationStd(); float face_x = fxy_list[0]; float face_y = fxy_list[1]; float face_std = std::max(std_list[0], std_list[1]); float alpha = 0.7; if (face_std > 0.15) { alpha = std::max(0.7 - (face_std-0.15)*3.5, 0.0); } const int box_size = 220; // use approx instead of distort_points int fbox_x = 1080.0 - 1714.0 * face_x; int fbox_y = -135.0 + (504.0 + std::abs(face_x)*112.0) + (1205.0 - std::abs(face_x)*724.0) * face_y; p.setPen(QPen(QColor(255, 255, 255, alpha * 255), 10)); p.drawRoundedRect(fbox_x - box_size / 2, fbox_y - box_size / 2, box_size, box_size, 35.0, 35.0); } // icon const int img_offset = 60; const int img_x = is_rhd ? rect().right() - FACE_IMG_SIZE - img_offset : rect().left() + img_offset; const int img_y = rect().bottom() - FACE_IMG_SIZE - img_offset; p.setOpacity(face_detected ? 1.0 : 0.2); p.drawPixmap(img_x, img_y, face_img); }
2301_81045437/openpilot
selfdrive/ui/qt/offroad/driverview.cc
C++
mit
2,668
#pragma once #include "selfdrive/ui/qt/widgets/cameraview.h" class DriverViewWindow : public CameraWidget { Q_OBJECT public: explicit DriverViewWindow(QWidget *parent); signals: void done(); protected: void showEvent(QShowEvent *event) override; void hideEvent(QHideEvent *event) override; void paintGL() override; Params params; QPixmap face_img; };
2301_81045437/openpilot
selfdrive/ui/qt/offroad/driverview.h
C++
mit
373
#include "selfdrive/ui/qt/offroad/experimental_mode.h" #include <QDebug> #include <QHBoxLayout> #include <QPainter> #include <QPainterPath> #include <QStyle> #include "selfdrive/ui/ui.h" ExperimentalModeButton::ExperimentalModeButton(QWidget *parent) : QPushButton(parent) { chill_pixmap = QPixmap("../assets/img_couch.svg").scaledToWidth(img_width, Qt::SmoothTransformation); experimental_pixmap = QPixmap("../assets/img_experimental_grey.svg").scaledToWidth(img_width, Qt::SmoothTransformation); // go to toggles and expand experimental mode description connect(this, &QPushButton::clicked, [=]() { emit openSettings(2, "ExperimentalMode"); }); setFixedHeight(125); QHBoxLayout *main_layout = new QHBoxLayout; main_layout->setContentsMargins(horizontal_padding, 0, horizontal_padding, 0); mode_label = new QLabel; mode_icon = new QLabel; mode_icon->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); main_layout->addWidget(mode_label, 1, Qt::AlignLeft); main_layout->addWidget(mode_icon, 0, Qt::AlignRight); setLayout(main_layout); setStyleSheet(R"( QPushButton { border: none; } QLabel { font-size: 45px; font-weight: 300; text-align: left; font-family: JetBrainsMono; color: #000000; } )"); } void ExperimentalModeButton::paintEvent(QPaintEvent *event) { QPainter p(this); p.setPen(Qt::NoPen); p.setRenderHint(QPainter::Antialiasing); QPainterPath path; path.addRoundedRect(rect(), 10, 10); // gradient bool pressed = isDown(); QLinearGradient gradient(rect().left(), 0, rect().right(), 0); if (experimental_mode) { gradient.setColorAt(0, QColor(255, 155, 63, pressed ? 0xcc : 0xff)); gradient.setColorAt(1, QColor(219, 56, 34, pressed ? 0xcc : 0xff)); } else { gradient.setColorAt(0, QColor(20, 255, 171, pressed ? 0xcc : 0xff)); gradient.setColorAt(1, QColor(35, 149, 255, pressed ? 0xcc : 0xff)); } p.fillPath(path, gradient); // vertical line p.setPen(QPen(QColor(0, 0, 0, 0x4d), 3, Qt::SolidLine)); int line_x = rect().right() - img_width - (2 * horizontal_padding); p.drawLine(line_x, rect().bottom(), line_x, rect().top()); } void ExperimentalModeButton::showEvent(QShowEvent *event) { experimental_mode = params.getBool("ExperimentalMode"); mode_icon->setPixmap(experimental_mode ? experimental_pixmap : chill_pixmap); mode_label->setText(experimental_mode ? tr("EXPERIMENTAL MODE ON") : tr("CHILL MODE ON")); }
2301_81045437/openpilot
selfdrive/ui/qt/offroad/experimental_mode.cc
C++
mit
2,492
#pragma once #include <QLabel> #include <QPushButton> #include "common/params.h" class ExperimentalModeButton : public QPushButton { Q_OBJECT public: explicit ExperimentalModeButton(QWidget* parent = 0); signals: void openSettings(int index = 0, const QString &toggle = ""); private: void showEvent(QShowEvent *event) override; Params params; bool experimental_mode; int img_width = 100; int horizontal_padding = 30; QPixmap experimental_pixmap; QPixmap chill_pixmap; QLabel *mode_label; QLabel *mode_icon; protected: void paintEvent(QPaintEvent *event) override; };
2301_81045437/openpilot
selfdrive/ui/qt/offroad/experimental_mode.h
C++
mit
601
#include "selfdrive/ui/qt/offroad/onboarding.h" #include <string> #include <QLabel> #include <QPainter> #include <QQmlContext> #include <QQuickWidget> #include <QTransform> #include <QVBoxLayout> #include "common/util.h" #include "common/params.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/input.h" TrainingGuide::TrainingGuide(QWidget *parent) : QFrame(parent) { setAttribute(Qt::WA_OpaquePaintEvent); } void TrainingGuide::mouseReleaseEvent(QMouseEvent *e) { if (click_timer.elapsed() < 250) { return; } click_timer.restart(); auto contains = [this](QRect r, const QPoint &pt) { if (image.size() != image_raw_size) { QTransform transform; transform.translate((width()- image.width()) / 2.0, (height()- image.height()) / 2.0); transform.scale(image.width() / (float)image_raw_size.width(), image.height() / (float)image_raw_size.height()); r= transform.mapRect(r); } return r.contains(pt); }; if (contains(boundingRect[currentIndex], e->pos())) { if (currentIndex == 9) { const QRect yes = QRect(707, 804, 531, 164); Params().putBool("RecordFront", contains(yes, e->pos())); } currentIndex += 1; } else if (currentIndex == (boundingRect.size() - 2) && contains(boundingRect.last(), e->pos())) { currentIndex = 0; } if (currentIndex >= (boundingRect.size() - 1)) { emit completedTraining(); } else { update(); } } void TrainingGuide::showEvent(QShowEvent *event) { currentIndex = 0; click_timer.start(); } QImage TrainingGuide::loadImage(int id) { QImage img(img_path + QString("step%1.png").arg(id)); image_raw_size = img.size(); if (image_raw_size != rect().size()) { img = img.scaled(width(), height(), Qt::KeepAspectRatio, Qt::SmoothTransformation); } return img; } void TrainingGuide::paintEvent(QPaintEvent *event) { QPainter painter(this); QRect bg(0, 0, painter.device()->width(), painter.device()->height()); painter.fillRect(bg, QColor("#000000")); image = loadImage(currentIndex); QRect rect(image.rect()); rect.moveCenter(bg.center()); painter.drawImage(rect.topLeft(), image); // progress bar if (currentIndex > 0 && currentIndex < (boundingRect.size() - 2)) { const int h = 20; const int w = (currentIndex / (float)(boundingRect.size() - 2)) * width(); painter.fillRect(QRect(0, height() - h, w, h), QColor("#465BEA")); } } void TermsPage::showEvent(QShowEvent *event) { // late init, building QML widget takes 200ms if (layout()) { return; } QVBoxLayout *main_layout = new QVBoxLayout(this); main_layout->setContentsMargins(45, 35, 45, 45); main_layout->setSpacing(0); QLabel *title = new QLabel(tr("Terms & Conditions")); title->setStyleSheet("font-size: 90px; font-weight: 600;"); main_layout->addWidget(title); main_layout->addSpacing(30); QQuickWidget *text = new QQuickWidget(this); text->setResizeMode(QQuickWidget::SizeRootObjectToView); text->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); text->setAttribute(Qt::WA_AlwaysStackOnTop); text->setClearColor(QColor("#1B1B1B")); QString text_view = util::read_file("../assets/offroad/tc.html").c_str(); text->rootContext()->setContextProperty("text_view", text_view); text->setSource(QUrl::fromLocalFile("qt/offroad/text_view.qml")); main_layout->addWidget(text, 1); main_layout->addSpacing(50); QObject *obj = (QObject*)text->rootObject(); QObject::connect(obj, SIGNAL(scroll()), SLOT(enableAccept())); QHBoxLayout* buttons = new QHBoxLayout; buttons->setMargin(0); buttons->setSpacing(45); main_layout->addLayout(buttons); QPushButton *decline_btn = new QPushButton(tr("Decline")); buttons->addWidget(decline_btn); QObject::connect(decline_btn, &QPushButton::clicked, this, &TermsPage::declinedTerms); accept_btn = new QPushButton(tr("Scroll to accept")); accept_btn->setEnabled(false); accept_btn->setStyleSheet(R"( QPushButton { background-color: #465BEA; } QPushButton:pressed { background-color: #3049F4; } QPushButton:disabled { background-color: #4F4F4F; } )"); buttons->addWidget(accept_btn); QObject::connect(accept_btn, &QPushButton::clicked, this, &TermsPage::acceptedTerms); } void TermsPage::enableAccept() { accept_btn->setText(tr("Agree")); accept_btn->setEnabled(true); } void DeclinePage::showEvent(QShowEvent *event) { if (layout()) { return; } QVBoxLayout *main_layout = new QVBoxLayout(this); main_layout->setMargin(45); main_layout->setSpacing(40); QLabel *text = new QLabel(this); text->setText(tr("You must accept the Terms and Conditions in order to use openpilot.")); text->setStyleSheet(R"(font-size: 80px; font-weight: 300; margin: 200px;)"); text->setWordWrap(true); main_layout->addWidget(text, 0, Qt::AlignCenter); QHBoxLayout* buttons = new QHBoxLayout; buttons->setSpacing(45); main_layout->addLayout(buttons); QPushButton *back_btn = new QPushButton(tr("Back")); buttons->addWidget(back_btn); QObject::connect(back_btn, &QPushButton::clicked, this, &DeclinePage::getBack); QPushButton *uninstall_btn = new QPushButton(tr("Decline, uninstall %1").arg(getBrand())); uninstall_btn->setStyleSheet("background-color: #B73D3D"); buttons->addWidget(uninstall_btn); QObject::connect(uninstall_btn, &QPushButton::clicked, [=]() { Params().putBool("DoUninstall", true); }); } void OnboardingWindow::updateActiveScreen() { if (!accepted_terms) { setCurrentIndex(0); } else if (!training_done) { setCurrentIndex(1); } else { emit onboardingDone(); } } OnboardingWindow::OnboardingWindow(QWidget *parent) : QStackedWidget(parent) { std::string current_terms_version = params.get("TermsVersion"); std::string current_training_version = params.get("TrainingVersion"); accepted_terms = params.get("HasAcceptedTerms") == current_terms_version; training_done = params.get("CompletedTrainingVersion") == current_training_version; TermsPage* terms = new TermsPage(this); addWidget(terms); connect(terms, &TermsPage::acceptedTerms, [=]() { params.put("HasAcceptedTerms", current_terms_version); accepted_terms = true; updateActiveScreen(); }); connect(terms, &TermsPage::declinedTerms, [=]() { setCurrentIndex(2); }); TrainingGuide* tr = new TrainingGuide(this); addWidget(tr); connect(tr, &TrainingGuide::completedTraining, [=]() { training_done = true; params.put("CompletedTrainingVersion", current_training_version); updateActiveScreen(); }); DeclinePage* declinePage = new DeclinePage(this); addWidget(declinePage); connect(declinePage, &DeclinePage::getBack, [=]() { updateActiveScreen(); }); setStyleSheet(R"( * { color: white; background-color: black; } QPushButton { height: 160px; font-size: 55px; font-weight: 400; border-radius: 10px; background-color: #4F4F4F; } )"); updateActiveScreen(); }
2301_81045437/openpilot
selfdrive/ui/qt/offroad/onboarding.cc
C++
mit
7,029
#pragma once #include <QElapsedTimer> #include <QImage> #include <QMouseEvent> #include <QPushButton> #include <QStackedWidget> #include <QWidget> #include "common/params.h" #include "selfdrive/ui/qt/qt_window.h" class TrainingGuide : public QFrame { Q_OBJECT public: explicit TrainingGuide(QWidget *parent = 0); private: void showEvent(QShowEvent *event) override; void paintEvent(QPaintEvent *event) override; void mouseReleaseEvent(QMouseEvent* e) override; QImage loadImage(int id); QImage image; QSize image_raw_size; int currentIndex = 0; // Bounding boxes for each training guide step const QRect continueBtn = {1840, 0, 320, 1080}; QVector<QRect> boundingRect { QRect(112, 804, 618, 164), continueBtn, continueBtn, QRect(1641, 558, 210, 313), QRect(1662, 528, 184, 108), continueBtn, QRect(1814, 621, 211, 170), QRect(1350, 0, 497, 755), QRect(1540, 386, 468, 238), QRect(112, 804, 1126, 164), QRect(1598, 199, 316, 333), continueBtn, QRect(1364, 90, 796, 990), continueBtn, QRect(1593, 114, 318, 853), QRect(1379, 511, 391, 243), continueBtn, continueBtn, QRect(630, 804, 626, 164), QRect(108, 804, 426, 164), }; const QString img_path = "../assets/training/"; QElapsedTimer click_timer; signals: void completedTraining(); }; class TermsPage : public QFrame { Q_OBJECT public: explicit TermsPage(QWidget *parent = 0) : QFrame(parent) {} public slots: void enableAccept(); private: void showEvent(QShowEvent *event) override; QPushButton *accept_btn; signals: void acceptedTerms(); void declinedTerms(); }; class DeclinePage : public QFrame { Q_OBJECT public: explicit DeclinePage(QWidget *parent = 0) : QFrame(parent) {} private: void showEvent(QShowEvent *event) override; signals: void getBack(); }; class OnboardingWindow : public QStackedWidget { Q_OBJECT public: explicit OnboardingWindow(QWidget *parent = 0); inline void showTrainingGuide() { setCurrentIndex(1); } inline bool completed() const { return accepted_terms && training_done; } private: void updateActiveScreen(); Params params; bool accepted_terms = false, training_done = false; signals: void onboardingDone(); };
2301_81045437/openpilot
selfdrive/ui/qt/offroad/onboarding.h
C++
mit
2,268
#include <cassert> #include <cmath> #include <string> #include <tuple> #include <vector> #include <QDebug> #include "common/watchdog.h" #include "common/util.h" #include "selfdrive/ui/qt/network/networking.h" #include "selfdrive/ui/qt/offroad/settings.h" #include "selfdrive/ui/qt/qt_window.h" #include "selfdrive/ui/qt/widgets/prime.h" #include "selfdrive/ui/qt/widgets/scrollview.h" #include "selfdrive/ui/qt/widgets/ssh_keys.h" TogglesPanel::TogglesPanel(SettingsWindow *parent) : ListWidget(parent) { // param, title, desc, icon std::vector<std::tuple<QString, QString, QString, QString>> toggle_defs{ { "OpenpilotEnabledToggle", tr("Enable openpilot"), tr("Use the openpilot system for adaptive cruise control and lane keep driver assistance. Your attention is required at all times to use this feature. Changing this setting takes effect when the car is powered off."), "../assets/offroad/icon_openpilot.png", }, { "ExperimentalLongitudinalEnabled", tr("openpilot Longitudinal Control (Alpha)"), QString("<b>%1</b><br><br>%2") .arg(tr("WARNING: openpilot longitudinal control is in alpha for this car and will disable Automatic Emergency Braking (AEB).")) .arg(tr("On this car, openpilot defaults to the car's built-in ACC instead of openpilot's longitudinal control. " "Enable this to switch to openpilot longitudinal control. Enabling Experimental mode is recommended when enabling openpilot longitudinal control alpha.")), "../assets/offroad/icon_speed_limit.png", }, { "ExperimentalMode", tr("Experimental Mode"), "", "../assets/img_experimental_white.svg", }, { "DisengageOnAccelerator", tr("Disengage on Accelerator Pedal"), tr("When enabled, pressing the accelerator pedal will disengage openpilot."), "../assets/offroad/icon_disengage_on_accelerator.svg", }, { "IsLdwEnabled", tr("Enable Lane Departure Warnings"), tr("Receive alerts to steer back into the lane when your vehicle drifts over a detected lane line without a turn signal activated while driving over 31 mph (50 km/h)."), "../assets/offroad/icon_warning.png", }, { "AlwaysOnDM", tr("Always-On Driver Monitoring"), tr("Enable driver monitoring even when openpilot is not engaged."), "../assets/offroad/icon_monitoring.png", }, { "RecordFront", tr("Record and Upload Driver Camera"), tr("Upload data from the driver facing camera and help improve the driver monitoring algorithm."), "../assets/offroad/icon_monitoring.png", }, { "IsMetric", tr("Use Metric System"), tr("Display speed in km/h instead of mph."), "../assets/offroad/icon_metric.png", }, #ifdef ENABLE_MAPS { "NavSettingTime24h", tr("Show ETA in 24h Format"), tr("Use 24h format instead of am/pm"), "../assets/offroad/icon_metric.png", }, { "NavSettingLeftSide", tr("Show Map on Left Side of UI"), tr("Show map on left side when in split screen view."), "../assets/offroad/icon_road.png", }, #endif }; std::vector<QString> longi_button_texts{tr("Aggressive"), tr("Standard"), tr("Relaxed")}; long_personality_setting = new ButtonParamControl("LongitudinalPersonality", tr("Driving Personality"), tr("Standard is recommended. In aggressive mode, openpilot will follow lead cars closer and be more aggressive with the gas and brake. " "In relaxed mode openpilot will stay further away from lead cars. On supported cars, you can cycle through these personalities with " "your steering wheel distance button."), "../assets/offroad/icon_speed_limit.png", longi_button_texts); // set up uiState update for personality setting QObject::connect(uiState(), &UIState::uiUpdate, this, &TogglesPanel::updateState); for (auto &[param, title, desc, icon] : toggle_defs) { auto toggle = new ParamControl(param, title, desc, icon, this); bool locked = params.getBool((param + "Lock").toStdString()); toggle->setEnabled(!locked); addItem(toggle); toggles[param.toStdString()] = toggle; // insert longitudinal personality after NDOG toggle if (param == "DisengageOnAccelerator") { addItem(long_personality_setting); } } // Toggles with confirmation dialogs toggles["ExperimentalMode"]->setActiveIcon("../assets/img_experimental.svg"); toggles["ExperimentalMode"]->setConfirmation(true, true); toggles["ExperimentalLongitudinalEnabled"]->setConfirmation(true, false); connect(toggles["ExperimentalLongitudinalEnabled"], &ToggleControl::toggleFlipped, [=]() { updateToggles(); }); } void TogglesPanel::updateState(const UIState &s) { const SubMaster &sm = *(s.sm); if (sm.updated("controlsState")) { auto personality = sm["controlsState"].getControlsState().getPersonality(); if (personality != s.scene.personality && s.scene.started && isVisible()) { long_personality_setting->setCheckedButton(static_cast<int>(personality)); } uiState()->scene.personality = personality; } } void TogglesPanel::expandToggleDescription(const QString &param) { toggles[param.toStdString()]->showDescription(); } void TogglesPanel::showEvent(QShowEvent *event) { updateToggles(); } void TogglesPanel::updateToggles() { auto experimental_mode_toggle = toggles["ExperimentalMode"]; auto op_long_toggle = toggles["ExperimentalLongitudinalEnabled"]; const QString e2e_description = QString("%1<br>" "<h4>%2</h4><br>" "%3<br>" "<h4>%4</h4><br>" "%5<br>") .arg(tr("openpilot defaults to driving in <b>chill mode</b>. Experimental mode enables <b>alpha-level features</b> that aren't ready for chill mode. Experimental features are listed below:")) .arg(tr("End-to-End Longitudinal Control")) .arg(tr("Let the driving model control the gas and brakes. openpilot will drive as it thinks a human would, including stopping for red lights and stop signs. " "Since the driving model decides the speed to drive, the set speed will only act as an upper bound. This is an alpha quality feature; " "mistakes should be expected.")) .arg(tr("New Driving Visualization")) .arg(tr("The driving visualization will transition to the road-facing wide-angle camera at low speeds to better show some turns. The Experimental mode logo will also be shown in the top right corner.")); const bool is_release = params.getBool("IsReleaseBranch"); auto cp_bytes = params.get("CarParamsPersistent"); if (!cp_bytes.empty()) { AlignedBuffer aligned_buf; capnp::FlatArrayMessageReader cmsg(aligned_buf.align(cp_bytes.data(), cp_bytes.size())); cereal::CarParams::Reader CP = cmsg.getRoot<cereal::CarParams>(); if (!CP.getExperimentalLongitudinalAvailable() || is_release) { params.remove("ExperimentalLongitudinalEnabled"); } op_long_toggle->setVisible(CP.getExperimentalLongitudinalAvailable() && !is_release); if (hasLongitudinalControl(CP)) { // normal description and toggle experimental_mode_toggle->setEnabled(true); experimental_mode_toggle->setDescription(e2e_description); long_personality_setting->setEnabled(true); } else { // no long for now experimental_mode_toggle->setEnabled(false); long_personality_setting->setEnabled(false); params.remove("ExperimentalMode"); const QString unavailable = tr("Experimental mode is currently unavailable on this car since the car's stock ACC is used for longitudinal control."); QString long_desc = unavailable + " " + \ tr("openpilot longitudinal control may come in a future update."); if (CP.getExperimentalLongitudinalAvailable()) { if (is_release) { long_desc = unavailable + " " + tr("An alpha version of openpilot longitudinal control can be tested, along with Experimental mode, on non-release branches."); } else { long_desc = tr("Enable the openpilot longitudinal control (alpha) toggle to allow Experimental mode."); } } experimental_mode_toggle->setDescription("<b>" + long_desc + "</b><br><br>" + e2e_description); } experimental_mode_toggle->refresh(); } else { experimental_mode_toggle->setDescription(e2e_description); op_long_toggle->setVisible(false); } } DevicePanel::DevicePanel(SettingsWindow *parent) : ListWidget(parent) { setSpacing(50); addItem(new LabelControl(tr("Dongle ID"), getDongleId().value_or(tr("N/A")))); addItem(new LabelControl(tr("Serial"), params.get("HardwareSerial").c_str())); pair_device = new ButtonControl(tr("Pair Device"), tr("PAIR"), tr("Pair your device with comma connect (connect.comma.ai) and claim your comma prime offer.")); connect(pair_device, &ButtonControl::clicked, [=]() { PairingPopup popup(this); popup.exec(); }); addItem(pair_device); // offroad-only buttons auto dcamBtn = new ButtonControl(tr("Driver Camera"), tr("PREVIEW"), tr("Preview the driver facing camera to ensure that driver monitoring has good visibility. (vehicle must be off)")); connect(dcamBtn, &ButtonControl::clicked, [=]() { emit showDriverView(); }); addItem(dcamBtn); auto resetCalibBtn = new ButtonControl(tr("Reset Calibration"), tr("RESET"), ""); connect(resetCalibBtn, &ButtonControl::showDescriptionEvent, this, &DevicePanel::updateCalibDescription); connect(resetCalibBtn, &ButtonControl::clicked, [&]() { if (ConfirmationDialog::confirm(tr("Are you sure you want to reset calibration?"), tr("Reset"), this)) { params.remove("CalibrationParams"); params.remove("LiveTorqueParameters"); } }); addItem(resetCalibBtn); auto retrainingBtn = new ButtonControl(tr("Review Training Guide"), tr("REVIEW"), tr("Review the rules, features, and limitations of openpilot")); connect(retrainingBtn, &ButtonControl::clicked, [=]() { if (ConfirmationDialog::confirm(tr("Are you sure you want to review the training guide?"), tr("Review"), this)) { emit reviewTrainingGuide(); } }); addItem(retrainingBtn); if (Hardware::TICI()) { auto regulatoryBtn = new ButtonControl(tr("Regulatory"), tr("VIEW"), ""); connect(regulatoryBtn, &ButtonControl::clicked, [=]() { const std::string txt = util::read_file("../assets/offroad/fcc.html"); ConfirmationDialog::rich(QString::fromStdString(txt), this); }); addItem(regulatoryBtn); } auto translateBtn = new ButtonControl(tr("Change Language"), tr("CHANGE"), ""); connect(translateBtn, &ButtonControl::clicked, [=]() { QMap<QString, QString> langs = getSupportedLanguages(); QString selection = MultiOptionDialog::getSelection(tr("Select a language"), langs.keys(), langs.key(uiState()->language), this); if (!selection.isEmpty()) { // put language setting, exit Qt UI, and trigger fast restart params.put("LanguageSetting", langs[selection].toStdString()); qApp->exit(18); watchdog_kick(0); } }); addItem(translateBtn); QObject::connect(uiState(), &UIState::primeTypeChanged, [this] (PrimeType type) { pair_device->setVisible(type == PrimeType::UNPAIRED); }); QObject::connect(uiState(), &UIState::offroadTransition, [=](bool offroad) { for (auto btn : findChildren<ButtonControl *>()) { if (btn != pair_device) { btn->setEnabled(offroad); } } }); // power buttons QHBoxLayout *power_layout = new QHBoxLayout(); power_layout->setSpacing(30); QPushButton *reboot_btn = new QPushButton(tr("Reboot")); reboot_btn->setObjectName("reboot_btn"); power_layout->addWidget(reboot_btn); QObject::connect(reboot_btn, &QPushButton::clicked, this, &DevicePanel::reboot); QPushButton *poweroff_btn = new QPushButton(tr("Power Off")); poweroff_btn->setObjectName("poweroff_btn"); power_layout->addWidget(poweroff_btn); QObject::connect(poweroff_btn, &QPushButton::clicked, this, &DevicePanel::poweroff); if (!Hardware::PC()) { connect(uiState(), &UIState::offroadTransition, poweroff_btn, &QPushButton::setVisible); } setStyleSheet(R"( #reboot_btn { height: 120px; border-radius: 15px; background-color: #393939; } #reboot_btn:pressed { background-color: #4a4a4a; } #poweroff_btn { height: 120px; border-radius: 15px; background-color: #E22C2C; } #poweroff_btn:pressed { background-color: #FF2424; } )"); addItem(power_layout); } void DevicePanel::updateCalibDescription() { QString desc = tr("openpilot requires the device to be mounted within 4° left or right and " "within 5° up or 9° down. openpilot is continuously calibrating, resetting is rarely required."); std::string calib_bytes = params.get("CalibrationParams"); if (!calib_bytes.empty()) { try { AlignedBuffer aligned_buf; capnp::FlatArrayMessageReader cmsg(aligned_buf.align(calib_bytes.data(), calib_bytes.size())); auto calib = cmsg.getRoot<cereal::Event>().getLiveCalibration(); if (calib.getCalStatus() != cereal::LiveCalibrationData::Status::UNCALIBRATED) { double pitch = calib.getRpyCalib()[1] * (180 / M_PI); double yaw = calib.getRpyCalib()[2] * (180 / M_PI); desc += tr(" Your device is pointed %1° %2 and %3° %4.") .arg(QString::number(std::abs(pitch), 'g', 1), pitch > 0 ? tr("down") : tr("up"), QString::number(std::abs(yaw), 'g', 1), yaw > 0 ? tr("left") : tr("right")); } } catch (kj::Exception) { qInfo() << "invalid CalibrationParams"; } } qobject_cast<ButtonControl *>(sender())->setDescription(desc); } void DevicePanel::reboot() { if (!uiState()->engaged()) { if (ConfirmationDialog::confirm(tr("Are you sure you want to reboot?"), tr("Reboot"), this)) { // Check engaged again in case it changed while the dialog was open if (!uiState()->engaged()) { params.putBool("DoReboot", true); } } } else { ConfirmationDialog::alert(tr("Disengage to Reboot"), this); } } void DevicePanel::poweroff() { if (!uiState()->engaged()) { if (ConfirmationDialog::confirm(tr("Are you sure you want to power off?"), tr("Power Off"), this)) { // Check engaged again in case it changed while the dialog was open if (!uiState()->engaged()) { params.putBool("DoShutdown", true); } } } else { ConfirmationDialog::alert(tr("Disengage to Power Off"), this); } } void DevicePanel::showEvent(QShowEvent *event) { pair_device->setVisible(uiState()->primeType() == PrimeType::UNPAIRED); ListWidget::showEvent(event); } void SettingsWindow::showEvent(QShowEvent *event) { setCurrentPanel(0); } void SettingsWindow::setCurrentPanel(int index, const QString &param) { panel_widget->setCurrentIndex(index); nav_btns->buttons()[index]->setChecked(true); if (!param.isEmpty()) { emit expandToggleDescription(param); } } SettingsWindow::SettingsWindow(QWidget *parent) : QFrame(parent) { // setup two main layouts sidebar_widget = new QWidget; QVBoxLayout *sidebar_layout = new QVBoxLayout(sidebar_widget); panel_widget = new QStackedWidget(); // close button QPushButton *close_btn = new QPushButton(tr("×")); close_btn->setStyleSheet(R"( QPushButton { font-size: 140px; padding-bottom: 20px; border-radius: 100px; background-color: #292929; font-weight: 400; } QPushButton:pressed { background-color: #3B3B3B; } )"); close_btn->setFixedSize(200, 200); sidebar_layout->addSpacing(45); sidebar_layout->addWidget(close_btn, 0, Qt::AlignCenter); QObject::connect(close_btn, &QPushButton::clicked, this, &SettingsWindow::closeSettings); // setup panels DevicePanel *device = new DevicePanel(this); QObject::connect(device, &DevicePanel::reviewTrainingGuide, this, &SettingsWindow::reviewTrainingGuide); QObject::connect(device, &DevicePanel::showDriverView, this, &SettingsWindow::showDriverView); TogglesPanel *toggles = new TogglesPanel(this); QObject::connect(this, &SettingsWindow::expandToggleDescription, toggles, &TogglesPanel::expandToggleDescription); QList<QPair<QString, QWidget *>> panels = { {tr("Device"), device}, {tr("Network"), new Networking(this)}, {tr("Toggles"), toggles}, {tr("Software"), new SoftwarePanel(this)}, }; nav_btns = new QButtonGroup(this); for (auto &[name, panel] : panels) { QPushButton *btn = new QPushButton(name); btn->setCheckable(true); btn->setChecked(nav_btns->buttons().size() == 0); btn->setStyleSheet(R"( QPushButton { color: grey; border: none; background: none; font-size: 65px; font-weight: 500; } QPushButton:checked { color: white; } QPushButton:pressed { color: #ADADAD; } )"); btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); nav_btns->addButton(btn); sidebar_layout->addWidget(btn, 0, Qt::AlignRight); const int lr_margin = name != tr("Network") ? 50 : 0; // Network panel handles its own margins panel->setContentsMargins(lr_margin, 25, lr_margin, 25); ScrollView *panel_frame = new ScrollView(panel, this); panel_widget->addWidget(panel_frame); QObject::connect(btn, &QPushButton::clicked, [=, w = panel_frame]() { btn->setChecked(true); panel_widget->setCurrentWidget(w); }); } sidebar_layout->setContentsMargins(50, 50, 100, 50); // main settings layout, sidebar + main panel QHBoxLayout *main_layout = new QHBoxLayout(this); sidebar_widget->setFixedWidth(500); main_layout->addWidget(sidebar_widget); main_layout->addWidget(panel_widget); setStyleSheet(R"( * { color: white; font-size: 50px; } SettingsWindow { background-color: black; } QStackedWidget, ScrollView { background-color: #292929; border-radius: 30px; } )"); }
2301_81045437/openpilot
selfdrive/ui/qt/offroad/settings.cc
C++
mit
18,697
#pragma once #include <map> #include <string> #include <QButtonGroup> #include <QFrame> #include <QLabel> #include <QPushButton> #include <QStackedWidget> #include <QWidget> #include "selfdrive/ui/ui.h" #include "selfdrive/ui/qt/util.h" #include "selfdrive/ui/qt/widgets/controls.h" // ********** settings window + top-level panels ********** class SettingsWindow : public QFrame { Q_OBJECT public: explicit SettingsWindow(QWidget *parent = 0); void setCurrentPanel(int index, const QString &param = ""); protected: void showEvent(QShowEvent *event) override; signals: void closeSettings(); void reviewTrainingGuide(); void showDriverView(); void expandToggleDescription(const QString &param); private: QPushButton *sidebar_alert_widget; QWidget *sidebar_widget; QButtonGroup *nav_btns; QStackedWidget *panel_widget; }; class DevicePanel : public ListWidget { Q_OBJECT public: explicit DevicePanel(SettingsWindow *parent); void showEvent(QShowEvent *event) override; signals: void reviewTrainingGuide(); void showDriverView(); private slots: void poweroff(); void reboot(); void updateCalibDescription(); private: Params params; ButtonControl *pair_device; }; class TogglesPanel : public ListWidget { Q_OBJECT public: explicit TogglesPanel(SettingsWindow *parent); void showEvent(QShowEvent *event) override; public slots: void expandToggleDescription(const QString &param); private slots: void updateState(const UIState &s); private: Params params; std::map<std::string, ParamControl*> toggles; ButtonParamControl *long_personality_setting; void updateToggles(); }; class SoftwarePanel : public ListWidget { Q_OBJECT public: explicit SoftwarePanel(QWidget* parent = nullptr); private: void showEvent(QShowEvent *event) override; void updateLabels(); void checkForUpdates(); bool is_onroad = false; QLabel *onroadLbl; LabelControl *versionLbl; ButtonControl *installBtn; ButtonControl *downloadBtn; ButtonControl *targetBranchBtn; Params params; ParamWatcher *fs_watch; };
2301_81045437/openpilot
selfdrive/ui/qt/offroad/settings.h
C++
mit
2,083