npm package: @georgemichel/react-native-xprinter-manager
Description: Complete XPrinter thermal printer management library with TCP/IP support, receipt printing, and auto-connect
Author: Vuedale
Latest version: 1.0.0

# React Native XPrinter Manager

A **complete, standalone** React Native library for managing XPrinter thermal printers over TCP/IP connection. Provides React hooks for connection management, printer storage, auto-connect functionality, and receipt printing.

## Features

- 📦 **All Dependencies Included** - No manual linking required
- 🔌 **Easy Connection Management** - Connect/disconnect with simple hooks
- 💾 **Persistent Storage** - Save printer configurations locally
- 🔄 **Auto-Connect** - Automatically connect to saved printers on app start
- 🧾 **Receipt Printing** - Pre-built receipt template with customization
- 📝 **ESC/POS Commands** - Full suite of thermal printer commands
- ⚡ **React Hooks** - Modern React hooks API
- 🎯 **TypeScript Ready** - (Types can be added)
- 🚀 **Production Ready** - Battle-tested and documented

## Installation

### Install from Private NPM

**One command - everything included!**

```bash
npm install @yourcompany/react-native-xprinter-manager
```

**That's it!** All dependencies (`react-native-tcp-socket`, `@react-native-async-storage/async-storage`) are included automatically.

### For Expo Projects

After installing, rebuild your native code:

```bash
npx expo prebuild
npm run android  # or npm run ios
```

### Setup Authentication

Create `.npmrc` in your project root:

```
@yourcompany:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR-GITHUB-TOKEN
```

See `SETUP.md` for complete publishing and installation instructions.

## Quick Start

### 1. Basic Connection

```javascript
import React from 'react';
import { View, Button, Text } from 'react-native';
import { usePrinterConnection } from '@yourcompany/react-native-xprinter-manager';

function App() {
  const {
    isConnected,
    connectedPrinter,
    connect,
    disconnect,
    sendData
  } = usePrinterConnection();

  const handleConnect = async () => {
    try {
      await connect('192.168.100.99', 9100, 'Main Printer');
      alert('Connected!');
    } catch (error) {
      alert('Connection failed: ' + error.message);
    }
  };

  return (
    <View>
      {isConnected ? (
        <>
          <Text>Connected to: {connectedPrinter.deviceName}</Text>
          <Button title="Disconnect" onPress={disconnect} />
        </>
      ) : (
        <Button title="Connect" onPress={handleConnect} />
      )}
    </View>
  );
}
```

### 2. Print a Receipt

```javascript
import { usePrinterConnection, printReceipt } from '@yourcompany/react-native-xprinter-manager';

function ReceiptScreen() {
  const { socket, isConnected } = usePrinterConnection();

  const handlePrint = async () => {
    if (!isConnected) {
      alert('Not connected to printer');
      return;
    }

    const receiptData = {
      storeName: "My Store",
      storeAddress: "123 Main St, City, State",
      storePhone: "(555) 123-4567",
      receiptNumber: "INV-001",
      items: [
        { name: "Coffee", qty: 2, price: 3.50 },
        { name: "Sandwich", qty: 1, price: 7.99 },
      ],
      subtotal: 14.99,
      tax: 1.20,
      total: 16.19,
      paymentMethod: "Cash",
      footerText: "Thank you!"
    };

    try {
      await printReceipt(socket, receiptData);
      alert('Receipt printed!');
    } catch (error) {
      alert('Print failed: ' + error.message);
    }
  };

  return (
    <Button title="Print Receipt" onPress={handlePrint} />
  );
}
```

### 3. Save and Auto-Connect

```javascript
import {
  usePrinterConnection,
  usePrinterStorage,
  useAutoConnect
} from '@yourcompany/react-native-xprinter-manager';

function PrinterManager() {
  const { connect, isConnected } = usePrinterConnection();
  const { addPrinter, savedPrinters } = usePrinterStorage();
  const { isAutoConnecting } = useAutoConnect({ enabled: true });

  const handleAddPrinter = async () => {
    const printer = await addPrinter({
      ip: '192.168.100.99',
      port: 9100,
      deviceName: 'Main Counter Printer',
      autoConnect: true // Will auto-connect on app start
    });

    // Manually connect now
    await connect(printer.ip, printer.port, printer.deviceName);
  };

  return (
    <View>
      {isAutoConnecting && <Text>Auto-connecting...</Text>}
      {savedPrinters.map(printer => (
        <Text key={printer.id}>{printer.deviceName}</Text>
      ))}
      <Button title="Add Printer" onPress={handleAddPrinter} />
    </View>
  );
}
```

## API Reference

### Hooks

#### `usePrinterConnection()`

Manages TCP socket connection to printer.

