npm package: @heromatic/node-red-contrib-tcp-process-manager
Description: tcp-process-manager
Author: DHB
Latest version: 1.0.7

# TcpProcessManager Node

**Dual Mode TCP Connection Manager** - Manages TCP connections in both server and client modes with dynamic mode switching

## Installation

```bash
npm install @heromatic/node-red-contrib-tcp-process-manager
```

## Overview

The TcpProcessManager node is a powerful dual-mode TCP connection manager that can operate as either:
- **Server Mode**: Listen for incoming TCP connections from clients
- **Client Mode**: Connect to remote TCP servers

The node supports dynamic mode switching, allowing you to change between server and client modes without restarting Node-RED.

## Features

### Dual Mode Operation
- **Server Mode**: Bind to ports and accept incoming connections
- **Client Mode**: Connect to remote servers with automatic reconnection
- **Dynamic Switching**: Change modes via setup messages

### Connection Management
- Multiple simultaneous connections in both modes
- **Automatic reconnection for client mode** - Follows Node-RED's TCP node pattern
- Connection status monitoring and reporting
- Graceful cleanup and resource management
- **Handles server-initiated disconnections** (timeouts, inactivity) with automatic reconnection

### Data Processing
- Real-time data transmission and reception
- Broadcast to all connections or target specific ones
- Comprehensive error handling and recovery
- Detailed status reporting and metadata

## Usage

### Basic Setup

#### Server Mode Configuration
```json
{
  "topic": "setup",
  "payload": {
    "mode": "server",
    "connections": [
      {
        "connectionId": "server1",
        "host": "0.0.0.0",
        "port": 8080,
        "timeout": 30000,
        "maxConnections": 10,
        "keepAlive": true
      },
      {
        "connectionId": "server2",
        "host": "127.0.0.1",
        "port": 8081
    }
    ]
  }
}
```

#### Client Mode Configuration
```json
{
  "topic": "setup",
  "payload": {
    "mode": "client",
    "connections": [
      {
        "connectionId": "client1",
        "host": "192.168.1.100",
        "port": 8080,
        "timeout": 5000,
        "maxReconnections": 0, // 0 = infinite reconnection (default)
        "reconnectDelay": 3000, // 3 seconds (default)
        "keepAlive": true
      },
      {
        "connectionId": "client2",
        "host": "192.168.1.101",
        "port": 8081,
        "maxReconnections": 5 // Limited to 5 attempts
      }
    ]
  }
}
```

### Data Processing

#### Server Mode - Send to Clients
```json
{
  "topic": "process",
  "payload": {
    "data": "Hello connected clients!"
  }
}
```

#### Client Mode - Send to Servers
```json
{
  "topic": "process",
  "payload": {
    "data": "Hello remote server!",
    "targetConnection": "client1"  // Optional: send to specific connection
  }
}
```

### Close Connections
```json
{
  "topic": "close",
  "payload": {}
}
```

## Output Format

### Server Mode - Received Data
```json
{
  "connectionId": "server1",
  "host": "0.0.0.0",
  "port": 8080,
  "clientAddress": "192.168.1.100",
  "clientPort": 54321,
  "data": "Hello from client!",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "success": true
}
```

### Client Mode - Received Data
```json
{
  "connectionId": "client1",
  "host": "192.168.1.100",
  "port": 8080,
  "data": "Response from server!",
  "timestamp": "2024-01-15T10:30:00.000Z",
  "success": true
}
```

## Configuration Parameters

### Server Mode Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `connectionId` | string | Yes | - | Unique identifier for the server |
| `host` | string | No | "0.0.0.0" | Host to bind to |
| `port` | number | Yes | - | Port to listen on |
| `timeout` | number | No | 30000 | Client connection timeout (ms) |
| `maxConnections` | number | No | 10 | Maximum concurrent clients |
| `maxReconnections` | number | No | 3 | Maximum reconnection attempts |
| `reconnectDelay` | number | No | 1000 | Reconnection delay (ms) |
| `keepAlive` | boolean | No | true | Enable TCP keep-alive |

