# Omada API Setup Guide

**Last Updated:** 2025-01-20  
**Document Version:** 1.0

---

## Overview

This guide covers setting up API integration for TP-Link Omada devices (ER605 router, SG218R switch, and Omada Controller) using the Omada API library and MCP server.

## Prerequisites

- Omada Controller running and accessible (typically on port 8043)
- Admin access to Omada Controller web interface
- Node.js 18+ and pnpm installed

## Step 1: Enable Open API on Omada Controller

1. **Access Omada Controller Web Interface**
   - Navigate to: `https://<omada-controller-ip>:8043`
   - Log in with administrator credentials

2. **Enable Open API**
   - Navigate to: **Settings** → **Platform Integration** → **Open API**
   - Click **Add New App**

3. **Configure API Application**
   - **App Name**: Enter a descriptive name (e.g., "MCP Integration")
   - **Access Mode**: Select **Client Credentials** (for system-to-system integration)
   - Click **Apply** to create the application

4. **Save Credentials**
   - **Client ID** (API Key): Copy and save securely
   - **Client Secret**: Copy and save securely (shown only once)
   - **Note**: Store these credentials securely - the secret cannot be retrieved later

## Step 2: Install Packages

From the project root:

```bash
pnpm install
pnpm omada:build
```

This will:
- Install dependencies for `omada-api` and `mcp-omada`
- Build TypeScript to JavaScript

## Step 3: Configure Environment Variables

Create or update `~/.env` with Omada Controller credentials:

```bash
# Omada Controller Configuration
OMADA_CONTROLLER_URL=https://192.168.11.8:8043
OMADA_API_KEY=your-client-id-here
OMADA_API_SECRET=your-client-secret-here
OMADA_SITE_ID=your-site-id  # Optional - will use default site if not provided
OMADA_VERIFY_SSL=false  # Set to true for production with valid SSL certs
```

**Note:** For automation and scripts, use the `proxmox-controller` API application (Client Credentials mode):
- Client ID: `94327608913c41bb9c32ce8d1d6e87d3`
- Client Secret: `600b924a541a4139a386cb7c63ac47b5`

For interactive access, use the `Datacenter-Control-Complete` API application (Authorization Code mode):
- Client ID: `8437ff7e3e39452294234ce23bbd105f`
- Client Secret: `f2d19e1bdcdd49adabe10f489ce09a79`

See the [Physical Hardware Inventory](../../config/physical-hardware-inventory.md) for complete API credential details.

### Finding Your Site ID

If you don't know your site ID:

1. Use the API to list sites:
   ```typescript
   import { OmadaClient } from 'omada-api';
   
   const client = new OmadaClient({
     baseUrl: process.env.OMADA_CONTROLLER_URL!,
     clientId: process.env.OMADA_API_KEY!,
     clientSecret: process.env.OMADA_API_SECRET!,
   });
   
   const sites = await client.request('GET', '/sites');
   console.log(sites);
   ```

2. Or use the MCP tool `omada_list_sites` once configured

## Step 4: Verify Installation

### Test the Core Library

Create a test file `test-omada.js`:

```javascript
import { OmadaClient } from './omada-api/dist/index.js';

const client = new OmadaClient({
  baseUrl: process.env.OMADA_CONTROLLER_URL,
  clientId: process.env.OMADA_API_KEY,
  clientSecret: process.env.OMADA_API_SECRET,
});

async function test() {
  try {
    const sites = await client.request('GET', '/sites');
    console.log('Sites:', sites);
    
    const devices = await client.request('GET', `/sites/${sites[0].id}/devices`);
    console.log('Devices:', devices);
  } catch (error) {
    console.error('Error:', error);
  }
}

test();
```

Run:
```bash
node test-omada.js
```

### Test the MCP Server

```bash
pnpm omada:start
```

The server should start without errors.

## Step 5: Configure Claude Desktop (Optional)

To use the MCP server with Claude Desktop:

1. **Locate Claude Desktop Config File**
   - **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
   - **Linux**: `~/.config/Claude/claude_desktop_config.json`

2. **Add MCP Server Configuration**

```json
{
  "mcpServers": {
    "omada": {
      "command": "node",
      "args": ["/home/intlc/projects/proxmox/mcp-omada/dist/index.js"]
    }
  }
}
```

3. **Restart Claude Desktop**

After restarting, you can use tools like:
- "List all routers in my Omada network"
- "Show me the VLAN configurations"
- "Get statistics for device XYZ"

