Structure
The sandbox uses a state machine pattern. A state machine is a convenient way to structure a program and a way to structure the complexity of larger applications. State machines clearly define boundaries of what is possible under which conditions and can alleviate edge case bugs and help reduce complexity in general. State machines consist of states and events, where the events can be actions or transitions. Transitions bring the state machine between states, whilst actions are just some actions done within the current state. To illustrate this, the following diagram represents how the sandbox is structured:
Firstly a network connection event has to be registered and then the state machine can be transitioned to the Connected to network state, which starts connecting to the MQTT broker. When the broker connection event is received, a transition is made to the Connected to broker state. When the "Start sensor data streaming" button on the webpage is then clicked, the start publish data event is triggered and a transition is made to the Streaming data state. In the Streaming data state the state machine will stream the data which appears on the website.
Do notice that there are some events which point back to the state they are coming from. These events are not transitions, but simply events that are handled in the state. For example, if a send heartbeat event is issued in the Connected to broker state a heartbeat is sent to the MQTT broker, but no transition to another state is needed. The heartbeat event sends a message to the MQTT broker such that the MQTT broker knows that the device is operating normally.
With the structure outlined, let's dive into the code.