Skip to content

Base

ActuatorBase

Bases: OfflineMixin, ABC

Base class defining the structure and interface for an actuator.

This abstract class provides common functionality for controlling an actuator, including managing control mode transitions, restricting method calls based on mode, and exposing actuator properties.

Examples:

>>> class DummyActuator(ActuatorBase):
...     @property
...     def _CONTROL_MODE_CONFIGS(self):
...         return CONTROL_MODE_CONFIGS()
...     def start(self):
...         print("Started")
...     def stop(self):
...         print("Stopped")
...     def update(self):
...         print("Updated")
...     def set_motor_voltage(self, value: float) -> None:
...         print(f"Motor voltage set to {value}")
...     def set_motor_current(self, value: float) -> None:
...         print(f"Motor current set to {value}")
...     def set_motor_position(self, value: float) -> None:
...         print(f"Motor position set to {value}")
...     def set_motor_torque(self, value: float) -> None:
...         print(f"Motor torque set to {value}")
...     def set_output_torque(self, value: float) -> None:
...         print(f"Output torque set to {value}")
...     def set_current_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
...         print("Current gains set")
...     def set_position_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
...         print("Position gains set")
...     def _set_impedance_gains(self, k: float, b: float) -> None:
...         print("Impedance gains set")
...     def home(self) -> None:
...         print("Homed")
...     @property
...     def motor_position(self) -> float:
...         return 100.0
...     @property
...     def motor_velocity(self) -> float:
...         return 10.0
...     @property
...     def motor_voltage(self) -> float:
...         return 24.0
...     @property
...     def motor_current(self) -> float:
...         return 0.5
...     @property
...     def motor_torque(self) -> float:
...         return 2.0
...     @property
...     def case_temperature(self) -> float:
...         return 70.0
...     @property
...     def winding_temperature(self) -> float:
...         return 90.0
>>> actuator = DummyActuator(
...     tag="act1",
...     gear_ratio=100,
...     motor_constants=MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
... )
>>> actuator.start()
Started
Source code in opensourceleg/actuators/base.py
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
class ActuatorBase(OfflineMixin, ABC):
    """
    Base class defining the structure and interface for an actuator.

    This abstract class provides common functionality for controlling an actuator,
    including managing control mode transitions, restricting method calls based on mode,
    and exposing actuator properties.

    Examples:
        >>> class DummyActuator(ActuatorBase):
        ...     @property
        ...     def _CONTROL_MODE_CONFIGS(self):
        ...         return CONTROL_MODE_CONFIGS()
        ...     def start(self):
        ...         print("Started")
        ...     def stop(self):
        ...         print("Stopped")
        ...     def update(self):
        ...         print("Updated")
        ...     def set_motor_voltage(self, value: float) -> None:
        ...         print(f"Motor voltage set to {value}")
        ...     def set_motor_current(self, value: float) -> None:
        ...         print(f"Motor current set to {value}")
        ...     def set_motor_position(self, value: float) -> None:
        ...         print(f"Motor position set to {value}")
        ...     def set_motor_torque(self, value: float) -> None:
        ...         print(f"Motor torque set to {value}")
        ...     def set_output_torque(self, value: float) -> None:
        ...         print(f"Output torque set to {value}")
        ...     def set_current_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
        ...         print("Current gains set")
        ...     def set_position_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
        ...         print("Position gains set")
        ...     def _set_impedance_gains(self, k: float, b: float) -> None:
        ...         print("Impedance gains set")
        ...     def home(self) -> None:
        ...         print("Homed")
        ...     @property
        ...     def motor_position(self) -> float:
        ...         return 100.0
        ...     @property
        ...     def motor_velocity(self) -> float:
        ...         return 10.0
        ...     @property
        ...     def motor_voltage(self) -> float:
        ...         return 24.0
        ...     @property
        ...     def motor_current(self) -> float:
        ...         return 0.5
        ...     @property
        ...     def motor_torque(self) -> float:
        ...         return 2.0
        ...     @property
        ...     def case_temperature(self) -> float:
        ...         return 70.0
        ...     @property
        ...     def winding_temperature(self) -> float:
        ...         return 90.0
        >>> actuator = DummyActuator(
        ...     tag="act1",
        ...     gear_ratio=100,
        ...     motor_constants=MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
        ... )
        >>> actuator.start()
        Started
    """

    # Class-level mapping of methods to their required control modes
    _METHOD_REQUIRED_MODES: ClassVar[dict[str, set[CONTROL_MODES]]] = {
        "set_motor_voltage": {CONTROL_MODES.VOLTAGE},
        "set_motor_current": {CONTROL_MODES.CURRENT},
        "set_motor_position": {CONTROL_MODES.POSITION, CONTROL_MODES.IMPEDANCE},
        "set_output_position": {CONTROL_MODES.POSITION, CONTROL_MODES.IMPEDANCE},
        "set_motor_impedance": {CONTROL_MODES.IMPEDANCE},
        "set_output_impedance": {CONTROL_MODES.IMPEDANCE},
        "set_motor_torque": {CONTROL_MODES.CURRENT, CONTROL_MODES.TORQUE},
        "set_output_torque": {CONTROL_MODES.CURRENT, CONTROL_MODES.TORQUE},
        "set_current_gains": {CONTROL_MODES.CURRENT, CONTROL_MODES.TORQUE},
        "set_position_gains": {CONTROL_MODES.POSITION},
    }

    # Offline mode configuration for OfflineMixin
    _OFFLINE_METHODS: ClassVar[list[str]] = HARDWARE_REQUIRED_METHODS
    _OFFLINE_PROPERTIES: ClassVar[list[str]] = HARDWARE_REQUIRED_PROPERTIES
    _OFFLINE_PROPERTY_DEFAULTS: ClassVar[dict[str, Any]] = {
        "motor_position": 0.0,
        "motor_velocity": 0.0,
        "motor_voltage": 0.0,
        "motor_current": 0.0,
        "motor_torque": 0.0,
        "case_temperature": 25.0,  # Room temperature
        "winding_temperature": 25.0,  # Room temperature
    }

    def __init__(
        self,
        tag: str,
        gear_ratio: float,
        motor_constants: MOTOR_CONSTANTS,
        frequency: int = 1000,
        offline: bool = False,
        **kwargs: Any,
    ) -> None:
        """
        Initialize an actuator.

        Args:
            tag (str): A unique identifier for the actuator.
            gear_ratio (float): The gear ratio of the actuator.
            motor_constants (MOTOR_CONSTANTS): Motor constant configuration parameters.
            frequency (int, optional): Control frequency in Hz. Defaults to 1000.
            offline (bool, optional): Flag indicating if the actuator operates in offline mode. Defaults to False.
            **kwargs (Any): Additional keyword arguments.

        Examples:
            >>> actuator = DummyActuator(
            ...     tag="act1",
            ...     gear_ratio=100,
            ...     motor_constants=MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
            ... )
        """
        self._MOTOR_CONSTANTS: MOTOR_CONSTANTS = motor_constants
        self._gear_ratio: float = gear_ratio
        self._tag: str = tag
        self._frequency: int = frequency
        self._data: Any = None
        self._is_homed: bool = False

        self._mode: CONTROL_MODES = CONTROL_MODES.IDLE

        self._motor_zero_position: float = 0.0

        self._is_open: bool = False
        self._is_streaming: bool = False

        self._original_methods: dict[str, MethodWithRequiredModes] = {}

        # Initialize OfflineMixin first so _is_offline is available
        super().__init__(offline=offline, **kwargs)

        self._set_original_methods()
        self._set_mutated_methods()

    def __enter__(self) -> "ActuatorBase":
        """
        Enter the runtime context related to this actuator.

        Starts the actuator and returns the instance.

        Returns:
            ActuatorBase: The actuator instance.

        Examples:
            >>> with actuator as a:
            ...     print("Inside context")
            Started
            Inside context
            Stopped
        """
        self.start()
        return self

    def __exit__(self, exc_type: Any, exc_value: Any, exc_traceback: Any) -> None:
        """
        Exit the runtime context and stop the actuator.

        Args:
            exc_type (Any): Exception type, if any.
            exc_value (Any): Exception value, if any.
            exc_traceback (Any): Exception traceback, if any.

        Examples:
            >>> try:
            ...     with actuator:
            ...         raise ValueError("Test error")
            ... except ValueError:
            ...     pass  # actuator.stop() was automatically called
        """
        self.stop()

    def _restricted_method(self, method_name: str, *args: Any, **kwargs: Any) -> None:
        """
        Fallback method for restricted operations.

        Logs an error indicating that the requested method is not available
        in the current control mode.

        Args:
            method_name (str): Name of the restricted method.
            *args (Any): Positional arguments passed to the method.
            **kwargs (Any): Keyword arguments passed to the method.

        Examples:
            >>> actuator._restricted_method("set_motor_voltage")
            # (Logs an error message and returns None)
        """
        raise ControlModeException(tag=self._tag, attribute=method_name, mode=self._mode.name)

    def _set_original_methods(self) -> None:
        """
        Store the original methods that require specific control modes.

        Uses a class-level mapping of methods to their required control modes
        to ensure proper inheritance of restrictions in derived classes.

        Examples:
            >>> print(actuator._original_methods)  # Dictionary of method names to methods
        """
        # Get the method-to-required-modes mapping for this class
        method_modes_map = getattr(self.__class__, "_METHOD_REQUIRED_MODES", {})

        for method_name, _required_modes in method_modes_map.items():
            try:
                method = getattr(self, method_name)
                if callable(method):
                    self._original_methods[method_name] = method
                    # LOGGER.debug(
                    #     msg=f"[{self.tag}] {method_name}() is available in modes: "
                    #     f"{[mode.name for mode in required_modes]}"
                    # )
            except AttributeError:
                LOGGER.debug(msg=f"[{self.tag}] {method_name}() is not implemented in {self.__class__.__name__}.")

    def _set_mutated_methods(self) -> None:
        """
        Update actuator methods based on the current control mode.

        For each method stored in `_original_methods`, if the current control mode
        is permitted, the original method is used; otherwise, a restricted version
        that logs an error is assigned.

        Examples:
            >>> actuator._set_mutated_methods()
        """
        for method_name, method in self._original_methods.items():
            # In offline mode, hardware methods are already stubbed by OfflineMixin
            if self._is_offline and method_name in HARDWARE_REQUIRED_METHODS:
                # Skip - method is already patched by OfflineMixin
                continue
            elif self._mode in self._METHOD_REQUIRED_MODES[method_name]:
                setattr(self, method_name, method)
            else:
                setattr(self, method_name, partial(self._restricted_method, method_name))

    @property
    @abstractmethod
    def _CONTROL_MODE_CONFIGS(self) -> CONTROL_MODE_CONFIGS:
        """
        Abstract property to obtain control mode configurations.

        Returns:
            CONTROL_MODE_CONFIGS: The configuration settings for each control mode.

        Examples:
            >>> config = actuator._CONTROL_MODE_CONFIGS  # Implemented in subclass
        """
        pass

    @abstractmethod
    def start(self) -> None:
        """
        Start the actuator.

        Must be implemented by subclasses to initialize and activate the actuator.

        Examples:
            >>> actuator.start()
            Started
        """
        pass

    @abstractmethod
    def stop(self) -> None:
        """
        Stop the actuator.

        Must be implemented by subclasses to safely deactivate the actuator.

        Examples:
            >>> actuator.stop()
            Stopped
        """
        pass

    @abstractmethod
    def update(self) -> None:
        """
        Update the actuator's state.

        Must be implemented by subclasses to refresh or recalculate state values.

        Examples:
            >>> actuator.update()
            Updated
        """
        pass

    def _get_control_mode_config(self, mode: CONTROL_MODES) -> Optional[ControlModeConfig]:
        """
        Retrieve the control mode configuration for a specified mode.

        Args:
            mode (CONTROL_MODES): The control mode for which to retrieve the configuration.

        Returns:
            Optional[ControlModeConfig]: The configuration if it exists; otherwise, None.

        Examples:
            >>> config = actuator._get_control_mode_config(CONTROL_MODES.IDLE)
            >>> print(config)
            None
        """
        return cast(
            Optional[ControlModeConfig],
            getattr(self._CONTROL_MODE_CONFIGS, mode.name),
        )

    def set_control_mode(self, mode: CONTROL_MODES) -> None:
        """
        Set the actuator's control mode.

        If the mode is changing, the exit callback for the current mode and
        the entry callback for the new mode are executed, and methods are updated
        to reflect any restrictions imposed by the new mode.

        Args:
            mode (CONTROL_MODES): The new control mode to be set.

        Examples:
            >>> actuator.set_control_mode(CONTROL_MODES.POSITION)
        """
        if self.mode == mode:
            LOGGER.debug(msg=f"[{self.tag}] Already in {self.mode.name} control mode.")
            return

        current_config = self._get_control_mode_config(self.mode)
        if current_config:
            current_config.exit_callback(self)

        self._mode = mode

        new_config = self._get_control_mode_config(self.mode)
        if new_config:
            new_config.entry_callback(self)

        self._set_mutated_methods()

    @abstractmethod
    def set_motor_voltage(self, value: float) -> None:
        """
        Set the motor voltage.

        Args:
            value (float): The voltage value to be applied to the motor.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_motor_voltage(12.0)
        """
        pass

    @abstractmethod
    def set_motor_current(self, value: float) -> None:
        """
        Set the motor current.

        Args:
            value (float): The current value to be applied to the motor.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_motor_current(1.5)
        """
        pass

    @abstractmethod
    def set_motor_position(self, value: float) -> None:
        """
        Set the motor position.

        Args:
            value (float): The target motor position in radians.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_motor_position(0.5)
        """
        pass

    def set_output_position(self, value: float) -> None:
        """
        Set the output position of the actuator.

        Converts the desired output position (in radians) to a motor position by
        applying the gear ratio, then delegates to `set_motor_position`.

        Args:
            value (float): The desired output position in radians.

        Examples:
            >>> # Assuming gear_ratio is 100, this will set the motor position to 100 * value.
            >>> actuator.set_motor_position = lambda value: print(f"Motor position set to {value}")
            >>> actuator.set_output_position(1.0)
            Motor position set to 100.0
        """
        self.set_motor_position(value=value * self.gear_ratio)

    @abstractmethod
    def set_motor_torque(self, value: float) -> None:
        """
        Set the motor torque.

        Args:
            value (float): The torque value to be applied to the motor.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_motor_torque(5.0)
        """
        pass

    @abstractmethod
    def set_output_torque(self, value: float) -> None:
        """
        Set the output torque.

        Args:
            value (float): The torque value to be applied to the joint.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_output_torque(5.0)
        """
        pass

    @abstractmethod
    def set_current_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
        """
        Set the current control gains.

        Args:
            kp (float): Proportional gain.
            ki (float): Integral gain.
            kd (float): Derivative gain.
            ff (float): Feed-forward gain.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_current_gains(1.0, 0.1, 0.01, 0.0)
        """
        pass

    @abstractmethod
    def set_position_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
        """
        Set the position control gains.

        Args:
            kp (float): Proportional gain.
            ki (float): Integral gain.
            kd (float): Derivative gain.
            ff (float): Feed-forward gain.

        Must be implemented by subclasses.

        Examples:
            >>> actuator.set_position_gains(1.0, 0.1, 0.01, 0.0)
        """
        pass

    @abstractmethod
    def _set_impedance_gains(self, k: float, b: float) -> None:
        """
        Set the impedance control gains.

        Args:
            k (float): Stiffness coefficient.
            b (float): Damping coefficient.

        Must be implemented by subclasses.

        Examples:
            >>> actuator._set_impedance_gains(0.5, 0.05)
        """
        pass

    @abstractmethod
    def home(
        self,
        homing_voltage: int = 2000,
        homing_frequency: Optional[int] = None,
        homing_direction: int = -1,
        output_position_offset: float = 0.0,
        current_threshold: int = 5000,
        velocity_threshold: float = 0.001,
        callback: Optional[Callable[[], None]] = None,
    ) -> None:
        """
        Home the actuator.

        Aligns the actuator to a known reference position.
        Must be implemented by subclasses.

        Args:
            homing_voltage (int): Voltage to use for homing.
            homing_frequency (Optional[int]): Frequency to use for homing.
            homing_direction (int): Direction to move the actuator during homing.
            output_position_offset (float): Offset to add to the output position.
            current_threshold (int): Current threshold to stop homing.
            velocity_threshold (float): Velocity threshold to stop homing.
            callback (Optional[Callable[[], None]]): Optional callback function to be
                        called when homing completes. The function should take no arguments and return None.

        Examples:
            >>> actuator.home()
            Homed
        """
        pass

    def set_motor_zero_position(self, value: float) -> None:
        """
        Set the motor zero position.

        Args:
            value (float): The motor zero position in radians.

        Examples:
            >>> actuator.set_motor_zero_position(0.0)
            >>> actuator.motor_zero_position
            0.0
        """
        self._motor_zero_position = value

    @property
    @abstractmethod
    def motor_position(self) -> float:
        """
        Get the motor position.

        Returns:
            float: The current motor position in radians.

        Must be implemented by subclasses.

        Examples:
            >>> pos = actuator.motor_position
            >>> print(pos)
            100.0
        """
        pass

    @property
    def output_position(self) -> float:
        """
        Get the output position.

        Returns:
            float: The output position in radians, calculated by dividing the motor
                   position by the gear ratio. Note that this does not account for SEA compliance.

        Examples:
            >>> # If motor_position is 100.0 and gear_ratio is 100, output_position will be 1.0
            >>> actuator.output_position
            1.0
        """
        return self.motor_position / self.gear_ratio

    @property
    @abstractmethod
    def motor_velocity(self) -> float:
        """
        Get the motor velocity.

        Returns:
            float: The current motor velocity in radians per second.

        Must be implemented by subclasses.

        Examples:
            >>> velocity = actuator.motor_velocity
            >>> print(velocity)
            10.0
        """
        pass

    @property
    def output_velocity(self) -> float:
        """
        Get the output velocity.

        Returns:
            float: The output velocity in radians per second, calculated by dividing the motor
                   velocity by the gear ratio. Note that this does not account for SEA compliance.

        Examples:
            >>> # If motor_velocity is 10.0 and gear_ratio is 100, output_velocity will be 0.1
            >>> actuator.output_velocity
            0.1
        """
        return self.motor_velocity / self.gear_ratio

    @property
    @abstractmethod
    def motor_voltage(self) -> float:
        """
        Get the motor voltage.

        Returns:
            float: The current motor voltage.

        Must be implemented by subclasses.

        Examples:
            >>> voltage = actuator.motor_voltage
            >>> print(voltage)
            24.0
        """
        pass

    @property
    @abstractmethod
    def motor_current(self) -> float:
        """
        Get the motor current.

        Returns:
            float: The current motor current.

        Must be implemented by subclasses.

        Examples:
            >>> current = actuator.motor_current
            >>> print(current)
            0.5
        """
        pass

    @property
    @abstractmethod
    def motor_torque(self) -> float:
        """
        Get the motor torque.

        Returns:
            float: The current motor torque.

        Must be implemented by subclasses.

        Examples:
            >>> torque = actuator.motor_torque
            >>> print(torque)
            2.0
        """
        pass

    @property
    def MOTOR_CONSTANTS(self) -> MOTOR_CONSTANTS:
        """
        Get the motor constants configuration.

        Returns:
            MOTOR_CONSTANTS: The motor constants.

        Examples:
            >>> constants = actuator.MOTOR_CONSTANTS
            >>> constants.MAX_CASE_TEMPERATURE
            80.0
        """
        return self._MOTOR_CONSTANTS

    @MOTOR_CONSTANTS.setter
    def MOTOR_CONSTANTS(self, value: MOTOR_CONSTANTS) -> None:
        """
        Set the motor constants configuration.

        Args:
            value (MOTOR_CONSTANTS): The new motor constants to set.

        Examples:
            >>> new_constants = MOTOR_CONSTANTS(2048, 0.03, 0.001, 0.0001, 85.0, 125.0)
            >>> actuator.MOTOR_CONSTANTS = new_constants
            >>> actuator.MOTOR_CONSTANTS.MAX_CASE_TEMPERATURE
            85.0
        """
        self._MOTOR_CONSTANTS = value

    @property
    def mode(self) -> CONTROL_MODES:
        """
        Get the current control mode.

        Returns:
            CONTROL_MODES: The actuator's current control mode.

        Examples:
            >>> actuator.mode
            <CONTROL_MODES.IDLE: -1>
        """
        return self._mode

    @property
    def tag(self) -> str:
        """
        Get the actuator tag.

        Returns:
            str: The unique identifier for the actuator.

        Examples:
            >>> actuator.tag
            "act1"
        """
        return self._tag

    @property
    def is_homed(self) -> bool:
        """
        Check if the actuator has been homed.

        Returns:
            bool: True if the actuator is homed; otherwise, False.

        Examples:
            >>> actuator.is_homed
            False
        """
        return self._is_homed

    @property
    def frequency(self) -> int:
        """
        Get the actuator's control frequency.

        Returns:
            int: The control frequency in Hz.

        Examples:
            >>> actuator.frequency
            1000
        """
        return self._frequency

    @property
    def gear_ratio(self) -> float:
        """
        Get the gear ratio.

        Returns:
            float: The gear ratio of the actuator.

        Examples:
            >>> actuator.gear_ratio
            100
        """
        return self._gear_ratio

    @property
    def max_case_temperature(self) -> float:
        """
        Get the maximum allowed case temperature.

        Returns:
            float: The maximum case temperature defined in motor constants.

        Examples:
            >>> actuator.max_case_temperature
            80.0
        """
        return self._MOTOR_CONSTANTS.MAX_CASE_TEMPERATURE

    @property
    @abstractmethod
    def case_temperature(self) -> float:
        """
        Get the current case temperature.

        Returns:
            float: The current case temperature.

        Must be implemented by subclasses.

        Examples:
            >>> temp = actuator.case_temperature
            >>> print(temp)
            70.0
        """
        pass

    @property
    @abstractmethod
    def winding_temperature(self) -> float:
        """
        Get the current winding temperature.

        Returns:
            float: The current winding temperature.

        Must be implemented by subclasses.

        Examples:
            >>> temp = actuator.winding_temperature
            >>> print(temp)
            90.0
        """
        pass

    @property
    def max_winding_temperature(self) -> float:
        """
        Get the maximum allowed winding temperature.

        Returns:
            float: The maximum winding temperature defined in motor constants.

        Examples:
            >>> actuator.max_winding_temperature
            120.0
        """
        return self._MOTOR_CONSTANTS.MAX_WINDING_TEMPERATURE

    @property
    def motor_zero_position(self) -> float:
        """
        Get the motor zero position.

        Returns:
            float: The motor zero position in radians.

        Examples:
            >>> actuator.set_motor_zero_position(0.0)
            >>> actuator.motor_zero_position
            0.0
        """
        return self._motor_zero_position

    @property
    def is_open(self) -> bool:
        """
        Check if the actuator is open.

        Returns:
            bool: True if open; otherwise, False.

        Examples:
            >>> actuator._is_open = True
            >>> actuator.is_open
            True
        """
        return self._is_open

    @property
    def is_streaming(self) -> bool:
        """
        Check if the actuator is streaming data.

        Returns:
            bool: True if streaming; otherwise, False.

        Examples:
            >>> actuator._is_streaming = True
            >>> actuator.is_streaming
            True
        """
        return self._is_streaming

