
# Safe Mode (OS7 or later)

If the CPU detects a reboot caused by a system error or internal issue, it will automatically start in **Safe Mode**. In this mode, the device disables certain functions to prioritize and establish a stable connection with the cloud.

## Reasons for Entering Safe Mode

The device automatically enters Safe Mode when the following issues occur:

- **CPU Operational Issues:** A system crash (e.g., a "Panic") or other critical errors occurred.
- **Insufficient Memory:** The system was forced to reboot due to a memory shortage (Out of Memory).
- **Watchdog:** The hardware watchdog or the task monitor reset the device. See [Error Detection and Watchdogs](./connectivity#error-detection-and-watchdogs).

In these cases, the CPU restarts automatically and boots into Safe Mode to prevent continuous failure.

The following restarts are normal restarts and do not enter Safe Mode:

- A restart by the communication monitor (`Hang Detect. Rebooting...`)
- A restart with `obniz.reboot()` or `os.reboot()`
- Turning the power off and on

## Safe Mode Behavior

In Safe Mode, the system's primary goal is to **connect to the cloud server as reliably as possible.** To achieve this, the device disables features that are likely causes of instability. Specifically, the following function is disabled:

- **Lua Plugin:** Automatically disabled during startup. The log shows `Safe mode. Plugin not loaded.`

Safe Mode does not end on its own. It continues until the next restart, even while the device stays connected to the cloud for a long time. While in Safe Mode, the Lua plugin does not run, so features that the plugin provides, such as BLE handling, do not work either.

## Detecting Safe Mode

From obniz.js, check whether the plugin is running when the device connects.

When the plugin defines the `plugin_name()` function, obnizOS sends its return value on connection, and obniz.js stores it in `obniz.plugin_name`. In Safe Mode, the plugin is not loaded, so `obniz.plugin_name` is not set. See [Plugin](/reference/common/plugin/) for `plugin_name()`.

The reason for the last restart is available in `obniz.boot_reason`.

## Returning to Normal Mode

Restart the device. A restart with `obniz.reboot()` is a normal restart, so the device starts in normal mode and loads the Lua plugin.

```javascript
obniz.onconnect = async () => {
  if (obniz.plugin_name !== "my_plugin") {
    // The plugin is not running: Safe Mode, or the plugin is not installed.
    console.log("plugin is not running. boot reason:", obniz.boot_reason);
    obniz.reboot();
  }
};
```

:::warning
If the plugin is not installed, or it fails to load because of a Lua error, the code above restarts the device on every connection. In that case, write the plugin again instead of restarting, or limit how many times you restart.
:::
