#pragma once
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
#ifdef _WIN32
#if MSC_VER < 1400
# define override
#endif
#include <windows.h>
#else
void Sleep(uint32_t ms);
#endif
enum serial_gpio_t{
GPIO_RTS = 1,
GPIO_DTR,
GPIO_BRK,
};
/* all options and flags used to open and configure an interface */
struct port_options {
const char *device;
uint32_t baudRate;
char mode[4]; //databits,parity,stopbits
int bus_addr;
int rx_frame_max;
int tx_frame_max;
};
/* Specify the length of reply for command GET
* This is helpful for frame-oriented protocols, e.g. i2c, to avoid time
* consuming try-fail-timeout-retry operation.
* On byte-oriented protocols, i.e. UART, this information would be skipped
* after read the first byte, so not needed. */
struct varlen_cmd {
uint8_t version,length;
};
struct Port {
enum flags_t{
F_BYTE =1<<0, // byte (not frame) oriented
F_GVR_ETX =1<<1, // cmd GVR returns protection status
F_CMD_INIT =1<<2, // use INIT cmd to autodetect speed
F_RETRY =1<<3, // allowed read() retry after timeout
F_STRETCH_W =1<<4, // warning for no-stretching commands
};
enum err_t{
OK,
ERR_NODEV, /* No such device */
ERR_TIMEDOUT, /* Operation timed out */
ERR_UNKNOWN,
};
const char*name;
unsigned flags;
Port(const char*n,unsigned f=0,const varlen_cmd*v=0):name(n),flags(f),cmd_get_reply(v) {}
virtual operator bool() const {return false;}
virtual ~Port() {}
virtual err_t flush() const {return OK;}
virtual err_t read(void*, size_t) const {return ERR_NODEV;}
virtual err_t write(const void*, size_t) const {return ERR_NODEV;}
virtual err_t gpio(serial_gpio_t n, int level) const {return OK;}
virtual const char*get_cfg_str() const{return 0;}
const varlen_cmd*cmd_get_reply;
static const char*find_com(int n=0);
};
Port*port_open(const port_options&ops);
struct PortSerial:public Port {
PortSerial(const port_options&ops);
virtual ~PortSerial();
virtual operator bool() const override {return !!fd;}
virtual err_t read(void*, size_t) const override;
virtual err_t write(const void*, size_t) const override;
virtual err_t gpio(serial_gpio_t n, bool level) const override;
virtual const char*get_cfg_str() const{return setup_str;}
private:
HANDLE fd;
DCB oldtio,newtio;
char setup_str[16];
};
#ifdef __linux__
struct PortI2c:public Port {
PortI2c(const port_options&ops);
virtual ~PortI2c();
virtual err_t flush() override;
virtual err_t read(void*buf, size_t nbyte) const override;
virtual err_t write(const void*buf, size_t nbyte) const override;
virtual err_t gpio(serial_gpio_t n, int level) const override;
virtual const char*get_cfg_str() const;
private:
int fd,addr;
PortI2c(const port_options&ops):Port("i2c") {}
};
#endif
Detected encoding: ASCII (7 bit) | 2
|