MOTOR_CONSTANTS property writable

Get the motor constants configuration.

Returns:

Name Type Description
MOTOR_CONSTANTS MOTOR_CONSTANTS

The motor constants.

Examples:

>>> constants = actuator.MOTOR_CONSTANTS
>>> constants.MAX_CASE_TEMPERATURE
80.0

case_temperature abstractmethod property

Get the current case temperature.

Returns:

Name Type Description
float float

The current case temperature.

Must be implemented by subclasses.

Examples:

>>> temp = actuator.case_temperature
>>> print(temp)
70.0

frequency property

Get the actuator's control frequency.

Returns:

Name Type Description
int int

The control frequency in Hz.

Examples:

>>> actuator.frequency
1000

gear_ratio property

Get the gear ratio.

Returns:

Name Type Description
float float

The gear ratio of the actuator.

Examples:

>>> actuator.gear_ratio
100

is_homed property

Check if the actuator has been homed.

Returns:

Name Type Description
bool bool

True if the actuator is homed; otherwise, False.

Examples:

>>> actuator.is_homed
False

is_open property

Check if the actuator is open.

Returns:

Name Type Description
bool bool

True if open; otherwise, False.

Examples:

>>> actuator._is_open = True
>>> actuator.is_open
True

is_streaming property

Check if the actuator is streaming data.

