/** * Simplified Connection API for Thermal Printers * Uses native wrapper for all native calls */ import {EmitterSubscription, NativeEventEmitter, Platform} from 'react-native' import {NativePrinter} from '../native' import { ConnectionError, ConnectionErrorCode, ConnectionEventPayload, ConnectionEventType, TestConnectionResult, } from './types' // For events only - will be refactored later import {NativeModules} from 'react-native' const eventEmitter = new NativeEventEmitter(NativeModules.RNThermalPrinter) /** * Test connection to a printer * @param address Printer address in format: "ble:MAC", "bt:MAC", or "lan:IP:PORT" * @returns Test result with device info */ export async function testConnection(address: string): Promise { try { // Validate address format if (!address) { throw new ConnectionError(ConnectionErrorCode.INVALID_ADDRESS, 'Address is required') } // Check if address has valid prefix const validPrefixes = ['ble:', 'bt:', 'lan:'] const hasValidPrefix = validPrefixes.some((prefix) => address.startsWith(prefix)) if (!hasValidPrefix) { throw new ConnectionError( ConnectionErrorCode.INVALID_ADDRESS, 'Invalid address format. Use: ble:MAC, bt:MAC, or lan:IP:PORT', ) } // Check platform support for Bluetooth Classic const [type] = address.split(':') if (type === 'bt' && Platform.OS === 'ios') { throw new ConnectionError( ConnectionErrorCode.CONNECTION_FAILED, 'Bluetooth Classic is not supported on iOS. Use BLE instead.', ) } // Call native testConnection through wrapper const result = await NativePrinter.testConnection(address) return result } catch (error: any) { // Map native error to ConnectionError if (error instanceof ConnectionError) throw error throw ConnectionError.fromNative(error) } } /** * Disconnect from printer * @param address Optional printer address (disconnects all if not provided) */ export async function disconnect(address?: string): Promise { try { await NativePrinter.disconnect(address) } catch (error: any) { // Ignore disconnect errors - best effort console.warn('[JS] Connection.disconnect - WARN:', error.message) } } /** * Disconnect all printers */ export async function disconnectAll(): Promise { return disconnect() } /** * Add event listener for connection events with type safety */ export function addConnectionEventListener( event: T, listener: (data: ConnectionEventPayload[T]) => void, ): EmitterSubscription { return eventEmitter.addListener(event, listener) } /** * Remove event listener */ export function removeConnectionEventListener(subscription: EmitterSubscription): void { subscription.remove() }