// The MIT License (MIT)
//
// Copyright (C) 2026 Scott Duensing
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

// Socket shim  -- provides rs232-compatible API backed by TCP sockets
// Used by the Linux proxy to reuse the packet and secLink layers.
//
// Design: the packet and secLink layers call rs232Read/rs232Write assuming
// a real UART underneath. By providing a socket-backed implementation with
// the same function signatures, we can reuse the entire protocol stack
// on Linux without any #ifdefs in the packet or secLink code.
//
// The #define RS232_H below is intentional: it prevents the real rs232.h
// from being included if someone includes both headers. The shim only
// implements the subset of rs232 functions that packet and secLink use
// (open, close, read, write). Hardware-specific functions (IRQ, FIFO,
// flow control) are not needed and not provided.

#ifndef SOCKSHIM_H
#define SOCKSHIM_H

// Prevent the real rs232.h from being included alongside this shim
#define RS232_H

#include <stdint.h>
#include <stdbool.h>

// rs232-compatible constants (subset used by packet and secLink)
#define RS232_NUM_PORTS                 4
#define RS232_COM1                      0
#define RS232_COM2                      1
#define RS232_COM3                      2
#define RS232_COM4                      3

#define RS232_HANDSHAKE_NONE            0

#define RS232_SUCCESS                   0
#define RS232_ERR_NOT_OPEN             -2
#define RS232_ERR_INVALID_PORT         -5


// Associate a socket fd with a COM index. Must be called before
// rs232Open/pktOpen/secLinkOpen. Sets the socket to non-blocking.
void sockShimSetFd(int com, int fd);

// rs232-compatible functions backed by TCP sockets
int rs232Close(int com);
int rs232Open(int com, int32_t bps, int dataBits, char parity, int stopBits, int handshake);
int rs232Read(int com, char *data, int len);
int rs232Write(int com, const char *data, int len);

#endif