Returns:

Name Type Description
bool bool

True if streaming; otherwise, False.

Examples:

>>> actuator._is_streaming = True
>>> actuator.is_streaming
True

max_case_temperature property

Get the maximum allowed case temperature.

Returns:

Name Type Description
float float

The maximum case temperature defined in motor constants.

Examples:

>>> actuator.max_case_temperature
80.0

max_winding_temperature property

Get the maximum allowed winding temperature.

Returns:

Name Type Description
float float

The maximum winding temperature defined in motor constants.

Examples:

>>> actuator.max_winding_temperature
120.0

mode property

Get the current control mode.

Returns:

Name Type Description
CONTROL_MODES CONTROL_MODES

The actuator's current control mode.

Examples:

>>> actuator.mode
<CONTROL_MODES.IDLE: -1>

motor_current abstractmethod property

Get the motor current.

Returns:

Name Type Description
float float

The current motor current.

Must be implemented by subclasses.

Examples:

>>> current = actuator.motor_current
>>> print(current)
0.5

motor_position abstractmethod property

Get the motor position.

Returns:

Name Type Description
float float

The current motor position in radians.

Must be implemented by subclasses.

Examples:

>>> pos = actuator.motor_position
>>> print(pos)
100.0

motor_torque abstractmethod property

Get the motor torque.

