From e4d70a22b70cf4270b97ef89673087284a1a023d Mon Sep 17 00:00:00 2001 From: Samuel Sadok Date: Thu, 14 May 2020 11:31:30 +0200 Subject: [PATCH] Initial implementation of interface autogenerator. TODO: - write to endpoints from float (for PWM/analog input) - ascii protocol --- Firmware/.gitignore | 1 + Firmware/MotorControl/axis.cpp | 4 +- Firmware/MotorControl/axis.hpp | 127 +- Firmware/MotorControl/controller.hpp | 90 +- Firmware/MotorControl/encoder.hpp | 86 +- Firmware/MotorControl/endstop.hpp | 21 +- Firmware/MotorControl/low_level.cpp | 32 +- Firmware/MotorControl/main.cpp | 81 +- Firmware/MotorControl/motor.cpp | 2 +- Firmware/MotorControl/motor.hpp | 147 +-- Firmware/MotorControl/odrive_main.h | 91 +- .../MotorControl/sensorless_estimator.hpp | 26 +- Firmware/MotorControl/trapTraj.hpp | 10 - Firmware/Tupfile.lua | 16 +- Firmware/ascii_type_info_template.j2 | 90 ++ Firmware/build.lua | 2 +- Firmware/communication/ascii_protocol.cpp | 17 +- Firmware/communication/can_simple.cpp | 2 +- Firmware/communication/communication.cpp | 161 +-- Firmware/communication/communication.h | 4 - Firmware/communication/interface_can.cpp | 10 +- Firmware/communication/interface_can.hpp | 35 +- Firmware/communication/interface_usb.cpp | 2 +- Firmware/fibre/cpp/endpoints_template.j2 | 71 + Firmware/fibre/cpp/function_stubs_template.j2 | 40 + Firmware/fibre/cpp/include/fibre/bufptr.hpp | 93 ++ .../fibre/cpp/include/fibre/cpp_utils.hpp | 1145 ++++++++++++++++- Firmware/fibre/cpp/include/fibre/protocol.hpp | 748 ++--------- .../fibre/cpp/include/fibre/simple_serdes.hpp | 77 ++ Firmware/fibre/cpp/interfaces_template.j2 | 67 + Firmware/fibre/cpp/protocol.cpp | 91 +- Firmware/interface_generator.py | 589 +++++++++ Firmware/odrive-interface.yaml | 662 ++++++++++ docs/interface-definition-file.md | 133 ++ 34 files changed, 3321 insertions(+), 1452 deletions(-) create mode 100644 Firmware/ascii_type_info_template.j2 create mode 100644 Firmware/fibre/cpp/endpoints_template.j2 create mode 100644 Firmware/fibre/cpp/function_stubs_template.j2 create mode 100644 Firmware/fibre/cpp/include/fibre/bufptr.hpp create mode 100644 Firmware/fibre/cpp/include/fibre/simple_serdes.hpp create mode 100644 Firmware/fibre/cpp/interfaces_template.j2 create mode 100644 Firmware/interface_generator.py create mode 100644 Firmware/odrive-interface.yaml create mode 100644 docs/interface-definition-file.md diff --git a/Firmware/.gitignore b/Firmware/.gitignore index 496462db..a4c86dc2 100644 --- a/Firmware/.gitignore +++ b/Firmware/.gitignore @@ -1,5 +1,6 @@ #build folder +autogen/ build/ deploy/ .dep/ diff --git a/Firmware/MotorControl/axis.cpp b/Firmware/MotorControl/axis.cpp index c1d11a4b..71edd5f1 100644 --- a/Firmware/MotorControl/axis.cpp +++ b/Firmware/MotorControl/axis.cpp @@ -161,9 +161,9 @@ bool Axis::do_checks() { if ((current_state_ != AXIS_STATE_IDLE) && (motor_.armed_state_ == Motor::ARMED_STATE_DISARMED)) // motor got disarmed in something other than the idle loop error_ |= ERROR_MOTOR_DISARMED; - if (!(vbus_voltage >= board_config.dc_bus_undervoltage_trip_level)) + if (!(vbus_voltage >= odrv.config_.dc_bus_undervoltage_trip_level)) error_ |= ERROR_DC_BUS_UNDER_VOLTAGE; - if (!(vbus_voltage <= board_config.dc_bus_overvoltage_trip_level)) + if (!(vbus_voltage <= odrv.config_.dc_bus_overvoltage_trip_level)) error_ |= ERROR_DC_BUS_OVER_VOLTAGE; // Sub-components should use set_error which will propegate to this error_ diff --git a/Firmware/MotorControl/axis.hpp b/Firmware/MotorControl/axis.hpp index 63925753..31cc118e 100644 --- a/Firmware/MotorControl/axis.hpp +++ b/Firmware/MotorControl/axis.hpp @@ -5,43 +5,8 @@ #error "This file should not be included directly. Include odrive_main.h instead." #endif -class Axis { +class Axis : public AxisIntf { public: - enum Error { - ERROR_NONE = 0x00, - ERROR_INVALID_STATE = 0x01, //decode_step_dir_pins(); } + void set_dir_gpio_pin(uint16_t value) { dir_gpio_pin = value; parent->decode_step_dir_pins(); } }; struct Homing_t { @@ -98,13 +68,6 @@ public: M_SIGNAL_PH_CURRENT_MEAS = 1u << 0 }; - enum LockinState_t { - LOCKIN_STATE_INACTIVE, - LOCKIN_STATE_RAMP, - LOCKIN_STATE_ACCELERATE, - LOCKIN_STATE_CONST_VEL, - }; - Axis(int axis_num, const AxisHardwareConfig_t& hw_config, Config_t& config, @@ -143,7 +106,7 @@ public: sensorless_estimator_.error_ = SensorlessEstimator::ERROR_NONE; encoder_.error_ = Encoder::ERROR_NONE; - error_ = Axis::ERROR_NONE; + error_ = ERROR_NONE; } // True if there are no errors @@ -250,85 +213,17 @@ public: GPIO_TypeDef* dir_port_; uint16_t dir_pin_; - State_t requested_state_ = AXIS_STATE_STARTUP_SEQUENCE; - std::array task_chain_ = { AXIS_STATE_UNDEFINED }; - State_t& current_state_ = task_chain_.front(); + AxisState requested_state_ = AXIS_STATE_STARTUP_SEQUENCE; + std::array task_chain_ = { AXIS_STATE_UNDEFINED }; + AxisState& current_state_ = task_chain_.front(); uint32_t loop_counter_ = 0; - LockinState_t lockin_state_ = LOCKIN_STATE_INACTIVE; + LockinState lockin_state_ = LOCKIN_STATE_INACTIVE; Homing_t homing_; uint32_t last_heartbeat_ = 0; // watchdog uint32_t watchdog_current_value_= 0; - - // Communication protocol definitions - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_property("error", &error_), - make_protocol_ro_property("step_dir_active", &step_dir_active_), - make_protocol_ro_property("current_state", ¤t_state_), - make_protocol_property("requested_state", &requested_state_), - make_protocol_ro_property("loop_counter", &loop_counter_), - make_protocol_ro_property("lockin_state", &lockin_state_), - make_protocol_property("is_homed", &homing_.is_homed), - make_protocol_object("config", - make_protocol_property("startup_motor_calibration", &config_.startup_motor_calibration), - make_protocol_property("startup_encoder_index_search", &config_.startup_encoder_index_search), - make_protocol_property("startup_encoder_offset_calibration", &config_.startup_encoder_offset_calibration), - make_protocol_property("startup_closed_loop_control", &config_.startup_closed_loop_control), - make_protocol_property("startup_sensorless_control", &config_.startup_sensorless_control), - make_protocol_property("startup_homing", &config_.startup_homing), - make_protocol_property("enable_step_dir", &config_.enable_step_dir), - make_protocol_property("step_dir_always_on", &config_.step_dir_always_on), - make_protocol_property("counts_per_step", &config_.counts_per_step), - make_protocol_property("watchdog_timeout", &config_.watchdog_timeout), - make_protocol_property("enable_watchdog", &config_.enable_watchdog), - make_protocol_property("step_gpio_pin", &config_.step_gpio_pin, - [](void* ctx) { static_cast(ctx)->decode_step_dir_pins(); }, this), - make_protocol_property("dir_gpio_pin", &config_.dir_gpio_pin, - [](void* ctx) { static_cast(ctx)->decode_step_dir_pins(); }, this), - make_protocol_object("calibration_lockin", - make_protocol_property("current", &config_.calibration_lockin.current), - make_protocol_property("ramp_time", &config_.calibration_lockin.ramp_time), - make_protocol_property("ramp_distance", &config_.calibration_lockin.ramp_distance), - make_protocol_property("accel", &config_.calibration_lockin.accel), - make_protocol_property("vel", &config_.calibration_lockin.vel)), - make_protocol_object("sensorless_ramp", - make_protocol_property("current", &config_.sensorless_ramp.current), - make_protocol_property("ramp_time", &config_.sensorless_ramp.ramp_time), - make_protocol_property("ramp_distance", &config_.sensorless_ramp.ramp_distance), - make_protocol_property("accel", &config_.sensorless_ramp.accel), - make_protocol_property("vel", &config_.sensorless_ramp.vel), - make_protocol_property("finish_distance", &config_.sensorless_ramp.finish_distance), - make_protocol_property("finish_on_vel", &config_.sensorless_ramp.finish_on_vel), - make_protocol_property("finish_on_distance", &config_.sensorless_ramp.finish_on_distance), - make_protocol_property("finish_on_enc_idx", &config_.sensorless_ramp.finish_on_enc_idx)), - make_protocol_object("general_lockin", - make_protocol_property("current", &config_.general_lockin.current), - make_protocol_property("ramp_time", &config_.general_lockin.ramp_time), - make_protocol_property("ramp_distance", &config_.general_lockin.ramp_distance), - make_protocol_property("accel", &config_.general_lockin.accel), - make_protocol_property("vel", &config_.general_lockin.vel), - make_protocol_property("finish_distance", &config_.general_lockin.finish_distance), - make_protocol_property("finish_on_vel", &config_.general_lockin.finish_on_vel), - make_protocol_property("finish_on_distance", &config_.general_lockin.finish_on_distance), - make_protocol_property("finish_on_enc_idx", &config_.general_lockin.finish_on_enc_idx)), - make_protocol_property("can_node_id", &config_.can_node_id), - make_protocol_property("can_heartbeat_rate_ms", &config_.can_heartbeat_rate_ms)), - make_protocol_object("motor", motor_.make_protocol_definitions()), - make_protocol_object("controller", controller_.make_protocol_definitions()), - make_protocol_object("encoder", encoder_.make_protocol_definitions()), - make_protocol_object("sensorless_estimator", sensorless_estimator_.make_protocol_definitions()), - make_protocol_object("trap_traj", trap_traj_.make_protocol_definitions()), - make_protocol_object("min_endstop", min_endstop_.make_protocol_definitions()), - make_protocol_object("max_endstop", max_endstop_.make_protocol_definitions()), - make_protocol_function("watchdog_feed", *this, &Axis::watchdog_feed), - make_protocol_function("clear_errors", *this, &Axis::clear_errors) - ); - } }; -DEFINE_ENUM_FLAG_OPERATORS(Axis::Error) - #endif /* __AXIS_HPP */ diff --git a/Firmware/MotorControl/controller.hpp b/Firmware/MotorControl/controller.hpp index 293b892a..f1529d96 100644 --- a/Firmware/MotorControl/controller.hpp +++ b/Firmware/MotorControl/controller.hpp @@ -5,38 +5,8 @@ #error "This file should not be included directly. Include odrive_main.h instead." #endif -class Controller { +class Controller : public ControllerIntf { public: - enum Error { - ERROR_NONE = 0, - ERROR_OVERSPEED = 0x01, - ERROR_INVALID_INPUT_MODE = 0x02, - ERROR_UNSTABLE_GAIN = 0x04, - ERROR_INVALID_MIRROR_AXIS = 0x08, - ERROR_INVALID_LOAD_ENCODER = 0x10, - ERROR_INVALID_ESTIMATE = 0x20, - }; - - // Note: these should be sorted from lowest level of control to - // highest level of control, to allow "<" style comparisons. - enum ControlMode{ - CONTROL_MODE_VOLTAGE_CONTROL = 0, - CONTROL_MODE_CURRENT_CONTROL = 1, - CONTROL_MODE_VELOCITY_CONTROL = 2, - CONTROL_MODE_POSITION_CONTROL = 3 - }; - - enum InputMode{ - INPUT_MODE_INACTIVE, - INPUT_MODE_PASSTHROUGH, - INPUT_MODE_VEL_RAMP, - INPUT_MODE_POS_FILTER, - INPUT_MODE_MIX_CHANNELS, - INPUT_MODE_TRAP_TRAJ, - INPUT_MODE_CURRENT_RAMP, - INPUT_MODE_MIRROR, - }; - typedef struct { uint32_t index = 0; float cogging_map[3600]; @@ -48,7 +18,7 @@ public: bool anticogging_enabled = true; } Anticogging_t; - struct Config_t { + struct Config_t : ConfigIntf { ControlMode control_mode = CONTROL_MODE_POSITION_CONTROL; //see: ControlMode InputMode input_mode = INPUT_MODE_PASSTHROUGH; //see: InputMode float pos_gain = 20.0f; // [(counts/s) / counts] @@ -72,6 +42,10 @@ public: uint8_t axis_to_mirror = -1; float mirror_ratio = 1.0f; uint8_t load_encoder_axis = -1; // default depends on Axis number and is set in load_configuration() + + // custom setters + Controller* parent; + void set_input_filter_bandwidth(float value) { input_filter_bandwidth = value; parent->update_filter_gains(); } }; explicit Controller(Config_t& config); @@ -121,56 +95,8 @@ public: bool anticogging_valid_ = false; - // Communication protocol definitions - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_property("error", &error_), - make_protocol_property("input_pos", &input_pos_, - [](void* ctx) { static_cast(ctx)->input_pos_updated(); }, this), - make_protocol_property("input_vel", &input_vel_), - make_protocol_property("input_current", &input_current_), - make_protocol_ro_property("pos_setpoint", &pos_setpoint_), - make_protocol_ro_property("vel_setpoint", &vel_setpoint_), - make_protocol_ro_property("current_setpoint", ¤t_setpoint_), - make_protocol_ro_property("trajectory_done", &trajectory_done_), - make_protocol_property("vel_integrator_current", &vel_integrator_current_), - make_protocol_property("anticogging_valid", &anticogging_valid_), - make_protocol_property("gain_scheduling_width", &config_.gain_scheduling_width), - make_protocol_object("config", - make_protocol_property("enable_vel_limit", &config_.enable_vel_limit), - make_protocol_property("enable_current_mode_vel_limit", &config_.enable_current_mode_vel_limit), - make_protocol_property("enable_gain_scheduling", &config_.enable_gain_scheduling), - make_protocol_property("enable_overspeed_error", &config_.enable_overspeed_error), - make_protocol_property("control_mode", &config_.control_mode), - make_protocol_property("input_mode", &config_.input_mode), - make_protocol_property("pos_gain", &config_.pos_gain), - make_protocol_property("vel_gain", &config_.vel_gain), - make_protocol_property("vel_integrator_gain", &config_.vel_integrator_gain), - make_protocol_property("vel_limit", &config_.vel_limit), - make_protocol_property("vel_limit_tolerance", &config_.vel_limit_tolerance), - make_protocol_property("vel_ramp_rate", &config_.vel_ramp_rate), - make_protocol_property("current_ramp_rate", &config_.current_ramp_rate), - make_protocol_property("homing_speed", &config_.homing_speed), - make_protocol_property("inertia", &config_.inertia), - make_protocol_property("axis_to_mirror", &config_.axis_to_mirror), - make_protocol_property("mirror_ratio", &config_.mirror_ratio), - make_protocol_property("load_encoder_axis", &config_.load_encoder_axis), - make_protocol_property("input_filter_bandwidth", &config_.input_filter_bandwidth, - [](void* ctx) { static_cast(ctx)->update_filter_gains(); }, this), - make_protocol_object("anticogging", - make_protocol_ro_property("index", &config_.anticogging.index), - make_protocol_property("pre_calibrated", &config_.anticogging.pre_calibrated), - make_protocol_ro_property("calib_anticogging", &config_.anticogging.calib_anticogging), - make_protocol_property("calib_pos_threshold", &config_.anticogging.calib_pos_threshold), - make_protocol_property("calib_vel_threshold", &config_.anticogging.calib_vel_threshold), - make_protocol_ro_property("cogging_ratio", &config_.anticogging.cogging_ratio), - make_protocol_property("anticogging_enabled", &config_.anticogging.anticogging_enabled))), - make_protocol_function("move_incremental", *this, &Controller::move_incremental, "displacement", "from_goal_point"), - make_protocol_function("start_anticogging_calibration", *this, &Controller::start_anticogging_calibration) - ); - } + // custom setters + void set_input_pos(float value) { input_pos_ = value; input_pos_updated(); } }; -DEFINE_ENUM_FLAG_OPERATORS(Controller::Error) - #endif // __CONTROLLER_HPP diff --git a/Firmware/MotorControl/encoder.hpp b/Firmware/MotorControl/encoder.hpp index 77ad84b1..04471e62 100644 --- a/Firmware/MotorControl/encoder.hpp +++ b/Firmware/MotorControl/encoder.hpp @@ -5,33 +5,12 @@ #error "This file should not be included directly. Include odrive_main.h instead." #endif -class Encoder { +class Encoder : public EncoderIntf { public: - enum Error { - ERROR_NONE = 0, - ERROR_UNSTABLE_GAIN = 0x01, - ERROR_CPR_POLEPAIRS_MISMATCH = 0x02, - ERROR_NO_RESPONSE = 0x04, - ERROR_UNSUPPORTED_ENCODER_MODE = 0x08, - ERROR_ILLEGAL_HALL_STATE = 0x10, - ERROR_INDEX_NOT_FOUND_YET = 0x20, - ERROR_ABS_SPI_TIMEOUT = 0x40, - ERROR_ABS_SPI_COM_FAIL = 0x80, - ERROR_ABS_SPI_NOT_READY = 0x100, - }; - - enum Mode_t { - MODE_INCREMENTAL, - MODE_HALL, - MODE_SINCOS, - MODE_SPI_ABS_CUI = 0x100, //!< compatible with CUI AMT23xx - MODE_SPI_ABS_AMS = 0x101, //!< compatible with AMS AS5047P, AS5048A/AS5048B (no daisy chain support) - MODE_SPI_ABS_AEAT = 0x102, //!< not yet implemented - }; const uint32_t MODE_FLAG_ABS = 0x100; - struct Config_t { - Encoder::Mode_t mode = Encoder::MODE_INCREMENTAL; + struct Config_t : EncoderIntf::ConfigIntf { + Mode mode = MODE_INCREMENTAL; bool use_index = false; bool pre_calibrated = false; // If true, this means the offset stored in // configuration is valid and does not need @@ -53,6 +32,14 @@ public: uint16_t abs_spi_cs_gpio_pin = 1; uint16_t sincos_gpio_pin_sin = 3; uint16_t sincos_gpio_pin_cos = 4; + + // custom setters + Encoder* parent = nullptr; + void set_use_index(bool value) { use_index = value; parent->set_idx_subscribe(); } + void set_find_idx_on_lockin_only(bool value) { find_idx_on_lockin_only = value; parent->set_idx_subscribe(); } + void set_abs_spi_cs_gpio_pin(uint16_t value) { abs_spi_cs_gpio_pin = value; parent->abs_spi_cs_pin_init(); } + void set_pre_calibrated(bool value) { pre_calibrated = value; parent->check_pre_calibrated(); } + void set_bandwidth(float value) { bandwidth = value; parent->update_pll_gains(); } }; Encoder(const EncoderHardwareConfig_t& hw_config, @@ -113,7 +100,7 @@ public: uint16_t abs_spi_dma_tx_[1] = {0xFFFF}; uint16_t abs_spi_dma_rx_[1]; bool abs_spi_pos_updated_ = false; - Mode_t mode_ = MODE_INCREMENTAL; + Mode mode_ = MODE_INCREMENTAL; GPIO_TypeDef* abs_spi_cs_port_; uint16_t abs_spi_cs_pin_; uint32_t abs_spi_cr1; @@ -122,55 +109,6 @@ public: constexpr float getCoggingRatio(){ return config_.cpr / 3600.0f; } - - // Communication protocol definitions - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_property("error", &error_), - make_protocol_ro_property("is_ready", &is_ready_), - make_protocol_ro_property("index_found", const_cast(&index_found_)), - make_protocol_ro_property("shadow_count", &shadow_count_), - make_protocol_ro_property("count_in_cpr", &count_in_cpr_), - make_protocol_ro_property("interpolation", &interpolation_), - make_protocol_ro_property("phase", &phase_), - make_protocol_ro_property("pos_estimate", &pos_estimate_), - make_protocol_ro_property("pos_cpr", &pos_cpr_), - make_protocol_ro_property("hall_state", &hall_state_), - make_protocol_ro_property("vel_estimate", &vel_estimate_), - make_protocol_ro_property("calib_scan_response", &calib_scan_response_), - make_protocol_property("pos_abs", &pos_abs_), - make_protocol_ro_property("spi_error_rate", &spi_error_rate_), - - make_protocol_object("config", - make_protocol_property("mode", &config_.mode), - make_protocol_property("use_index", &config_.use_index, - [](void* ctx) { static_cast(ctx)->set_idx_subscribe(); }, this), - make_protocol_property("find_idx_on_lockin_only", &config_.find_idx_on_lockin_only, - [](void* ctx) { static_cast(ctx)->set_idx_subscribe(); }, this), - make_protocol_property("abs_spi_cs_gpio_pin", &config_.abs_spi_cs_gpio_pin, - [](void* ctx) { static_cast(ctx)->abs_spi_cs_pin_init(); }, this), - make_protocol_property("zero_count_on_find_idx", &config_.zero_count_on_find_idx), - make_protocol_property("cpr", &config_.cpr), - make_protocol_property("offset", &config_.offset), - make_protocol_property("pre_calibrated", &config_.pre_calibrated, - [](void* ctx) { static_cast(ctx)->check_pre_calibrated(); }, this), - make_protocol_property("offset_float", &config_.offset_float), - make_protocol_property("enable_phase_interpolation", &config_.enable_phase_interpolation), - make_protocol_property("bandwidth", &config_.bandwidth, - [](void* ctx) { static_cast(ctx)->update_pll_gains(); }, this), - make_protocol_property("calib_range", &config_.calib_range), - make_protocol_property("calib_scan_distance", &config_.calib_scan_distance), - make_protocol_property("calib_scan_omega", &config_.calib_scan_omega), - make_protocol_property("idx_search_unidirectional", &config_.idx_search_unidirectional), - make_protocol_property("ignore_illegal_hall_state", &config_.ignore_illegal_hall_state), - make_protocol_property("sincos_gpio_pin_sin", &config_.sincos_gpio_pin_sin), - make_protocol_property("sincos_gpio_pin_cos", &config_.sincos_gpio_pin_cos) - ), - make_protocol_function("set_linear_count", *this, &Encoder::set_linear_count, "count") - ); - } }; -DEFINE_ENUM_FLAG_OPERATORS(Encoder::Error) - #endif // __ENCODER_HPP diff --git a/Firmware/MotorControl/endstop.hpp b/Firmware/MotorControl/endstop.hpp index 6983fa6c..e9412f89 100644 --- a/Firmware/MotorControl/endstop.hpp +++ b/Firmware/MotorControl/endstop.hpp @@ -11,6 +11,12 @@ class Endstop { bool enabled = false; bool is_active_high = false; bool pullup = true; + + // custom setters + Endstop* parent = nullptr + void set_gpio_num(uint16_t value) { gpio_num = value; parent->update_config(); } + void set_enabled(uint32_t value) { enabled = value; parent->update_config(); } + void set_debounce_ms(uint32_t value) { debounce_ms = value; parent->update_config(); } }; explicit Endstop(Endstop::Config_t& config); @@ -26,21 +32,6 @@ class Endstop { bool endstop_state_ = false; - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_ro_property("endstop_state", &endstop_state_), - make_protocol_object("config", - make_protocol_property("gpio_num", &config_.gpio_num, - [](void* ctx) { static_cast(ctx)->update_config(); }, this), - make_protocol_property("enabled", &config_.enabled, - [](void* ctx) { static_cast(ctx)->update_config(); }, this), - make_protocol_property("offset", &config_.offset), - make_protocol_property("is_active_high", &config_.is_active_high), - make_protocol_property("pullup", &config_.pullup), - make_protocol_property("debounce_ms", &config_.debounce_ms, - [](void* ctx) { static_cast(ctx)->update_config(); }, this))); - } - private: bool pin_state_ = false; float pos_when_pressed_ = 0.0f; diff --git a/Firmware/MotorControl/low_level.cpp b/Firmware/MotorControl/low_level.cpp index f0e32f0c..5c2886cf 100644 --- a/Firmware/MotorControl/low_level.cpp +++ b/Firmware/MotorControl/low_level.cpp @@ -613,11 +613,11 @@ void update_brake_current() { } // Don't start braking until -Ibus > regen_current_allowed - float brake_current = -Ibus_sum - board_config.max_regen_current; - float brake_duty = brake_current * board_config.brake_resistance / vbus_voltage; + float brake_current = -Ibus_sum - odrv.config_.max_regen_current; + float brake_duty = brake_current * odrv.config_.brake_resistance / vbus_voltage; - if (board_config.enable_dc_bus_overvoltage_ramp && (board_config.brake_resistance > 0.0f) && (board_config.dc_bus_overvoltage_ramp_start < board_config.dc_bus_overvoltage_ramp_end)) { - brake_duty += std::fmax((vbus_voltage - board_config.dc_bus_overvoltage_ramp_start) / (board_config.dc_bus_overvoltage_ramp_end - board_config.dc_bus_overvoltage_ramp_start), 0.0f); + if (odrv.config_.enable_dc_bus_overvoltage_ramp && (odrv.config_.brake_resistance > 0.0f) && (odrv.config_.dc_bus_overvoltage_ramp_start < odrv.config_.dc_bus_overvoltage_ramp_end)) { + brake_duty += std::fmax((vbus_voltage - odrv.config_.dc_bus_overvoltage_ramp_start) / (odrv.config_.dc_bus_overvoltage_ramp_end - odrv.config_.dc_bus_overvoltage_ramp_start), 0.0f); } if (std::isnan(brake_duty)) { @@ -634,15 +634,15 @@ void update_brake_current() { brake_duty = std::clamp(brake_duty, 0.0f, 0.95f); // Special handling to avoid the case 0.0/0.0 == NaN. - Ibus_sum += brake_duty ? (brake_duty * vbus_voltage / board_config.brake_resistance) : 0.0f; + Ibus_sum += brake_duty ? (brake_duty * vbus_voltage / odrv.config_.brake_resistance) : 0.0f; ibus_ = Ibus_sum; - if (Ibus_sum > board_config.dc_max_positive_current) { + if (Ibus_sum > odrv.config_.dc_max_positive_current) { low_level_fault(Motor::ERROR_DC_BUS_OVER_CURRENT); return; } - if (Ibus_sum < board_config.dc_max_negative_current) { + if (Ibus_sum < odrv.config_.dc_max_negative_current) { low_level_fault(Motor::ERROR_DC_BUS_OVER_REGEN_CURRENT); return; } @@ -715,7 +715,7 @@ void pwm_in_init() { #else int gpio_num = 4; { #endif - if (is_endpoint_ref_valid(board_config.pwm_mappings[gpio_num - 1].endpoint)) { + if (fibre::is_endpoint_ref_valid(odrv.config_.pwm_mappings[gpio_num - 1].endpoint)) { GPIO_InitStruct.Pin = get_gpio_pin_by_pin(gpio_num); HAL_GPIO_DeInit(get_gpio_port_by_pin(gpio_num), get_gpio_pin_by_pin(gpio_num)); HAL_GPIO_Init(get_gpio_port_by_pin(gpio_num), &GPIO_InitStruct); @@ -742,14 +742,10 @@ void handle_pulse(int gpio_num, uint32_t high_time) { if (high_time > PWM_MAX_HIGH_TIME) high_time = PWM_MAX_HIGH_TIME; float fraction = (float)(high_time - PWM_MIN_HIGH_TIME) / (float)(PWM_MAX_HIGH_TIME - PWM_MIN_HIGH_TIME); - float value = board_config.pwm_mappings[gpio_num - 1].min + - (fraction * (board_config.pwm_mappings[gpio_num - 1].max - board_config.pwm_mappings[gpio_num - 1].min)); + float value = odrv.config_.pwm_mappings[gpio_num - 1].min + + (fraction * (odrv.config_.pwm_mappings[gpio_num - 1].max - odrv.config_.pwm_mappings[gpio_num - 1].min)); - Endpoint* endpoint = get_endpoint(board_config.pwm_mappings[gpio_num - 1].endpoint); - if (!endpoint) - return; - - endpoint->set_from_float(value); + fibre::set_endpoint_from_float(odrv.config_.pwm_mappings[gpio_num - 1].endpoint, value); } void pwm_in_cb(int channel, uint32_t timestamp) { @@ -780,16 +776,16 @@ static void update_analog_endpoint(const struct PWMMapping_t *map, int gpio) { float fraction = get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)) / 3.3f; float value = map->min + (fraction * (map->max - map->min)); - get_endpoint(map->endpoint)->set_from_float(value); + fibre::set_endpoint_from_float(map->endpoint, value); } static void analog_polling_thread(void *) { while (true) { for (int i = 0; i < GPIO_COUNT; i++) { - struct PWMMapping_t *map = &board_config.analog_mappings[i]; + struct PWMMapping_t *map = &odrv.config_.analog_mappings[i]; - if (is_endpoint_ref_valid(map->endpoint)) + if (fibre::is_endpoint_ref_valid(map->endpoint)) update_analog_endpoint(map, i + 1); } osDelay(10); diff --git a/Firmware/MotorControl/main.cpp b/Firmware/MotorControl/main.cpp index d3864ed0..5ea0a827 100644 --- a/Firmware/MotorControl/main.cpp +++ b/Firmware/MotorControl/main.cpp @@ -10,7 +10,6 @@ #include #include -BoardConfig_t board_config; ODriveCAN::Config_t can_config; Encoder::Config_t encoder_configs[AXIS_COUNT]; SensorlessEstimator::Config_t sensorless_configs[AXIS_COUNT]; @@ -20,12 +19,10 @@ Axis::Config_t axis_configs[AXIS_COUNT]; TrapezoidalTrajectory::Config_t trap_configs[AXIS_COUNT]; Endstop::Config_t min_endstop_configs[AXIS_COUNT]; Endstop::Config_t max_endstop_configs[AXIS_COUNT]; -bool user_config_loaded_; - -SystemStats_t system_stats_; std::array axes; ODriveCAN *odCAN = nullptr; +ODrive odrv{}; typedef Config< BoardConfig_t, @@ -39,9 +36,9 @@ typedef Config< Endstop::Config_t[AXIS_COUNT], Axis::Config_t[AXIS_COUNT]> ConfigFormat; -void save_configuration(void) { +void ODrive::save_configuration(void) { if (ConfigFormat::safe_store_config( - &board_config, + &odrv.config_, &can_config, &encoder_configs, &sensorless_configs, @@ -53,7 +50,7 @@ void save_configuration(void) { &axis_configs)) { printf("saving configuration failed\r\n"); osDelay(5); } else { - user_config_loaded_ = true; + odrv.user_config_loaded_ = true; } } @@ -61,7 +58,7 @@ extern "C" int load_configuration(void) { // Try to load configs if (NVM_init() || ConfigFormat::safe_load_config( - &board_config, + &odrv.config_, &can_config, &encoder_configs, &sensorless_configs, @@ -72,7 +69,7 @@ extern "C" int load_configuration(void) { &max_endstop_configs, &axis_configs)) { //If loading failed, restore defaults - board_config = BoardConfig_t(); + odrv.config_ = BoardConfig_t(); can_config = ODriveCAN::Config_t(); for (size_t i = 0; i < AXIS_COUNT; ++i) { encoder_configs[i] = Encoder::Config_t(); @@ -89,12 +86,12 @@ extern "C" int load_configuration(void) { controller_configs[i].load_encoder_axis = i; } } else { - user_config_loaded_ = true; + odrv.user_config_loaded_ = true; } - return user_config_loaded_; + return odrv.user_config_loaded_; } -void erase_configuration(void) { +void ODrive::erase_configuration(void) { NVM_erase(); // FIXME: this reboot is a workaround because we don't want the next save_configuration @@ -105,8 +102,8 @@ void erase_configuration(void) { NVIC_SystemReset(); } -void enter_dfu_mode() { - if ((hw_version_major == 3) && (hw_version_minor >= 5)) { +void ODrive::enter_dfu_mode() { + if ((hw_version_major_ == 3) && (hw_version_minor_ >= 5)) { __asm volatile ("CPSID I\n\t":::"memory"); // disable interrupts _reboot_cookie = 0xDEADBEEF; NVIC_SystemReset(); @@ -125,7 +122,7 @@ void enter_dfu_mode() { extern "C" int construct_objects(){ #if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3 - if (board_config.enable_i2c_instead_of_can) { + if (odrv.config_.enable_i2c_instead_of_can) { // Set up the direction GPIO as input GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; @@ -149,7 +146,7 @@ extern "C" int construct_objects(){ MX_CAN1_Init(); HAL_UART_DeInit(&huart4); - huart4.Init.BaudRate = board_config.uart_baudrate; + huart4.Init.BaudRate = odrv.config_.uart_baudrate; HAL_UART_Init(&huart4); // Init general user ADC on some GPIOs. @@ -170,7 +167,7 @@ extern "C" int construct_objects(){ #endif // Construct all objects. - odCAN = new ODriveCAN(&hcan1, can_config); + odCAN = new ODriveCAN(can_config, &hcan1); for (size_t i = 0; i < AXIS_COUNT; ++i) { Encoder *encoder = new Encoder(hw_configs[i].encoder_config, encoder_configs[i], motor_configs[i]); @@ -184,8 +181,14 @@ extern "C" int construct_objects(){ Endstop *max_endstop = new Endstop(max_endstop_configs[i]); axes[i] = new Axis(i, hw_configs[i].axis_config, axis_configs[i], *encoder, *sensorless_estimator, *controller, *motor, *trap, *min_endstop, *max_endstop); + + controller_configs[i].parent = controller; + encoder_configs[i].parent = encoder; + motor_configs[i].parent = motor; + min_endstop_configs[i].parent = min_endstop; + max_endstop_configs[i].parent = max_endstop; + axis_configs[i].parent = axes[i]; } - initTree(); return 0; } @@ -199,27 +202,27 @@ void vApplicationStackOverflowHook(xTaskHandle *pxTask, signed portCHAR *pcTaskN for (;;); // TODO: safe action } void vApplicationIdleHook(void) { - if (system_stats_.fully_booted) { - system_stats_.uptime = xTaskGetTickCount(); - system_stats_.min_heap_space = xPortGetMinimumEverFreeHeapSize(); - system_stats_.min_stack_space_comms = uxTaskGetStackHighWaterMark(comm_thread) * sizeof(StackType_t); - system_stats_.min_stack_space_axis0 = uxTaskGetStackHighWaterMark(axes[0]->thread_id_) * sizeof(StackType_t); - system_stats_.min_stack_space_axis1 = uxTaskGetStackHighWaterMark(axes[1]->thread_id_) * sizeof(StackType_t); - system_stats_.min_stack_space_usb = uxTaskGetStackHighWaterMark(usb_thread) * sizeof(StackType_t); - system_stats_.min_stack_space_uart = uxTaskGetStackHighWaterMark(uart_thread) * sizeof(StackType_t); - system_stats_.min_stack_space_usb_irq = uxTaskGetStackHighWaterMark(usb_irq_thread) * sizeof(StackType_t); - system_stats_.min_stack_space_startup = uxTaskGetStackHighWaterMark(defaultTaskHandle) * sizeof(StackType_t); - system_stats_.min_stack_space_can = uxTaskGetStackHighWaterMark(odCAN->thread_id_) * sizeof(StackType_t); + if (odrv.system_stats_.fully_booted) { + odrv.system_stats_.uptime = xTaskGetTickCount(); + odrv.system_stats_.min_heap_space = xPortGetMinimumEverFreeHeapSize(); + odrv.system_stats_.min_stack_space_comms = uxTaskGetStackHighWaterMark(comm_thread) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_axis0 = uxTaskGetStackHighWaterMark(axes[0]->thread_id_) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_axis1 = uxTaskGetStackHighWaterMark(axes[1]->thread_id_) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_usb = uxTaskGetStackHighWaterMark(usb_thread) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_uart = uxTaskGetStackHighWaterMark(uart_thread) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_usb_irq = uxTaskGetStackHighWaterMark(usb_irq_thread) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_startup = uxTaskGetStackHighWaterMark(defaultTaskHandle) * sizeof(StackType_t); + odrv.system_stats_.min_stack_space_can = uxTaskGetStackHighWaterMark(odCAN->thread_id_) * sizeof(StackType_t); // Actual usage, in bytes, so we don't have to math - system_stats_.stack_usage_axis0 = axes[0]->stack_size_ - system_stats_.min_stack_space_axis0; - system_stats_.stack_usage_axis1 = axes[1]->stack_size_ - system_stats_.min_stack_space_axis1; - system_stats_.stack_usage_comms = stack_size_comm_thread - system_stats_.min_stack_space_comms; - system_stats_.stack_usage_usb = stack_size_usb_thread - system_stats_.min_stack_space_usb; - system_stats_.stack_usage_uart = stack_size_uart_thread - system_stats_.min_stack_space_uart; - system_stats_.stack_usage_usb_irq = stack_size_usb_irq_thread - system_stats_.min_stack_space_usb_irq; - system_stats_.stack_usage_startup = stack_size_default_task - system_stats_.min_stack_space_startup; - system_stats_.stack_usage_can = odCAN->stack_size_ - system_stats_.min_stack_space_can; + odrv.system_stats_.stack_usage_axis0 = axes[0]->stack_size_ - odrv.system_stats_.min_stack_space_axis0; + odrv.system_stats_.stack_usage_axis1 = axes[1]->stack_size_ - odrv.system_stats_.min_stack_space_axis1; + odrv.system_stats_.stack_usage_comms = stack_size_comm_thread - odrv.system_stats_.min_stack_space_comms; + odrv.system_stats_.stack_usage_usb = stack_size_usb_thread - odrv.system_stats_.min_stack_space_usb; + odrv.system_stats_.stack_usage_uart = stack_size_uart_thread - odrv.system_stats_.min_stack_space_uart; + odrv.system_stats_.stack_usage_usb_irq = stack_size_usb_irq_thread - odrv.system_stats_.min_stack_space_usb_irq; + odrv.system_stats_.stack_usage_startup = stack_size_default_task - odrv.system_stats_.min_stack_space_startup; + odrv.system_stats_.stack_usage_can = odCAN->stack_size_ - odrv.system_stats_.min_stack_space_can; } } } @@ -230,7 +233,7 @@ int odrive_main(void) { // TODO: make dynamically reconfigurable #if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3 - if (board_config.enable_uart) { + if (odrv.config_.enable_uart) { SetGPIO12toUART(); } #endif @@ -271,6 +274,6 @@ int odrive_main(void) { start_analog_thread(); - system_stats_.fully_booted = true; + odrv.system_stats_.fully_booted = true; return 0; } diff --git a/Firmware/MotorControl/motor.cpp b/Firmware/MotorControl/motor.cpp index 6b8c8d0f..f924f13f 100644 --- a/Firmware/MotorControl/motor.cpp +++ b/Firmware/MotorControl/motor.cpp @@ -127,7 +127,7 @@ bool Motor::check_DRV_fault() { GPIO_PinState nFAULT_state = HAL_GPIO_ReadPin(gate_driver_config_.nFAULT_port, gate_driver_config_.nFAULT_pin); if (nFAULT_state == GPIO_PIN_RESET) { // Update DRV Fault Code - drv_fault_ = DRV8301_getFaultType(&gate_driver_); + gate_driver_exported_.drv_fault = (GateDriverIntf::DrvFault)DRV8301_getFaultType(&gate_driver_); // Update/Cache all SPI device registers // DRV_SPI_8301_Vars_t* local_regs = &gate_driver_regs_; // local_regs->RcvCmd = true; diff --git a/Firmware/MotorControl/motor.hpp b/Firmware/MotorControl/motor.hpp index 67a0751d..88a735e3 100644 --- a/Firmware/MotorControl/motor.hpp +++ b/Firmware/MotorControl/motor.hpp @@ -7,35 +7,8 @@ #include "drv8301.h" -class Motor { +class Motor : public MotorIntf { public: - enum Error { - ERROR_NONE = 0, - ERROR_PHASE_RESISTANCE_OUT_OF_RANGE = 0x0001, - ERROR_PHASE_INDUCTANCE_OUT_OF_RANGE = 0x0002, - ERROR_ADC_FAILED = 0x0004, - ERROR_DRV_FAULT = 0x0008, - ERROR_CONTROL_DEADLINE_MISSED = 0x0010, - ERROR_NOT_IMPLEMENTED_MOTOR_TYPE = 0x0020, - ERROR_BRAKE_CURRENT_OUT_OF_RANGE = 0x0040, - ERROR_MODULATION_MAGNITUDE = 0x0080, - ERROR_BRAKE_DEADTIME_VIOLATION = 0x0100, - ERROR_UNEXPECTED_TIMER_CALLBACK = 0x0200, - ERROR_CURRENT_SENSE_SATURATION = 0x0400, - ERROR_INVERTER_OVER_TEMP = 0x0800, - ERROR_CURRENT_LIMIT_VIOLATION = 0x1000, - ERROR_BRAKE_DUTY_CYCLE_NAN = 0x2000, - ERROR_DC_BUS_OVER_REGEN_CURRENT = 0x4000, // too much current pushed into the power supply - ERROR_DC_BUS_OVER_CURRENT = 0x8000, // too much current pulled out of the power supply - }; - - enum MotorType_t { - MOTOR_TYPE_HIGH_CURRENT = 0, - // MOTOR_TYPE_LOW_CURRENT = 1, //Not yet implemented - MOTOR_TYPE_GIMBAL = 2, - MOTOR_TYPE_ACIM = 3, - }; - struct Iph_BC_t { float phB; float phC; @@ -65,7 +38,7 @@ public: // NOTE: for gimbal motors, all units of A are instead V. // example: vel_gain is [V/(count/s)] instead of [A/(count/s)] // example: current_lim and calibration_current will instead determine the maximum voltage applied to the motor. - struct Config_t { + struct Config_t : public ConfigIntf { bool pre_calibrated = false; // can be set to true to indicate that all values here are valid int32_t pole_pairs = 7; float calibration_current = 10.0f; // [A] @@ -73,7 +46,7 @@ public: float phase_inductance = 0.0f; // to be set by measure_phase_inductance float phase_resistance = 0.0f; // to be set by measure_phase_resistance int32_t direction = 0; // 1 or -1 (0 = unspecified) - MotorType_t motor_type = MOTOR_TYPE_HIGH_CURRENT; + MotorType motor_type = MOTOR_TYPE_HIGH_CURRENT; // Read out max_allowed_current to see max supported value for current_lim. // float current_lim = 70.0f; //[A] float current_lim = 10.0f; //[A] @@ -89,6 +62,16 @@ public: bool acim_autoflux_enable = false; float acim_autoflux_attack_gain = 10.0f; float acim_autoflux_decay_gain = 1.0f; + + // custom property setters + Motor* parent = nullptr; + void set_pre_calibrated(bool value) { + pre_calibrated = value; + parent->is_calibrated_ = parent->is_calibrated_ || parent->config_.pre_calibrated; + } + void set_phase_inductance(float value) { phase_inductance = value; parent->update_current_controller_gains(); } + void set_phase_resistance(float value) { phase_resistance = value; parent->update_current_controller_gains(); } + void set_current_control_bandwidth(float value) { current_control_bandwidth = value; parent->update_current_controller_gains(); } }; enum TimingLog_t { @@ -107,13 +90,6 @@ public: TIMING_LOG_NUM_SLOTS }; - enum ArmedState_t { - ARMED_STATE_DISARMED, - ARMED_STATE_WAITING_FOR_TIMINGS, - ARMED_STATE_WAITING_FOR_UPDATE, - ARMED_STATE_ARMED, - }; - Motor(const MotorHardwareConfig_t& hw_config, const GateDriverHardwareConfig_t& gate_driver_config, Config_t& config); @@ -160,13 +136,17 @@ public: bool next_timings_valid_ = false; uint16_t last_cpu_time_ = 0; int timing_log_index_ = 0; - uint16_t timing_log_[TIMING_LOG_NUM_SLOTS] = { 0 }; + struct { + uint16_t& operator[](size_t idx) { return content[idx]; } + uint16_t& get(size_t idx) { return content[idx]; } + uint16_t content[TIMING_LOG_NUM_SLOTS]; + } timing_log_; // variables exposed on protocol Error error_ = ERROR_NONE; // Do not write to this variable directly! // It is for exclusive use by the safety_critical_... functions. - ArmedState_t armed_state_ = ARMED_STATE_DISARMED; + ArmedState armed_state_ = ARMED_STATE_DISARMED; bool is_calibrated_ = config_.pre_calibrated; Iph_BC_t current_meas_ = {0.0f, 0.0f}; Iph_BC_t DC_calib_ = {0.0f, 0.0f}; @@ -190,95 +170,12 @@ public: .async_phase_vel = 0.0f, .async_phase_offset = 0.0f, }; - DRV8301_FaultType_e drv_fault_ = DRV8301_FaultType_NoFault; + struct : GateDriverIntf { + DrvFault drv_fault = DRV_FAULT_NO_FAULT; + } gate_driver_exported_; DRV_SPI_8301_Vars_t gate_driver_regs_; //Local view of DRV registers (initialized by DRV8301_setup) float thermal_current_lim_ = 10.0f; //[A] float inverter_temp_ = 20.0f; - - // Communication protocol definitions - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_property("error", &error_), - make_protocol_ro_property("armed_state", &armed_state_), - make_protocol_ro_property("is_calibrated", &is_calibrated_), - make_protocol_ro_property("current_meas_phB", ¤t_meas_.phB), - make_protocol_ro_property("current_meas_phC", ¤t_meas_.phC), - make_protocol_property("DC_calib_phB", &DC_calib_.phB), - make_protocol_property("DC_calib_phC", &DC_calib_.phC), - make_protocol_property("phase_current_rev_gain", &phase_current_rev_gain_), - make_protocol_ro_property("thermal_current_lim", &thermal_current_lim_), - make_protocol_ro_property("inverter_temp", &inverter_temp_), - make_protocol_object("current_control", - make_protocol_property("p_gain", ¤t_control_.p_gain), - make_protocol_property("i_gain", ¤t_control_.i_gain), - make_protocol_property("v_current_control_integral_d", ¤t_control_.v_current_control_integral_d), - make_protocol_property("v_current_control_integral_q", ¤t_control_.v_current_control_integral_q), - make_protocol_property("Ibus", ¤t_control_.Ibus), - make_protocol_property("final_v_alpha", ¤t_control_.final_v_alpha), - make_protocol_property("final_v_beta", ¤t_control_.final_v_beta), - make_protocol_property("Id_setpoint", ¤t_control_.Id_setpoint), - make_protocol_ro_property("Iq_setpoint", ¤t_control_.Iq_setpoint), - make_protocol_property("Iq_measured", ¤t_control_.Iq_measured), - make_protocol_property("Id_measured", ¤t_control_.Id_measured), - make_protocol_property("I_measured_report_filter_k", ¤t_control_.I_measured_report_filter_k), - make_protocol_ro_property("max_allowed_current", ¤t_control_.max_allowed_current), - make_protocol_ro_property("overcurrent_trip_level", ¤t_control_.overcurrent_trip_level), - make_protocol_property("acim_rotor_flux", ¤t_control_.acim_rotor_flux), - make_protocol_ro_property("async_phase_vel", ¤t_control_.async_phase_vel), - make_protocol_property("async_phase_offset", ¤t_control_.async_phase_offset) - ), - make_protocol_object("gate_driver", - make_protocol_ro_property("drv_fault", &drv_fault_) - // make_protocol_ro_property("status_reg_1", &gate_driver_regs_.Stat_Reg_1_Value), - // make_protocol_ro_property("status_reg_2", &gate_driver_regs_.Stat_Reg_2_Value), - // make_protocol_ro_property("ctrl_reg_1", &gate_driver_regs_.Ctrl_Reg_1_Value), - // make_protocol_ro_property("ctrl_reg_2", &gate_driver_regs_.Ctrl_Reg_2_Value) - ), - make_protocol_object("timing_log", - make_protocol_ro_property("TIMING_LOG_GENERAL", &timing_log_[TIMING_LOG_GENERAL]), - make_protocol_ro_property("TIMING_LOG_ADC_CB_I", &timing_log_[TIMING_LOG_ADC_CB_I]), - make_protocol_ro_property("TIMING_LOG_ADC_CB_DC", &timing_log_[TIMING_LOG_ADC_CB_DC]), - make_protocol_ro_property("TIMING_LOG_MEAS_R", &timing_log_[TIMING_LOG_MEAS_R]), - make_protocol_ro_property("TIMING_LOG_MEAS_L", &timing_log_[TIMING_LOG_MEAS_L]), - make_protocol_ro_property("TIMING_LOG_ENC_CALIB", &timing_log_[TIMING_LOG_ENC_CALIB]), - make_protocol_ro_property("TIMING_LOG_IDX_SEARCH", &timing_log_[TIMING_LOG_IDX_SEARCH]), - make_protocol_ro_property("TIMING_LOG_FOC_VOLTAGE", &timing_log_[TIMING_LOG_FOC_VOLTAGE]), - make_protocol_ro_property("TIMING_LOG_FOC_CURRENT", &timing_log_[TIMING_LOG_FOC_CURRENT]), - make_protocol_ro_property("TIMING_LOG_SPI_START", &timing_log_[TIMING_LOG_SPI_START]), - make_protocol_ro_property("TIMING_LOG_SAMPLE_NOW", &timing_log_[TIMING_LOG_SAMPLE_NOW]), - make_protocol_ro_property("TIMING_LOG_SPI_END", &timing_log_[TIMING_LOG_SPI_END]) - ), - make_protocol_object("config", - make_protocol_property("pre_calibrated", &config_.pre_calibrated, - [](void* ctx) { static_cast(ctx)->is_calibrated_ = - static_cast(ctx)->is_calibrated_ || static_cast(ctx)->config_.pre_calibrated; }, this), - make_protocol_property("pole_pairs", &config_.pole_pairs), - make_protocol_property("calibration_current", &config_.calibration_current), - make_protocol_property("resistance_calib_max_voltage", &config_.resistance_calib_max_voltage), - make_protocol_property("phase_inductance", &config_.phase_inductance, - [](void* ctx) { static_cast(ctx)->update_current_controller_gains(); }, this), - make_protocol_property("phase_resistance", &config_.phase_resistance, - [](void* ctx) { static_cast(ctx)->update_current_controller_gains(); }, this), - make_protocol_property("direction", &config_.direction), - make_protocol_property("motor_type", &config_.motor_type), - make_protocol_property("current_lim", &config_.current_lim), - make_protocol_property("current_lim_margin", &config_.current_lim_margin), - make_protocol_property("inverter_temp_limit_lower", &config_.inverter_temp_limit_lower), - make_protocol_property("inverter_temp_limit_upper", &config_.inverter_temp_limit_upper), - make_protocol_property("requested_current_range", &config_.requested_current_range), - make_protocol_property("current_control_bandwidth", &config_.current_control_bandwidth, - [](void* ctx) { static_cast(ctx)->update_current_controller_gains(); }, this), - make_protocol_property("acim_slip_velocity", &config_.acim_slip_velocity), - make_protocol_property("acim_gain_min_flux", &config_.acim_gain_min_flux), - make_protocol_property("acim_autoflux_min_Id", &config_.acim_autoflux_min_Id), - make_protocol_property("acim_autoflux_enable", &config_.acim_autoflux_enable), - make_protocol_property("acim_autoflux_attack_gain", &config_.acim_autoflux_attack_gain), - make_protocol_property("acim_autoflux_decay_gain", &config_.acim_autoflux_decay_gain) - ) - ); - } }; -DEFINE_ENUM_FLAG_OPERATORS(Motor::Error) - #endif // __MOTOR_HPP diff --git a/Firmware/MotorControl/odrive_main.h b/Firmware/MotorControl/odrive_main.h index 6ae7594e..a3eb4447 100644 --- a/Firmware/MotorControl/odrive_main.h +++ b/Firmware/MotorControl/odrive_main.h @@ -10,6 +10,8 @@ #ifdef __cplusplus #include +#include +#include extern "C" { #endif @@ -41,11 +43,13 @@ static const int current_meas_hz = CURRENT_MEAS_HZ; // extern const float elec_rad_per_enc; extern uint32_t _reboot_cookie; -extern bool user_config_loaded_; extern uint64_t serial_number; extern char serial_number_str[13]; +#ifdef __cplusplus +} + typedef struct { bool fully_booted; uint32_t uptime; // [ms] @@ -67,11 +71,10 @@ typedef struct { uint32_t stack_usage_usb_irq; uint32_t stack_usage_startup; uint32_t stack_usage_can; -} SystemStats_t; -extern SystemStats_t system_stats_; -#ifdef __cplusplus -} + USBStats_t& usb = usb_stats_; + I2CStats_t& i2c = i2c_stats_; +} SystemStats_t; struct PWMMapping_t { endpoint_ref_t endpoint; @@ -148,8 +151,6 @@ struct BoardConfig_t { */ uint32_t uart_baudrate = 115200; }; -extern BoardConfig_t board_config; -extern bool user_config_loaded_; // Forward Declarations class Axis; @@ -176,6 +177,7 @@ inline ENUMTYPE &operator &= (ENUMTYPE &a, ENUMTYPE b) { return reinterpret_cast inline ENUMTYPE &operator ^= (ENUMTYPE &a, ENUMTYPE b) { return reinterpret_cast(reinterpret_cast&>(a) ^= static_cast>(b)); } \ inline ENUMTYPE operator ~ (ENUMTYPE a) { return static_cast(~static_cast>(a)); } +#include "autogen/interfaces.hpp" // ODrive specific includes #include @@ -190,12 +192,79 @@ inline ENUMTYPE operator ~ (ENUMTYPE a) { return static_cast(~static_c #include #include -#endif // __cplusplus +#include "autogen/version.h" // general system functions defined in main.cpp -void save_configuration(void); -void erase_configuration(void); -void enter_dfu_mode(void); +class ODrive : public OdriveIntf { +public: + void save_configuration() override; + void erase_configuration() override; + void reboot() override { NVIC_SystemReset(); } + void enter_dfu_mode() override; + + float get_oscilloscope_val(uint32_t index) override { + return oscilloscope[index]; + } + + float get_adc_voltage(uint32_t gpio) override { + return ::get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); + } + + int32_t test_function(int32_t delta) override { + static int cnt = 0; + return cnt += delta; + } + + Axis& get_axis(int num) { return *axes[num]; } + ODriveCAN& get_can() { return *odCAN; } + + float& vbus_voltage_ = ::vbus_voltage; // TODO: make this the actual variable + float& ibus_ = ::ibus_; // TODO: make this the actual variable + + const uint64_t& serial_number_ = ::serial_number; + +#if HW_VERSION_MAJOR == 3 + // Determine start address of the OTP struct: + // The OTP is organized into 16-byte blocks. + // If the first block starts with "0xfe" we use the first block. + // If the first block starts with "0x00" and the second block starts with "0xfe", + // we use the second block. This gives the user the chance to screw up once. + // If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL). + const uint8_t* otp_ptr = + (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE : + (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL : + (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL : + (uint8_t*)(FLASH_OTP_BASE + 0x10); + + // Read hardware version from OTP if available, otherwise fall back + // to software defined version. + const uint8_t hw_version_major_ = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR; + const uint8_t hw_version_minor_ = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR; + const uint8_t hw_version_variant_ = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE; +#else +#error "not implemented" +#endif + + // the corresponding macros are defined in the autogenerated version.h + const uint8_t fw_version_major_ = FW_VERSION_MAJOR; + const uint8_t fw_version_minor_ = FW_VERSION_MINOR; + const uint8_t fw_version_revision_ = FW_VERSION_REVISION; + const uint8_t fw_version_unreleased_ = FW_VERSION_UNRELEASED; // 0 for official releases, 1 otherwise + + bool& brake_resistor_armed_ = ::brake_resistor_armed; // TODO: make this the actual variable + bool& brake_resistor_saturated_ = ::brake_resistor_saturated; // TODO: make this the actual variable + + SystemStats_t system_stats_; + + BoardConfig_t config_; + bool user_config_loaded_; + + uint32_t test_property_ = 0; +}; + +extern ODrive odrv; // defined in main.cpp + +#endif // __cplusplus #endif /* __ODRIVE_MAIN_H */ diff --git a/Firmware/MotorControl/sensorless_estimator.hpp b/Firmware/MotorControl/sensorless_estimator.hpp index dd48c705..99c339be 100644 --- a/Firmware/MotorControl/sensorless_estimator.hpp +++ b/Firmware/MotorControl/sensorless_estimator.hpp @@ -1,13 +1,8 @@ #ifndef __SENSORLESS_ESTIMATOR_HPP #define __SENSORLESS_ESTIMATOR_HPP -class SensorlessEstimator { +class SensorlessEstimator : public SensorlessEstimatorIntf { public: - enum Error { - ERROR_NONE = 0, - ERROR_UNSTABLE_GAIN = 0x01, - }; - struct Config_t { float observer_gain = 1000.0f; // [rad/s] float pll_bandwidth = 1000.0f; // [rad/s] @@ -32,25 +27,6 @@ public: float flux_state_[2] = {0.0f, 0.0f}; // [Vs] float V_alpha_beta_memory_[2] = {0.0f, 0.0f}; // [V] bool estimator_good_ = false; - - // Communication protocol definitions - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_property("error", &error_), - make_protocol_property("phase", &phase_), - make_protocol_property("pll_pos", &pll_pos_), - make_protocol_property("vel_estimate", &vel_estimate_), - // make_protocol_property("pll_kp", &pll_kp_), - // make_protocol_property("pll_ki", &pll_ki_), - make_protocol_object("config", - make_protocol_property("observer_gain", &config_.observer_gain), - make_protocol_property("pll_bandwidth", &config_.pll_bandwidth), - make_protocol_property("pm_flux_linkage", &config_.pm_flux_linkage) - ) - ); - } }; -DEFINE_ENUM_FLAG_OPERATORS(SensorlessEstimator::Error) - #endif /* __SENSORLESS_ESTIMATOR_HPP */ diff --git a/Firmware/MotorControl/trapTraj.hpp b/Firmware/MotorControl/trapTraj.hpp index fd142da5..c3df57b9 100644 --- a/Firmware/MotorControl/trapTraj.hpp +++ b/Firmware/MotorControl/trapTraj.hpp @@ -20,16 +20,6 @@ public: float Vmax, float Amax, float Dmax); Step_t eval(float t); - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_object("config", - make_protocol_property("vel_limit", &config_.vel_limit), - make_protocol_property("accel_limit", &config_.accel_limit), - make_protocol_property("decel_limit", &config_.decel_limit) - ) - ); - } - Axis* axis_ = nullptr; // set by Axis constructor Config_t& config_; diff --git a/Firmware/Tupfile.lua b/Firmware/Tupfile.lua index 4577bde1..dec3547d 100644 --- a/Firmware/Tupfile.lua +++ b/Firmware/Tupfile.lua @@ -1,6 +1,17 @@ tup.include('build.lua') +tup.frule{inputs={'fibre/cpp/interfaces_template.j2'}, command='python3 interface_generator.py --definitions odrive-interface.yaml --template %f --output %o', outputs='autogen/interfaces.hpp'} +tup.frule{inputs={'fibre/cpp/function_stubs_template.j2'}, command='python3 interface_generator.py --definitions odrive-interface.yaml --template %f --output %o', outputs='autogen/function_stubs.hpp'} +tup.frule{inputs={'fibre/cpp/endpoints_template.j2'}, command='python3 interface_generator.py --definitions odrive-interface.yaml --template %f --output %o', outputs='autogen/endpoints.hpp'} +tup.frule{inputs={'ascii_type_info_template.j2'}, command='python3 interface_generator.py --definitions odrive-interface.yaml --template %f --output %o', outputs='autogen/ascii_type_info.hpp'} + +tup.frule{ + command='python ../tools/odrive/version.py --output %o', + outputs={'autogen/version.h'} +} + + -- Switch between board versions boardversion = tup.getconfig("BOARD_VERSION") if boardversion == "v3.1" then @@ -86,7 +97,6 @@ if tup.getconfig("STRICT") == "true" then FLAGS += '-Werror' end - -- C-specific flags FLAGS += '-D__weak="__attribute__((weak))"' FLAGS += '-D__packed="__attribute__((__packed__))"' @@ -145,10 +155,6 @@ build{ includes=stm_includes } -tup.frule{ - command='python ../tools/odrive/version.py --output %o', - outputs={'build/version.h'} -} build{ name='ODriveFirmware', diff --git a/Firmware/ascii_type_info_template.j2 b/Firmware/ascii_type_info_template.j2 new file mode 100644 index 00000000..200eb1ba --- /dev/null +++ b/Firmware/ascii_type_info_template.j2 @@ -0,0 +1,90 @@ +/*[# This is the original template, thus the warning below does not apply to this file #] + * ============================ WARNING ============================ + * ==== This is an autogenerated file. ==== + * ==== Any changes to this file will be lost when recompiling. ==== + * ================================================================= + * + * This file contains support functions for the ODrive ASCII protocol. + * + * TODO: might generalize this as an approach to runtime introspection. + */ + + +class TypeInfo; + +struct PropertyInfo { + const char * name; + void*(*getter)(void*); + TypeInfo* type_info; +}; + +class TypeInfo { +public: + TypeInfo(const PropertyInfo* property_table, size_t property_table_length) + : property_table_(property_table), property_table_length_(property_table_length) {} + + //virtual bool read_string(void* ctx) { return false; }; + //virtual bool write_string(void* ctx) { return false; }; + + const PropertyInfo* get_property_info(const char * name, size_t length) { + for (const PropertyInfo* prop = property_table_; prop < (property_table_ + property_table_length_); ++prop) { + if (!strncmp(name, prop->name, length)) { + return prop; + } + } + return nullptr; + } + +private: + const PropertyInfo* property_table_; + size_t property_table_length_; +}; + + +class Introspectable { +public: + Introspectable(void* obj, TypeInfo* type_info) : obj_(obj), type_info_(type_info) {} + + Introspectable get_child(const char * path, size_t length) { + Introspectable current = *this; + + const char * begin = path; + const char * end = path + length; + + while ((begin < end) && current.obj_ && current.type_info_) { + const char * end_of_token = std::find(begin, end, '.'); + const PropertyInfo* prop_info = current.type_info_->get_property_info(begin, end_of_token - begin); + if (prop_info) { + current = Introspectable{(*prop_info->getter)(obj_), prop_info->type_info}; + } else { + current = Introspectable{nullptr, nullptr}; + } + begin = std::min(end, end_of_token + 1); + } + + return current; + }; + +private: + void* obj_; + TypeInfo* type_info_; +}; + +[% for intf in interfaces.values() %] + +template +struct [[intf.fullname | to_pascal_case]]TypeInfo : TypeInfo { + static const PropertyInfo property_table[]; + static const TypeInfo singleton; +}; + +template +const PropertyInfo [[intf.name | to_pascal_case]]TypeInfo::property_table[] = { +[%- for property in intf.attributes.values() %] + {"[[property.name]]", [](void* obj){ return (void*)static_cast<[[property.type.c_type]]*>(&((T*)obj)->[[property.name | to_snake_case]]); }, [[property.type.fullname | to_pascal_case]]TypeInfo().[[property.name | to_snake_case]])>::singleton}, +[%- endfor %] +}; +template +const TypeInfo [[intf.fullname | to_pascal_case]]TypeInfo::singleton{[[intf.fullname | to_pascal_case]]TypeInfo::property_table, sizeof([[intf.fullname | to_pascal_case]]TypeInfo::property_table) / sizeof([[intf.fullname | to_pascal_case]]TypeInfo::property_table[0])}; + +[% endfor %] diff --git a/Firmware/build.lua b/Firmware/build.lua index 016f6d8e..0f91697f 100644 --- a/Firmware/build.lua +++ b/Firmware/build.lua @@ -72,7 +72,7 @@ function GCCToolchain(prefix, builddir, compiler_flags, linker_flags) else extra_outputs = {} end - if src == 'communication/communication.cpp' then extra_inputs = 'build/version.h' end -- TODO: fix hack + extra_inputs = {'autogen/version.h', 'autogen/interfaces.hpp', 'autogen/function_stubs.hpp', 'autogen/endpoints.hpp'} -- TODO: fix hack tup.frule{ inputs= { src, extra_inputs=extra_inputs }, command=compiler..' -c %f '.. diff --git a/Firmware/communication/ascii_protocol.cpp b/Firmware/communication/ascii_protocol.cpp index 628dea63..4eaaf611 100644 --- a/Firmware/communication/ascii_protocol.cpp +++ b/Firmware/communication/ascii_protocol.cpp @@ -8,12 +8,15 @@ /* Includes ------------------------------------------------------------------*/ #include "odrive_main.h" -#include "../build/version.h" // autogenerated based on Git state +#include "../autogen/version.h" // autogenerated based on Git state #include "communication.h" #include "ascii_protocol.hpp" #include #include +//#include "autogen/interfaces.hpp" +//#include "autogen/ascii_type_info.hpp" + /* Private macros ------------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Global constant data ------------------------------------------------------*/ @@ -208,19 +211,20 @@ void ASCII_protocol_process_line(const uint8_t* buffer, size_t len, StreamSink& // respond(response_channel, use_checksum, "Signature: %#x", STM_ID_GetSignature()); // respond(response_channel, use_checksum, "Revision: %#x", STM_ID_GetRevision()); // respond(response_channel, use_checksum, "Flash Size: %#x KiB", STM_ID_GetFlashSize()); - respond(response_channel, use_checksum, "Hardware version: %d.%d-%dV", HW_VERSION_MAJOR, HW_VERSION_MINOR, HW_VERSION_VOLTAGE); - respond(response_channel, use_checksum, "Firmware version: %d.%d.%d", FW_VERSION_MAJOR, FW_VERSION_MINOR, FW_VERSION_REVISION); + respond(response_channel, use_checksum, "Hardware version: %d.%d-%dV", odrv.hw_version_major_, odrv.hw_version_minor_, odrv.hw_version_variant_); + respond(response_channel, use_checksum, "Firmware version: %d.%d.%d", odrv.fw_version_major_, odrv.fw_version_minor_, odrv.fw_version_revision_); respond(response_channel, use_checksum, "Serial number: %s", serial_number_str); } else if (cmd[0] == 's'){ // System if(cmd[1] == 's') { // Save config - save_configuration(); + odrv.save_configuration(); } else if (cmd[1] == 'e'){ // Erase config - erase_configuration(); + odrv.erase_configuration(); } else if (cmd[1] == 'r'){ // Reboot - NVIC_SystemReset(); + odrv.reboot(); } +#if 0 } else if (cmd[0] == 'r') { // read property char name[MAX_LINE_LENGTH]; int numscan = sscanf(cmd, "r %255s", name); @@ -256,6 +260,7 @@ void ASCII_protocol_process_line(const uint8_t* buffer, size_t len, StreamSink& respond(response_channel, use_checksum, "not implemented"); } } +#endif } else if (cmd[0] == 'u') { // Update axis watchdog. unsigned motor_number; diff --git a/Firmware/communication/can_simple.cpp b/Firmware/communication/can_simple.cpp index 5ff8009a..4ec91660 100644 --- a/Firmware/communication/can_simple.cpp +++ b/Firmware/communication/can_simple.cpp @@ -188,7 +188,7 @@ void CANSimple::set_axis_nodeid_callback(Axis* axis, can_Message_t& msg) { } void CANSimple::set_axis_requested_state_callback(Axis* axis, can_Message_t& msg) { - axis->requested_state_ = static_cast(can_getSignal(msg, 0, 16, true)); + axis->requested_state_ = static_cast(can_getSignal(msg, 0, 16, true)); } void CANSimple::set_axis_startup_config_callback(Axis* axis, can_Message_t& msg) { // Not Implemented diff --git a/Firmware/communication/communication.cpp b/Firmware/communication/communication.cpp index c318040b..4e732a9c 100644 --- a/Firmware/communication/communication.cpp +++ b/Firmware/communication/communication.cpp @@ -13,7 +13,7 @@ #include "utils.hpp" #include "gpio_utils.hpp" -#include "../build/version.h" // autogenerated based on Git state +#include "../autogen/version.h" // autogenerated based on Git state #include #include @@ -36,50 +36,11 @@ char serial_number_str[13]; // 12 digits + null termination /* Private constant data -----------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ -#if HW_VERSION_MAJOR == 3 -// Determine start address of the OTP struct: -// The OTP is organized into 16-byte blocks. -// If the first block starts with "0xfe" we use the first block. -// If the first block starts with "0x00" and the second block starts with "0xfe", -// we use the second block. This gives the user the chance to screw up once. -// If none of the above is the case, we consider the OTP invalid (otp_ptr will be NULL). -const uint8_t* otp_ptr = - (*(uint8_t*)FLASH_OTP_BASE == 0xfe) ? (uint8_t*)FLASH_OTP_BASE : - (*(uint8_t*)FLASH_OTP_BASE != 0x00) ? NULL : - (*(uint8_t*)(FLASH_OTP_BASE + 0x10) != 0xfe) ? NULL : - (uint8_t*)(FLASH_OTP_BASE + 0x10); - -// Read hardware version from OTP if available, otherwise fall back -// to software defined version. -const uint8_t hw_version_major = otp_ptr ? otp_ptr[3] : HW_VERSION_MAJOR; -const uint8_t hw_version_minor = otp_ptr ? otp_ptr[4] : HW_VERSION_MINOR; -const uint8_t hw_version_variant = otp_ptr ? otp_ptr[5] : HW_VERSION_VOLTAGE; -#else -#error "not implemented" -#endif - -// the corresponding macros are defined in the autogenerated version.h -const uint8_t fw_version_major = FW_VERSION_MAJOR; -const uint8_t fw_version_minor = FW_VERSION_MINOR; -const uint8_t fw_version_revision = FW_VERSION_REVISION; -const uint8_t fw_version_unreleased = FW_VERSION_UNRELEASED; // 0 for official releases, 1 otherwise - osThreadId comm_thread; const uint32_t stack_size_comm_thread = 4096; // Bytes volatile bool endpoint_list_valid = false; -static uint32_t test_property = 0; - /* Private function prototypes -----------------------------------------------*/ - -auto make_protocol_definitions(PWMMapping_t& mapping) { - return make_protocol_member_list( - make_protocol_property("endpoint", &mapping.endpoint), - make_protocol_property("min", &mapping.min), - make_protocol_property("max", &mapping.max) - ); -} - /* Function implementations --------------------------------------------------*/ void init_communication(void) { @@ -96,120 +57,6 @@ void init_communication(void) { float oscilloscope[OSCILLOSCOPE_SIZE] = {0}; size_t oscilloscope_pos = 0; -// Helper class because the protocol library doesn't yet -// support non-member functions -// TODO: make this go away -class StaticFunctions { -public: - void save_configuration_helper() { save_configuration(); } - void erase_configuration_helper() { erase_configuration(); } - void NVIC_SystemReset_helper() { NVIC_SystemReset(); } - void enter_dfu_mode_helper() { enter_dfu_mode(); } - float get_oscilloscope_val(uint32_t index) { return oscilloscope[index]; } - float get_adc_voltage_(uint32_t gpio) { return get_adc_voltage(get_gpio_port_by_pin(gpio), get_gpio_pin_by_pin(gpio)); } - int32_t test_function(int32_t delta) { static int cnt = 0; return cnt += delta; } -} static_functions; - -// When adding new functions/variables to the protocol, be careful not to -// blow the communication stack. You can check comm_stack_info to see -// how much headroom you have. -static inline auto make_obj_tree() { - return make_protocol_member_list( - make_protocol_ro_property("vbus_voltage", &vbus_voltage), - make_protocol_ro_property("ibus", &ibus_), - make_protocol_ro_property("serial_number", &serial_number), - make_protocol_ro_property("hw_version_major", &hw_version_major), - make_protocol_ro_property("hw_version_minor", &hw_version_minor), - make_protocol_ro_property("hw_version_variant", &hw_version_variant), - make_protocol_ro_property("fw_version_major", &fw_version_major), - make_protocol_ro_property("fw_version_minor", &fw_version_minor), - make_protocol_ro_property("fw_version_revision", &fw_version_revision), - make_protocol_ro_property("fw_version_unreleased", &fw_version_unreleased), - make_protocol_ro_property("user_config_loaded", const_cast(&user_config_loaded_)), - make_protocol_ro_property("brake_resistor_armed", &brake_resistor_armed), - make_protocol_property("brake_resistor_saturated", &brake_resistor_saturated), - make_protocol_object("system_stats", - make_protocol_ro_property("uptime", &system_stats_.uptime), - make_protocol_ro_property("min_heap_space", &system_stats_.min_heap_space), - make_protocol_ro_property("min_stack_space_axis0", &system_stats_.min_stack_space_axis0), - make_protocol_ro_property("min_stack_space_axis1", &system_stats_.min_stack_space_axis1), - make_protocol_ro_property("min_stack_space_comms", &system_stats_.min_stack_space_comms), - make_protocol_ro_property("min_stack_space_usb", &system_stats_.min_stack_space_usb), - make_protocol_ro_property("min_stack_space_uart", &system_stats_.min_stack_space_uart), - make_protocol_ro_property("min_stack_space_can", &system_stats_.min_stack_space_can), - make_protocol_ro_property("min_stack_space_usb_irq", &system_stats_.min_stack_space_usb_irq), - make_protocol_ro_property("min_stack_space_startup", &system_stats_.min_stack_space_startup), - make_protocol_ro_property("stack_usage_axis0", &system_stats_.stack_usage_axis0), - make_protocol_ro_property("stack_usage_axis1", &system_stats_.stack_usage_axis1), - make_protocol_ro_property("stack_usage_comms", &system_stats_.stack_usage_comms), - make_protocol_ro_property("stack_usage_usb", &system_stats_.stack_usage_usb), - make_protocol_ro_property("stack_usage_uart", &system_stats_.stack_usage_uart), - make_protocol_ro_property("stack_usage_usb_irq", &system_stats_.stack_usage_usb_irq), - make_protocol_ro_property("stack_usage_startup", &system_stats_.stack_usage_startup), - make_protocol_ro_property("stack_usage_can", &system_stats_.stack_usage_can), - make_protocol_object("usb", - make_protocol_ro_property("rx_cnt", &usb_stats_.rx_cnt), - make_protocol_ro_property("tx_cnt", &usb_stats_.tx_cnt), - make_protocol_ro_property("tx_overrun_cnt", &usb_stats_.tx_overrun_cnt) - ), - make_protocol_object("i2c", - make_protocol_ro_property("addr", &i2c_stats_.addr), - make_protocol_ro_property("addr_match_cnt", &i2c_stats_.addr_match_cnt), - make_protocol_ro_property("rx_cnt", &i2c_stats_.rx_cnt), - make_protocol_ro_property("error_cnt", &i2c_stats_.error_cnt) - ) - ), - make_protocol_object("config", - make_protocol_property("brake_resistance", &board_config.brake_resistance), - make_protocol_property("max_regen_current", &board_config.max_regen_current), - // TODO: changing this currently requires a reboot - fix this - make_protocol_property("enable_uart", &board_config.enable_uart), - make_protocol_property("uart_baudrate", &board_config.uart_baudrate), // requires a reboot - make_protocol_property("enable_i2c_instead_of_can" , &board_config.enable_i2c_instead_of_can), // requires a reboot - make_protocol_property("enable_ascii_protocol_on_usb", &board_config.enable_ascii_protocol_on_usb), - make_protocol_property("dc_bus_undervoltage_trip_level", &board_config.dc_bus_undervoltage_trip_level), - make_protocol_property("dc_bus_overvoltage_trip_level", &board_config.dc_bus_overvoltage_trip_level), - make_protocol_property("enable_dc_bus_overvoltage_ramp", &board_config.enable_dc_bus_overvoltage_ramp), - make_protocol_property("dc_bus_overvoltage_ramp_start", &board_config.dc_bus_overvoltage_ramp_start), - make_protocol_property("dc_bus_overvoltage_ramp_end", &board_config.dc_bus_overvoltage_ramp_end), - make_protocol_property("dc_max_negative_current", &board_config.dc_max_negative_current), - make_protocol_property("dc_max_positive_current", &board_config.dc_max_positive_current), -#if HW_VERSION_MAJOR == 3 && HW_VERSION_MINOR >= 3 - make_protocol_object("gpio1_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[0])), - make_protocol_object("gpio2_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[1])), - make_protocol_object("gpio3_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[2])), -#endif - make_protocol_object("gpio4_pwm_mapping", make_protocol_definitions(board_config.pwm_mappings[3])), - - make_protocol_object("gpio3_analog_mapping", make_protocol_definitions(board_config.analog_mappings[2])), - make_protocol_object("gpio4_analog_mapping", make_protocol_definitions(board_config.analog_mappings[3])) - ), - make_protocol_object("axis0", axes[0]->make_protocol_definitions()), - make_protocol_object("axis1", axes[1]->make_protocol_definitions()), - make_protocol_object("can", odCAN->make_protocol_definitions()), - make_protocol_property("test_property", &test_property), - make_protocol_function("test_function", static_functions, &StaticFunctions::test_function, "delta"), - make_protocol_function("get_oscilloscope_val", static_functions, &StaticFunctions::get_oscilloscope_val, "index"), - make_protocol_function("get_adc_voltage", static_functions, &StaticFunctions::get_adc_voltage_, "gpio"), - make_protocol_function("save_configuration", static_functions, &StaticFunctions::save_configuration_helper), - make_protocol_function("erase_configuration", static_functions, &StaticFunctions::erase_configuration_helper), - make_protocol_function("reboot", static_functions, &StaticFunctions::NVIC_SystemReset_helper), - make_protocol_function("enter_dfu_mode", static_functions, &StaticFunctions::enter_dfu_mode_helper) - ); -} - -using tree_type = decltype(make_obj_tree()); -uint8_t tree_buffer[sizeof(tree_type)]; - - -void initTree(){ - // TODO: this is supposed to use the move constructor, but currently - // the compiler uses the copy-constructor instead. Thus the make_obj_tree - // ends up with a stupid stack size of around 8000 bytes. Fix this. - auto tree_ptr = new (tree_buffer) tree_type(make_obj_tree()); - fibre_publish(*tree_ptr); -} - // Thread to handle deffered processing of USB interrupt, and // read commands out of the UART DMA circular buffer void communication_task(void * ctx) { @@ -220,7 +67,7 @@ void communication_task(void * ctx) { start_uart_server(); start_usb_server(); - if (board_config.enable_i2c_instead_of_can) { + if (odrv.config_.enable_i2c_instead_of_can) { start_i2c_server(); } else { odCAN->start_can_server(); @@ -245,3 +92,7 @@ int _write(int file, const char* data, int len) { #endif return len; } + + +#include "../autogen/function_stubs.hpp" +#include "../autogen/endpoints.hpp" diff --git a/Firmware/communication/communication.h b/Firmware/communication/communication.h index 85519b39..6987aa11 100644 --- a/Firmware/communication/communication.h +++ b/Firmware/communication/communication.h @@ -17,10 +17,6 @@ extern "C" { extern osThreadId comm_thread; extern const uint32_t stack_size_comm_thread; -extern const uint8_t hw_version_major; -extern const uint8_t hw_version_minor; -extern const uint8_t hw_version_variant; - void init_communication(void); void initTree(); void communication_task(void * ctx); diff --git a/Firmware/communication/interface_can.cpp b/Firmware/communication/interface_can.cpp index 339ef9ff..659958c7 100644 --- a/Firmware/communication/interface_can.cpp +++ b/Firmware/communication/interface_can.cpp @@ -16,9 +16,9 @@ // std::unordered_map ctxMap; // Constructor is called by communication.cpp and the handle is assigned appropriately -ODriveCAN::ODriveCAN(CAN_HandleTypeDef *handle, ODriveCAN::Config_t &config) - : handle_{handle}, - config_{config} { +ODriveCAN::ODriveCAN(ODriveCAN::Config_t &config, CAN_HandleTypeDef *handle) + : config_{config}, + handle_{handle} { // ctxMap[handle_] = this; } @@ -32,7 +32,7 @@ void ODriveCAN::can_server_thread() { while (available()) { read(rxmsg); switch (config_.protocol) { - case CAN_PROTOCOL_SIMPLE: + case Config_t::PROTOCOL_SIMPLE: CANSimple::handle_can_message(rxmsg); break; } @@ -183,7 +183,7 @@ void ODriveCAN::send_heartbeat(Axis *axis) { uint32_t now = osKernelSysTick(); if ((now - axis->last_heartbeat_) >= axis->config_.can_heartbeat_rate_ms) { switch (config_.protocol) { - case CAN_PROTOCOL_SIMPLE: + case Config_t::PROTOCOL_SIMPLE: CANSimple::send_heartbeat(axis); break; } diff --git a/Firmware/communication/interface_can.hpp b/Firmware/communication/interface_can.hpp index fca28822..44791a33 100644 --- a/Firmware/communication/interface_can.hpp +++ b/Firmware/communication/interface_can.hpp @@ -19,23 +19,14 @@ enum { CAN_BAUD_1M = 1000000 }; -enum CAN_Protocol_t { - CAN_PROTOCOL_SIMPLE -}; - -class ODriveCAN { +class ODriveCAN : public OdriveIntf::CanIntf { public: - struct Config_t { + struct Config_t : ConfigIntf { uint32_t baud_rate = CAN_BAUD_250K; - CAN_Protocol_t protocol = CAN_PROTOCOL_SIMPLE; + Protocol protocol = PROTOCOL_SIMPLE; }; - enum Error { - ERROR_NONE = 0x00, - ERROR_DUPLICATE_CAN_IDS = 0x01 - }; - - ODriveCAN(CAN_HandleTypeDef *handle, ODriveCAN::Config_t &config); + ODriveCAN(ODriveCAN::Config_t &config, CAN_HandleTypeDef *handle); // Thread Relevant Data osThreadId thread_id_; @@ -55,24 +46,12 @@ class ODriveCAN { uint32_t write(can_Message_t &txmsg); bool read(can_Message_t &rxmsg); - // Communication Protocol Handling - auto make_protocol_definitions() { - return make_protocol_member_list( - make_protocol_property("error", &error_), - make_protocol_object("config", - make_protocol_ro_property("baud_rate", &config_.baud_rate)), - make_protocol_property("can_protocol", &config_.protocol), - make_protocol_function("set_baud_rate", *this, &ODriveCAN::set_baud_rate, "baudRate")); - } - - private: - CAN_HandleTypeDef *handle_ = nullptr; ODriveCAN::Config_t &config_; +private: + CAN_HandleTypeDef *handle_ = nullptr; + void set_baud_rate(uint32_t baudRate); }; - -DEFINE_ENUM_FLAG_OPERATORS(ODriveCAN::Error) - #endif // __INTERFACE_CAN_HPP diff --git a/Firmware/communication/interface_usb.cpp b/Firmware/communication/interface_usb.cpp index 21273dee..83632bcd 100644 --- a/Firmware/communication/interface_usb.cpp +++ b/Firmware/communication/interface_usb.cpp @@ -127,7 +127,7 @@ static void usb_server_thread(void * ctx) { // CDC Interface if (CDC_interface.data_pending) { CDC_interface.data_pending = false; - if (board_config.enable_ascii_protocol_on_usb) { + if (odrv.config_.enable_ascii_protocol_on_usb) { ASCII_protocol_parse_stream(CDC_interface.rx_buf, CDC_interface.rx_len, usb_stream_output); } else { diff --git a/Firmware/fibre/cpp/endpoints_template.j2 b/Firmware/fibre/cpp/endpoints_template.j2 new file mode 100644 index 00000000..98c5eb1d --- /dev/null +++ b/Firmware/fibre/cpp/endpoints_template.j2 @@ -0,0 +1,71 @@ +/*[# This is the original template, thus the warning below does not apply to this file #] + * ============================ WARNING ============================ + * ==== This is an autogenerated file. ==== + * ==== Any changes to this file will be lost when recompiling. ==== + * ================================================================= + * + * This file contains the toplevel handler for Fibre v0.1 endpoint operations. + * + * This endpoint-oriented approach will be deprecated in Fibre v0.2 in favor of + * a function-oriented approach and a more powerful object model. + * + */ +#ifndef __FIBRE_INTERFACES_HPP +#define __FIBRE_INTERFACES_HPP + +namespace fibre { + +const unsigned char embedded_json[] = [[embedded_endpoint_definitions | to_c_string]]; +const size_t embedded_json_length = sizeof(embedded_json) - 1; +const uint16_t json_crc_ = calc_crc16(PROTOCOL_VERSION, embedded_json, embedded_json_length); +const uint32_t json_version_id_ = (json_crc_ << 16) | calc_crc16(json_crc_, embedded_json, embedded_json_length); + +// Note: with -Og this function reserves a huge amount of stack space because it +// reserves separate space for the stack frame of each of the inlined functions. +// The minimum known set of flags to prevent this is `-O1 -fipa-sra`. +// `-O2` is a superset of this so that's what we use here. +bool endpoint_handler(int idx, cbufptr_t* input_buffer, bufptr_t* output_buffer) __attribute__ ((optimize(2))); + +bool endpoint_handler(int idx, cbufptr_t* input_buffer, bufptr_t* output_buffer) { + switch (idx) { +[%- for endpoint in endpoints %] + case [[endpoint.id]]: { return [[endpoint.function.fullname | to_snake_case]]([% for k, arg in endpoint.function.in.items() %][% if k in endpoint.in_bindings %]static_cast<[[arg.type.c_type]]>([[endpoint.in_bindings[k]]])[% else %]std::nullopt[% endif %], [% endfor %][% for k, arg in endpoint.function.out.items() %][% if k in endpoint.out_bindings %]static_cast<[[arg.type.c_type]]*>([[endpoint.out_bindings[k]]])[% else %]nullptr[% endif %], [% endfor %]input_buffer, output_buffer); } break; +[%- endfor %] + default: return false; + } +} + +bool is_endpoint_ref_valid(endpoint_ref_t endpoint_ref) { + if (endpoint_ref.json_crc != json_crc_) { + return false; + } + + switch (endpoint_ref.endpoint_id) { +[%- for endpoint in endpoints %] + case [[endpoint.id]]: return true; +[%- endfor %] + default: return false; + } +} + +bool set_endpoint_from_float(endpoint_ref_t endpoint_ref, float value) { + if (endpoint_ref.json_crc != json_crc_) { + return false; + } + + return false; + // TODO: implement + /*cbufptr_t input_buffer{}; + bufptr_t output_buffer{}; + + switch (idx) { +[%- for endpoint in endpoints %] + case [[endpoint.id]]: return [[endpoint.function.fullname | to_snake_case]]([% for k, arg in endpoint.function.in.items() %][% if k in endpoint.in_bindings %]static_cast<[[arg.type.c_type]]>([[endpoint.in_bindings[k]]])[% else %]std::nullopt[% endif %], [% endfor %]&input_buffer, &output_buffer); +[%- endfor %] + default: return false; + }*/ +} + +} + +#endif // __FIBRE_INTERFACES_HPP \ No newline at end of file diff --git a/Firmware/fibre/cpp/function_stubs_template.j2 b/Firmware/fibre/cpp/function_stubs_template.j2 new file mode 100644 index 00000000..759b49eb --- /dev/null +++ b/Firmware/fibre/cpp/function_stubs_template.j2 @@ -0,0 +1,40 @@ +/*[# This is the original template, thus the warning below does not apply to this file #] + * ============================ WARNING ============================ + * ==== This is an autogenerated file. ==== + * ==== Any changes to this file will be lost when recompiling. ==== + * ================================================================= + * + * This file contains serializing/deserializing stubs for the functions defined + * in your interface file. + * + */ + +#include + +[% for intf in interfaces.values() %] +[% for func in intf.functions.values() %] +static inline bool [[func.fullname | to_snake_case]]([% for arg in func.in.values() %]std::optional<[[arg.type.c_type]]> in_[[arg.name]], [% endfor %][% for arg in func.out.values() %][[arg.type.c_type]]* out_[[arg.name]], [% endfor %]fibre::cbufptr_t* input_buffer, fibre::bufptr_t* output_buffer) { +[%- if func.in %] + bool success = [% for arg in func.in.values() %](in_[[arg.name]].has_value() || (in_[[arg.name]] = fibre::Codec<[[arg.type.c_type]]>::decode(input_buffer)).has_value()[% if arg.optional %] || true[% endif %])[% if not loop.last %] + && [% endif %][% endfor %]; +[%- else %] + bool success = true; +[%- endif %] + if (!success) { + return false; + } +[%- if func.implementation %] + [% if func.out %]std::tuple<[% for arg in func.out.values() %][[arg.type.c_type]][[', ' if not loop.last]][% endfor %]> ret = [% endif %][[func.implementation]]([% for arg in func.in.values() %]in_[[arg.name]][% if not arg.optional %].value()[% endif %][[', ' if not loop.last]][% endfor %]); +[%- else %] + [% if func.out %]std::tuple<[% for arg in func.out.values() %][[arg.type.c_type]][[', ' if not loop.last]][% endfor %]> ret = [% endif %]in_[[(func.in.values() | first).name]].value()->[[func.name]]([% for arg in func.in.values() | skip_first %]in_[[arg.name]][% if not arg.optional %].value()[% endif %][[', ' if not loop.last]][% endfor %]); +[%- endif %] +[%- if func.out %] + return [% for arg in func.out.values() %]((out_[[arg.name]] && ((*out_[[arg.name]] = std::get<[[loop.index0]]>(ret)), true)) || fibre::Codec<[[arg.type.c_type]]>::encode(std::get<[[loop.index0]]>(ret), output_buffer))[% if not loop.last %] + && [% endif %][% endfor %]; +[%- else %] + return true; +[%- endif %] +} +[% endfor %] +[% endfor %] + diff --git a/Firmware/fibre/cpp/include/fibre/bufptr.hpp b/Firmware/fibre/cpp/include/fibre/bufptr.hpp new file mode 100644 index 00000000..2ce3fefb --- /dev/null +++ b/Firmware/fibre/cpp/include/fibre/bufptr.hpp @@ -0,0 +1,93 @@ +#ifndef __FIBRE_BUFPTR_HPP +#define __FIBRE_BUFPTR_HPP + +namespace fibre { + +static inline bool soft_assert(bool expr) { return expr; } // TODO: implement + +/** + * @brief Holds a reference to a buffer and a length. + * Since this class implements begin() and end(), you can use it with many + * standard algorithms that operate on iterable objects. + */ +template +struct generic_bufptr_t { + using iterator = T*; + using const_iterator = const T*; + + generic_bufptr_t(T* begin, size_t length) : begin_(begin), end_(begin + length) {} + + generic_bufptr_t(T* begin, T* end) : begin_(begin), end_(end) {} + + generic_bufptr_t() : begin_(nullptr), end_(nullptr) {} + + template + generic_bufptr_t(T (&begin)[I]) : generic_bufptr_t(begin, I) {} + + generic_bufptr_t(const std::vector>& vector) + : generic_bufptr_t(vector.data(), vector.size()) {} + + generic_bufptr_t(const generic_bufptr_t>& other) + : generic_bufptr_t(other.begin_, other.end_) {} + + generic_bufptr_t& operator+=(size_t num) { + if (!soft_assert(num <= size())) { + num = size(); + } + begin_ += num; + return *this; + } + + generic_bufptr_t operator++(int) { + generic_bufptr_t result = *this; + *this += 1; + return result; + } + + T& operator*() { + return *begin_; + } + + generic_bufptr_t take(size_t num) const { + if (!soft_assert(num <= size())) { + num = size(); + } + generic_bufptr_t result = {begin_, num}; + return result; + } + + generic_bufptr_t skip(size_t num, size_t* processed_bytes = nullptr) const { + if (!soft_assert(num <= size())) { + num = size(); + } + if (processed_bytes) + (*processed_bytes) += num; + return {begin_ + num, end_}; + } + + size_t size() const { + return end_ - begin_; + } + + bool empty() const { + return size() == 0; + } + + T*& begin() { return begin_; } + T*& end() { return end_; } + T* const & begin() const { return begin_; } + T* const & end() const { return end_; } + T& front() const { return *begin(); } + T& back() const { return *(end() - 1); } + T& operator[](size_t idx) { return *(begin() + idx); } + + T* begin_; + T* end_; +}; + +using cbufptr_t = generic_bufptr_t; +using bufptr_t = generic_bufptr_t; + +} + +#endif // __FIBRE_BUFPTR_HPP diff --git a/Firmware/fibre/cpp/include/fibre/cpp_utils.hpp b/Firmware/fibre/cpp/include/fibre/cpp_utils.hpp index 4b97f367..b2d84256 100644 --- a/Firmware/fibre/cpp/include/fibre/cpp_utils.hpp +++ b/Firmware/fibre/cpp/include/fibre/cpp_utils.hpp @@ -1,6 +1,3 @@ -#ifndef __CPP_UTILS_HPP -#define __CPP_UTILS_HPP - /* ## Advanced C++ Topics @@ -78,8 +75,20 @@ public: */ -// Backport definitions from C++14 -#if __cplusplus <= 201103L +#ifndef __CPP_UTILS_HPP +#define __CPP_UTILS_HPP + +#include +#include +#include +#include +//#include +#include +#include + +/* Backport features from C++14 and C++17 ------------------------------------*/ + +#if __cplusplus < 201402L namespace std { template< class T > using underlying_type_t = typename underlying_type::type; @@ -87,9 +96,377 @@ namespace std { // source: http://en.cppreference.com/w/cpp/types/enable_if template< bool B, class T = void > using enable_if_t = typename enable_if::type; + + // source: https://en.cppreference.com/w/cpp/types/conditional + template< bool B, class T, class F > + using conditional_t = typename conditional::type; + + // source: http://en.cppreference.com/w/cpp/utility/tuple/tuple_element + template + using tuple_element_t = typename tuple_element::type; + + // source: https://en.cppreference.com/w/cpp/types/remove_cv + template< class T > + using remove_cv_t = typename remove_cv::type; + template< class T > + using remove_const_t = typename remove_const::type; + template< class T > + using remove_volatile_t = typename remove_volatile::type; + template< class T > + using remove_reference_t = typename remove_reference::type; + + template< class T > + using decay_t = typename decay::type; + + // integer_sequence implementation adapted from + // https://stackoverflow.com/questions/17424477/implementation-c14-make-integer-sequence + + /// Class template integer_sequence + template + struct integer_sequence { + using type = integer_sequence; + typedef _Tp value_type; + static constexpr size_t size() noexcept { return sizeof...(_Idx); } + }; + + template + struct _merge_and_renumber; + + template + struct _merge_and_renumber, integer_sequence<_Tp, I2...>> + : integer_sequence<_Tp, I1..., (sizeof...(I1)+I2)...> + { }; + + template + struct make_integer_sequence + : _merge_and_renumber::type, + typename make_integer_sequence<_Tp, N - N/2>::type> + { }; + + template struct make_integer_sequence<_Tp, 0> : integer_sequence<_Tp> { }; + template struct make_integer_sequence<_Tp, 1> : integer_sequence<_Tp, 0> { }; + + /// Alias template index_sequence + template + using index_sequence = integer_sequence; + + /// Alias template make_index_sequence + template + using make_index_sequence = typename make_integer_sequence::type; } #endif +namespace fibre { + // Creates the index sequence { IFrom, IFrom + 1, IFrom + 2, ..., ITo - 1 } + template + struct make_integer_sequence_from_to_impl { + using type = typename make_integer_sequence_from_to_impl<_Tp, IFrom, ITo - 1, ITo - 1, I...>::type; + }; + + template + struct make_integer_sequence_from_to_impl<_Tp, IFrom, IFrom, I...> { + using type = std::index_sequence; + }; + + template + using make_integer_sequence_from_to = typename make_integer_sequence_from_to_impl<_Tp, IFrom, ITo>::type; +} + +#if __cplusplus < 201703L +namespace std { +//template>{}, int> = 0> +//using enable_ + +template struct invoke_result_impl; + +template +struct invoke_result_impl>{}>, + Fn, Args...> { + typedef decltype(std::mem_fn(std::declval())(std::declval()...)) type; +}; + +template +struct invoke_result_impl>{}>, + Fn, Args...> { + typedef decltype(std::declval()(std::declval()...)) type; +}; + +template +using invoke_result = invoke_result_impl; + +template +using invoke_result_t = typename invoke_result::type; + +template>{}, int> = 0 > +constexpr invoke_result_t invoke(Fn&& f, Args&&... args) + noexcept(noexcept(std::mem_fn(f)(std::forward(args)...))) +{ + return std::mem_fn(f)(std::forward(args)...); +} + +template>{}, int> = 0> +constexpr invoke_result_t invoke(Fn&& f, Args&&... args) + noexcept(noexcept(std::forward(f)(std::forward(args)...))) +{ + return std::forward(f)(std::forward(args)...); +} +} + +namespace std { +namespace detail { +template +struct apply_result_impl; + +// TODO: apply_result is not part of C++17, therefore we should move this out of +// the #if block +template +struct apply_result_impl> { + //typedef std::invoke_result_t...> type; + typedef std::invoke_result_t(std::declval()))...> type; +}; + +template +using apply_result = apply_result_impl>::value>>; + +template +using apply_result_t = typename apply_result::type; + +template +constexpr apply_result_t apply_impl( F&& f, Tuple&& t, std::index_sequence ) +{ + return std::invoke(std::forward(f), std::get(std::forward(t))...); +} +} // namespace detail + +template +constexpr detail::apply_result_t apply(F&& f, Tuple&& t) +{ + return detail::apply_impl(std::forward(f), std::forward(t), + std::make_index_sequence>::value>{}); +} +} + + +namespace std { + +template +struct identity { using type = T; }; + +template +struct overload_resolver; + +template<> +struct overload_resolver<> { void operator()() const; }; + +template +struct overload_resolver : overload_resolver { + using overload_resolver::operator(); + identity operator()(T) const; +}; + +template +struct index_of : integral_constant::value + 1)> {}; + +template +struct index_of : integral_constant {}; + +/** + * @brief Heavily simplified version of the C++17 std::variant. + * Whatever compiles should work as one would expect from the C++17 variant. + */ +template +class variant; + +// Empty variant is ill-formed. Only used for clean recursion here. +template<> +class variant<> { +public: + using storage_t = char[0]; + storage_t content_; + + static void selective_destructor(char* storage, size_t index) { + throw; + } + + static void selective_copy_constuctor(char* target, const char* source, size_t index) { + throw; + } + + static bool selective_eq(const char* lhs, const char* rhs, size_t index) { + throw; + } + + static bool selective_neq(const char* lhs, const char* rhs, size_t index) { + throw; + } + + template + static void selective_invoke_const(const char* content, size_t index, TFunc functor, TArgs&&... args) { + throw; + } + + template + static void selective_invoke(const char* content, size_t index, TFunc functor, TArgs&&... args) { + throw; + } +}; + +template +class variant { +public: + using storage_t = char[sizeof(T) > sizeof(typename variant::storage_t) ? sizeof(T) : sizeof(typename variant::storage_t)]; + + static void selective_copy_constuctor(char* target, const char* source, size_t index) { + if (index == 0) { + new ((T*)target) T{*(T*)source}; // in-place construction using first type's copy constructor + } else { + variant::selective_copy_constuctor(target, source, index - 1); + } + } + + static void selective_destructor(char* storage, size_t index) { + if (index == 0) { + ((T*)storage)->~T(); + } else { + variant::selective_destructor(storage, index - 1); + } + } + + static bool selective_eq(const char* lhs, const char* rhs, size_t index) { + if (index == 0) { + return ((*(T*)lhs) == (*(T*)rhs)); + } else { + return variant::selective_eq(lhs, rhs, index - 1); + } + } + + static bool selective_neq(const char* lhs, const char* rhs, size_t index) { + if (index == 0) { + return ((*(T*)lhs) != (*(T*)rhs)); + } else { + return variant::selective_neq(lhs, rhs, index - 1); + } + } + + template + static void selective_invoke_const(const char* content, size_t index, TFunc functor, TArgs&&... args) { + if (index == 0) { + functor(*(T*)content, std::forward(args)...); + } else { + variant::selective_invoke_const(content, index - 1, functor, std::forward(args)...); + } + } + + template + static void selective_invoke(char* content, size_t index, TFunc functor, TArgs&&... args) { + if (index == 0) { + functor(*(T*)content, std::forward(args)...); + } else { + variant::selective_invoke(content, index - 1, functor, std::forward(args)...); + } + } + + variant() : index_(0) { + new ((T*)content_) T{}; // in-place construction using first type's default constructor + } + + variant(const variant & other) : index_(other.index_) { + selective_copy_constuctor(content_, other.content_, index_); + } + + variant(variant&& other) : index_(other.index_) { + // TODO: implement + selective_copy_constuctor(content_, other.content_, index_); + } + + // Find the best match out of `T, Ts...` with `TArg` as the argument. + template + using best_match = decltype(overload_resolver()(std::declval())); + + template::type> //, typename=typename std::enable_if_t, variant>::value)>, typename TTarget=decltype(indicator_func(std::forward(std::declval()))), typename TIndex=index_of> + variant(TArg&& arg) { + new ((TTarget*)content_) TTarget{std::forward(arg)}; + index_ = index_of::value; + } + + ~variant() { + selective_destructor(content_, index_); + } + + inline variant& operator=(const variant & other) { + selective_destructor(content_, index_); + index_ = other.index_; + selective_copy_constuctor(content_, other.content_, index_); + return *this; + } + + inline bool operator==(const variant& rhs) const { + return (index_ == rhs.index_) && selective_eq(this->content_, rhs.content_, index_); + } + + inline bool operator!=(const variant& rhs) const { + return (index_ != rhs.index_) || selective_neq(this->content_, rhs.content_, index_); + } + + template + void invoke(TFunc functor, TArgs&&... args) const { + selective_invoke_const(content_, index_, functor, std::forward(args)...); + } + + template + void invoke(TFunc functor, TArgs&&... args) { + selective_invoke(content_, index_, functor, std::forward(args)...); + } + + storage_t content_; + size_t index_; + + size_t index() const { return index_; } +}; + +template +std::tuple_element_t>& get(std::variant& val) { + if (val.index() != I) + throw; + using T = std::tuple_element_t>; + return *((T*)val.content_); +} + +template +T& get(std::variant& val) { + constexpr size_t index = std::index_of::value; + return std::get(val); +} + +} // namespace std + +#endif + +/* Stuff that should be in the STL but isn't ---------------------------------*/ + +// source: https://en.cppreference.com/w/cpp/experimental/to_array +namespace detail { +template +constexpr std::array, N> + to_array_impl(T (&a)[N], std::index_sequence) +{ + return { {a[I]...} }; +} + +template +constexpr std::array, N> to_array(T (&a)[N]) +{ + return detail::to_array_impl(a, std::make_index_sequence{}); +} +} + + + +/* Custom utils --------------------------------------------------------------*/ + // @brief Supports various queries on a list of types template class TypeChecker; @@ -112,6 +489,7 @@ public: return std::is_base_of::value && TypeChecker::template all_are(); } + constexpr static const size_t count = TypeChecker::count + 1; }; template<> @@ -125,11 +503,17 @@ public: constexpr static inline bool all_are() { return std::true_type::value; } + constexpr static const size_t count = 0; }; +template +TypeChecker make_type_checker(Ts ...) { + return TypeChecker(); +} + #include #define ENABLE_IF(...) \ - typename = std::enable_if_t<__VA_ARGS__> + typename = typename std::enable_if_t<__VA_ARGS__> #define ENABLE_IF_SAME(a, b, type) \ template typename std::enable_if_t::value, type> @@ -151,15 +535,83 @@ class function_traits { public: template static TRet invoke(TObj& obj, TRet(TObj::*func_ptr)(TArgs...), std::tuple packed_args, TUnpackedArgs ... args) { - return invoke(obj, func_ptr, packed_args, args..., std::get(packed_args)); + return invoke(obj, func_ptr, packed_args, std::forward(args)..., std::get(packed_args)); } template static TRet invoke(TObj& obj, TRet(TObj::*func_ptr)(TArgs...), std::tuple packed_args, TArgs ... args) { - return (obj.*func_ptr)(args...); + return (obj.*func_ptr)(std::forward(args)...); } }; + +/* @brief return_type::type represents the C++ native return type +* of a function returning 0 or more arguments. +* +* For an empty TypeList, the return type is void. For a list with +* one type, the return type is equal to that type. For a list with +* more than one items, the return type is a tuple. +*/ +template +struct return_type; + +template<> +struct return_type<> { typedef void type; }; +template +struct return_type { typedef T type; }; +template +struct return_type { typedef std::tuple type; }; + + + +template +struct static_function_traits; + +// TODO: All invoke-related functions should be superseeded by a proper std::apply implementation +#if 0 +template +struct static_function_traits, std::tuple> { + using TRet = typename return_type::type; + + //template + //static std::tuple invoke(std::tuple packed_args, TUnpackedInputs ... args) { + // return invoke(packed_args, args..., std::get(packed_args)); + //} + + template + static std::tuple invoke(std::tuple& packed_args) { + return invoke_impl(packed_args, std::make_index_sequence()); + } + + template + static std::tuple invoke_impl(std::tuple packed_args, std::index_sequence) { + return invoke_impl_2(std::get(packed_args)...); + } + + //template + //static std::enable_if_t<(sizeof...(TOutputs) == 0), std::tuple> + template>*/> + static std::enable_if_t<(IOutputs == 0), std::tuple> + invoke_impl_2(TInputs ... args) { + Function(args...); + return std::make_tuple<>(); + } + + //template + //static std::enable_if_t<(sizeof...(TOutputs) == 1), std::tuple> + template>*/> + static std::enable_if_t<(IOutputs == 1), std::tuple> + invoke_impl_2(TInputs ... args) { + return std::make_tuple(Function(args...)); + } +// +// template= 2)> +// static /* std::enable_if_t= 2, */ std::tuple //> +// invoke_impl_2(std::tuple packed_args, TInputs ... args) { +// return Function(args...); +// } +}; + /* @brief Invoke a class member function with a variable number of arguments that are supplied as a tuple Example usage: @@ -180,4 +632,681 @@ TRet invoke_function_with_tuple(TObj& obj, TRet(TObj::*func_ptr)(TArgs...), std: return function_traits::template invoke<0>(obj, func_ptr, packed_args); } +template(*Function)(TIn...)> +std::tuple invoke_with_tuples(std::tuple inputs) { + static_function_traits::template invoke<0>(inputs); +} +#endif + + +template +struct sum_impl; +template +struct sum_impl { static constexpr TInt value = 0; }; +template +struct sum_impl { static constexpr TInt value = I + sum_impl::value; }; + +template +using sum = sum_impl; + + +// source: https://akrzemi1.wordpress.com/2017/05/18/asserts-in-constexpr-functions/ +#if defined NDEBUG +# define X_ASSERT(CHECK) void(0) +#else +# define X_ASSERT(CHECK) \ + ( (CHECK) ? void(0) : []{assert(!#CHECK);}() ) +#endif + +template +struct for_each_in_tuple_result_impl; + +template +struct for_each_in_tuple_result_impl> { + typedef std::tuple(std::declval())(std::get(std::declval())))...> type; +}; + +template +using for_each_in_tuple_result = for_each_in_tuple_result_impl>::value>>; + +template +using for_each_in_tuple_result_t = typename for_each_in_tuple_result::type; + +template +for_each_in_tuple_result_t for_each_in_tuple_impl(Fn&& f, Tuple&& t, std::index_sequence) { + return for_each_in_tuple_result_t(std::forward(f)(std::get(t))...); +} + +template +for_each_in_tuple_result_t for_each_in_tuple(Fn&& f, Tuple&& t) { + return for_each_in_tuple_impl(std::forward(f), std::forward(t), std::make_index_sequence>::value>{}); +} +//template +//for_each_in_tuple_result_t for_each_in_tuple(Fn&& f, Tuple&& t) { +// return 5; +//} + + +/* constexpr strings --------------------------------------------------------*/ +/* adapted from: +* https://akrzemi1.wordpress.com/2017/06/28/compile-time-string-concatenation/ +*/ + + +// TODO: the functionality +// sstring::substring, sstring::get_last_part and sstring::after_last_index_of and sstring::last_index_of +// was removed during refactoring. Add again if needed. + +/** + * @brief Represents a string that is known at compile time by encoding it as a + * type. + */ +template +struct sstring { + static constexpr const char chars[] = {CHARS..., 0}; + static constexpr const char* c_str() { return chars; } + static constexpr size_t size() { return sizeof...(CHARS); } + static constexpr std::array as_array() { return {CHARS...}; } + + template + constexpr bool operator==(const sstring & other) { + return as_array() == other.as_array(); + } +}; +template +constexpr const char sstring::chars[/*sizeof...(CHARS) + 1*/]; + +template +struct sstring_concat_impl; + +template +struct sstring_concat_impl, sstring> { + using type = sstring; +}; + +/** @brief Represents the result type of concatenating two static strings */ +template +using sstring_concat_t = typename sstring_concat_impl::type; + +/** @brief Concatenates two static strings */ +template +constexpr sstring operator+(sstring, sstring) { + return {}; +} + + +/** @brief Helper class for the MAKE_SSTRING macro */ +template +struct sstring_builder; + +template +struct sstring_builder<0, CHAR, CHARS...> { + using type = sstring<>; +}; + +template +struct sstring_builder { + using type = sstring_concat_t, typename sstring_builder::type>; +}; + +template +using sstring_builder_t = typename sstring_builder::type; + +#define MACRO_GET_1(str, i) \ + (sizeof(str) > (i) ? str[(i)] : 0) + +#define MACRO_GET_4(str, i) \ + MACRO_GET_1(str, i+0), \ + MACRO_GET_1(str, i+1), \ + MACRO_GET_1(str, i+2), \ + MACRO_GET_1(str, i+3) + +#define MACRO_GET_16(str, i) \ + MACRO_GET_4(str, i+0), \ + MACRO_GET_4(str, i+4), \ + MACRO_GET_4(str, i+8), \ + MACRO_GET_4(str, i+12) + +#define MACRO_GET_64(str, i) \ + MACRO_GET_16(str, i+0), \ + MACRO_GET_16(str, i+16), \ + MACRO_GET_16(str, i+32), \ + MACRO_GET_16(str, i+48) + +/** + * @brief Builds a compile-time string type from a string literal. + * + * Passing more than 64 characters will prune the string. + * + * Usage: + * MAKE_SSTRING("hello world") my_str{}; + * or + * auto my_str = MAKE_SSTRING("hello world"){}; + * + * Both examples create a compile-time variable "my_str" of which the type + * itself stores the content "hello world". + */ +#define MAKE_SSTRING(literal) sstring_builder_t + +namespace std { +template +static std::ostream& operator<<(std::ostream& stream, const sstring& val) { + stream << val.chars; + return stream; +} +} + +template +struct join_sstring_impl; + +template +struct join_sstring_impl> { + using type = sstring<>; +}; + +template +struct join_sstring_impl, sstring> { + using type = sstring; +}; + +template +struct join_sstring_impl, sstring, TStr...> { + using type = sstring_concat_t, typename join_sstring_impl, TStr...>::type>; +}; + +template +using join_sstring_t = typename join_sstring_impl::type; + +template +constexpr join_sstring_t join_sstring(const TDelimiter& delimiter, const TStr& ... str) { + return {}; +} + +template +using sstring_arr = std::tuple...>; + + +// source: https://stackoverflow.com/questions/40159732/return-other-value-if-key-not-found-in-the-map +template +TValue& get_or(std::unordered_map& m, const TKey& key, TValue& default_value) { + auto it = m.find(key); + if (it == m.end()) { + return default_value; + } else { + return it->second; + } +} +template +TValue* get_ptr(std::unordered_map& m, const TKey& key) { + auto it = m.find(key); + if (it == m.end()) + return nullptr; + else + return &(it->second); +} + +template +std::true_type is_complete_impl(T *); +std::false_type is_complete_impl(...); + +/** @brief is_complete resolves to std::true_type if T is complete + * and to std::false_type otherwise. This can be used to check if a certain template + * specialization exists. + **/ +template +using is_complete = decltype(is_complete_impl(std::declval())); + +template +struct dynamic_get_impl { + template + static TRet* get(size_t i, TTuple& t) { + if (i == I::value) + return &static_cast(std::get(t)); + else if (i > I::value) + return dynamic_get_impl, TRet, Ts...>::get(i, t); + return nullptr; // this should not happen + } +}; + +template +struct dynamic_get_impl, TRet, Ts...> { + static TRet* get(size_t i, const std::tuple& t) { + return nullptr; + } +}; + +template +TRet* dynamic_get(size_t i, std::tuple& t) { + return dynamic_get_impl, TRet, Ts...>::get(i, t); +} + +template +TRet* dynamic_get(size_t i, const std::tuple& t) { + return dynamic_get_impl, TRet, Ts...>::get(i, t); +} + +/* Hex to numbers ------------------------------------------------------------*/ + +template +constexpr size_t hex_digits() { + return (std::numeric_limits::digits + 3) / 4; +} + +/* @brief Converts a hexadecimal digit to a uint8_t. +* @param output If not null, the digit's value is stored in this output +* Returns true if the char is a valid hex digit, false otherwise +*/ +static bool hex_digit_to_byte(char ch, uint8_t* output) { + uint8_t nil_output = 0; + if (!output) + output = &nil_output; + if (ch >= '0' && ch <= '9') + return (*output) = ch - '0', true; + if (ch >= 'a' && ch <= 'f') + return (*output) = ch - 'a' + 10, true; + if (ch >= 'A' && ch <= 'F') + return (*output) = ch - 'A' + 10, true; + return false; +} + +/* @brief Converts a hex string to an integer +* @param output If not null, the result is stored in this output +* Returns true if the string represents a valid hex value, false otherwise. +*/ +template +bool hex_string_to_int(const char * str, size_t length, TInt* output) { + constexpr size_t N_DIGITS = hex_digits(); + TInt result = 0; + if (length > N_DIGITS) + length = N_DIGITS; + for (size_t i = 0; i < length && str[i]; i++) { + uint8_t digit = 0; + if (!hex_digit_to_byte(str[i], &digit)) + return false; + result <<= 4; + result += digit; + } + if (output) + *output = result; + return true; +} + +template +bool hex_string_to_int(const char * str, TInt* output) { + return hex_string_to_int(str, hex_digits(), output); +} + +template +bool hex_string_to_int_arr(const char * str, size_t length, TInt (&output)[ICount]) { + for (size_t i = 0; i < ICount; i++) { + if (!hex_string_to_int(&str[i * hex_digits()], &output[i])) + return false; + } + return true; +} + +template +bool hex_string_to_int_arr(const char * str, TInt (&output)[ICount]) { + return hex_string_to_int_arr(str, hex_digits() * ICount, output); +} + +namespace fibre { + +// TODO: move to print_utils.hpp +template +class HexPrinter { +public: + HexPrinter(T val, bool prefix) : val_(val) /*, prefix_(prefix)*/ { + const char digits[] = "0123456789abcdef"; + size_t prefix_length = prefix ? 2 : 0; + if (prefix) { + str[0] = '0'; + str[1] = 'x'; + } + str[prefix_length + hex_digits()] = '\0'; + + for (size_t i = 0; i < hex_digits(); ++i) { + str[prefix_length + hex_digits() - i - 1] = digits[val & 0xf]; + val >>= 4; + } + } + std::string to_string() const { return str; } + void to_string(char* buf) const { + for (size_t i = 0; (i < sizeof(str)) && str[i]; ++i) + buf[i] = str[i]; + } + + T val_; + //bool prefix_; + char str[hex_digits() + 3]; // 3 additional characters 0x and \0 +}; + +template +std::ostream& operator<<(std::ostream& stream, const HexPrinter& printer) { + // TODO: specialize for char + return stream << printer.to_string(); +} + +template +HexPrinter as_hex(T val, bool prefix = true) { return HexPrinter(val, prefix); } + +template +class HexArrayPrinter { +public: + HexArrayPrinter(T* ptr, size_t length) : ptr_(ptr), length_(length) {} + T* ptr_; + size_t length_; +}; + +template +std::ostream& operator<<(std::ostream& stream, const HexArrayPrinter& printer) { + for (size_t pos = 0; pos < printer.length_; ++pos) { + stream << " " << as_hex(printer.ptr_[pos]); + if (((pos + 1) % 16) == 0) + stream << std::endl; + } + return stream; +} + +template +HexArrayPrinter as_hex(T (&val)[ILength]) { return HexArrayPrinter(val, ILength); } + +} + + +template +class simple_iterator : std::iterator { + TDereferenceable *container_; + size_t i_; +public: + using reference = TResult; + explicit simple_iterator(TDereferenceable& container, size_t pos) : container_(&container), i_(pos) {} + simple_iterator& operator++() { ++i_; return *this; } + simple_iterator operator++(int) { simple_iterator retval = *this; ++(*this); return retval; } + bool operator==(simple_iterator other) const { return (container_ == other.container_) && (i_ == other.i_); } + bool operator!=(simple_iterator other) const { return !(*this == other); } + bool operator<(simple_iterator other) const { return i_ < other.i_; } + bool operator>(simple_iterator other) const { return i_ > other.i_; } + bool operator<=(simple_iterator other) const { return (*this < other) || (*this == other); } + bool operator>=(simple_iterator other) const { return (*this > other) || (*this == other); } + TResult operator*() const { return (*container_)[i_]; } +}; + + + +/** + * @brief Extracts the argument types of a function signature and provides them + * as a std::tuple. + * TODO: if an STL alternative exists, use that + */ +template +struct args_of; + +template +struct args_of { + using type = std::tuple; +}; + +template +struct args_of> { + using type = std::tuple; +}; + +template +struct args_of { + using type = std::tuple; +}; + +template +struct args_of : public args_of {}; + +template +using args_of_t = typename args_of::type; + +/** + * @brief Extracts the return type of a function signature + * + * This is provided because std::result_of is deprecated since C++17 + */ +template +struct result_of; + +template +struct result_of { + using type = TRet; +}; + +template +struct result_of { + using type = TRet; +}; + +template +struct result_of { + using type = TRet; +}; + +template +using result_of_t = typename result_of::type; + + +/** + * @brief Returns the type that results when concatenating multiple tuples + */ +template +using tuple_cat_t = decltype(std::tuple_cat(std::declval()...)); + +template +constexpr std::array array_cat_impl(std::array arr1, std::array arr2, std::index_sequence, std::index_sequence) { + return { arr1[PACK1]..., arr2[PACK2]... }; +} + +template +constexpr std::array array_cat(std::array arr1, std::array arr2) { + return array_cat_impl(arr1, arr2, std::make_index_sequence(), std::make_index_sequence()); +} + +/** + * @brief Returns the type that results when concatenating multiple tuples + */ +template +using tuple_cat_t = decltype(std::tuple_cat(std::declval()...)); + + +/** + * @brief Ensures that a given type is wrapped in a tuple + */ +template +struct as_tuple { + using type = std::tuple; +}; + +template<> +struct as_tuple { + using type = std::tuple<>; +}; + +template +struct as_tuple> { + using type = std::tuple; +}; + +template +using as_tuple_t = typename as_tuple::type; + +/** + * @brief Removes a reference OR pointer from the given type. + * + * This is similar to std::remove_reference, however it can also remove a + * pointer and it does not work for types that are neither a reference or + * a pointer. + */ +template +struct remove_ref_or_ptr { + static_assert(std::is_reference() || std::is_pointer(), "the type T is neither a reference or a pointer"); +}; + +template +struct remove_ref_or_ptr { using type = T; }; + +template +struct remove_ref_or_ptr { using type = T; }; + +template +using remove_ref_or_ptr_t = typename remove_ref_or_ptr::type; + +/** + * @brief Applies remove_ref_or_ptr_t to every type of a tuple type + */ +template +struct remove_refs_or_ptrs_from_tuple; + +template +struct remove_refs_or_ptrs_from_tuple> { + using type = std::tuple...>; +}; + +template +using remove_refs_or_ptrs_from_tuple_t = typename remove_refs_or_ptrs_from_tuple::type; + +/** + * @brief The convert(val) function returns a reference or a pointer to val + * depending on TTo. + * TODO: this could be a functor + */ +template +struct add_ref_or_ptr; + +template +struct add_ref_or_ptr { + static T& convert(T& value) { + return value; + } +}; + +template +struct add_ref_or_ptr { + static T* convert(T& value) { + return &value; + } +}; + + +/** + * @brief The convert() function turns a given tuple of values into a tuple of + * pointers or references based on the template argument TTo. + */ +template +struct add_ref_or_ptr_to_tuple; + +template +struct add_ref_or_ptr_to_tuple> { + template + static std::tuple convert_impl(std::tuple&& t, std::index_sequence) { + using to_type = std::tuple; + to_type result(add_ref_or_ptr>::convert(std::get(t))...); + return result; + } + + template + static std::tuple convert(std::tuple&& t) { + static_assert(sizeof...(TFrom) == sizeof...(TTo), "both tuples must have the same size"); + return convert_impl(std::forward>(t), std::make_index_sequence()); + } +}; + +template +struct add_ptrs_to_tuple_type; + +template +struct add_ptrs_to_tuple_type> { + using type = std::tuple; +}; + +template +using add_ptrs_to_tuple_t = typename add_ptrs_to_tuple_type::type; + +template +struct add_refs_to_tuple_type; + +template +struct add_refs_to_tuple_type> { + using type = std::tuple; +}; + +template +using add_refs_to_tuple_t = typename add_refs_to_tuple_type::type; + + +template struct is_tuple: std::false_type {}; +template struct is_tuple>: std::true_type {}; + + +template +struct tuple_select_type_impl; + +template +struct tuple_select_type_impl, TTuple> { + using type = std::tuple...>; +}; + +template +typename tuple_select_type_impl, TTuple>::type +tuple_select_impl(TTuple tuple, std::index_sequence) { + return typename tuple_select_type_impl, TTuple>::type(std::get(tuple)...); +}; + + +template +struct tuple_take_type { + static_assert(I <= std::tuple_size::value, "cannot take more elements than tuple size"); + using type = typename tuple_select_type_impl, TTuple>::type; +}; + +template +using tuple_take_t = typename tuple_take_type::type; + +/** + * @brief Returns the first I elements from the tuple as a tuple. + * The resulting type is tuple_take_t. + * See also: tuple_skip + */ +template +tuple_take_t tuple_take(TTuple tuple) { + return tuple_select_impl(tuple, std::make_index_sequence{}); +}; + + +template +struct tuple_skip_type { + static_assert(I <= std::tuple_size::value, "cannot skip more elements than tuple size"); + using type = typename tuple_select_type_impl::value>, TTuple>::type; +}; + +template +using tuple_skip_t = typename tuple_skip_type::type; + +/** + * @brief Returns all but the first I elements from the tuple as a tuple. + * The resulting type is tuple_skip_t. + * See also: tuple_take + */ +template +tuple_skip_t tuple_skip(TTuple tuple) { + return tuple_select_impl(tuple, fibre::make_integer_sequence_from_to::value>{}); +}; + +template +struct repeat_type_impl { + using type = typename repeat_type_impl::type; +}; + +template +struct repeat_type_impl<0, T, Ts...> { + using type = std::tuple; +}; + +template +using repeat_t = typename repeat_type_impl::type; + #endif // __CPP_UTILS_HPP diff --git a/Firmware/fibre/cpp/include/fibre/protocol.hpp b/Firmware/fibre/cpp/include/fibre/protocol.hpp index 883ba544..30a0b8a8 100644 --- a/Firmware/fibre/cpp/include/fibre/protocol.hpp +++ b/Firmware/fibre/cpp/include/fibre/protocol.hpp @@ -13,8 +13,12 @@ see protocol.md for the protocol specification #include //#include #include +#include +#include #include "crc.hpp" #include "cpp_utils.hpp" +#include "bufptr.hpp" +#include "simple_serdes.hpp" // Note that this option cannot be used to debug UART because it prints on UART //#define DEBUG_FIBRE @@ -63,9 +67,6 @@ struct ReceiverState { /*******************************************************/ - -#include - constexpr uint16_t PROTOCOL_VERSION = 1; // This value must not be larger than USB_TX_DATA_SIZE defined in usbd_cdc_if.h @@ -78,11 +79,22 @@ constexpr uint32_t PROTOCOL_SERVER_TIMEOUT_MS = 10; typedef struct { uint16_t json_crc = 0; - uint16_t node_id = 0; uint16_t endpoint_id = 0; } endpoint_ref_t; -#include + +namespace fibre { +// These symbols are defined in the autogenerated endpoints.hpp +extern const unsigned char embedded_json[]; +extern const size_t embedded_json_length; +extern const uint16_t json_crc_; +extern const uint32_t json_version_id_; +bool endpoint_handler(int idx, cbufptr_t* input_buffer, bufptr_t* output_buffer); +bool endpoint0_handler(cbufptr_t* input_buffer, bufptr_t* output_buffer); +bool is_endpoint_ref_valid(endpoint_ref_t endpoint_ref); +bool set_endpoint_from_float(endpoint_ref_t endpoint_ref, float value); +} + template::value>> inline size_t write_le(T value, uint8_t* buffer){ @@ -326,168 +338,65 @@ private: }; -// @brief Endpoint request handler -// -// When passed a valid endpoint context, implementing functions shall handle an -// endpoint read/write request by reading the provided input data and filling in -// output data. The exact semantics of this function depends on the corresponding -// endpoint's specification. -// -// @param input: pointer to the input data -// @param input_length: number of available input bytes -// @param output: The stream where to write the output to. Can be null. -// The handler shall abort as soon as the stream returns -// a non-zero error code on write. -typedef std::function EndpointHandler; - - -// @brief Default endpoint handler for const types -// @return: True if endpoint was written to, False otherwise -template -std::enable_if_t::value && std::is_const::value, bool> -default_readwrite_endpoint_handler(T* value, const uint8_t* input, size_t input_length, StreamSink* output) { - // If the old value was requested, call the corresponding little endian serialization function - if (output) { - // TODO: make buffer size dependent on the type - uint8_t buffer[sizeof(T)]; - size_t cnt = write_le(*value, buffer); - if (cnt <= output->get_free_space()) - output->process_bytes(buffer, cnt, nullptr); - } - return false; // We don't ever write to const types -} - -// @brief Default endpoint handler for non-const types -template -std::enable_if_t::value && !std::is_const::value, bool> -default_readwrite_endpoint_handler(T* value, const uint8_t* input, size_t input_length, StreamSink* output) { - // Read the endpoint value into output - default_readwrite_endpoint_handler(const_cast(value), input, input_length, output); - - // If a new value was passed, call the corresponding little endian deserialization function - uint8_t buffer[sizeof(T)] = { 0 }; // TODO: make buffer size dependent on the type - if (input_length >= sizeof(buffer)) { - read_le(value, input); - return true; - } else { - return false; - } -} - -// @brief Default endpoint handler for endpoint_ref_t types -template -bool default_readwrite_endpoint_handler(endpoint_ref_t* value, const uint8_t* input, size_t input_length, StreamSink* output) { - constexpr size_t size = sizeof(value->endpoint_id) + sizeof(value->json_crc); - if (output) { - // TODO: make buffer size dependent on the type - uint8_t buffer[size]; - size_t cnt = write_leendpoint_id)>(value->endpoint_id, buffer); - cnt += write_lejson_crc)>(value->json_crc, buffer + cnt); - if (cnt <= output->get_free_space()) - output->process_bytes(buffer, cnt, nullptr); - } - - // If a new value was passed, call the corresponding little endian deserialization function - if (input_length >= size) { - read_leendpoint_id)>(&value->endpoint_id, input); - read_lejson_crc)>(&value->json_crc, input + 2); - return true; - } else { - return false; - } -} - -template -static constexpr inline const char* get_default_json_modifier(); - -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"float\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"float\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"int64\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"int64\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint64\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint64\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"int32\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"int32\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint32\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint32\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint32\",\"access\":\"r\""; // TODO: automatically detect size -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint32\",\"access\":\"rw\""; // TODO: automatically detect size -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint16\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint16\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint8\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"uint8\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"bool\",\"access\":\"r\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"bool\",\"access\":\"rw\""; -} -template<> -inline constexpr const char* get_default_json_modifier() { - return "\"type\":\"endpoint_ref\",\"access\":\"rw\""; -} - -class Endpoint { -public: - //const char* const name_; - virtual void handle(const uint8_t* input, size_t input_length, StreamSink* output) = 0; - virtual bool get_string(char * output, size_t length) { return false; } - virtual bool set_string(char * buffer, size_t length) { return false; } - virtual bool set_from_float(float value) { return false; } +namespace fibre { +template +struct Codec { + static std::optional decode(cbufptr_t* buffer) { return std::nullopt; } }; -static inline int write_string(const char* str, StreamSink* output) { - return output->process_bytes(reinterpret_cast(str), strlen(str), nullptr); +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return (buffer->begin() == buffer->end()) ? std::nullopt : std::make_optional((bool)*(buffer->begin()++)); } + static bool encode(bool value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(int8_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(uint8_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(int16_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(uint16_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(int32_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(uint32_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(int64_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { return SimpleSerializer::read(&(buffer->begin()), buffer->end()); } + static bool encode(uint64_t value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; +template<> struct Codec { + static std::optional decode(cbufptr_t* buffer) { + std::optional int_val = Codec::decode(buffer); + return int_val.has_value() ? std::optional(*reinterpret_cast(&int_val.value())) : std::nullopt; + } + static bool encode(float value, bufptr_t* buffer) { + return Codec::encode(*reinterpret_cast(&value), buffer); + } +}; +template +struct Codec::value>> { + static std::optional decode(cbufptr_t* buffer) { + std::optional int_val = SimpleSerializer::read(&(buffer->begin()), buffer->end()); + return int_val.has_value() ? std::make_optional(static_cast(int_val.value())) : std::nullopt; + } + static bool encode(T value, bufptr_t* buffer) { return SimpleSerializer::write(value, &(buffer->begin()), buffer->end()); } +}; } @@ -612,112 +521,6 @@ static bool from_string(const char * buffer, size_t length, T* property, ...) { } -/* Object tree ---------------------------------------------------------------*/ - -template -struct MemberList; - -template<> -struct MemberList<> { -public: - static constexpr size_t endpoint_count = 0; - static constexpr bool is_empty = true; - void write_json(size_t id, StreamSink* output) { - // no action - } - void register_endpoints(Endpoint** list, size_t id, size_t length) { - // no action - } - Endpoint* get_by_name(const char * name, size_t length) { - return nullptr; - } - std::tuple<> get_names_as_tuple() const { return std::tuple<>(); } -}; - -template -struct MemberList { -public: - static constexpr size_t endpoint_count = TMember::endpoint_count + MemberList::endpoint_count; - static constexpr bool is_empty = false; - - MemberList(TMember&& this_member, TMembers&&... subsequent_members) : - this_member_(std::forward(this_member)), - subsequent_members_(std::forward(subsequent_members)...) {} - - MemberList(TMember&& this_member, MemberList&& subsequent_members) : - this_member_(std::forward(this_member)), - subsequent_members_(std::forward>(subsequent_members)) {} - - // @brief Move constructor -/* MemberList(MemberList&& other) : - this_member_(std::move(other.this_member_)), - subsequent_members_(std::move(other.subsequent_members_)) {}*/ - - void write_json(size_t id, StreamSink* output) /*final*/ { - this_member_.write_json(id, output); - if (!MemberList::is_empty) - write_string(",", output); - subsequent_members_.write_json(id + TMember::endpoint_count, output); - } - - Endpoint* get_by_name(const char * name, size_t length) { - Endpoint* result = this_member_.get_by_name(name, length); - if (result) return result; - else return subsequent_members_.get_by_name(name, length); - } - - void register_endpoints(Endpoint** list, size_t id, size_t length) /*final*/ { - this_member_.register_endpoints(list, id, length); - subsequent_members_.register_endpoints(list, id + TMember::endpoint_count, length); - } - - TMember this_member_; - MemberList subsequent_members_; -}; - -template -MemberList make_protocol_member_list(TMembers&&... member_list) { - return MemberList(std::forward(member_list)...); -} - -template -class ProtocolObject { -public: - ProtocolObject(const char * name, TMembers&&... member_list) : - name_(name), - member_list_(std::forward(member_list)...) {} - - static constexpr size_t endpoint_count = MemberList::endpoint_count; - - void write_json(size_t id, StreamSink* output) { - write_string("{\"name\":\"", output); - write_string(name_, output); - write_string("\",\"type\":\"object\",\"members\":[", output); - member_list_.write_json(id, output), - write_string("]}", output); - } - - Endpoint* get_by_name(const char * name, size_t length) { - size_t segment_length = strlen(name); - if (!strncmp(name, name_, length)) - return member_list_.get_by_name(name + segment_length + 1, length - segment_length - 1); - else - return nullptr; - } - - void register_endpoints(Endpoint** list, size_t id, size_t length) { - member_list_.register_endpoints(list, id, length); - } - - const char * name_; - MemberList member_list_; -}; - -template -ProtocolObject make_protocol_object(const char * name, TMembers&&... member_list) { - return ProtocolObject(name, std::forward(member_list)...); -} - //template //bool set_from_float_ex(float value, T* property) { // return false; @@ -747,396 +550,39 @@ bool set_from_float(float value, T* property) { } } -//template -//bool set_from_float_ex<>(float value, T* property) { -// return false; -//} - -template -class ProtocolProperty : public Endpoint { -public: - static constexpr const char * json_modifier = get_default_json_modifier(); - static constexpr size_t endpoint_count = 1; - - ProtocolProperty(const char * name, TProperty* property, - void (*written_hook)(void*), void* ctx) - : name_(name), property_(property), written_hook_(written_hook), ctx_(ctx) - {} - -/* TODO: find out why the move constructor is not used when it could be - ProtocolProperty(const ProtocolProperty&) = delete; - // @brief Move constructor - ProtocolProperty(ProtocolProperty&& other) : - Endpoint(std::move(other)), - name_(std::move(other.name_)), - property_(other.property_) - {} - constexpr ProtocolProperty& operator=(const ProtocolProperty& other) = delete; - constexpr ProtocolProperty& operator=(const ProtocolProperty& other) { - //Endpoint(std::move(other)), - //name_(std::move(other.name_)), - //property_(other.property_) - name_ = other.name_; - property_ = other.property_; - return *this; - } - ProtocolProperty& operator=(ProtocolProperty&& other) - : name_(other.name_), property_(other.property_) - {} - ProtocolProperty& operator=(const ProtocolProperty& other) - : name_(other.name_), property_(other.property_) - {}*/ - - void write_json(size_t id, StreamSink* output) { - // write name - write_string("{\"name\":\"", output); - LOG_FIBRE("json: this at %x, name at %x is s\r\n", (uintptr_t)this, (uintptr_t)name_); - //LOG_FIBRE("json\r\n"); - write_string(name_, output); - - // write endpoint ID - write_string("\",\"id\":", output); - char id_buf[10]; - snprintf(id_buf, sizeof(id_buf), "%u", (unsigned)id); // TODO: get rid of printf - write_string(id_buf, output); - - // write additional JSON data - if (json_modifier && json_modifier[0]) { - write_string(",", output); - write_string(json_modifier, output); - } - - write_string("}", output); - } - - // special-purpose function - to be moved - Endpoint* get_by_name(const char * name, size_t length) { - if (!strncmp(name, name_, length)) - return this; - else - return nullptr; - } - - // special-purpose function - to be moved - bool get_string(char * buffer, size_t length) final { - return to_string(*property_, buffer, length, 0); - } - - // special-purpose function - to be moved - bool set_string(char * buffer, size_t length) final { - return from_string(buffer, length, property_, 0); - } - - bool set_from_float(float value) final { - return conversion::set_from_float(value, property_); - } - - void register_endpoints(Endpoint** list, size_t id, size_t length) { - if (id < length) - list[id] = this; - } - void handle(const uint8_t* input, size_t input_length, StreamSink* output) final { - bool wrote = default_readwrite_endpoint_handler(property_, input, input_length, output); - if (wrote && written_hook_ != nullptr) { - written_hook_(ctx_); - } - } - /*void handle(const uint8_t* input, size_t input_length, StreamSink* output) { - handle(input, input_length, output); - }*/ - - const char* name_; - TProperty* property_; - void (*written_hook_)(void*); +template +struct Property { + Property(void* ctx, T(*getter)(void*), void(*setter)(void*, T)) + : ctx_(ctx), getter_(getter), setter_(setter) {} + Property* operator->() { return this; } + void* ctx_; -}; + T(*getter_)(void*); + void(*setter_)(void*, T); -// Non-const non-enum types -template::value)> -ProtocolProperty make_protocol_property(const char * name, TProperty* property, - void (*written_hook)(void*) = nullptr, void* ctx = nullptr) { - return ProtocolProperty(name, property, written_hook, ctx); -}; - -// Const non-enum types -template::value)> -ProtocolProperty make_protocol_ro_property(const char * name, TProperty* property, - void (*written_hook)(void*) = nullptr, void* ctx = nullptr) { - return ProtocolProperty(name, property, written_hook, ctx); -}; - -// Non-const enum types -template::value)> -ProtocolProperty> make_protocol_property(const char * name, TProperty* property, - void (*written_hook)(void*) = nullptr, void* ctx = nullptr) { - return ProtocolProperty>( - name, reinterpret_cast*>(property), written_hook, ctx); -}; - -// Const enum types -template::value)> -ProtocolProperty> make_protocol_ro_property(const char * name, TProperty* property, - void (*written_hook)(void*) = nullptr, void* ctx = nullptr) { - return ProtocolProperty>( - name, reinterpret_cast*>(property), written_hook, ctx); -}; - - -template -struct PropertyListFactory; - -template<> -struct PropertyListFactory<> { - template - static MemberList<> make_property_list(std::array names, std::tuple& values) { - return MemberList<>(); - } -}; - -template -struct PropertyListFactory { - template - static MemberList, ProtocolProperty...> - make_property_list(std::array names, std::tuple& values) { - return MemberList, ProtocolProperty...>( - make_protocol_property(std::get(names), &std::get(values)), - PropertyListFactory::template make_property_list(names, values) - ); - } -}; - -/* @brief return_type::type represents the true return type -* of a function returning 0 or more arguments. -* -* For an empty TypeList, the return type is void. For a list with -* one type, the return type is equal to that type. For a list with -* more than one items, the return type is a tuple. -*/ -template -struct return_type; - -template<> -struct return_type<> { typedef void type; }; -template -struct return_type { typedef T type; }; -template -struct return_type { typedef std::tuple type; }; - - -template -class ProtocolFunction; - -template -class ProtocolFunction, std::tuple> : Endpoint { -public: - // @brief The return type of the function as written by a C++ programmer - using TRet = typename return_type::type; - - static constexpr size_t endpoint_count = 1 + MemberList...>::endpoint_count + MemberList...>::endpoint_count; - - ProtocolFunction(const char * name, TObj& obj, TRet(TObj::*func_ptr)(TInputs...), - std::array input_names, - std::array output_names) : - name_(name), obj_(&obj), func_ptr_(func_ptr), - input_names_{input_names}, output_names_{output_names}, - input_properties_(PropertyListFactory::template make_property_list<0>(input_names_, in_args_)), - output_properties_(PropertyListFactory::template make_property_list<0>(output_names_, out_args_)) - { - LOG_FIBRE("my tuple is at %x and of size %u\r\n", (uintptr_t)&in_args_, sizeof(in_args_)); - } - - // The custom copy constructor is needed because otherwise the - // input_properties_ and output_properties_ would point to memory - // locations of the old object. - ProtocolFunction(const ProtocolFunction& other) : - name_(other.name_), obj_(other.obj_), func_ptr_(other.func_ptr_), - input_names_{other.input_names_}, output_names_{other.output_names_}, - input_properties_(PropertyListFactory::template make_property_list<0>(input_names_, in_args_)), - output_properties_(PropertyListFactory::template make_property_list<0>(output_names_, out_args_)) - { - LOG_FIBRE("COPIED! my tuple is at %x and of size %u\r\n", (uintptr_t)&in_args_, sizeof(in_args_)); - } - - void write_json(size_t id, StreamSink* output) { - // write name - write_string("{\"name\":\"", output); - write_string(name_, output); - - // write endpoint ID - write_string("\",\"id\":", output); - char id_buf[10]; - snprintf(id_buf, sizeof(id_buf), "%u", (unsigned)id); // TODO: get rid of printf - write_string(id_buf, output); - - // write arguments - write_string(",\"type\":\"function\",\"inputs\":[", output); - input_properties_.write_json(id + 1, output), - write_string("],\"outputs\":[", output); - output_properties_.write_json(id + 1 + decltype(input_properties_)::endpoint_count, output), - write_string("]}", output); - } - - // special-purpose function - to be moved - Endpoint* get_by_name(const char * name, size_t length) { - return nullptr; // can't address functions by name - } - - void register_endpoints(Endpoint** list, size_t id, size_t length) { - if (id < length) - list[id] = this; - input_properties_.register_endpoints(list, id + 1, length); - output_properties_.register_endpoints(list, id + 1 + decltype(input_properties_)::endpoint_count, length); - } - - template std::enable_if_t - handle_ex() { - invoke_function_with_tuple(*obj_, func_ptr_, in_args_); - } - - template std::enable_if_t - handle_ex() { - std::get<0>(out_args_) = invoke_function_with_tuple(*obj_, func_ptr_, in_args_); - } - - template std::enable_if_t= 2> - handle_ex() { - out_args_ = invoke_function_with_tuple(*obj_, func_ptr_, in_args_); - } - - void handle(const uint8_t* input, size_t input_length, StreamSink* output) final { - (void) input; - (void) input_length; - (void) output; - LOG_FIBRE("tuple still at %x and of size %u\r\n", (uintptr_t)&in_args_, sizeof(in_args_)); - LOG_FIBRE("invoke function using %d and %.3f\r\n", std::get<0>(in_args_), std::get<1>(in_args_)); - handle_ex(); - } - - const char * name_; - TObj* obj_; - TRet(TObj::*func_ptr_)(TInputs...); - std::array input_names_; // TODO: remove - std::array output_names_; // TODO: remove - std::tuple in_args_; - std::tuple out_args_; - MemberList...> input_properties_; - MemberList...> output_properties_; -}; - -template> -ProtocolFunction, std::tuple<>> make_protocol_function(const char * name, TObj& obj, void(TObj::*func_ptr)(TArgs...), TNames ... names) { - return ProtocolFunction, std::tuple<>>(name, obj, func_ptr, {names...}, {}); -} - -template::value>> -ProtocolFunction, std::tuple> make_protocol_function(const char * name, TObj& obj, TRet(TObj::*func_ptr)(TArgs...), TNames ... names) { - return ProtocolFunction, std::tuple>(name, obj, func_ptr, {names...}, {"result"}); -} - - -#define FIBRE_EXPORTS(CLASS, ...) \ - struct fibre_export_t { \ - static CLASS* obj; \ - using type = decltype(make_protocol_member_list(__VA_ARGS__)); \ - }; \ - fibre_export_t::type make_fibre_definitions() { \ - CLASS* obj = this; \ - return make_protocol_member_list(__VA_ARGS__); \ - } \ - fibre_export_t::type fibre_definitions = make_fibre_definitions() - - - - - -class EndpointProvider { -public: - virtual size_t get_endpoint_count() = 0; - virtual void write_json(size_t id, StreamSink* output) = 0; - virtual Endpoint* get_by_name(char * name, size_t length) = 0; - virtual void register_endpoints(Endpoint** list, size_t id, size_t length) = 0; -}; - -template -class EndpointProvider_from_MemberList : public EndpointProvider { -public: - EndpointProvider_from_MemberList(T& member_list) : member_list_(member_list) {} - size_t get_endpoint_count() final { - return T::endpoint_count; - } - void write_json(size_t id, StreamSink* output) final { - return member_list_.write_json(id, output); - } - void register_endpoints(Endpoint** list, size_t id, size_t length) final { - return member_list_.register_endpoints(list, id, length); - } - Endpoint* get_by_name(char * name, size_t length) final { - for (size_t i = 0; i < length; i++) { - if (name[i] == '.') - name[i] = 0; + T exchange(std::optional value) { + T old_value = (*getter_)(ctx_); + if (value.has_value()) { + (*setter_)(ctx_, value.value()); } - name[length-1] = 0; - return member_list_.get_by_name(name, length); + return old_value; } - T& member_list_; }; - - -class JSONDescriptorEndpoint : Endpoint { -public: - static constexpr size_t endpoint_count = 1; - void write_json(size_t id, StreamSink* output); - void register_endpoints(Endpoint** list, size_t id, size_t length); - void handle(const uint8_t* input, size_t input_length, StreamSink* output); -}; - -// defined in protocol.cpp -extern Endpoint** endpoint_list_; -extern size_t n_endpoints_; -extern uint16_t json_crc_; -extern uint32_t json_version_id_; // exposed to hosts to facilitate cache lookup -extern JSONDescriptorEndpoint json_file_endpoint_; -extern EndpointProvider* application_endpoints_; - -bool is_endpoint_ref_valid(endpoint_ref_t endpoint_ref); -Endpoint* get_endpoint(endpoint_ref_t endpoint_ref); - -// @brief Registers the specified application object list using the provided endpoint table. -// This function should only be called once during the lifetime of the application. TODO: fix this. -// @param application_objects The application objects to be registred. template -int fibre_publish(T& application_objects) { - static constexpr size_t endpoint_list_size = 1 + T::endpoint_count; - static Endpoint* endpoint_list[endpoint_list_size]; - static auto endpoint_provider = EndpointProvider_from_MemberList(application_objects); - - json_file_endpoint_.register_endpoints(endpoint_list, 0, endpoint_list_size); - application_objects.register_endpoints(endpoint_list, 1, endpoint_list_size); - - // Update the global endpoint table - endpoint_list_ = endpoint_list; - n_endpoints_ = endpoint_list_size; - application_endpoints_ = &endpoint_provider; +struct Property { + Property(void* ctx, T(*getter)(void*)) + : ctx_(ctx), getter_(getter) {} + Property* operator->() { return this; } - // Calculate the CRC16 of the JSON file. - // The init value is the protocol version. - CRC16Calculator crc16_calculator(PROTOCOL_VERSION); + void* ctx_; + T(*getter_)(void*); - uint8_t offset[4] = { 0 }; - json_file_endpoint_.handle(offset, sizeof(offset), &crc16_calculator); - json_crc_ = crc16_calculator.get_crc16(); - - // Add entropy for fibre cache - json_file_endpoint_.handle(offset, sizeof(offset), &crc16_calculator); - json_version_id_ = (uint32_t) crc16_calculator.get_crc16(); - json_version_id_ += json_crc_ << 16; - - return 0; -} + T read() { + return (*getter_)(ctx_); + } +}; #endif diff --git a/Firmware/fibre/cpp/include/fibre/simple_serdes.hpp b/Firmware/fibre/cpp/include/fibre/simple_serdes.hpp new file mode 100644 index 00000000..32c09f27 --- /dev/null +++ b/Firmware/fibre/cpp/include/fibre/simple_serdes.hpp @@ -0,0 +1,77 @@ +#ifndef __FIBRE_SIMPLE_SERDES +#define __FIBRE_SIMPLE_SERDES + +//#include "stream.hpp" + + +template +struct SimpleSerializer; +template +using LittleEndianSerializer = SimpleSerializer; +template +using BigEndianSerializer = SimpleSerializer; + + +/* @brief Serializer/deserializer for arbitrary integral number types */ +// TODO: allow reading an arbitrary number of bits +template +struct SimpleSerializer::value>> { + static constexpr size_t BIT_WIDTH = std::numeric_limits::digits; + static constexpr size_t BYTE_WIDTH = (BIT_WIDTH + 7) / 8; + + template + static std::optional read(TIterator* begin, TIterator end = nullptr) { + T result = 0; + if (BigEndian) { + for (size_t i = BYTE_WIDTH; i > 0; (i++, (*begin)++)) { + if (end && !(*begin < end)) + return std::nullopt; + uint8_t byte = **begin; + result |= static_cast(byte) << ((i - 1) << 3); + } + } else { + for (size_t i = 0; i < BYTE_WIDTH; (i++, (*begin)++)) { + if (end && !(*begin < end)) + return std::nullopt; + uint8_t byte = **begin; + result |= static_cast(byte) << (i << 3); + } + } + return result; + } + + template + static bool write(T value, TIterator* begin, TIterator end = nullptr) { + if (BigEndian) { + for (size_t i = BYTE_WIDTH; i > 0; (i--, (*begin)++)) { + if (end && !(*begin < end)) + return false; + uint8_t byte = static_cast((value >> ((i - 1) << 3)) & 0xff); + **begin = byte; + } + } else { + for (size_t i = 0; i < BYTE_WIDTH; (i++, (*begin)++)) { + if (end && !(*begin < end)) + return false; + uint8_t byte = static_cast((value >> (i << 3)) & 0xff); + **begin = byte; + } + } + return true; + } +}; + +template +inline std::optional read_le(fibre::cbufptr_t* buffer) { + static_assert(is_complete>(), "no LittleEndianSerializer is defined for type T"); + return LittleEndianSerializer::read(&buffer->begin(), buffer->end()); +} + +template +inline bool write_le(T value, fibre::bufptr_t* buffer) { + static_assert(is_complete>(), "no LittleEndianSerializer is defined for type T"); + return LittleEndianSerializer::write(value, &buffer->begin(), buffer->end()); +} + + +#endif \ No newline at end of file diff --git a/Firmware/fibre/cpp/interfaces_template.j2 b/Firmware/fibre/cpp/interfaces_template.j2 new file mode 100644 index 00000000..76e0c90d --- /dev/null +++ b/Firmware/fibre/cpp/interfaces_template.j2 @@ -0,0 +1,67 @@ +/*[# This is the original template, thus the warning below does not apply to this file #] + * ============================ WARNING ============================ + * ==== This is an autogenerated file. ==== + * ==== Any changes to this file will be lost when recompiling. ==== + * ================================================================= + * + * This file contains base classes that correspond to the interfaces defined in + * your interface file. The objects you publish should inherit from these + * interfaces. + * + */ + +[%- macro rettype(func) %] +[%- if not func.out -%] +void +[%- elif func.out | length == 1 -%] +[[(func.out.values() | first).type.c_type]] +[%- else -%] +[% for arg in func.out.values() %][[arg.type]][[', ' if not loop.last]][% endfor %] +[%- endif -%] +[%- endmacro %] + +[%- macro render_interface(intf) %] +class [[intf.name | to_pascal_case]]Intf { +public: +[%- for intf in intf.interfaces -%] +[[render_interface(intf) | indent(4)]] +[%- endfor %] +[%- for enum in intf.enums %] + enum [[enum.name | to_pascal_case]] { +[%- for k, value in enum['values'].items() %] + [[((enum.name + k) | to_macro_case).ljust(32)]] = [% if enum.is_flags %]0x[['%08x' | format(value.value)]][% else %][[value.value]][% endif %], +[%- endfor %] + }; +[%- endfor %] +[%- for func in intf.functions.values() %] + virtual [[rettype(func)]] [[func.name | to_snake_case]]([% for in in func.in.values() %][% if loop.index0 %][[in.type.c_type]] [[in.name]][[', ' if not loop.last]][% endif %][% endfor %]) = 0; +[%- endfor %] +[%- for func in intf.functions.values() %] +[%- for k, arg in func.in.items() | skip_first %] + [[arg.type.c_type]] [[func.name | to_snake_case]]_in_[[arg.name]]_; // for internal use by Fibre +[%- endfor %] +[%- for k, arg in func.out.items() %] + [[arg.type.c_type]] [[func.name | to_snake_case]]_out_[[arg.name]]_; // for internal use by Fibre +[%- endfor %] +[%- endfor %] +}; +[%- endmacro %] + +[% for intf in toplevel_interfaces %] +[[render_interface(intf)]] +[% endfor %] + +[%- for _, enum in value_types.items() %] +[%- if enum.is_flags %] +// this is technically not thread-safe but practically it might be +inline [[enum.c_type]] operator | ([[enum.c_type]] a, [[enum.c_type]] b) { return static_cast<[[enum.c_type]]>(static_cast>(a) | static_cast>(b)); } +inline [[enum.c_type]] operator & ([[enum.c_type]] a, [[enum.c_type]] b) { return static_cast<[[enum.c_type]]>(static_cast>(a) & static_cast>(b)); } +inline [[enum.c_type]] operator ^ ([[enum.c_type]] a, [[enum.c_type]] b) { return static_cast<[[enum.c_type]]>(static_cast>(a) ^ static_cast>(b)); } +inline [[enum.c_type]]& operator |= ([[enum.c_type]] &a, [[enum.c_type]] b) { return reinterpret_cast<[[enum.c_type]]&>(reinterpret_cast&>(a) |= static_cast>(b)); } +inline [[enum.c_type]]& operator &= ([[enum.c_type]] &a, [[enum.c_type]] b) { return reinterpret_cast<[[enum.c_type]]&>(reinterpret_cast&>(a) &= static_cast>(b)); } +inline [[enum.c_type]]& operator ^= ([[enum.c_type]] &a, [[enum.c_type]] b) { return reinterpret_cast<[[enum.c_type]]&>(reinterpret_cast&>(a) ^= static_cast>(b)); } +inline [[enum.c_type]] operator ~ ([[enum.c_type]] a) { return static_cast<[[enum.c_type]]>(~static_cast>(a)); } +[%- endif %] +[%- endfor %] + + diff --git a/Firmware/fibre/cpp/protocol.cpp b/Firmware/fibre/cpp/protocol.cpp index d5af8a0b..e8285c87 100644 --- a/Firmware/fibre/cpp/protocol.cpp +++ b/Firmware/fibre/cpp/protocol.cpp @@ -13,19 +13,11 @@ /* Global constant data ------------------------------------------------------*/ /* Global variables ----------------------------------------------------------*/ -Endpoint** endpoint_list_ = nullptr; // initialized by calling fibre_publish -size_t n_endpoints_ = 0; // initialized by calling fibre_publish -uint16_t json_crc_; // initialized by calling fibre_publish -uint32_t json_version_id_; // initialized by calling fibre_publish -JSONDescriptorEndpoint json_file_endpoint_ = JSONDescriptorEndpoint(); -EndpointProvider* application_endpoints_; - /* Private constant data -----------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void hexdump(const uint8_t* buf, size_t len); -static inline int write_string(const char* str, StreamSink* output); /* Function implementations --------------------------------------------------*/ @@ -116,45 +108,26 @@ int StreamBasedPacketSink::process_packet(const uint8_t *buffer, size_t length) } - -void JSONDescriptorEndpoint::write_json(size_t id, StreamSink* output) { - write_string("{\"name\":\"\",", output); - - // write endpoint ID - write_string("\"id\":", output); - char id_buf[10]; - snprintf(id_buf, sizeof(id_buf), "%u", (unsigned)id); // TODO: get rid of printf - write_string(id_buf, output); - - write_string(",\"type\":\"json\",\"access\":\"r\"}", output); -} - -void JSONDescriptorEndpoint::register_endpoints(Endpoint** list, size_t id, size_t length) { - if (id < length) - list[id] = this; -} - // Returns part of the JSON interface definition. -void JSONDescriptorEndpoint::handle(const uint8_t* input, size_t input_length, StreamSink* output) { +bool fibre::endpoint0_handler(fibre::cbufptr_t* input_buffer, fibre::bufptr_t* output_buffer) { // The request must contain a 32 bit integer to specify an offset - if (input_length < 4) - return; - uint32_t offset = 0; - read_le(&offset, input); - - // If the offset is special value 0xFFFFFFFF, send back the JSON version ID instead - if (offset == 0xffffffff) { - default_readwrite_endpoint_handler(&json_version_id_, nullptr, 0, output); + std::optional offset = read_le(input_buffer); + + if (!offset.has_value()) { + // Didn't receive any offset + return false; + } else if (offset.value() == 0xffffffff) { + // If the offset is special value 0xFFFFFFFF, send back the JSON version ID instead + return write_le(json_version_id_, output_buffer); + } else if (offset.value() >= embedded_json_length) { + // Attempt to read beyond the buffer end - return empty response + return true; } else { - NullStreamSink output_with_offset = NullStreamSink(offset, *output); - - size_t id = 0; - write_string("[", &output_with_offset); - json_file_endpoint_.write_json(id, &output_with_offset); - id += decltype(json_file_endpoint_)::endpoint_count; - write_string(",", &output_with_offset); - application_endpoints_->write_json(id, &output_with_offset); - write_string("]", &output_with_offset); + // Return part of the json file + size_t n_copy = std::min(output_buffer->size(), embedded_json_length - (size_t)offset.value()); + memcpy(output_buffer->begin(), embedded_json + offset.value(), n_copy); + *output_buffer = output_buffer->skip(n_copy); + return true; } } @@ -176,19 +149,10 @@ int BidirectionalPacketBasedChannel::process_packet(const uint8_t* buffer, size_ bool expect_response = endpoint_id & 0x8000; endpoint_id &= 0x7fff; - if (endpoint_id >= n_endpoints_) - return -1; - - Endpoint* endpoint = endpoint_list_[endpoint_id]; - if (!endpoint) { - LOG_FIBRE("critical: no endpoint at %d", endpoint_id); - return -1; - } - // Verify packet trailer. The expected trailer value depends on the selected endpoint. // For endpoint 0 this is just the protocol version, for all other endpoints it's a // CRC over the entire JSON descriptor tree (this may change in future versions). - uint16_t expected_trailer = endpoint_id ? json_crc_ : PROTOCOL_VERSION; + uint16_t expected_trailer = endpoint_id ? fibre::json_crc_ : PROTOCOL_VERSION; uint16_t actual_trailer = buffer[length - 2] | (buffer[length - 1] << 8); if (expected_trailer != actual_trailer) { LOG_FIBRE("trailer mismatch for endpoint %d: expected %04x, got %04x\r\n", endpoint_id, expected_trailer, actual_trailer); @@ -204,12 +168,13 @@ int BidirectionalPacketBasedChannel::process_packet(const uint8_t* buffer, size_ if (expected_response_length > sizeof(tx_buf_) - 2) expected_response_length = sizeof(tx_buf_) - 2; - MemoryStreamSink output(tx_buf_ + 2, expected_response_length); - endpoint->handle(buffer, length - 2, &output); + fibre::cbufptr_t input_buffer{buffer, length - 2}; + fibre::bufptr_t output_buffer{tx_buf_ + 2, expected_response_length}; + fibre::endpoint_handler(endpoint_id, &input_buffer, &output_buffer); // Send response if (expect_response) { - size_t actual_response_length = expected_response_length - output.get_free_space() + 2; + size_t actual_response_length = expected_response_length - output_buffer.size() + 2; write_le(seq_no | 0x8000, tx_buf_); LOG_FIBRE("send packet:\r\n"); @@ -220,15 +185,3 @@ int BidirectionalPacketBasedChannel::process_packet(const uint8_t* buffer, size_ return 0; } - -bool is_endpoint_ref_valid(endpoint_ref_t endpoint_ref) { - return (endpoint_ref.json_crc == json_crc_) - && (endpoint_ref.endpoint_id < n_endpoints_); -} - -Endpoint* get_endpoint(endpoint_ref_t endpoint_ref) { - if (is_endpoint_ref_valid(endpoint_ref)) - return endpoint_list_[endpoint_ref.endpoint_id]; - else - return nullptr; -} diff --git a/Firmware/interface_generator.py b/Firmware/interface_generator.py new file mode 100644 index 00000000..38468036 --- /dev/null +++ b/Firmware/interface_generator.py @@ -0,0 +1,589 @@ +#!/bin/python3 + +import yaml +import json +import jinja2 +import jsonschema +import re +import argparse +import sys + +# This schema describes what we expect interface definition files to look like +validator = jsonschema.Draft7Validator(yaml.safe_load(""" +definitions: + interface: + type: object + properties: + c_is_class: {type: boolean} + c_name: {type: string} + functions: + type: object + additionalProperties: {"$ref": "#/definitions/function"} + attributes: + type: object + additionalProperties: {"$ref": "#/definitions/attribute"} + __line__: {type: object} + __column__: {type: object} + additionalProperties: false + + valuetype: + type: object + properties: + mode: {type: string} # this shouldn't be here + c_name: {type: string} + values: {type: object} + flags: {type: object} + nullflag: {type: string} + __line__: {type: object} + __column__: {type: object} + additionalProperties: false + + intf_or_val_type: + anyOf: + - {"$ref": "#/definitions/interface"} + - {"$ref": "#/definitions/valuetype"} + - {"type": "string"} + + attribute: + anyOf: # this is probably not being used correctly + - {"$ref": "#/definitions/intf_or_val_type"} + - type: object + - type: object + properties: + type: {"$ref": "#/definitions/intf_or_val_type"} + c_name: {"type": string} + unit: {"type": string} + doc: {"type": string} + additionalProperties: false + + function: + anyOf: + - type: 'null' + - type: object + properties: + in: {type: object} + out: {type: object} + doc: {type: string} + __line__: {type: object} + __column__: {type: object} + additionalProperties: false + + +type: object +properties: + ns: {type: string} + version: {type: string} + summary: {type: string} + interfaces: + type: object + additionalProperties: { "$ref": "#/definitions/interface" } + valuetypes: + type: object + additionalProperties: { "$ref": "#/definitions/valuetype" } + __line__: {type: object} + __column__: {type: object} +additionalProperties: false +""")) + +# Source: https://stackoverflow.com/a/53647080/3621512 +class SafeLineLoader(yaml.SafeLoader): + pass +# def compose_node(self, parent, index): +# # the line number where the previous token has ended (plus empty lines) +# line = self.line +# node = super(SafeLineLoader, self).compose_node(parent, index) +# node.__line__ = line + 1 +# return node +# +# def construct_mapping(self, node, deep=False): +# mapping = super(SafeLineLoader, self).construct_mapping(node, deep=deep) +# mapping['__line__'] = node.__line__ +# #mapping['__column__'] = node.start_mark.column + 1 +# return mapping + + + +def get_words(string): + """ + Splits a string in PascalCase into a list of lower case words + """ + return [w.lower() for w in re.findall('[a-z0-9]+|[A-Z][a-z0-9]*', string)] + +def join_name(*names, delimiter: str = '.'): + """ + Joins two name components. + e.g. 'io.helloworld' + 'sayhello' => 'io.helloworld.sayhello' + """ + return delimiter.join(y for x in names for y in x.split(delimiter) if y != '') + +def split_name(name, delimiter: str = '.'): + def replace_delimiter_in_parentheses(): + parenthesis_depth = 0 + for c in name: + parenthesis_depth += 1 if c == '<' else -1 if c == '>' else 0 + yield c if (parenthesis_depth == 0) or (c != delimiter) else ':' + return [part.replace(':', '.') for part in ''.join(replace_delimiter_in_parentheses()).split('.')] + +def to_pascal_case(s): return ''.join([w.title() for w in get_words(s)]) +def to_camel_case(s): return ''.join([(c.lower() if i == 0 else c) for i, c in enumerate(''.join([w.title() for w in get_words(s)]))]) +def to_macro_case(s): return '_'.join(get_words(s)).upper() +def to_snake_case(s): return '_'.join(get_words(s)).lower() +def to_kebab_case(s): return '-'.join(get_words(s)).lower() + +value_types = { + 'bool': {'builtin': True, 'fullname': 'bool', 'name': 'bool', 'c_type': 'bool'}, + 'float32': {'builtin': True, 'fullname': 'float32', 'name': 'float32', 'c_type': 'float'}, + 'uint8': {'builtin': True, 'fullname': 'uint8', 'name': 'uint8', 'c_type': 'uint8_t'}, + 'uint16': {'builtin': True, 'fullname': 'uint16', 'name': 'uint16', 'c_type': 'uint16_t'}, + 'uint32': {'builtin': True, 'fullname': 'uint32', 'name': 'uint32', 'c_type': 'uint32_t'}, + 'uint64': {'builtin': True, 'fullname': 'uint64', 'name': 'uint64', 'c_type': 'uint64_t'}, + 'int8': {'builtin': True, 'fullname': 'int8', 'name': 'int8', 'c_type': 'int8_t'}, + 'int16': {'builtin': True, 'fullname': 'int16', 'name': 'int16', 'c_type': 'int16_t'}, + 'int32': {'builtin': True, 'fullname': 'int32', 'name': 'int32', 'c_type': 'int32_t'}, + 'int64': {'builtin': True, 'fullname': 'int64', 'name': 'int64', 'c_type': 'int64_t'}, +} + +enums = {} + +interfaces = {} + +def make_property_type(typeargs): + value_type = resolve_valuetype('', typeargs['fibre.Property.type']) + mode = typeargs.get('fibre.Property.mode', 'readwrite') + name = 'Property<' + value_type['fullname'] + ', ' + mode + '>' + fullname = join_name('fibre', name) + if fullname in interfaces: + return interfaces[fullname] + + c_type = 'Property<' + ('const ' if mode == 'readonly' else '') + value_type['c_type'] + '>' + prop_type = { + 'name': name, + 'fullname': fullname, + 'c_type': c_type, + 'value_type': value_type, # TODO: should be a metaarg + 'mode': mode, # TODO: should be a metaarg + 'attributes': {}, + 'functions': {} + } + if mode != 'readonly': + prop_type['functions']['exchange'] = { + 'name': 'exchange', + 'fullname': join_name(fullname, 'exchange'), + 'in': {'obj': {'name': 'obj', 'type': {'c_type': c_type}}, 'value': {'name': 'value', 'type': value_type, 'optional': True}}, + 'out': {'value': {'name': 'value', 'type': value_type}}, + #'implementation': 'fibre_property_exchange<' + value_type['c_type'] + '>' + } + else: + prop_type['functions']['read'] = { + 'name': 'read', + 'fullname': join_name(fullname, 'read'), + 'in': {'obj': {'name': 'obj', 'type': {'c_type': c_type}}}, + 'out': {'value': {'name': 'value', 'type': value_type}}, + #'implementation': 'fibre_property_read<' + value_type['c_type'] + '>' + } + + interfaces[fullname] = prop_type + return prop_type + +generics = { + 'fibre.Property': make_property_type # TODO: improve generic support +} + + +def make_ref_type(interface): + name = 'Ref<' + interface['fullname'] + '>' + fullname = join_name('fibre', name) + if fullname in interfaces: + return interfaces[fullname] + + ref_type = { + 'builtin': True, + 'name': name, + 'fullname': fullname, + 'c_type': interface['fullname'].replace('.', 'Intf::') + 'Intf*' + } + value_types[fullname] = ref_type + + return ref_type + +def get_dict(elem, key): + return elem.get(key, None) or {} + +def regularize_arg(path, name, elem): + if elem is None: + elem = {} + elif isinstance(elem, str): + elem = {'type': elem} + elem['name'] = name + elem['fullname'] = path = join_name(path, name) + elem['type'] = regularize_valuetype(path, name, elem['type']) + return elem + +def regularize_func(path, name, elem, prepend_args): + if elem is None: + elem = {} + elem['name'] = name + elem['fullname'] = path = join_name(path, name) + elem['in'] = {n: regularize_arg(path, n, arg) + for n, arg in {**prepend_args, **get_dict(elem, 'in')}.items()} + elem['out'] = {n: regularize_arg(path, n, arg) + for n, arg in get_dict(elem, 'out').items()} + return elem + +def regularize_attribute(path, name, elem, c_is_class): + if elem is None: + elem = {} + if isinstance(elem, str): + elem = {'type': elem} + elif not 'type' in elem: + elem['type'] = {} + if 'attributes' in elem: elem['type']['attributes'] = elem.pop('attributes') + if 'functions' in elem: elem['type']['functions'] = elem.pop('functions') + if 'values' in elem: elem['type']['values'] = elem.pop('values') + if 'flags' in elem: elem['type']['flags'] = elem.pop('flags') + if 'nullflag' in elem: elem['type']['nullflag'] = elem.pop('nullflag') + + elem['name'] = name + elem['fullname'] = join_name(path, name) + elem['typeargs'] = elem.get('typeargs', {}) + elem['c_name'] = elem.get('c_name', None) or (elem['name'] + ('_' if c_is_class else '')) + + if isinstance(elem['type'], str) and elem['type'].startswith('readonly '): + elem['typeargs']['fibre.Property.mode'] = 'readonly' + elem['typeargs']['fibre.Property.type'] = elem['type'][len('readonly '):] + elem['type'] = 'fibre.Property' + elif ('flags' in elem['type']) or ('values' in elem['type']): + elem['typeargs']['fibre.Property.mode'] = elem['typeargs'].get('fibre.Property.mode', None) or 'readwrite' + elem['typeargs']['fibre.Property.type'] = regularize_valuetype(path, to_pascal_case(name), elem['type']) + elem['type'] = 'fibre.Property' + else: + elem['type'] = regularize_interface(path, to_pascal_case(name), elem['type']) + return elem + + +def regularize_interface(path, name, elem): + if elem is None: + elem = {} + if isinstance(elem, str): + return elem # will be resolved during type resolution + #if path is None: + # max_anonymous_type = max([int((re.findall('^' + join_name(path, 'AnonymousType') + '([1-9]+)$', x) + ['0'])[0]) for x in interfaces.keys()]) + # path = 'AnonymousType' + str(max_anonymous_type + 1) + elem['name'] = split_name(name)[-1] + elem['fullname'] = path = join_name(path, name) + elem['c_type'] = elem.get('c_type', elem['fullname'].replace('.', 'Intf::')) + 'Intf' + interfaces[path] = elem + elem['functions'] = {name: regularize_func(path, name, func, {'obj': {'type': make_ref_type(elem)}}) + for name, func in get_dict(elem, 'functions').items()} + treat_as_class = elem.get('c_is_class', None) or (len(elem['functions']) > 0) + elem['attributes'] = {name: regularize_attribute(path, name, prop, treat_as_class) + for name, prop in get_dict(elem, 'attributes').items()} + elem['interfaces'] = [] + elem['enums'] = [] + return elem + +def regularize_valuetype(path, name, elem): + if elem is None: + elem = {} + if isinstance(elem, str): + return elem # will be resolved during type resolution + elem['name'] = split_name(name)[-1] + elem['fullname'] = path = join_name(path, name) + elem['c_type'] = elem.get('c_type', elem['fullname'].replace('.', 'Intf::')) + value_types[path] = elem + + if 'flags' in elem: # treat as flags + bit = 0 + for k, v in elem['flags'].items(): + elem['flags'][k] = elem['flags'][k] or {} + current_bit = elem['flags'][k].get('bit', bit) + elem['flags'][k]['bit'] = current_bit + elem['flags'][k]['value'] = 0 if current_bit is None else (1 << current_bit) + bit = bit if current_bit is None else current_bit + 1 + if 'nullflag' in elem: + elem['flags'] = {elem['nullflag']: {'value': 0, 'bit': None}, **elem['flags']} + elem['values'] = elem['flags'] + elem['is_flags'] = True + elem['is_enum'] = True + enums[path] = elem + + elif 'values' in elem: # treat as enum + val = 0 + for k, v in elem['values'].items(): + elem['values'][k] = elem['values'][k] or {} + val = elem['values'][k].get('value', val) + elem['values'][k]['value'] = val + val += 1 + enums[path] = elem + elem['is_enum'] = True + + return elem + +def resolve_interface(scope, name, typeargs): + """ + Resolves a type name (i.e. interface name or value type name) given as a + string to an interface object. The innermost scope is searched first. + At every scope level, if no matching interface is found, it is checked if a + matching value type exists. If so, the interface type fibre.Property + is returned. + """ + if not isinstance(name, str): + return name + + if 'fibre.Property.type' in typeargs: + typeargs['fibre.Property.type'] = resolve_valuetype(scope, typeargs['fibre.Property.type']) + + scope = scope.split('.') + for probe_scope in [join_name(*scope[:(len(scope)-i)]) for i in range(len(scope)+1)]: + probe_name = join_name(probe_scope, name) + #print('probing ' + probe_name) + if probe_name in interfaces: + return interfaces[probe_name] + elif probe_name in value_types: + typeargs['fibre.Property.type'] = value_types[probe_name] + return make_property_type(typeargs) + elif probe_name in generics: + return generics[probe_name](typeargs) + + raise Exception(f'could not resolve type {name} in {join_name(*scope)}. Known interfaces are: {list(interfaces.keys())}. Known value types are: {list(value_types.keys())}') + +def resolve_valuetype(scope, name): + """ + Resolves a type name given as a string to the type object. + The innermost scope is searched first. + """ + if not isinstance(name, str): + return name + + scope = scope.split('.') + for probe_scope in [join_name(*scope[:(len(scope)-i)]) for i in range(len(scope)+1)]: + probe_name = join_name(probe_scope, name) + if probe_name in value_types: + return value_types[probe_name] + + raise Exception(f'could not resolve type {name} in {join_name(*scope)}. Known value types are: {list(value_types.keys())}') + + +def map_to_fibre01_type(t): + if t.get('is_enum', False): + return 'int32' + elif t['fullname'] == 'float32': + return 'float' + return t['fullname'] + +def generate_endpoint_for_property(prop, bindto, idx): + c_value_type = prop['type']['value_type']['c_type'] + if prop.get('c_setter', None) is None: + c_setter = '[](void* ctx, ' + c_value_type + ' val){ ((decltype(&' + bindto + '))ctx)->' + prop['c_name'] + ' = val; }' + else: + c_setter = '[](void* ctx, ' + c_value_type + ' val){ ((decltype(&' + bindto + '))ctx)->' + prop['c_setter'] + '(val); }' + c_getter = '[](void* ctx) { return (const ' + c_value_type + '&)((decltype(&' + bindto + '))ctx)->' + prop['c_name'] + '; }' + + prop_intf = interfaces[prop['type']['fullname']] + if prop['type']['mode'] == 'readonly': + attr_bindto = prop_intf['c_type'] + '{(void*)&' + bindto + ', ' + c_getter + '}' + else: + attr_bindto = prop_intf['c_type'] + '{(void*)&' + bindto + ', ' + c_getter + ', ' + c_setter + '}' + + endpoint = { + 'id': idx, + 'function': prop_intf['functions']['read' if prop['type']['mode'] == 'readonly' else 'exchange'], + 'in_bindings': {'obj': attr_bindto}, + 'out_bindings': [] + } + endpoint_definition = { + 'name': prop['name'], + 'id': idx, + 'type': map_to_fibre01_type(prop['type']['value_type']), + 'access': 'r' if prop['type']['mode'] == 'readonly' else 'rw', + } + return endpoint, endpoint_definition + +def generate_endpoint_table(intf, bindto, idx): + """ + Generates a Fibre v0.1 endpoint table for a given interface. + This will probably be deprecated in the future. + The object must have no circular property types (i.e. A.b has type B and B.a has type A). + """ + endpoints = [] + endpoint_definitions = [] + cnt = 0 + + for k, prop in intf['attributes'].items(): + property_value_type = re.findall('^fibre\.Property<([^>]*), (readonly|readwrite)>$', prop['type']['fullname']) + #attr_bindto = join_name(bindto, bindings_map.get(join_name(intf['fullname'], k), k + ('_' if len(intf['functions']) or (intf['fullname'] in treat_as_classes) else ''))) + if len(property_value_type): + # Special handling for Property<...> attributes: they resolve to one single endpoint + endpoint, endpoint_definition = generate_endpoint_for_property(prop, bindto, idx + cnt) + endpoints.append(endpoint) + endpoint_definitions.append(endpoint_definition) + cnt += 1 + else: + attr_bindto = join_name(bindto, prop['c_name']) + inner_endpoints, inner_endpoint_definitions, inner_cnt = generate_endpoint_table(prop['type'], attr_bindto, idx + cnt) + endpoints += inner_endpoints + endpoint_definitions.append({ + 'name': k, + 'type': 'object', + 'members': inner_endpoint_definitions + }) + cnt += inner_cnt + + for k, func in intf['functions'].items(): + endpoints.append({ + 'id': idx + cnt, + 'function': func, + 'in_bindings': {**{'obj': '&' + bindto}, **{k_arg: bindto + '.' + func['name'] + '_in_' + k_arg + '_' for k_arg in list(func['in'].keys())[1:]}}, + 'out_bindings': {k_arg: '&' + bindto + '.' + func['name'] + '_out_' + k_arg + '_' for k_arg in func['out'].keys()}, + }) + in_def = [] + out_def = [] + for i, (k_arg, arg) in enumerate(list(func['in'].items())[1:]): + endpoint, endpoint_definition = generate_endpoint_for_property({ + 'name': arg['name'], + 'c_name': func['name'] + '_in_' + k_arg + '_', + 'type': make_property_type({'fibre.Property.type': arg['type'], 'fibre.Property.mode': 'readwrite'}) + }, bindto, idx + cnt + 1 + i) + endpoints.append(endpoint) + in_def.append(endpoint_definition) + for i, (k_arg, arg) in enumerate(func['out'].items()): + endpoint, endpoint_definition = generate_endpoint_for_property({ + 'name': arg['name'], + 'c_name': func['name'] + '_out_' + k_arg + '_', + 'type': make_property_type({'fibre.Property.type': arg['type'], 'fibre.Property.mode': 'readwrite'}) + }, bindto, idx + cnt + len(func['in']) + i) + endpoints.append(endpoint) + out_def.append(endpoint_definition) + + endpoint_definitions.append({ + 'name': k, + 'id': idx + cnt, + 'type': 'function', + 'inputs': in_def, + 'outputs': out_def + }) + cnt += len(func['in']) + len(func['out']) + + return endpoints, endpoint_definitions, cnt + + +# Parse arguments + +parser = argparse.ArgumentParser(description="Gernerate code from YAML interface definitions") +parser.add_argument("--version", action="store_true", + help="print version information") +parser.add_argument("-v", "--verbose", action="store_true", + help="print debug information (on stderr)") +parser.add_argument("-d", "--definitions", type=argparse.FileType('r'), nargs='+', + help="the YAML interface definition file(s) used to generate the code") +parser.add_argument("-t", "--template", type=argparse.FileType('r'), + help="the code template") +parser.add_argument("-o", "--output", type=argparse.FileType('w'), default='-', + help="path of the generated output") +args = parser.parse_args() + +if args.version: + print("0.0.1") + sys.exit(0) + + +definition_files = args.definitions +template_file = args.template +output_file = args.output + + +# Load definition files + +for definition_file in definition_files: + try: + file_content = yaml.load(definition_file, Loader=SafeLineLoader) + except yaml.scanner.ScannerError as ex: + print("YAML parsing error: " + str(ex), file=sys.stderr) + sys.exit(1) + for err in validator.iter_errors(file_content): + if '__line__' in err.absolute_path: + continue + if '__column__' in err.absolute_path: + continue + #instance = err.instance.get(re.findall("([^']*)' (?:was|were) unexpected\)", err.message)[0], err.instance) + # TODO: print line number + raise Exception(err.message + '\nat ' + str(list(err.absolute_path))) + interfaces = {**interfaces, **get_dict(file_content, 'interfaces')} + value_types = {**value_types, **get_dict(file_content, 'valuetypes')} + + +# Preprocess definitions + +# Regularize everything into a wellknown form +for k, item in list(interfaces.items()): + regularize_interface('', k, item) +for k, item in list(value_types.items()): + regularize_valuetype('', k, item) + +if args.verbose: + print('Known interfaces: ' + ''.join([('\n ' + k) for k in interfaces.keys()])) + print('Known value types: ' + ''.join([('\n ' + k) for k in value_types.keys()])) + +# Resolve all types into references +for _, item in list(interfaces.items()): + for _, prop in item['attributes'].items(): + prop['type'] = resolve_interface(item['fullname'], prop['type'], prop['typeargs']) + for _, func in item['functions'].items(): + for _, arg in func['in'].items(): + arg['type'] = resolve_valuetype(item['fullname'], arg['type']) + for _, arg in func['out'].items(): + arg['type'] = resolve_valuetype(item['fullname'], arg['type']) + +# Attach interfaces to their parents +toplevel_interfaces = [] +for k, item in list(interfaces.items()): + k = split_name(k) + if len(k) == 1: + toplevel_interfaces.append(item) + else: + if k[:-1] != ['fibre']: # TODO: remove special handling + interfaces[join_name(*k[:-1])]['interfaces'].append(item) +toplevel_enums = [] +for k, item in list(enums.items()): + k = split_name(k) + if len(k) == 1: + toplevel_enums.append(item) + else: + if k[:-1] != ['fibre']: # TODO: remove special handling + interfaces[join_name(*k[:-1])]['enums'].append(item) + + + +endpoints, embedded_endpoint_definitions, _ = generate_endpoint_table(interfaces['Odrive'], 'odrv', 1) # TODO: make user-configurable +embedded_endpoint_definitions = [{'name': '', 'id': 0, 'type': 'json', 'access': 'r'}] + embedded_endpoint_definitions +endpoints = [{'id': 0, 'function': {'fullname': 'endpoint0_handler', 'in': {}, 'out': {}}, 'bindings': {}}] + endpoints + + +# Render template + +env = jinja2.Environment( + comment_start_string='[#', comment_end_string='#]', + block_start_string='[%', block_end_string='%]', + variable_start_string='[[', variable_end_string=']]' +) + +env.filters['to_pascal_case'] = to_pascal_case +env.filters['to_camel_case'] = to_camel_case +env.filters['to_macro_case'] = to_macro_case +env.filters['to_snake_case'] = to_snake_case +env.filters['to_kebab_case'] = to_kebab_case +env.filters['first'] = lambda x: next(iter(x)) +env.filters['skip_first'] = lambda x: list(x)[1:] +env.filters['to_c_string'] = lambda x: '\n'.join(('"' + line.replace('"', '\\"') + '"') for line in json.dumps(x, separators=(',', ':')).replace('{"name"', '\n{"name"').split('\n')) + +template = env.from_string(template_file.read()) + +output = template.render( + interfaces = interfaces, + value_types = value_types, + toplevel_interfaces = toplevel_interfaces, + endpoints = endpoints, + embedded_endpoint_definitions = embedded_endpoint_definitions +) + +output_file.write(output) diff --git a/Firmware/odrive-interface.yaml b/Firmware/odrive-interface.yaml new file mode 100644 index 00000000..ebf50db9 --- /dev/null +++ b/Firmware/odrive-interface.yaml @@ -0,0 +1,662 @@ +--- +version: 0.0.1 +ns: com.odriverobotics +summary: ODrive Interface Definitions + +interfaces: + Odrive: + attributes: + vbus_voltage: readonly float32 + ibus: readonly float32 + serial_number: readonly uint64 + hw_version_major: readonly uint8 + hw_version_minor: readonly uint8 + hw_version_variant: readonly uint8 + fw_version_major: readonly uint8 + fw_version_minor: readonly uint8 + fw_version_revision: readonly uint8 + fw_version_unreleased: + type: readonly uint8 + doc: 0 for official releases, 1 otherwise + brake_resistor_armed: readonly bool + brake_resistor_saturated: bool + system_stats: + attributes: + uptime: readonly uint32 + min_heap_space: readonly uint32 + min_stack_space_axis0: readonly uint32 + min_stack_space_axis1: readonly uint32 + min_stack_space_comms: readonly uint32 + min_stack_space_usb: readonly uint32 + min_stack_space_uart: readonly uint32 + min_stack_space_can: readonly uint32 + min_stack_space_usb_irq: readonly uint32 + min_stack_space_startup: readonly uint32 + stack_usage_axis0: readonly uint32 + stack_usage_axis1: readonly uint32 + stack_usage_comms: readonly uint32 + stack_usage_usb: readonly uint32 + stack_usage_uart: readonly uint32 + stack_usage_usb_irq: readonly uint32 + stack_usage_startup: readonly uint32 + stack_usage_can: readonly uint32 + usb: + attributes: + rx_cnt: readonly uint32 + tx_cnt: readonly uint32 + tx_overrun_cnt: readonly uint32 + i2c: + attributes: + addr: readonly uint8 + addr_match_cnt: readonly uint32 + rx_cnt: readonly uint32 + error_cnt: readonly uint32 + config: + attributes: + enable_uart: + type: bool + doc: 'TODO: changing this currently requires a reboot - fix this' + uart_baudrate: + type: uint32 + doc: "Defines the baudrate used on the UART interface. + Some baudrates will have a small timing error due to hardware limitations. + + Here's an (incomplete) list of baudrates for ODrive v3.x: + + Configured | Actual | Error [%] + -------------|---------------|----------- + 1.2 KBps | 1.2 KBps | 0 + 2.4 KBps | 2.4 KBps | 0 + 9.6 KBps | 9.6 KBps | 0 + 19.2 KBps | 19.195 KBps | 0.02 + 38.4 KBps | 38.391 KBps | 0.02 + 57.6 KBps | 57.613 KBps | 0.02 + 115.2 KBps | 115.068 KBps | 0.11 + 230.4 KBps | 230.769 KBps | 0.16 + 460.8 KBps | 461.538 KBps | 0.16 + 921.6 KBps | 913.043 KBps | 0.93 + 1.792 MBps | 1.826 MBps | 1.9 + 1.8432 MBps | 1.826 MBps | 0.93 + + For more information refer to Section 30.3.4 and Table 142 (the column with f_PCLK = 42 MHz) in the STM datasheet: + https://www.st.com/content/ccc/resource/technical/document/reference_manual/3d/6d/5a/66/b4/99/40/d4/DM00031020.pdf/files/DM00031020.pdf/jcr:content/translations/en.DM00031020.pdf" + enable_i2c_instead_of_can: + type: bool + doc: 'Changing this requires a reboot' + enable_ascii_protocol_on_usb: bool + max_regen_current: float32 + brake_resistance: + type: float32 + unit: Ohm + doc: Value of the brake resistor connected to the ODrive. Set to 0 to disable. + + dc_bus_undervoltage_trip_level: + type: float32 + unit: V + doc: Minimum voltage below which the motor stops operating. + dc_bus_overvoltage_trip_level: + type: float32 + unit: V + doc: Maximum voltage above which the motor stops operating. + This protects against cases in which the power supply fails to dissipate + the brake power if the brake resistor is disabled. + The default is 26V for the 24V board version and 52V for the 48V board version. + + enable_dc_bus_overvoltage_ramp: + type: bool + doc: 'If enabled, if the measured DC voltage exceeds `dc_bus_overvoltage_ramp_start`, + the ODrive will sink more power than usual into the the brake resistor + in an attempt to bring the voltage down again. + + The brake duty cycle is increased by the following amount: + vbus_voltage == dc_bus_overvoltage_ramp_start => brake_duty_cycle += 0% + vbus_voltage == dc_bus_overvoltage_ramp_end => brake_duty_cycle += 100% + + Remarks: + - This feature is active even when all motors are disarmed. + - This feature is disabled if `brake_resistance` is non-positive.' + dc_bus_overvoltage_ramp_start: + type: float32 + doc: See `enable_dc_bus_overvoltage_ramp`. + Do not set this lower than your usual vbus_voltage, + unless you like fried brake resistors. + dc_bus_overvoltage_ramp_end: + type: float32 + doc: See `enable_dc_bus_overvoltage_ramp`. + Must be larger than `dc_bus_overvoltage_ramp_start`, + otherwise the ramp feature is disabled. + + dc_max_positive_current: + type: float32 + unit: A + doc: Max current the power supply can source. + dc_max_negative_current: + type: float32 + unit: A + doc: Max current the power supply can sink. You most likely want a non-positive value here. Set to -INFINITY to disable. + + #gpio1_pwm_mapping: Endpoint # TODO: disable for ODrive v3.2 and older + #gpio2_pwm_mapping: Endpoint # TODO: disable for ODrive v3.2 and older + #gpio3_pwm_mapping: Endpoint # TODO: disable for ODrive v3.2 and older + #gpio4_pwm_mapping: Endpoint + #gpio3_analog_mapping: Endpoint + #gpio4_analog_mapping: Endpoint + user_config_loaded: readonly bool + + axis0: {type: Axis, c_name: get_axis(0)} + axis1: {type: Axis, c_name: get_axis(1)} + can: {type: Can, c_name: get_can()} + test_property: uint32 + + functions: + test_function: {in: {delta: int32}, out: {cnt: int32}} + get_oscilloscope_val: {in: {index: uint32}, out: {val: float32}} + get_adc_voltage: {in: {gpio: uint32}, out: {voltage: float32}} + save_configuration: + erase_configuration: + reboot: + enter_dfu_mode: + + Odrive.Can: + attributes: + error: + nullflag: None + flags: {DuplicateCanIds: } + config: + attributes: + baud_rate: readonly uint32 + protocol: + values: {Simple: } + functions: + set_baud_rate: {in: {baudRate: uint32}} + + Axis: + attributes: + error: + typeargs: {fibre.Property.mode: readonly} + nullflag: 'None' + flags: + InvalidState: + doc: An invalid state was requested. + DcBusUnderVoltage: + DcBusOverVoltage: + CurrentMeasurementTimeout: + BrakeResistorDisarmed: + doc: The brake resistor was unexpectedly disarmed. + MotorDisarmed: + doc: The motor was unexpectedly disarmed. + MotorFailed: + doc: Check `motor.error` for more information. + SensorlessEstimatorFailed: + EncoderFailed: + doc: Check `encoder.error` for more information. + ControllerFailed: + PosCtrlDuringSensorless: + doc: DEPRECATED + WatchdogTimerExpired: + MinEndstopPressed: + MaxEndstopPressed: + EstopRequested: + HomingWithoutEndstop: + doc: the min endstop was not enabled during homing + step_dir_active: readonly bool + current_state: readonly AxisState + requested_state: AxisState + loop_counter: readonly uint32 + lockin_state: + typeargs: {fibre.Property.mode: readonly} + values: + Inactive: + Ramp: + Accelerate: + ConstVel: + is_homed: {type: bool, c_name: homing_.is_homed} + config: + attributes: + startup_motor_calibration: + type: bool + doc: run motor calibration at startup, skip otherwise + startup_encoder_index_search: + type: bool + doc: run encoder index search after startup, skip otherwise this only has an effect if encoder.config.use_index is also true + startup_encoder_offset_calibration: + type: bool + doc: run encoder offset calibration after startup, skip otherwise + startup_closed_loop_control: + type: bool + doc: enable closed loop control after calibration/startup + startup_sensorless_control: + type: bool + doc: enable sensorless control after calibration/startup + startup_homing: + type: bool + doc: enable homing after calibration/startup + enable_step_dir: + type: bool + doc: Enable step/dir input after calibration. + For M0 this has no effect if `enable_uart` is true. + step_dir_always_on: + type: bool + doc: Keep step/dir enabled while the motor is disabled. + This is ignored if enable_step_dir is false. + This setting only takes effect on a state transition + into idle or out of closed loop control. + counts_per_step: float32 + watchdog_timeout: + type: float32 + unit: s + doc: 0 disables watchdog + enable_watchdog: bool + step_gpio_pin: {type: uint16, c_setter: 'set_step_gpio_pin'} + dir_gpio_pin: {type: uint16, c_setter: 'set_dir_gpio_pin'} + calibration_lockin: # TODO: this is a subset of lockin state + attributes: + current: float32 + ramp_time: float32 + ramp_distance: float32 + accel: float32 + vel: float32 + sensorless_ramp: LockinState + general_lockin: LockinState + can_node_id: + type: uint8 + doc: Both axes will have the same id to start + can_heartbeat_rate_ms: uint32 + motor: Motor + controller: Controller + encoder: Encoder + sensorless_estimator: SensorlessEstimator + trap_traj: TrapezoidalTrajectory + min_endstop: Endstop + max_endstop: Endstop + functions: + watchdog_feed: + doc: Feed the watchdog to prevent watchdog timeouts. + clear_errors: + doc: Check the watchdog timer for expiration. Also sets the watchdog error bit if expired. + + Axis.LockinState: + attributes: + current: + type: float32 + unit: A + ramp_time: + type: float32 + unit: s + ramp_distance: + type: float32 + unit: rad + accel: + type: float32 + unit: rad/s^2 + vel: + type: float32 + unit: rad/s + finish_distance: + type: float32 + unit: rad + finish_on_vel: bool + finish_on_distance: bool + finish_on_enc_idx: bool + + + Motor: + c_is_class: True + attributes: + error: + nullflag: None + flags: + PhaseResistanceOutOfRange: + PhaseInductanceOutOfRange: + AdcFailed: + DrvFault: + ControlDeadlineMissed: + NotImplementedMotorType: + BrakeCurrentOutOfRange: + ModulationMagnitude: + BrakeDeadtimeViolation: + UnexpectedTimerCallback: + CurrentSenseSaturation: + InverterOverTemp: + CurrentLimitViolation: + BrakeDutyCycleNan: + DcBusOverRegenCurrent: {doc: too much current pushed into the power supply} + DcBusOverCurrent: {doc: too much current pulled out of the power supply} + armed_state: + typeargs: {fibre.Property.mode: readonly} + values: + Disarmed: + WaitingForTimings: + WaitingForUpdate: + Armed: + is_calibrated: readonly bool + current_meas_phB: {type: readonly float32, c_name: current_meas_.phB} + current_meas_phC: {type: readonly float32, c_name: current_meas_.phC} + DC_calib_phB: {type: float32, c_name: DC_calib_.phB} + DC_calib_phC: {type: float32, c_name: DC_calib_.phC} + phase_current_rev_gain: float32 + thermal_current_lim: readonly float32 + inverter_temp: readonly float32 + current_control: + attributes: + p_gain: float32 + i_gain: float32 + v_current_control_integral_d: float32 + v_current_control_integral_q: float32 + Ibus: float32 + final_v_alpha: float32 + final_v_beta: float32 + Id_setpoint: float32 + Iq_setpoint: readonly float32 + Iq_measured: float32 + Id_measured: float32 + I_measured_report_filter_k: float32 + max_allowed_current: readonly float32 + overcurrent_trip_level: readonly float32 + acim_rotor_flux: float32 + async_phase_vel: readonly float32 + async_phase_offset: float32 + gate_driver: + c_name: gate_driver_exported_ + attributes: + drv_fault: + typeargs: {fibre.Property.mode: readonly} + nullflag: NoFault + flags: + FetLowCOvercurrent: {bit: 0, doc: FET Low side, Phase C Over Current fault} + FetHighCOvercurrent: {bit: 1, doc: FET High side, Phase C Over Current fault} + FetLowBOvercurrent: {bit: 2, doc: FET Low side, Phase B Over Current fault} + FetHighBOvercurrent: {bit: 3, doc: FET High side, Phase B Over Current fault} + FetLowAOvercurrent: {bit: 4, doc: FET Low side, Phase A Over Current fault} + FetHighAOvercurrent: {bit: 5, doc: FET High side, Phase A Over Current fault} + OvertemperatureWarning: {bit: 6, doc: Over Temperature Warning fault} + OvertemperatureShutdown: {bit: 7, doc: Over Temperature Shut Down fault} + PVddUndervoltage: {bit: 8, doc: Power supply Vdd Under Voltage fault} + GVddUndervoltage: {bit: 9, doc: DRV8301 Vdd Under Voltage fault} + GVddOvervoltage: {bit: 10, doc: DRV8301 Vdd Over Voltage fault} + # status_reg_1: readonly uint32 + # status_reg_2: readonly uint32 + # ctrl_reg_1: readonly uint32 + # ctrl_reg_2: readonly uint32 + timing_log: + attributes: + general: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_GENERAL)'} + adc_cb_i: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_ADC_CB_I)'} + adc_cb_dc: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_ADC_CB_DC)'} + meas_r: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_MEAS_R)'} + meas_l: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_MEAS_L)'} + enc_calib: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_ENC_CALIB)'} + idx_search: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_IDX_SEARCH)'} + foc_voltage: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_FOC_VOLTAGE)'} + foc_current: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_FOC_CURRENT)'} + spi_start: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_SPI_START)'} + sample_now: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_SAMPLE_NOW)'} + spi_end: {type: readonly uint16, c_name: 'get(Motor::TIMING_LOG_SPI_END)'} + config: + attributes: + pre_calibrated: {type: bool, c_setter: set_pre_calibrated} + pole_pairs: int32 + calibration_current: float32 + resistance_calib_max_voltage: float32 + phase_inductance: {type: float32, c_setter: set_phase_inductance} + phase_resistance: {type: float32, c_setter: set_phase_resistance} + direction: int32 + motor_type: MotorType + current_lim: float32 + current_lim_margin: float32 + inverter_temp_limit_lower: float32 + inverter_temp_limit_upper: float32 + requested_current_range: float32 + current_control_bandwidth: {type: float32, c_setter: set_current_control_bandwidth} + acim_slip_velocity: float32 + acim_gain_min_flux: float32 + acim_autoflux_min_Id: float32 + acim_autoflux_enable: bool + acim_autoflux_attack_gain: float32 + acim_autoflux_decay_gain: float32 + + + Controller: + attributes: + error: + nullflag: None + flags: + Overspeed: + InvalidInputMode: + UnstableGain: + InvalidMirrorAxis: + InvalidLoadEncoder: + InvalidEstimate: + input_pos: {type: float32, c_setter: set_input_pos} + input_vel: float32 + input_current: float32 + pos_setpoint: readonly float32 + vel_setpoint: readonly float32 + current_setpoint: readonly float32 + trajectory_done: readonly bool + vel_integrator_current: float32 + anticogging_valid: bool + config: + attributes: + gain_scheduling_width: float32 + enable_vel_limit: bool + enable_current_mode_vel_limit: + type: bool + doc: Enable velocity limit in current control mode (requires a valid velocity estimator). + enable_gain_scheduling: bool + enable_overspeed_error: bool + control_mode: ControlMode + input_mode: InputMode + pos_gain: + type: float32 + unit: (counts/s) / counts + vel_gain: + type: float32 + unit: 'A/(counts/s) (or A/(rad/s) in sensorless mode' + vel_integrator_gain: + type: float32 + unit: A/(counts/s * s) + vel_limit: + type: float32 + unit: counts/s + doc: Infinity to disable. + vel_limit_tolerance: + type: float32 + doc: Ratio to `vel_limit`. Infinity to disable. + vel_ramp_rate: float32 + current_ramp_rate: + type: float32 + unit: A / sec + homing_speed: + type: float32 + unit: counts/s + inertia: + type: float32 + unit: A/(count/s^2) + axis_to_mirror: uint8 + mirror_ratio: float32 + load_encoder_axis: + type: uint8 + # TODO: this is meaningless for a user. Should there be a separate developer note? + doc: Default depends on Axis number and is set in load_configuration() + input_filter_bandwidth: + type: float32 + unit: 1/s + c_setter: set_input_filter_bandwidth + anticogging: + attributes: + index: readonly uint32 + pre_calibrated: bool + calib_anticogging: readonly bool + calib_pos_threshold: float32 + calib_vel_threshold: float32 + cogging_ratio: readonly float32 + anticogging_enabled: bool + functions: + move_incremental: {in: {displacement: float32, from_input_pos: bool}} + start_anticogging_calibration: + + + Encoder: + attributes: + error: + nullflag: None + flags: + UnstableGain: + CprPolepairsMismatch: + NoResponse: + UnsupportedEncoderMode: + IllegalHallState: + IndexNotFoundYet: + AbsSpiTimeout: + AbsSpiComFail: + AbsSpiNotReady: + is_ready: readonly bool + index_found: readonly bool + shadow_count: readonly int32 + count_in_cpr: readonly int32 + interpolation: readonly float32 + phase: readonly float32 + pos_estimate: readonly float32 + pos_cpr: readonly float32 + hall_state: readonly uint8 + vel_estimate: readonly float32 + calib_scan_response: readonly float32 + pos_abs: int32 + spi_error_rate: readonly float32 + config: + attributes: + mode: Mode + use_index: {type: bool, c_setter: set_use_index} + find_idx_on_lockin_only: {type: bool, c_setter: set_find_idx_on_lockin_only} + abs_spi_cs_gpio_pin: {type: uint16, c_setter: set_abs_spi_cs_gpio_pin} + zero_count_on_find_idx: bool + cpr: int32 + offset: int32 + pre_calibrated: {type: bool, c_setter: set_pre_calibrated} + offset_float: float32 + enable_phase_interpolation: bool + bandwidth: {type: float32, c_setter: set_bandwidth} + calib_range: float32 + calib_scan_distance: float32 + calib_scan_omega: float32 + idx_search_unidirectional: bool + ignore_illegal_hall_state: bool + sincos_gpio_pin_sin: uint16 + sincos_gpio_pin_cos: uint16 + functions: + set_linear_count: {in: {count: int32}} + + + SensorlessEstimator: + c_is_class: True + attributes: + error: + nullflag: None + flags: + UnstableGain: + phase: float32 + pll_pos: float32 + vel_estimate: float32 + # pll_kp: float32 + # pll_ki: float32 + config: + attributes: + observer_gain: float32 + pll_bandwidth: float32 + pm_flux_linkage: float32 + + + TrapezoidalTrajectory: + c_is_class: True + attributes: + config: + attributes: + vel_limit: float32 + accel_limit: float32 + decel_limit: float32 + + + Endstop: + c_is_class: True + attributes: + endstop_state: readonly bool + config: + attributes: + gpio_num: {type: uint16, c_setter: set_gpio_num} + enabled: {type: bool, c_setter: set_enabled} + offset: float32 + is_active_high: bool + pullup: bool + debounce_ms: {type: uint32, c_setter: set_debounce_ms} + + +valuetypes: + Axis.AxisState: # TODO: remove redundant "Axis" in name + values: + Undefined: + doc: will fall through to idle + Idle: + doc: disable PWM and do nothing + StartupSequence: + doc: the actual sequence is defined by the config.startup... flags + FullCalibrationSequence: + doc: run all calibration procedures, then idle + MotorCalibration: + doc: run motor calibration + SensorlessControl: + doc: run sensorless control + EncoderIndexSearch: + doc: run encoder index search + EncoderOffsetCalibration: + doc: run encoder offset calibration + ClosedLoopControl: + doc: run closed loop control + LockinSpin: + doc: run lockin spin + EncoderDirFind: + Homing: + doc: run axis homing function + + Encoder.Mode: + values: + Incremental: + Hall: + Sincos: + SpiAbsCui: + value: 0x100 + doc: compatible with CUI AMT23xx + SpiAbsAms: + value: 0x101 + doc: compatible with AMS AS5047P, AS5048A/AS5048B (no daisy chain support) + SpiAbsAeat: + value: 0x102 + doc: not yet implemented + + Controller.ControlMode: + values: + # Note: these should be sorted from lowest level of control to + # highest level of control, to allow "<" style comparisons. + VoltageControl: + CurrentControl: + VelocityControl: + PositionControl: + + Controller.InputMode: + values: + Inactive: + Passthrough: + VelRamp: + PosFilter: + MixChannels: + TrapTraj: + CurrentRamp: + Mirror: + + + Motor.MotorType: + values: + HighCurrent: + LowCurrent: # TODO: hide this in code + Gimbal: + Acim: \ No newline at end of file diff --git a/docs/interface-definition-file.md b/docs/interface-definition-file.md new file mode 100644 index 00000000..9e4628e1 --- /dev/null +++ b/docs/interface-definition-file.md @@ -0,0 +1,133 @@ +# Interface Definition File + +This document describes the rules on which the ODrive Interface Definition file is built. It is intended for ODrive contributors who wish to modify it or ODrive users who want to autogenerate their own code from this file to interface with the ODrive. + +## Terms and Concepts + +*Value types* are a way of saying how values of this type are serialized/deserialized to/from raw bytes. +Value types can be: + - one of the well-known types `bool`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int32`, `uint32`, `int64`, `uint64`, `float32`, `float64`, `fibre.Ref` + - An enumeration (that is, a mapping between serialized numbers and well known value names) + - A set of flags (in many programming languages this is the same as normal enums) + +An *interface* is a collection of features (attributes and functions) that can be implemented by an object or used by a client as a filter for object discovery. + +A *function* is something that takes zero or more inputs from the client, does something, and then returns zero or more outputs to the client. Since these input and output arguments are transmitted as raw bytes, they each have a value type. + +An *attribute* is a reference to a subobject which again implements some interface. + +Many languages don't make clear distinctions between interfaces and value types so let's be clear on this: attributes _always_ have an interface type and function input/output arguments _always_ have a value type. If you see something that looks like an attribute with a value type (let's say `uint32`), it's actually an attribute with the interface type `fibre.Property`. If you see a function argument that looks like an interface type (let's say `MyIntf`) it's actually of the value type `fibre.Ref`. + + +## File Structure + +The top level contains a dictionary of interfaces and a dictionary of value types. +Interfaces as well as value types can be subordinate to other interfaces. Nested names are specified using dots in between the subnames. + +Example: + +```yaml +interfaces: + MyFirstInterface: ... + MyFirstInterface.SubInterface: ... + +valuetypes: + MyFirstEnum: ... + MyFirstInterface.SubEnum: ... +``` + +## Interfaces + +Interfaces consist of an `attributes` dictionary and a `functions` dictionary. + +**Attributes** have a type which is either given by name as a string or directly in place. +Even though attributes conceptually and internally are always resolved to an interface type, for your convenience you can also give a value type which is then implicitly resolved to `fibre.Property`. + +If the type is given as a string, it is resolved based on the scope in which it occurs. The search precedence is as follows: The innermost scope is searched first for an interface with that name and then for a value type with that name. If both names don't exist, the next outer scope is checked. Note that the order in which types are defined does not matter. The whole file is read before any type resolution occurs. + +**Functions** have an `in` and `out` dictionary specifying one or more argument names with their corresponding value types. Like with attributes, the types can be specified in place or as a name. Type resolution also works the same except that only value types are checked for. + +Example: +```yaml +interfaces: + Car: + attributes: + velocity: float + door_front_left: Door + door_front_right: Door + steering_wheel: + attributes: + angle: float + functions: + turn: {in: {delta_angle: float32}, out: {final_angle: float32}} + Car.Door: + attributes: + is_open: bool + part_of: Car + functions: + open: + close: +``` + +Let's see how the type resolution of the attibute `Car.Door.part_of: Car` would work here: + + 1. Interface `Car.Door.Car` => not found, proceed + 2. Value type `Car.Door.Car` => not found, proceed + 3. Interface `Car.Car` => not found, proceed + 4. Value type `Car.Car` => not found, proceed + 5. Interface `Car` => found. Link to this interface type. + + +## Enums + +Enums are values which are associated with a name. They are serialized as 32-bit numbers. + +Enumerators without an explicitly stated numerical value are guaranteed to have an underlying value one larger than that of the preceding enumerator. + +Each enumerator must have a unique value. + +Example: + +```yaml +valuetypes: + ModeOfTransport: + values: + Walking: + Bicycle: + Car: {value: 5} + Train: +``` + +This would be serialized as: + - Walking <=> `0x00000000` <=> `0x00 0x00 0x00 0x00` + - Bicycle <=> `0x00000001` <=> `0x01 0x00 0x00 0x00` + - Car <=> `0x00000005` <=> `0x05 0x00 0x00 0x00` + - Train <=> `0x00000006` <=> `0x06 0x00 0x00 0x00` + +## Flagfields + +Flagfields are serialized as 32-bit low endian values where each bit has a named meaning. + +A flag without an explicit bit number is guaranteed to have the bit number of the preceding flag plus one or bit 0 it it's the first in the list. + +Each flag must have a unique bit number. + +Example: + +```yaml +valuetypes: + Anchor: + nullflag: Nowhere + flags: + Top: + Left: + Bottom: {bit: 8} + Right: +``` + +This would be serialized as: + - Nowhere <=> `0x00000000` <=> `0x00 0x00 0x00 0x00` + - Top <=> `0x00000001` <=> `0x01 0x00 0x00 0x00` + - Top and Left <=> `0x00000003` <=> `0x03 0x00 0x00 0x00` + - Bottom <=> `0x00000100` <=> `0x00 0x01 0x00 0x00` + - Top and Bottom and Right <=> `0x00000301` <=> `0x01 0x03 0x00 0x00`