## Usage Examples

### Using the Core Library

```typescript
import {
  OmadaClient,
  DevicesService,
  NetworksService,
  RouterService,
  SwitchService,
} from 'omada-api';

// Initialize client
const client = new OmadaClient({
  baseUrl: 'https://192.168.11.8:8043',
  clientId: process.env.OMADA_API_KEY!,
  clientSecret: process.env.OMADA_API_SECRET!,
  siteId: 'your-site-id',
  verifySSL: false,
});

// Device management
const devicesService = new DevicesService(client);
const routers = await devicesService.getRouters();
const switches = await devicesService.getSwitches();

// Network configuration
const networksService = new NetworksService(client);
const vlans = await networksService.listVLANs();

// Router operations (ER605)
const routerService = new RouterService(client);
const wanPorts = await routerService.getWANPorts('router-device-id');

// Switch operations (SG218R)
const switchService = new SwitchService(client);
const ports = await switchService.getSwitchPorts('switch-device-id');
```

### Common Operations

#### List All Devices

```typescript
const devices = await devicesService.listDevices();
console.log('All devices:', devices);
```

#### Get ER605 Router WAN Configuration

```typescript
const routers = await devicesService.getRouters();
const er605 = routers.find(r => r.model.includes('ER605'));
if (er605) {
  const wanPorts = await routerService.getWANPorts(er605.id);
  console.log('WAN ports:', wanPorts);
}
```

#### Get SG218R Switch Ports

```typescript
const switches = await devicesService.getSwitches();
const sg218r = switches.find(s => s.model.includes('SG218R'));
if (sg218r) {
  const ports = await switchService.getSwitchPorts(sg218r.id);
  console.log('Switch ports:', ports);
}
```

#### List VLANs

```typescript
const vlans = await networksService.listVLANs();
console.log('VLANs:', vlans);
```

#### Reboot a Device

```typescript
await devicesService.rebootDevice('device-id');
```

## Troubleshooting

### Authentication Errors

**Problem**: `OmadaAuthenticationError: Authentication failed`

**Solutions**:
- Verify `OMADA_API_KEY` and `OMADA_API_SECRET` are correct
- Check that the API app is enabled in Omada Controller
- Ensure credentials are not wrapped in quotes in `.env` file
- Verify the Omada Controller URL is correct (include `https://` and port `:8043`)

### Connection Errors

**Problem**: `OmadaNetworkError: Failed to connect`

**Solutions**:
- Verify `OMADA_CONTROLLER_URL` is accessible from your machine
- Check firewall rules allow access to port 8043
- If using self-signed certificates, ensure `OMADA_VERIFY_SSL=false`
- Test connectivity: `curl -k https://<controller-ip>:8043`

### Device Not Found

**Problem**: `OmadaDeviceNotFoundError`

**Solutions**:
- Verify the `deviceId` is correct
- Check that the device is adopted in Omada Controller
- Ensure the device is online
- Verify `siteId` matches the device's site

### SSL Certificate Errors

**Problem**: SSL/TLS connection errors

**Solutions**:
- For development/testing: Set `OMADA_VERIFY_SSL=false` in `.env`
- For production: Install valid SSL certificate on Omada Controller
- Or: Set `verifySSL: false` in client configuration (development only)

## API Reference

See the library documentation:
- **Core Library**: `omada-api/README.md`
- **MCP Server**: `mcp-omada/README.md`
- **Type Definitions**: See `omada-api/src/types/` for complete TypeScript types

## Security Best Practices

1. **Never commit credentials** - Use `.env` file (already in `.gitignore`)
2. **Restrict API permissions** - Only grant necessary permissions in Omada Controller
3. **Use SSL in production** - Set `OMADA_VERIFY_SSL=true` for production environments
4. **Rotate credentials regularly** - Update API keys periodically
5. **Monitor API usage** - Review API access logs in Omada Controller

## Related Documentation

- **[ER605_ROUTER_CONFIGURATION.md](ER605_ROUTER_CONFIGURATION.md)** - Router configuration guide
- **[NETWORK_ARCHITECTURE.md](../02-architecture/NETWORK_ARCHITECTURE.md)** - Network architecture overview
- **[MCP_SETUP.md](MCP_SETUP.md)** - General MCP server setup

---

**Document Status:** Complete (v1.0)  
**Maintained By:** Infrastructure Team  
**Review Cycle:** Quarterly  
**Last Updated:** 2025-01-20

