:::info Sample code
Browse the Lua plugin examples on GitHub — [nodejs/plugin](https://github.com/obniz/obniz/tree/master/examples/nodejs/plugin).
:::

By default, obnizOS attempts to connect to a saved network immediately after startup and maintains a persistent connection.

With the Lua plugin, you can monitor the connection status and programmatically allow or stop connections. This enables advanced behaviors, such as remaining offline until specific data is acquired.

## on_event

By defining the `on_event()` function, you can receive callbacks for each step of the connection process.

| Event | Description |
| --- | --- |
| `power_on` | Called only once when the device powers on. |
| `setting_mode` | Indicates the device has entered setting mode (e.g., due to connection failure). |
| `connecting_to_network` | Attempting to connect to the network via Wi-Fi, LTE, etc. |
| `connecting_to_cloud` | Attempting to connect to obnizCloud after a successful network connection. |
| `online` | Connection to obnizCloud is established. |

If the connection is lost after going `online`, the rollback point in the sequence depends on whether the disconnection occurred at the TCP layer or the physical layer (Wi-Fi/LTE).

```lua
function on_event(event)
  if event == "power_on" then
    os.log(" - Lua PowerOn");
    -- Prevent hardware reset on disconnection
    os.resetOnDisconnect(false);
    os.log(" - No Reset On Disconnect");
  elseif event == "setting_mode" then
    -- Handle setting mode
  elseif event == "connecting_to_network" then
    -- Handle network connection start
  elseif event == "connecting_to_cloud" then
    -- Handle cloud connection start
  elseif event == "online" then
    os.log(" - Lua Online");
  end
end

```

### Understanding `power_on` vs. Global Scope

The behavior of the `power_on` event is similar to code written in the global scope, but there is a key difference:

| Location | Behavior |
| --- | --- |
| **power_on event** | Executed only once at boot. It will **not** be re-executed even if you replace the Lua script and call `obniz.plugin.reloadLua()`. |
| **Global Scope** | Executed whenever the Lua script starts. It runs at boot and is **re-executed** every time `obniz.plugin.reloadLua()` is called. |

**Best Practice:** Use `power_on` for initialization that must truly happen only once. Use the **global scope** for processes you want to re-run whenever the script is reloaded.

---

## cloud.connect() / disconnect()

While obnizOS manages the cloud connection automatically, you can override this via the plugin. The following example turns off the cloud connection at startup.

```lua
function on_event(event)
  if event == "power_on" then
    os.log(" - Lua PowerOn");
    os.resetOnDisconnect(false);
    cloud.disconnect(); -- Disconnect at startup
  elseif event == "online" then
    os.log(" - Lua Online");
  end
end

local lastTick = os.getTick();
local connecting = false;
local offlineTick = 0;

function on_offline_loop()
  -- Log message every 1 second
  if os.getTick() - lastTick > 1000 then
    lastTick = os.getTick();
    os.log("offline loop");
    wdt.feed(); -- Prevent Watchdog reset
  end

  -- Try to connect after 10 seconds of being offline
  if os.getTick() - offlineTick > 10 * 1000 and not connecting then
    os.log("connect to cloud");
    cloud.connect();
    connecting = true;
  end
end

-- Function triggered by a command (example)
function on_command(command)
  os.log("disconnect from cloud");
  cloud.disconnect();
  connecting = false;
  offlineTick = os.getTick();
end

```

### Disconnection Behavior

You can stop or cancel a connection by calling `cloud.disconnect()`. However, the behavior depends on the current state:

| Timing | Behavior |
| --- | --- |
| Before `connecting_to_network` | The connection attempt will not start. |
| Between `connecting_to_network` and `online` | The connection cannot be stopped immediately; it will be canceled after it briefly reaches the `online` state. |
| After reaching `online` | The device performs a disconnection process and goes offline. |

> [!TIP]
> **os.resetOnDisconnect(false)**
> By default (`true`), obnizOS resets peripherals like UART and SPI when the internet connection is lost. Setting this to `false` prevents unexpected hardware resets when managing connections or IO manually via Lua.

---

## Using Watchdog Timer (WDT) in Offline Mode

obnizOS includes a "keep-alive" monitoring feature. It considers a constant internet connection and data exchange as the "healthy" state. If the device remains disconnected for a certain period, it will automatically reboot.

When intentionally staying offline via a plugin, this can cause unwanted reboots. To prevent this, you must periodically call `wdt.feed()`.

```lua
function on_offline_loop()
  if os.getTick() - lastTick > 1000 then
    lastTick = os.getTick();
    os.log("offline loop");
    wdt.feed(); -- Feed the watchdog to prevent reboot
  end
end

```

### ⚠️ Important Caution

**Use `cloud.disconnect()` and `wdt.feed()` with extreme care.** Depending on your Lua logic, you may cause the device to remain offline indefinitely, making it impossible to update the script via the cloud.

We **strongly recommend** implementing the following safeguards:

* Ensure the device connects to the internet at least once after booting.
* Implement logic to force an internet connection after a specific duration.
* Stop calling `wdt.feed()` after a certain period to allow a failsafe reboot.

See [Watchdog](./wdt) for the timeouts and the details of `wdt.feed()`.
