@@ -513,27 +513,61 @@ function set_units_setting!(
513513 return
514514end
515515
516+ function _set_units_base! (system:: System , settings:: UnitSystem )
517+ to_change = (system. units_settings. unit_system != settings)
518+ to_change && (system. units_settings. unit_system = settings)
519+ return (to_change, settings)
520+ end
521+
522+ _set_units_base! (system:: System , settings:: String ) =
523+ _set_units_base! (system:: System , UNIT_SYSTEM_MAPPING[uppercase (settings)])
524+
516525"""
517526Sets the units base for the getter functions on the devices. It modifies the behavior of all getter functions
527+
528+ # Examples
529+ ```julia
530+ set_units_base_system!(sys, "NATURAL_UNITS")
531+ ```
532+ ```julia
533+ set_units_base_system!(sys, UnitSystem.SYSTEM_BASE)
534+ ```
518535"""
519- function set_units_base_system! (system:: System , settings:: String )
520- set_units_base_system! (system:: System , UNIT_SYSTEM_MAPPING[uppercase (settings)])
536+ function set_units_base_system! (system:: System , units:: Union{UnitSystem, String} )
537+ changed, new_units = _set_units_base! (system:: System , units)
538+ changed && @info " Unit System changed to $new_units "
521539 return
522540end
523541
524- function set_units_base_system! (system:: System , settings:: UnitSystem )
525- if system. units_settings. unit_system != settings
526- system. units_settings. unit_system = settings
527- @info " Unit System changed to $settings "
528- end
529- return
530- end
542+ _get_units_base (system:: System ) = system. units_settings. unit_system
531543
532544"""
533545Get the system's [unit base](@ref per_unit))
534546"""
535547function get_units_base (system:: System )
536- return string (system. units_settings. unit_system)
548+ return string (_get_units_base (system))
549+ end
550+
551+ """
552+ A "context manager" that sets the [`System`](@ref)'s [units base](@ref per_unit) to the
553+ given value, executes the function, then sets the units base back.
554+
555+ # Examples
556+ ```julia
557+ active_power_mw = with_units_base(sys, UnitSystem.NATURAL_UNITS) do
558+ get_active_power(gen)
559+ end
560+ # now active_power_mw is in natural units no matter what units base the system is in
561+ ```
562+ """
563+ function with_units_base (f:: Function , sys:: System , units:: Union{UnitSystem, String} )
564+ old_units = _get_units_base (sys)
565+ _set_units_base! (sys, units)
566+ try
567+ f ()
568+ finally
569+ _set_units_base! (sys, old_units)
570+ end
537571end
538572
539573function get_units_setting (component:: T ) where {T <: Component }
0 commit comments