**Returns:**
- `socket` - Active socket object
- `isConnected` - Connection status
- `isConnecting` - Connecting in progress
- `connectedPrinter` - Current printer info
- `error` - Last error message
- `receivedData` - Data received from printer
- `connect(ip, port, deviceName, options)` - Connect to printer
- `disconnect()` - Disconnect from printer
- `sendData(data, encoding)` - Send data to printer
- `checkPrinterAvailable(ip, port, timeout)` - Check if printer is online
- `clearReceivedData()` - Clear received data buffer

#### `usePrinterStorage()`

Manages saved printer configurations.

**Returns:**
- `savedPrinters` - Array of saved printers
- `isLoading` - Loading status
- `addPrinter(printer)` - Add new printer
- `removePrinter(printerId)` - Remove printer
- `updatePrinter(printerId, updates)` - Update printer
- `getPrinter(printerId)` - Get printer by ID
- `getPrinterByAddress(ip, port)` - Get printer by address
- `setAutoConnect(printerId, enabled)` - Set auto-connect
- `getAutoConnectPrinters()` - Get printers with auto-connect
- `updateLastConnected(printerId)` - Update last connected time
- `clearAllPrinters()` - Remove all printers
- `reload()` - Reload from storage

#### `useAutoConnect(options)`

Automatically connects to saved printers on app start.

**Options:**
- `enabled` - Enable auto-connect (default: true)
- `retryDelay` - Delay between retries in ms (default: 3000)
- `maxRetries` - Max retry attempts (default: 3)

**Returns:**
- `isAutoConnecting` - Auto-connect in progress
- `autoConnectStatus` - Array of connection attempts
- `triggerAutoConnect()` - Manually trigger auto-connect
- `resetAutoConnect()` - Reset auto-connect state

### Utilities

#### `printReceipt(socket, receiptData)`

Prints a formatted receipt.

**Parameters:**
- `socket` - Active TCP socket
- `receiptData` - Receipt data object (see example above)

**Returns:** `Promise<boolean>`

#### `Commands`

ESC/POS command constants:

```javascript
import { Commands } from '@yourcompany/react-native-xprinter-manager';

// Initialization
Commands.INIT

// Alignment
Commands.ALIGN_LEFT
Commands.ALIGN_CENTER
Commands.ALIGN_RIGHT

// Text Size
Commands.TEXT_SIZE_NORMAL
Commands.TEXT_SIZE_DOUBLE
Commands.TEXT_SIZE_LARGE

// Text Style
Commands.TEXT_BOLD_ON
Commands.TEXT_BOLD_OFF

// Paper Control
Commands.LINE_FEED
Commands.CUT_PAPER
```

#### Helper Functions

- `separator(char, length)` - Create separator line
- `formatLine(left, right, totalWidth)` - Format left/right aligned text
- `centerText(text, width)` - Center text
- `formatCurrency(amount, currency)` - Format currency

## Receipt Template

The library includes a customizable receipt template. Here's how to modify it:

```javascript
const receiptData = {
  // === HEADER ===
  storeName: "Your Store Name",           // Store name (centered, large)
  storeAddress: "123 Main St",            // Store address
  storePhone: "(555) 123-4567",           // Store phone

  // === RECEIPT INFO ===
  receiptNumber: "INV-001234",            // Invoice/order number

  // === ITEMS ===
  items: [
    {
      name: "Product Name",                // Item name
      qty: 2,                              // Quantity
      price: 10.00                         // Price per unit
    },
    // ... more items
  ],

  // === TOTALS ===
  subtotal: 45.00,                        // Subtotal
  tax: 3.60,                              // Tax amount
  total: 48.60,                           // Total amount

  // === PAYMENT ===
  paymentMethod: "Cash",                  // Payment method

  // === FOOTER ===
  footerText: "Thank you!\nVisit again!" // Footer message
};
```

## Configuration for Private NPM

To publish as a private npm package:

1. **Update package.json:**
```json
{
  "name": "@yourcompany/react-native-xprinter-manager",
  "private": false,
  "publishConfig": {
    "registry": "https://npm.pkg.github.com/"
  }
}
```

2. **Publish:**
```bash
cd lib
npm publish
```

3. **Install in projects:**
```bash
npm install @yourcompany/react-native-xprinter-manager
```

## Troubleshooting

### Connection Issues

1. **Check IP and Port:** Verify printer IP address and port (usually 9100)
2. **Network Connection:** Ensure device is on same network as printer
3. **Firewall:** Check if firewall is blocking TCP connections
4. **Printer Status:** Ensure printer is powered on and online

### Print Issues

1. **Paper Loaded:** Verify paper is loaded correctly
2. **ESC/POS Support:** Ensure printer supports ESC/POS commands
3. **Encoding:** Try different text encodings if characters appear wrong
4. **Commands:** Some printers may not support all ESC/POS commands

## License

MIT

## Support

For issues and questions, please open an issue on GitHub or contact support.