Enums in Modelica

Our enum type ServerState has an underlying int type.

type ServerState = enumeration(StateIdle, StateConnected, StateError, StateRetrying);

The possible values for ServerState are defined as constants in the enumeration. In Modelica, we define an enumeration with specific names without needing an automatic value generator like iota.

By defining a function to convert the enum value to a string, we can print out or convert ServerState values to strings.

function stateToString
  input ServerState ss;
  output String stateName;
algorithm
  stateName := match(ss)
    (ServerState.StateIdle, "idle"),
    (ServerState.StateConnected, "connected"),
    (ServerState.StateError, "error"),
    (ServerState.StateRetrying, "retrying");
end stateToString;

This function, stateToString, provides a way to convert the enumerated state values to their corresponding string representation.

The main function demonstrates how to transition between states and print them.

function transition
  input ServerState s;
  output ServerState nextState;
algorithm
  nextState := if s == ServerState.StateIdle then
                 ServerState.StateConnected
               else if (s == ServerState.StateConnected or s == ServerState.StateRetrying) then
                 ServerState.StateIdle
               else if s == ServerState.StateError then
                 ServerState.StateError
               else
                 error("unknown state: " + stateToString(s));
end transition;

The transition function emulates a state transition for a server; it takes the existing state and returns a new state.

model Main
  ServerState ns;
  ServerState ns2;
algorithm
  ns := transition(ServerState.StateIdle);
  print(stateToString(ns));

  ns2 := transition(ns);
  print(stateToString(ns2));
end Main;

Running this Modelica model will produce the results of the state transitions.

To run the program, compile the Modelica model using your Modelica toolchain (like OpenModelica or Dymola) and execute it.

$ omc Main.mos
$ ./Main
connected
idle

Modelica provides a robust way to define and manage state transitions using enumeration, ensuring compile-time type safety.