# Network Configuration

> **Overview**: Network configuration provides WiFi AP/STA, static IP, and a custom local domain. W5500 Ethernet and EC801E-CN cellular require build support and an enabled runtime feature. Settings are stored in `/config/network.json`; first boot falls back to AP provisioning.

This document describes the FastBee-Arduino network page, the live LittleFS file `/config/network.json`, and the supported network modes. The repository file `data/config/network.json` is only the factory template used to build a filesystem image.

Current network management uses `networkType` to determine the physical network channel:

| networkType | Network Mode | Typical Hardware | Use Case | Description |
| --- | --- | --- | --- | --- |
| `0` | WiFi | ESP32 built-in WiFi | Default recommended, regular LAN, first-time setup | Supports STA or AP mode |
| `1` | Ethernet | W5500 SPI to Ethernet module | Fixed installation, weak WiFi, low-latency LAN | Requires Ethernet compile switch |
| `2` | 4G Cellular | EC801E-CN module | Field deployment without wired/wireless LAN | Access carrier network via UART and APN |

> Note: W5500 and 4G require both compile support and active runtime features. C3/C6 release environments exclude them; other devices should still keep them disabled unless the hardware, pins and power are present.

## Interface Preview

Network configuration page is divided into basic, hotspot and advanced configuration. Before field modifications, confirm current IP and connection status; after modifying STA/AP, static IP or network mode, usually need to wait for network reconnection.