### Client Mode Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `connectionId` | string | Yes | - | Unique identifier for the client |
| `host` | string | Yes | - | Remote server hostname/IP |
| `port` | number | Yes | - | Remote server port |
| `timeout` | number | No | 5000 | Connection timeout (ms) |
| `maxReconnections` | number | No | 0 | Maximum reconnection attempts (0 = infinite) |
| `reconnectDelay` | number | No | 3000 | Reconnection delay (ms) |
| `keepAlive` | boolean | No | true | Enable TCP keep-alive |

## Node Status Colors

The node uses different colors to indicate its status:

- **🟢 Green**: Connected and working (all connections active)
- **🟡 Yellow**: Listening for connections (server mode) or connecting (client mode)
- **🟠 Orange**: Reconnecting (attempting to restore lost connections)
- **🔵 Blue**: Partial status (some connections working, others with issues)
- **🔴 Red**: Error or disconnected
- **⚫ Grey**: Stopped or not configured

## Node Outputs

The node has 3 outputs:

1. **Success Output** (Output 1): Successfully processed data and operations
2. **Error Output** (Output 2): Error messages and connection failures
3. **Status Output** (Output 3): Connection status, events, and metadata

## Status Messages

### Server Mode Events
- `server_started`: TCP server started and listening
- `client_connected`: New client connected to server
- `client_disconnected`: Client disconnected from server
- `data_received`: Data received from client
- `server_error`: Server error occurred
- `server_reconnecting`: Server attempting to reconnect
- `server_reconnected`: Server successfully reconnected

### Client Mode Events
- `client_connected`: Successfully connected to remote server
- `client_disconnected`: Disconnected from remote server
- `client_reconnecting`: Attempting to reconnect to server
- `client_reconnected`: Successfully reconnected to server
- `data_sent`: Data sent to remote server
- `data_received_from_server`: Data received from remote server
- `client_error`: Connection error occurred
- `client_reconnecting`: Attempting to reconnect to server
- `client_reconnected`: Successfully reconnected to server
- `reconnection_failed`: Failed to reconnect after max attempts

### General Events
- `setup_complete`: Node configuration completed
- `process_complete`: Data processing completed successfully
- `process_partial_error`: Some operations failed, others succeeded
- `close_complete`: All connections closed
- `mode_changed`: Successfully switched between server/client modes
- `status`: Current connection status and metadata

## Automatic Reconnection Behavior

The node follows Node-RED's TCP node pattern for automatic reconnection in client mode:

### Reconnection Triggers
- **Server disconnection**: When the remote server closes the connection
- **Network timeout**: When the connection times out
- **Connection errors**: When network errors occur
- **Server inactivity**: When the server closes due to inactivity

### Reconnection Logic
- **Immediate reconnection**: Attempts to reconnect automatically
- **Infinite reconnection by default**: Uses `maxReconnections: 0` (default: infinite attempts)
- **Configurable attempts**: Set `maxReconnections` to a number > 0 to limit attempts
- **Configurable delay**: Uses `reconnectDelay` parameter (default: 3000ms)
- **Status tracking**: Maintains connection status and attempt count
- **Graceful degradation**: Stops attempting after max attempts reached (if configured)
- **Connection cleanup**: Properly destroys old connections before creating new ones
- **Memory management**: Prevents connection leaks and multiple simultaneous connections

### Status States
- `connected`: Successfully connected to server
- `connecting`: Attempting initial connection
- `reconnecting`: Attempting to reconnect after disconnection
- `disconnected`: Connection lost, attempting reconnection
- `error`: Connection error occurred
- `stopped`: Manually stopped (no reconnection)

## Complete Examples

### Server Mode Flow
```javascript
// 1. Configure as server
msg = {
    topic: "setup",
    payload: {
        mode: "server",
        connections: [
            {
                connectionId: "main_server",
                host: "0.0.0.0",
                port: 8080
            }
        ]
    }
};

// 2. Send data to all connected clients
msg = {
    topic: "process",
    payload: {
        data: "Broadcast message to all clients"
    }
};

// 3. Close all connections
msg = {
    topic: "close",
    payload: {}
};
```