Returns:

Name Type Description
float float

The current motor torque.

Must be implemented by subclasses.

Examples:

>>> torque = actuator.motor_torque
>>> print(torque)
2.0

motor_velocity abstractmethod property

Get the motor velocity.

Returns:

Name Type Description
float float

The current motor velocity in radians per second.

Must be implemented by subclasses.

Examples:

>>> velocity = actuator.motor_velocity
>>> print(velocity)
10.0

motor_voltage abstractmethod property

Get the motor voltage.

Returns:

Name Type Description
float float

The current motor voltage.

Must be implemented by subclasses.

Examples:

>>> voltage = actuator.motor_voltage
>>> print(voltage)
24.0

motor_zero_position property

Get the motor zero position.

Returns:

Name Type Description
float float

The motor zero position in radians.

Examples:

>>> actuator.set_motor_zero_position(0.0)
>>> actuator.motor_zero_position
0.0

output_position property

Get the output position.

Returns:

Name Type Description
float float

The output position in radians, calculated by dividing the motor position by the gear ratio. Note that this does not account for SEA compliance.

Examples:

>>> # If motor_position is 100.0 and gear_ratio is 100, output_position will be 1.0
>>> actuator.output_position
1.0

output_velocity property

Get the output velocity.

Returns:

Name Type Description
float float

The output velocity in radians per second, calculated by dividing the motor velocity by the gear ratio. Note that this does not account for SEA compliance.

Examples:

>>> # If motor_velocity is 10.0 and gear_ratio is 100, output_velocity will be 0.1
>>> actuator.output_velocity
0.1

tag property

Get the actuator tag.

Returns:

Name Type Description
str str

The unique identifier for the actuator.

Examples:

>>> actuator.tag
"act1"

winding_temperature abstractmethod property

Get the current winding temperature.

Returns:

Name Type Description
float float

The current winding temperature.

Must be implemented by subclasses.

Examples:

>>> temp = actuator.winding_temperature
>>> print(temp)
90.0

__enter__()

Enter the runtime context related to this actuator.

Starts the actuator and returns the instance.

Returns:

Name Type Description
ActuatorBase ActuatorBase

The actuator instance.

Examples:

>>> with actuator as a:
...     print("Inside context")
Started
Inside context
Stopped
Source code in opensourceleg/actuators/base.py
def __enter__(self) -> "ActuatorBase":
    """
    Enter the runtime context related to this actuator.

    Starts the actuator and returns the instance.

    Returns:
        ActuatorBase: The actuator instance.

    Examples:
        >>> with actuator as a:
        ...     print("Inside context")
        Started
        Inside context
        Stopped
    """
    self.start()
    return self

__exit__(exc_type, exc_value, exc_traceback)

Exit the runtime context and stop the actuator.

Parameters:

Name Type Description Default
exc_type Any

Exception type, if any.

required
exc_value Any

Exception value, if any.

required
exc_traceback Any

Exception traceback, if any.

required

Examples:

>>> try:
...     with actuator:
...         raise ValueError("Test error")
... except ValueError:
...     pass  # actuator.stop() was automatically called
Source code in opensourceleg/actuators/base.py
def __exit__(self, exc_type: Any, exc_value: Any, exc_traceback: Any) -> None:
    """
    Exit the runtime context and stop the actuator.

    Args:
        exc_type (Any): Exception type, if any.
        exc_value (Any): Exception value, if any.
        exc_traceback (Any): Exception traceback, if any.

    Examples:
        >>> try:
        ...     with actuator:
        ...         raise ValueError("Test error")
        ... except ValueError:
        ...     pass  # actuator.stop() was automatically called
    """
    self.stop()

__init__(tag, gear_ratio, motor_constants, frequency=1000, offline=False, **kwargs)

Initialize an actuator.

Parameters:

Name Type Description Default
tag str

A unique identifier for the actuator.

required
gear_ratio float

The gear ratio of the actuator.

required
motor_constants MOTOR_CONSTANTS

Motor constant configuration parameters.

required
frequency int

Control frequency in Hz. Defaults to 1000.

1000
offline bool

Flag indicating if the actuator operates in offline mode. Defaults to False.

False
**kwargs Any

Additional keyword arguments.

{}

Examples:

>>> actuator = DummyActuator(
...     tag="act1",
...     gear_ratio=100,
...     motor_constants=MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
... )
Source code in opensourceleg/actuators/base.py
def __init__(
    self,
    tag: str,
    gear_ratio: float,
    motor_constants: MOTOR_CONSTANTS,
    frequency: int = 1000,
    offline: bool = False,
    **kwargs: Any,
) -> None:
    """
    Initialize an actuator.

    Args:
        tag (str): A unique identifier for the actuator.
        gear_ratio (float): The gear ratio of the actuator.
        motor_constants (MOTOR_CONSTANTS): Motor constant configuration parameters.
        frequency (int, optional): Control frequency in Hz. Defaults to 1000.
        offline (bool, optional): Flag indicating if the actuator operates in offline mode. Defaults to False.
        **kwargs (Any): Additional keyword arguments.

    Examples:
        >>> actuator = DummyActuator(
        ...     tag="act1",
        ...     gear_ratio=100,
        ...     motor_constants=MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
        ... )
    """
    self._MOTOR_CONSTANTS: MOTOR_CONSTANTS = motor_constants
    self._gear_ratio: float = gear_ratio
    self._tag: str = tag
    self._frequency: int = frequency
    self._data: Any = None
    self._is_homed: bool = False

    self._mode: CONTROL_MODES = CONTROL_MODES.IDLE

    self._motor_zero_position: float = 0.0

    self._is_open: bool = False
    self._is_streaming: bool = False

    self._original_methods: dict[str, MethodWithRequiredModes] = {}

    # Initialize OfflineMixin first so _is_offline is available
    super().__init__(offline=offline, **kwargs)

    self._set_original_methods()
    self._set_mutated_methods()

home(homing_voltage=2000, homing_frequency=None, homing_direction=-1, output_position_offset=0.0, current_threshold=5000, velocity_threshold=0.001, callback=None) abstractmethod

Home the actuator.

Aligns the actuator to a known reference position. Must be implemented by subclasses.

Parameters:

Name Type Description Default
homing_voltage int

Voltage to use for homing.

2000
homing_frequency Optional[int]

Frequency to use for homing.

None
homing_direction int

Direction to move the actuator during homing.

-1
output_position_offset float

Offset to add to the output position.

0.0
current_threshold int

Current threshold to stop homing.

5000
velocity_threshold float

Velocity threshold to stop homing.

0.001
callback Optional[Callable[[], None]]

Optional callback function to be called when homing completes. The function should take no arguments and return None.

None

Examples:

>>> actuator.home()
Homed
Source code in opensourceleg/actuators/base.py
@abstractmethod
def home(
    self,
    homing_voltage: int = 2000,
    homing_frequency: Optional[int] = None,
    homing_direction: int = -1,
    output_position_offset: float = 0.0,
    current_threshold: int = 5000,
    velocity_threshold: float = 0.001,
    callback: Optional[Callable[[], None]] = None,
) -> None:
    """
    Home the actuator.

    Aligns the actuator to a known reference position.
    Must be implemented by subclasses.

    Args:
        homing_voltage (int): Voltage to use for homing.
        homing_frequency (Optional[int]): Frequency to use for homing.
        homing_direction (int): Direction to move the actuator during homing.
        output_position_offset (float): Offset to add to the output position.
        current_threshold (int): Current threshold to stop homing.
        velocity_threshold (float): Velocity threshold to stop homing.
        callback (Optional[Callable[[], None]]): Optional callback function to be
                    called when homing completes. The function should take no arguments and return None.

    Examples:
        >>> actuator.home()
        Homed
    """
    pass

set_control_mode(mode)

Set the actuator's control mode.

If the mode is changing, the exit callback for the current mode and the entry callback for the new mode are executed, and methods are updated to reflect any restrictions imposed by the new mode.

Parameters:

Name Type Description Default
mode CONTROL_MODES

The new control mode to be set.

required

Examples:

>>> actuator.set_control_mode(CONTROL_MODES.POSITION)
Source code in opensourceleg/actuators/base.py
def set_control_mode(self, mode: CONTROL_MODES) -> None:
    """
    Set the actuator's control mode.

    If the mode is changing, the exit callback for the current mode and
    the entry callback for the new mode are executed, and methods are updated
    to reflect any restrictions imposed by the new mode.

    Args:
        mode (CONTROL_MODES): The new control mode to be set.

    Examples:
        >>> actuator.set_control_mode(CONTROL_MODES.POSITION)
    """
    if self.mode == mode:
        LOGGER.debug(msg=f"[{self.tag}] Already in {self.mode.name} control mode.")
        return

    current_config = self._get_control_mode_config(self.mode)
    if current_config:
        current_config.exit_callback(self)

    self._mode = mode

    new_config = self._get_control_mode_config(self.mode)
    if new_config:
        new_config.entry_callback(self)

    self._set_mutated_methods()

set_current_gains(kp, ki, kd, ff) abstractmethod

Set the current control gains.

Parameters:

Name Type Description Default
kp float

Proportional gain.

required
ki float

Integral gain.

required
kd float

Derivative gain.

required
ff float

Feed-forward gain.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_current_gains(1.0, 0.1, 0.01, 0.0)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_current_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
    """
    Set the current control gains.

    Args:
        kp (float): Proportional gain.
        ki (float): Integral gain.
        kd (float): Derivative gain.
        ff (float): Feed-forward gain.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_current_gains(1.0, 0.1, 0.01, 0.0)
    """
    pass