![Network Basic Configuration](https://www.fastbee.cn/doc/assets/network-settings.De0DweTs.png)

![Hotspot Configuration](https://www.fastbee.cn/doc/assets/network-ap-settings.BLYBXIBO.png)

![Network Advanced Configuration](https://www.fastbee.cn/doc/assets/network-advanced-settings.oN5VUouy.png)

Network configuration is recommended to follow the diagram below: first confirm device boot and saved configuration, then observe STA networking, AP fallback, IP acquisition and protocol online status.

```mermaid
%%{init: {"flowchart": {"htmlLabels": false}}}%%
flowchart TD
  A["Device Boot"] --> B["Load network.json\nInitialize networking"]
  B --> C["Attempt STA Networking\nConnect SSID\nWait for DHCP or static IP"]
  C --> D["Networking Successful\nDashboard shows IP\nWeb/API accessible"]
  D --> E["Protocol Online\nMQTT connects to platform\nPeripherals start working"]
  C --> F["Networking Failed or IP Unreachable\nEnable device AP\nKeep local config access"]
  F --> G["Check SSID / password / gateway / DNS / static IP"]
  G --> C
```

## Configuration Entry

Web interface path: `Network Settings`

The live device configuration is saved to:

```text
/config/network.json
```

Common APIs:

| API | Purpose |
| --- | --- |
| `GET /api/network/config` | Read network configuration |
| `PUT /api/network/config` | Save network configuration |
| `GET /api/network/status` | Read current network status |
| `GET /api/wifi/scan` | Scan nearby WiFi |

After saving configuration, if network mode, WiFi mode, SSID or IP type was changed, the system marks restart needed. Frontend will prompt to wait for device reconnection.

## Mobile AP Provisioning API

In AP mode the device exposes dedicated provisioning endpoints for mobile apps to complete WiFi setup and push device parameters. All provisioning endpoints are **public** (no login required) and can be called directly after joining the device hotspot.

### Provisioning Endpoints

| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/wifi/scan` | Scan nearby WiFi networks |
| `POST` | `/api/wifi/connect` | Connect to WiFi and push device parameters |
| `GET` | `/api/wifi/status` | Detect current device state (device info + network status) |
| `POST` | `/api/wifi/config` | Provisioning endpoint: save WiFi and device parameters, switch to STA |

### GET /api/wifi/scan

Scans nearby WiFi networks and returns the available list.

**Request parameters**: none

**Response example**:

```json
{
  "success": true,
  "networks": [
    { "ssid": "OfficeWiFi", "rssi": -45, "channel": 6, "encrypted": true },
    { "ssid": "GuestOpen", "rssi": -80, "channel": 1, "encrypted": false }
  ],
  "count": 2
}
```

**Response fields**:

| Field | Type | Description |
| --- | --- | --- |
| `success` | bool | Whether the request succeeded |
| `networks` | array | WiFi network list |
| `networks[].ssid` | string | Network name |
| `networks[].rssi` | int | Signal strength (dBm) |
| `networks[].channel` | int | WiFi channel |
| `networks[].encrypted` | bool | Whether encrypted |
| `count` | int | Number of networks |

### GET /api/wifi/status

Detects current device state, returning basic device info and network connection status. Suitable for the mobile side to probe device info and current network mode before provisioning.

**Request parameters**: none

**Response example**:

```json
{
  "success": true,
  "data": {
    "deviceName": "fastbee",
    "deviceId": "",
    "userId": "1",
    "firmwareVersion": "1.0.0",
    "networkMode": "ap",
    "connected": false,
    "ipAddress": "192.168.4.1",
    "apSSID": "fastbee-ap",
    "apIP": "192.168.4.1",
    "macAddress": "AA:BB:CC:DD:EE:FF",
    "chipModel": "ESP32-S3",
    "chipRevision": 0,
    "freeHeap": 180000
  }
}
```

**Response fields**:

| Field | Type | Description |
| --- | --- | --- |
| `deviceName` | string | Device name (from `device.json`) |
| `deviceId` | string | Device ID (from `device.json`) |
| `userId` | string | User ID (from `device.json`) |
| `firmwareVersion` | string | Firmware version |
| `networkMode` | string | Current network mode: `ap` / `sta` / `apsta` |
| `connected` | bool | Whether WiFi is connected (STA mode) |
| `ipAddress` | string | Current IP (local IP when STA connected, hotspot IP in AP mode) |
| `ssid` | string | Connected WiFi name (only when STA connected) |
| `rssi` | int | WiFi signal strength (only when STA connected) |
| `apSSID` | string | Device hotspot name |
| `apIP` | string | Device hotspot IP |
| `macAddress` | string | Device MAC address |
| `chipModel` | string | Chip model (e.g. `ESP32-S3`) |
| `chipRevision` | int | Chip revision |
| `freeHeap` | int | Free heap memory (bytes) |

### POST /api/wifi/config

Provisioning endpoint: saves WiFi configuration and device parameters. After successful provisioning the device automatically switches to STA mode to connect.

Difference from `/api/wifi/connect`: `/api/wifi/config` is a **pure configuration push** endpoint — WiFi info is written to `network.json`, device info to `device.json`, then the device restarts its network into STA mode; `/api/wifi/connect` is similar but with slightly different parameters.

**Request parameters**:

| Parameter | Required | Description |
| --- | --- | --- |
| `SSID` or `ssid` | Yes | WiFi name (case-insensitive alias) |
| `password` or `pwd` | Yes | WiFi password (alias supported) |
| `userId` | Yes | User ID, saved to `device.json` |
| `deviceNum` | No | Device number, saved to the `deviceId` field of `device.json` |
| `extra` | No | Product number, saved to the `productNumber` field of `device.json` |

**Success response**:

```json
{
  "success": true,
  "message": "设备已更新WiFi配置，正在连接...",
  "data": {
    "ssid": "your-wifi",
    "mode": 0
  }
}
```

**Missing parameters response** (HTTP 400):

```json
{
  "success": false,
  "message": "配网必须传递 SSID、WiFi密码和用户编号(userId)"
}
```

### POST /api/wifi/connect

Connects to the given WiFi network and can push device parameters at the same time. After successful provisioning the device automatically switches to STA mode.

**Request parameters**:

| Parameter | Required | Description |
| --- | --- | --- |
| `ssid` | Yes | WiFi name |
| `password` | Yes | WiFi password |
| `userId` | No | User ID, saved to the `userId` field of `device.json` |
| `deviceNum` | No | Device number, saved to the `deviceId` field of `device.json` |
| `extra` | No | Product number, saved to the `productNumber` field of `device.json` only when it is a valid positive integer |

**Response example**:

```json
{
  "success": true,
  "message": "WiFi configuration saved. Device will restart in STA mode."
}
```

### Provisioning Flow

1. Phone joins the device AP hotspot (default `fastbee-ap`, password `admin123`)
2. Call `GET http://192.168.4.1/api/wifi/status` to fetch device info and current network state
3. Call `GET http://192.168.4.1/api/wifi/scan` to fetch the WiFi list
4. User picks the target WiFi on the phone and enters the password
5. Call `POST http://192.168.4.1/api/wifi/config` to submit the configuration (must include SSID, password, userId)
6. Device saves configuration (WiFi → `network.json`, device parameters → `device.json`) and automatically switches to STA mode to join the target WiFi

## First-Time Setup and AP Fallback

When device boots for the first time or STA cannot connect, it enters AP hotspot mode for continued Web management interface access.

Default AP parameters:

| Field | Description | Default |
| --- | --- | --- |
| `apSSID` | Hotspot name | `fastbee-ap` |
| `apPassword` | Hotspot password | `admin123` |
| `apChannel` | WiFi channel | `1` |
| `apHidden` | Hide SSID | `false` |
| `apMaxConnections` | Max clients | `4` |
| AP IP | Management address | `192.168.4.1` |

If `apSSID` is empty, code uses `deviceName + "_" + ChipID first 6 chars` to generate hotspot name.

## WiFi Networking

WiFi is the default network mode, `networkType = 0`.

### WiFi Mode

| mode | Mode | Behavior |
| --- | --- | --- |
| `0` | STA | Connect to external router or hotspot, normal LAN/internet access |
| `1` | AP | Device self-hotspot, only for local access and setup |

Current frontend configuration only provides STA and AP modes. When STA fails, network manager falls back to AP mode, ensuring Web management access remains available.

### STA Configuration

| Field | Description | Example |
| --- | --- | --- |
| `staSSID` | Main WiFi name | `office-wifi` |
| `staPassword` | Main WiFi password | `password` |
| `networks` | Multi-SSID list | See example below |
| `connectTimeout` | First connection timeout, ms | `10000` or `20000` |
| `reconnectInterval` | Auto reconnect interval, ms | `5000` |
| `maxReconnectAttempts` | Max reconnect attempts | `5` |

Multi-SSID configuration example:

```json
{
  "networks": [
    { "ssid": "factory-main", "password": "pass1", "priority": 0 },
    { "ssid": "factory-backup", "password": "pass2", "priority": 1 }
  ]
}
```

At runtime, if `networks` is configured, the system scans nearby WiFi and selects the best network from configured SSIDs; if no configured items found, falls back to `staSSID` / `staPassword`.

### AP Configuration

| Field | Description | Recommendation |
| --- | --- | --- |
| `apSSID` | Device hotspot name | Include device ID for field deployment |
| `apPassword` | Hotspot password | WPA/WPA2 at least 8 chars; empty may form open hotspot |
| `apChannel` | Hotspot channel | Common: `1`, `6`, `11` |
| `apHidden` | Hide hotspot name | Generally not recommended, for easier maintenance |
| `apMaxConnections` | Max connections | Field maintenance usually 1-4 |

AP mode has no internet connection, mainly used for configuration, maintenance, reading device local pages.

## IP, DNS, and Local Domain

### DHCP and Static IP

| ipConfigType | Mode | Description |
| --- | --- | --- |
| `0` | DHCP | Router auto-assigns IP, default recommended |
| `1` | Static IP | Manually specify IP, gateway, subnet and DNS |

Static IP fields:

| Field | Description | Example |
| --- | --- | --- |
| `staticIP` | Device fixed IP | `192.168.1.50` |
| `gateway` | Default gateway | `192.168.1.1` |
| `subnet` | Subnet mask | `255.255.255.0` |
| `dns1` | Primary DNS | `8.8.8.8` |
| `dns2` | Backup DNS | `8.8.4.4` |

DNS can also be explicitly set in DHCP mode. Code uses `WiFi.config(0,0,0,0,dns1,dns2)` to enable DHCP and set DNS.

### Custom Local Domain

Advanced settings only require `customDomain`, for example `fastbee`. After saving, try:

```text
http://fastbee.local
```

The `.local` address works only on the same LAN and depends on client and router support. Use the device STA IP when it is unavailable. The page intentionally has no separate service switch, status panel, or redirect control. For the mDNS mechanism, multi-device domain assignment, and access methods for each network mode, see [mDNS Network](https://www.fastbee.cn/doc/en/device/v2/system/mdns-networking.md).

### IP Conflict and Failover

Configuration structure includes IP conflict detection and failover fields:

| Field | Description |
| --- | --- |
| `conflictDetection` | Conflict detection method, enum defined by `IPConflictMode` |
| `failoverStrategy` | Backup IP selection strategy |
| `autoFailover` | Auto switch after conflict detected |
| `conflictCheckInterval` | Conflict detection interval, ms |
| `maxFailoverAttempts` | Max failover attempts |
| `conflictThreshold` | Conflict threshold |
| `fallbackToDHCP` | Fallback to DHCP if backup IP fails |
| `backupIPs` | Backup static IP list |

For field fixed IP deployment, recommended to first do DHCP reservation on router, then use device static IP to reduce conflict probability.

## Ethernet W5500

Ethernet uses W5500 SPI to Ethernet module, `networkType = 1`.

Suitable for:

* Sites with poor WiFi signal or strong electromagnetic interference.
* Gateways, control cabinets, fixed installation devices.
* MQTT/Modbus gateways requiring stable LAN connection.

Default pins:

| Field | Description | Default |
| --- | --- | --- |
| `ethernet.spiMosi` | SPI MOSI | `11` |
| `ethernet.spiMiso` | SPI MISO | `13` |
| `ethernet.spiSck` | SPI SCK | `12` |
| `ethernet.csPin` | W5500 CS | `47` |
| `ethernet.rstPin` | W5500 RST | `48` |
| `ethernet.intPin` | W5500 INT | `14` |

Configuration steps:

1. Connect W5500 module to ESP32 SPI pins.
2. Connect RJ45 cable to router or switch.
3. Select `Ethernet (W5500)` in Web interface.
4. Modify SPI and control pins according to actual hardware.
5. Save configuration, wait for network restart.

Notes:

* W5500 needs stable 3.3V power, some modules have high peak current.
* `CS`, `RST`, `INT` should not conflict with enabled peripherals.
* Static IP configuration still uses common IP fields.
* If current build doesn't enable `FASTBEE_ENABLE_ETHERNET`, selecting this mode won't actually initialize adapter.

## 4G Cellular EC801E-CN

4G cellular uses EC801E-CN module, `networkType = 2`.

Suitable for:

* Sites without wired network or WiFi.
* Outdoor, mobile, temporary deployment.
* Reporting to cloud platform via MQTT.

### Hybrid Mode Architecture

4G mode uses **hybrid architecture**: 4G module handles internet access, while ESP32 built-in WiFi works in pure AP mode for local Web management access.

| Function | Channel | Description |
| --- | --- | --- |
| Internet access | 4G Cellular | Device accesses MQTT/MQTTS cloud services via the carrier network; HTTP is reserved for system functions such as NTP and OTA |
| Local Web management | WiFi AP | Device as hotspot, user connects to access management interface |

> **Access method**: In 4G mode, first connect phone/computer to device hotspot (default `fastbee-ap`), then access Web management interface via `http://192.168.4.1`.
>
> Device simultaneously provides MQTT reporting and other cloud functions via 4G network, both are independent.

Default pins and parameters:

| Field | Description | Default |
| --- | --- | --- |
| `cellular.txPin` | ESP32 TX, to module RX | `39` |
| `cellular.rxPin` | ESP32 RX, to module TX | `40` |
| `cellular.pwrPin` | Module power/enable control | `38` |
| `cellular.baudRate` | UART baud rate | `115200` |
| `cellular.apn` | Carrier APN | `CMNET` |

Common APNs:

| Carrier | Common APN |
| --- | --- |
| China Mobile | `CMNET`, `CMIOT` |
| China Unicom | `3GNET`, `WONET` |
| China Telecom | `CTNET` |

Configuration steps:

1. Insert SIM card with activated data service.
2. Confirm 4G antenna connection is reliable.
3. Cross-connect UART: ESP32 TX to module RX, ESP32 RX to module TX.
4. Connect or configure `pwrPin`, ensure module can power on.
5. Select `4G Cellular (EC801E)` in Web interface.
6. Enter APN, save configuration, wait for network initialization.

Notes:

* 4G module has high instantaneous current on power-on, insufficient power causes repeated restarts, no AT response or registration failure.
* APN error causes module to recognize SIM but unable to establish data connection.
* External high-gain antenna recommended for weak signal environments.
* Public network inbound access is usually unavailable in 4G mode; cloud data communication should use an outbound MQTT/MQTTS connection.
* In 4G mode WiFi only works in AP mode (no STA connection), so local management must connect to device hotspot.
* In 4G mode, use AP IP `192.168.4.1` for local management; the network page does not show local-domain settings.

## Network Mode Selection Recommendations

| Scenario | Recommended Mode | Reason |
| --- | --- | --- |
| Regular home/office testing | WiFi STA | Simple configuration, easy debugging |
| First-time setup or forgot network params | WiFi AP | Doesn't depend on external network |
| Industrial control cabinet, fixed gateway | W5500 Ethernet | Stable, low latency, interference resistant |
| Outdoor or no LAN sites | 4G Cellular | Doesn't depend on site network |

## Configuration File Example

```json
{
  "mode": 0,
  "networkType": 0,
  "deviceName": "FastBee-Device",
  "apSSID": "fastbee-ap",
  "apPassword": "admin123",
  "apChannel": 1,
  "apHidden": false,
  "apMaxConnections": 4,
  "staSSID": "factory-main",
  "staPassword": "wifi-password",
  "networks": [
    { "ssid": "factory-main", "password": "wifi-password", "priority": 0 },
    { "ssid": "factory-backup", "password": "backup-password", "priority": 1 }
  ],
  "ipConfigType": 0,
  "staticIP": "",
  "gateway": "",
  "subnet": "",
  "dns1": "8.8.8.8",
  "dns2": "8.8.4.4",
  "connectTimeout": 20000,
  "reconnectInterval": 5000,
  "maxReconnectAttempts": 5,
  "customDomain": "fastbee",
  "conflictDetection": 2,
  "failoverStrategy": 2,
  "autoFailover": true,
  "conflictCheckInterval": 30000,
  "maxFailoverAttempts": 3,
  "conflictThreshold": 2,
  "fallbackToDHCP": true,
  "ethernet": {
    "spiMosi": 11,
    "spiMiso": 13,
    "spiSck": 12,
    "csPin": 47,
    "rstPin": 48,
    "intPin": 14
  },
  "cellular": {
    "txPin": 39,
    "rxPin": 40,
    "pwrPin": 38,
    "baudRate": 115200,
    "apn": "CMNET"
  }
}
```

## Build Switches

Multiple network modes controlled by feature switches:

| Macro | Purpose |
| --- | --- |
| `FASTBEE_ENABLE_ETHERNET` | Compile W5500 Ethernet adapter |
| `FASTBEE_ENABLE_CELLULAR` | Compile 4G cellular adapter |

If a macro is `0`, corresponding adapter code won't be compiled into firmware. Fields preserved in Web configuration file don't mean current firmware supports that network mode.

## Troubleshooting Quick Reference

| Issue | Common Causes | Recommendations |
| --- | --- | --- |
| WiFi connection failed | SSID/password error, weak signal, router rejection | Rescan and select network, move closer to router, check 2.4GHz support |
| Cannot access device after STA save | IP changed or network switching | Wait 10-20s, then use the router-assigned IP or configured `.local` address |
| AP hotspot not found | `apHidden=true`, incompatible channel, AP start failed | Disable hidden SSID, use channel 1/6/11, restart device |
| Static IP inaccessible | IP/gateway/subnet mismatch or conflict | Revert to DHCP, or verify network segment and occupancy on router |
| `.local` address unavailable | Client unsupported, cross-segment, router isolation | Use the device IP; domain availability does not affect STA or MQTT |
| W5500 no connection | SPI pin error, cable/switch issue, insufficient power | Check MOSI/MISO/SCK/CS/RST/INT, confirm link light and 3.3V |
| W5500 has link but no IP | DHCP unavailable or static IP misconfigured | Check router DHCP, or enter correct static IP |
| 4G module no response | TX/RX reversed, insufficient power, PWR control issue | Cross-check serial, use independent regulated power, confirm module power-on sequence |
| 4G registration failed | SIM not activated, APN error, weak signal | Test SIM data service, confirm APN, check antenna and signal |

## Maintenance Recommendations

* During debugging phase, prioritize WiFi STA or AP, confirm protocol and peripheral logic before switching to 4G.
* For field fixed deployment, prioritize DHCP reserved address, then consider device static IP.
* After switching `networkType`, recommend restarting device and observing serial log, confirm actual adapter initialized.
* In production environment, change default AP password to avoid open maintenance entry.