### Client Mode Flow
```javascript
// 1. Configure as client
msg = {
    topic: "setup",
    payload: {
        mode: "client",
        connections: [
            {
                connectionId: "remote_server",
                host: "192.168.1.100",
                port: 8080
            }
        ]
    }
};

// 2. Send data to remote server
msg = {
    topic: "process",
    payload: {
        data: "Hello remote server!"
    }
};

// 3. Close all connections
msg = {
    topic: "close",
    payload: {}
};
```

### Mode Switching Flow
```javascript
// 1. Start as server
msg = {
    topic: "setup",
    payload: {
        mode: "server",
        connections: [...]
    }
};

// 2. Switch to client mode (previous server automatically closed)
msg = {
    topic: "setup",
    payload: {
        mode: "client",
        connections: [...]
    }
};

// 3. Switch back to server mode
msg = {
    topic: "setup",
    payload: {
        mode: "server",
        connections: [...]
    }
};
```

## Development

### Build

```bash
npm run build
```

### Development Mode

```bash
npm run dev
```

### Testing

```bash
npm test
npm run test:watch
npm run test:coverage
```

## Architecture

This node follows the Heromatic architecture pattern:

- **TypeScript**: Strong typing and modern JavaScript features
- **Factory Pattern**: Modular message processors
- **Service Layer**: Separated business logic
- **Interface Contracts**: Well-defined interfaces
- **Error Handling**: Comprehensive error management
- **Testing**: Unit tests with Jest

### Project Structure

```
src/
├── interfaces/          # TypeScript interfaces
│   ├── tcp-server.ts   # Unified TCP interfaces
│   ├── tcp-manager.ts  # TCP manager interface
│   └── index.ts        # Interface exports
├── services/           # Business logic services
│   ├── message-sender/ # Message handling
│   ├── message-processor/ # Message processors
│   ├── tcp-manager/    # TCP server management
│   ├── tcp-client-manager/ # TCP client management
│   └── tcp-connection-manager/ # Dual mode orchestrator
├── factories/          # Factory patterns
├── helpers/           # Utility functions
└── tcp-process-manager.ts   # Main node file
```

## API Reference

### TCP Connection Interface

```typescript
interface ITcpConnection {
    connectionId: string;
    host: string;
    port: number;
    timeout?: number;
    maxConnections?: number;
    maxReconnections?: number;
    reconnectDelay?: number;
    keepAlive?: boolean;
    mode: 'server' | 'client';
}
```

### TCP Message Interface

```typescript
interface ITcpMessageUnified {
    connectionId: string;
    host: string;
    port: number;
    data: any;
    timestamp: string;
    success: boolean;
    error?: string;
    clientAddress?: string;
    clientPort?: number;
}
```

## Error Handling

The node provides comprehensive error handling for both modes:

- **Connection errors**: Network timeouts, connection refused, host unreachable
- **Configuration errors**: Invalid parameters, port conflicts, missing required fields
- **Processing errors**: Data transmission failures, connection lost during send
- **Reconnection errors**: Failed reconnection attempts, max attempts exceeded
- **Mode switching errors**: Cleanup failures, resource conflicts

## Version History

### v3.0.0 - Dual Mode TCP Connection Manager
- Added client mode support
- Implemented dynamic mode switching
- Unified interfaces for server and client modes
- Enhanced error handling and recovery
- Comprehensive status reporting
- Automatic reconnection for client mode

### v2.0.0 - TCP Server Manager
- Multiple server support
- Client connection management
- Real-time data processing
- Connection monitoring

### v1.0.0 - Basic TCP Server
- Single server functionality
- Basic client handling
- Simple data transmission

---

**Generated with Heromatic CLI v3.0.0 - Dual Mode TCP Connection Manager**