set_motor_current(value) abstractmethod

Set the motor current.

Parameters:

Name Type Description Default
value float

The current value to be applied to the motor.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_motor_current(1.5)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_motor_current(self, value: float) -> None:
    """
    Set the motor current.

    Args:
        value (float): The current value to be applied to the motor.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_motor_current(1.5)
    """
    pass

set_motor_position(value) abstractmethod

Set the motor position.

Parameters:

Name Type Description Default
value float

The target motor position in radians.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_motor_position(0.5)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_motor_position(self, value: float) -> None:
    """
    Set the motor position.

    Args:
        value (float): The target motor position in radians.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_motor_position(0.5)
    """
    pass

set_motor_torque(value) abstractmethod

Set the motor torque.

Parameters:

Name Type Description Default
value float

The torque value to be applied to the motor.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_motor_torque(5.0)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_motor_torque(self, value: float) -> None:
    """
    Set the motor torque.

    Args:
        value (float): The torque value to be applied to the motor.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_motor_torque(5.0)
    """
    pass

set_motor_voltage(value) abstractmethod

Set the motor voltage.

Parameters:

Name Type Description Default
value float

The voltage value to be applied to the motor.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_motor_voltage(12.0)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_motor_voltage(self, value: float) -> None:
    """
    Set the motor voltage.

    Args:
        value (float): The voltage value to be applied to the motor.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_motor_voltage(12.0)
    """
    pass

set_motor_zero_position(value)

Set the motor zero position.

Parameters:

Name Type Description Default
value float

The motor zero position in radians.

required

Examples:

>>> actuator.set_motor_zero_position(0.0)
>>> actuator.motor_zero_position
0.0
Source code in opensourceleg/actuators/base.py
def set_motor_zero_position(self, value: float) -> None:
    """
    Set the motor zero position.

    Args:
        value (float): The motor zero position in radians.

    Examples:
        >>> actuator.set_motor_zero_position(0.0)
        >>> actuator.motor_zero_position
        0.0
    """
    self._motor_zero_position = value

set_output_position(value)

Set the output position of the actuator.

Converts the desired output position (in radians) to a motor position by applying the gear ratio, then delegates to set_motor_position.

Parameters:

Name Type Description Default
value float

The desired output position in radians.

required

Examples:

>>> # Assuming gear_ratio is 100, this will set the motor position to 100 * value.
>>> actuator.set_motor_position = lambda value: print(f"Motor position set to {value}")
>>> actuator.set_output_position(1.0)
Motor position set to 100.0
Source code in opensourceleg/actuators/base.py
def set_output_position(self, value: float) -> None:
    """
    Set the output position of the actuator.

    Converts the desired output position (in radians) to a motor position by
    applying the gear ratio, then delegates to `set_motor_position`.

    Args:
        value (float): The desired output position in radians.

    Examples:
        >>> # Assuming gear_ratio is 100, this will set the motor position to 100 * value.
        >>> actuator.set_motor_position = lambda value: print(f"Motor position set to {value}")
        >>> actuator.set_output_position(1.0)
        Motor position set to 100.0
    """
    self.set_motor_position(value=value * self.gear_ratio)

set_output_torque(value) abstractmethod

Set the output torque.

Parameters:

Name Type Description Default
value float

The torque value to be applied to the joint.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_output_torque(5.0)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_output_torque(self, value: float) -> None:
    """
    Set the output torque.

    Args:
        value (float): The torque value to be applied to the joint.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_output_torque(5.0)
    """
    pass

set_position_gains(kp, ki, kd, ff) abstractmethod

Set the position control gains.

Parameters:

Name Type Description Default
kp float

Proportional gain.

required
ki float

Integral gain.

required
kd float

Derivative gain.

required
ff float

Feed-forward gain.

required

Must be implemented by subclasses.

Examples:

>>> actuator.set_position_gains(1.0, 0.1, 0.01, 0.0)
Source code in opensourceleg/actuators/base.py
@abstractmethod
def set_position_gains(self, kp: float, ki: float, kd: float, ff: float) -> None:
    """
    Set the position control gains.

    Args:
        kp (float): Proportional gain.
        ki (float): Integral gain.
        kd (float): Derivative gain.
        ff (float): Feed-forward gain.

    Must be implemented by subclasses.

    Examples:
        >>> actuator.set_position_gains(1.0, 0.1, 0.01, 0.0)
    """
    pass

start() abstractmethod

Start the actuator.

Must be implemented by subclasses to initialize and activate the actuator.

Examples:

>>> actuator.start()
Started
Source code in opensourceleg/actuators/base.py
@abstractmethod
def start(self) -> None:
    """
    Start the actuator.

    Must be implemented by subclasses to initialize and activate the actuator.

    Examples:
        >>> actuator.start()
        Started
    """
    pass

stop() abstractmethod

Stop the actuator.

Must be implemented by subclasses to safely deactivate the actuator.

Examples:

>>> actuator.stop()
Stopped
Source code in opensourceleg/actuators/base.py
@abstractmethod
def stop(self) -> None:
    """
    Stop the actuator.

    Must be implemented by subclasses to safely deactivate the actuator.

    Examples:
        >>> actuator.stop()
        Stopped
    """
    pass

update() abstractmethod

Update the actuator's state.

Must be implemented by subclasses to refresh or recalculate state values.

Examples:

>>> actuator.update()
Updated
Source code in opensourceleg/actuators/base.py
@abstractmethod
def update(self) -> None:
    """
    Update the actuator's state.

    Must be implemented by subclasses to refresh or recalculate state values.

    Examples:
        >>> actuator.update()
        Updated
    """
    pass

CONTROL_MODES

Bases: Enum

Enum to define various control modes.

Examples:

>>> CONTROL_MODES.POSITION
<CONTROL_MODES.POSITION: 0>
Source code in opensourceleg/actuators/base.py
class CONTROL_MODES(Enum):
    """
    Enum to define various control modes.

    Examples:
        >>> CONTROL_MODES.POSITION
        <CONTROL_MODES.POSITION: 0>
    """

    IDLE = -1
    POSITION = 0
    VOLTAGE = 1
    CURRENT = 2
    IMPEDANCE = 3
    VELOCITY = 4
    TORQUE = 5

CONTROL_MODE_CONFIGS

Bases: NamedTuple

Named tuple containing control mode configurations.

Attributes:

Name Type Description
IDLE Optional[ControlModeConfig]

Configuration for IDLE mode.

POSITION Optional[ControlModeConfig]

Configuration for POSITION mode.

CURRENT Optional[ControlModeConfig]

Configuration for CURRENT mode.

VOLTAGE Optional[ControlModeConfig]

Configuration for VOLTAGE mode.

IMPEDANCE Optional[ControlModeConfig]

Configuration for IMPEDANCE mode.

VELOCITY Optional[ControlModeConfig]

Configuration for VELOCITY mode.

TORQUE Optional[ControlModeConfig]

Configuration for TORQUE mode.

Examples:

>>> idle_config = ControlModeConfig(
...     entry_callback=lambda a: print("Idle entered"),
...     exit_callback=lambda a: print("Idle exited")
...
>>> mode_configs = CONTROL_MODE_CONFIGS(IDLE=idle_config)
>>> mode_configs.IDLE.entry_callback(None)
Idle entered
Source code in opensourceleg/actuators/base.py
class CONTROL_MODE_CONFIGS(NamedTuple):
    """
    Named tuple containing control mode configurations.

    Attributes:
        IDLE (Optional[ControlModeConfig]): Configuration for IDLE mode.
        POSITION (Optional[ControlModeConfig]): Configuration for POSITION mode.
        CURRENT (Optional[ControlModeConfig]): Configuration for CURRENT mode.
        VOLTAGE (Optional[ControlModeConfig]): Configuration for VOLTAGE mode.
        IMPEDANCE (Optional[ControlModeConfig]): Configuration for IMPEDANCE mode.
        VELOCITY (Optional[ControlModeConfig]): Configuration for VELOCITY mode.
        TORQUE (Optional[ControlModeConfig]): Configuration for TORQUE mode.

    Examples:
        >>> idle_config = ControlModeConfig(
        ...     entry_callback=lambda a: print("Idle entered"),
        ...     exit_callback=lambda a: print("Idle exited")
        ...
        >>> mode_configs = CONTROL_MODE_CONFIGS(IDLE=idle_config)
        >>> mode_configs.IDLE.entry_callback(None)
        Idle entered
    """

    IDLE: Optional[ControlModeConfig] = None
    POSITION: Optional[ControlModeConfig] = None
    CURRENT: Optional[ControlModeConfig] = None
    VOLTAGE: Optional[ControlModeConfig] = None
    IMPEDANCE: Optional[ControlModeConfig] = None
    VELOCITY: Optional[ControlModeConfig] = None
    TORQUE: Optional[ControlModeConfig] = None

ControlGains dataclass

Class to define the control gains.

Examples:

>>> gains = ControlGains(kp=1.0, ki=0.1, kd=0.01, k=0.5, b=0.05, ff=0.0)
>>> gains.kp
1.0
Source code in opensourceleg/actuators/base.py
@dataclass
class ControlGains:
    """
    Class to define the control gains.

    Examples:
        >>> gains = ControlGains(kp=1.0, ki=0.1, kd=0.01, k=0.5, b=0.05, ff=0.0)
        >>> gains.kp
        1.0
    """

    kp: float = 0
    ki: float = 0
    kd: float = 0
    k: float = 0
    b: float = 0
    ff: float = 0

ControlModeConfig dataclass

Configuration for a control mode.

Attributes:

Name Type Description
entry_callback Callable[[Any], None]

Callback to execute when entering this mode.

exit_callback Callable[[Any], None]

Callback to execute when exiting this mode.

has_gains bool

Indicates if the control mode utilizes control gains.

max_gains Union[ControlGains, None]

The maximum allowable control gains (if applicable).

Examples:

>>> def enter(actuator):
...     print("Entering mode")
>>> def exit(actuator):
...     print("Exiting mode")
>>> config = ControlModeConfig(
...     entry_callback=enter,
...     exit_callback=exit,
...     has_gains=True,
...     max_gains=ControlGains(1.0, 0.1, 0.01, 0.5, 0.05, 0.0)
... )
>>> config.has_gains
True
Source code in opensourceleg/actuators/base.py
@dataclass
class ControlModeConfig:
    """
    Configuration for a control mode.

    Attributes:
        entry_callback (Callable[[Any], None]): Callback to execute when entering this mode.
        exit_callback (Callable[[Any], None]): Callback to execute when exiting this mode.
        has_gains (bool): Indicates if the control mode utilizes control gains.
        max_gains (Union[ControlGains, None]): The maximum allowable control gains (if applicable).

    Examples:
        >>> def enter(actuator):
        ...     print("Entering mode")
        >>> def exit(actuator):
        ...     print("Exiting mode")
        >>> config = ControlModeConfig(
        ...     entry_callback=enter,
        ...     exit_callback=exit,
        ...     has_gains=True,
        ...     max_gains=ControlGains(1.0, 0.1, 0.01, 0.5, 0.05, 0.0)
        ... )
        >>> config.has_gains
        True
    """

    entry_callback: Callable[[Any], None]
    exit_callback: Callable[[Any], None]
    has_gains: bool = False
    max_gains: Union[ControlGains, None] = None

MOTOR_CONSTANTS dataclass

Class to define the motor constants.

Examples:

>>> constants = MOTOR_CONSTANTS(
...     MOTOR_COUNT_PER_REV=2048,
...     NM_PER_AMP=0.02,
...     NM_PER_RAD_TO_K=0.001,
...     NM_S_PER_RAD_TO_B=0.0001,
...     MAX_CASE_TEMPERATURE=80.0,
...     MAX_WINDING_TEMPERATURE=120.0
... )
>>> print(constants.MOTOR_COUNT_PER_REV)
2048
Source code in opensourceleg/actuators/base.py
@dataclass
class MOTOR_CONSTANTS:
    """
    Class to define the motor constants.

    Examples:
        >>> constants = MOTOR_CONSTANTS(
        ...     MOTOR_COUNT_PER_REV=2048,
        ...     NM_PER_AMP=0.02,
        ...     NM_PER_RAD_TO_K=0.001,
        ...     NM_S_PER_RAD_TO_B=0.0001,
        ...     MAX_CASE_TEMPERATURE=80.0,
        ...     MAX_WINDING_TEMPERATURE=120.0
        ... )
        >>> print(constants.MOTOR_COUNT_PER_REV)
        2048
    """

    MOTOR_COUNT_PER_REV: float
    NM_PER_AMP: float  # Motor torque constant (Nm/A)
    MAX_CASE_TEMPERATURE: float  # Hard limit for case/housing temperature
    MAX_WINDING_TEMPERATURE: float  # Hard limit for winding temperature

    # TMotor Servo Mode specific parameters (Servo Mode does not support PID)
    NM_PER_RAD_TO_K: float = 0.001  # Default value for non-servo mode actuators
    NM_S_PER_RAD_TO_B: float = 0.0001  # Default value for non-servo mode actuators

    # Thermal model parameters from research paper (with defaults from Jake Schuchmann's tests)
    WINDING_THERMAL_CAPACITANCE: float = 0.20 * 81.46202695970649  # Cw (J/°C)
    CASE_THERMAL_CAPACITANCE: float = 512.249065845453  # Ch (J/°C)
    WINDING_TO_CASE_RESISTANCE: float = 1.0702867186480716  # Rw-h (°C/W)
    CASE_TO_AMBIENT_RESISTANCE: float = 1.9406620046327363  # Rh-a (°C/W)
    COPPER_TEMPERATURE_COEFFICIENT: float = 0.393 / 100  # alpha (1/°C)
    REFERENCE_TEMPERATURE: float = 65.0  # Reference temperature for resistance (°C)
    REFERENCE_RESISTANCE: float = 0.376  # Reference resistance at reference temp (Ohms)

    WINDING_SOFT_LIMIT: float = 70.0  # soft winding limit (°C)
    CASE_SOFT_LIMIT: float = 60.0  # soft case limit (°C)

    def __post_init__(self) -> None:
        """
        Function to validate the motor constants and thermal parameters.

        Examples:
            >>> # This will raise a ValueError because a negative value is invalid.
            >>> MOTOR_CONSTANTS(
            ...     MOTOR_COUNT_PER_REV=-2048,
            ...     NM_PER_AMP=0.02,
            ...     MAX_CASE_TEMPERATURE=80.0,
            ...     MAX_WINDING_TEMPERATURE=120.0
            ... )
        """
        if any(x <= 0 for x in self.__dict__.values()):
            raise ValueError("All values in MOTOR_CONSTANTS must be non-zero and positive.")

        # Validate thermal safety limits
        if self.MAX_WINDING_TEMPERATURE <= self.MAX_CASE_TEMPERATURE:
            raise ValueError("MAX_WINDING_TEMPERATURE must be greater than MAX_CASE_TEMPERATURE")
        if self.WINDING_SOFT_LIMIT >= self.MAX_WINDING_TEMPERATURE:
            raise ValueError("WINDING_SOFT_LIMIT must be less than MAX_WINDING_TEMPERATURE")
        if self.CASE_SOFT_LIMIT >= self.MAX_CASE_TEMPERATURE:
            raise ValueError("CASE_SOFT_LIMIT must be less than MAX_CASE_TEMPERATURE")

    @property
    def RAD_PER_COUNT(self) -> float:
        """
        Calculate the radians per count.

        Returns:
            float: Radians per count.

        Examples:
            >>> constants = MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
            >>> constants.RAD_PER_COUNT
            0.0030679615757712823
        """
        return 2 * np.pi / self.MOTOR_COUNT_PER_REV

    @property
    def NM_PER_MILLIAMP(self) -> float:
        """
        Convert NM per amp to NM per milliamp.

        Returns:
            float: NM per milliamp.

        Examples:
            >>> constants = MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
            >>> constants.NM_PER_MILLIAMP
            2e-05
        """
        return self.NM_PER_AMP / 1000

NM_PER_MILLIAMP property

Convert NM per amp to NM per milliamp.

Returns:

Name Type Description
float float

NM per milliamp.

Examples:

>>> constants = MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
>>> constants.NM_PER_MILLIAMP
2e-05

RAD_PER_COUNT property

Calculate the radians per count.

Returns:

Name Type Description
float float

Radians per count.

Examples:

>>> constants = MOTOR_CONSTANTS(2048, 0.02, 0.001, 0.0001, 80.0, 120.0)
>>> constants.RAD_PER_COUNT
0.0030679615757712823

__post_init__()

Function to validate the motor constants and thermal parameters.

Examples:

>>> # This will raise a ValueError because a negative value is invalid.
>>> MOTOR_CONSTANTS(
...     MOTOR_COUNT_PER_REV=-2048,
...     NM_PER_AMP=0.02,
...     MAX_CASE_TEMPERATURE=80.0,
...     MAX_WINDING_TEMPERATURE=120.0
... )
Source code in opensourceleg/actuators/base.py
def __post_init__(self) -> None:
    """
    Function to validate the motor constants and thermal parameters.

    Examples:
        >>> # This will raise a ValueError because a negative value is invalid.
        >>> MOTOR_CONSTANTS(
        ...     MOTOR_COUNT_PER_REV=-2048,
        ...     NM_PER_AMP=0.02,
        ...     MAX_CASE_TEMPERATURE=80.0,
        ...     MAX_WINDING_TEMPERATURE=120.0
        ... )
    """
    if any(x <= 0 for x in self.__dict__.values()):
        raise ValueError("All values in MOTOR_CONSTANTS must be non-zero and positive.")

    # Validate thermal safety limits
    if self.MAX_WINDING_TEMPERATURE <= self.MAX_CASE_TEMPERATURE:
        raise ValueError("MAX_WINDING_TEMPERATURE must be greater than MAX_CASE_TEMPERATURE")
    if self.WINDING_SOFT_LIMIT >= self.MAX_WINDING_TEMPERATURE:
        raise ValueError("WINDING_SOFT_LIMIT must be less than MAX_WINDING_TEMPERATURE")
    if self.CASE_SOFT_LIMIT >= self.MAX_CASE_TEMPERATURE:
        raise ValueError("CASE_SOFT_LIMIT must be less than MAX_CASE_TEMPERATURE")

MethodWithRequiredModes

Bases: Protocol

Protocol for methods that define required control modes.

Attributes:

Name Type Description
_required_modes set[CONTROL_MODES]

A set of control modes in which the method is permitted.

Examples:

>>> class Dummy:
...     _required_modes = {CONTROL_MODES.IDLE}
>>> isinstance(Dummy(), MethodWithRequiredModes)
True
Source code in opensourceleg/actuators/base.py
@runtime_checkable
class MethodWithRequiredModes(Protocol):
    """
    Protocol for methods that define required control modes.

    Attributes:
        _required_modes (set[CONTROL_MODES]): A set of control modes in which the method is permitted.

    Examples:
        >>> class Dummy:
        ...     _required_modes = {CONTROL_MODES.IDLE}
        >>> isinstance(Dummy(), MethodWithRequiredModes)
        True
    """

    _required_modes: set[CONTROL_MODES]

requires(*modes)

Decorator to specify required control modes for a method.

The decorator attaches a set of required modes to the function, ensuring that the function is only active in the specified control modes.

Parameters:

Name Type Description Default
*modes CONTROL_MODES

One or more control modes required for the method.

()

Raises:

Type Description
TypeError

If any argument is not an instance of CONTROL_MODES.

Returns:

Type Description
Callable[[T], T]

Callable[[T], T]: The decorated function with an attached _required_modes attribute.

Examples:

>>> @requires(CONTROL_MODES.POSITION, CONTROL_MODES.TORQUE)
... def some_method(self, value):
...     return value
>>> some_method._required_modes  # May output: {<CONTROL_MODES.POSITION: 0>, <CONTROL_MODES.TORQUE: 5>}
Source code in opensourceleg/actuators/base.py
def requires(*modes: CONTROL_MODES) -> Callable[[T], T]:
    """
    Decorator to specify required control modes for a method.

    The decorator attaches a set of required modes to the function,
    ensuring that the function is only active in the specified control modes.

    Args:
        *modes (CONTROL_MODES): One or more control modes required for the method.

    Raises:
        TypeError: If any argument is not an instance of CONTROL_MODES.

    Returns:
        Callable[[T], T]: The decorated function with an attached `_required_modes` attribute.

    Examples:
        >>> @requires(CONTROL_MODES.POSITION, CONTROL_MODES.TORQUE)
        ... def some_method(self, value):
        ...     return value
        >>> some_method._required_modes  # May output: {<CONTROL_MODES.POSITION: 0>, <CONTROL_MODES.TORQUE: 5>}
    """

    def decorator(func: T) -> T:
        """
        Attach required control modes to the decorated function.

        Args:
            func (T): The function to be decorated.

        Returns:
            T: The same function with an updated `_required_modes` attribute.
        """
        if not all(isinstance(mode, CONTROL_MODES) for mode in modes):
            raise TypeError("All arguments to 'requires' must be of type CONTROL_MODES")

        if not hasattr(func, "_required_modes"):
            func._required_modes = set(modes)  # type: ignore[attr-defined]
        else:
            func._required_modes.update(modes)

        return func

    return decorator