/*
    Tucnak - VHF contest log
    Copyright (C) 2011-2021 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#ifndef __SDEV_H
#define __SDEV_H

#include "header.h"

#define SDINIT char sdlen=0;int sdret;char sdbuf[256]
#define SDADD(a) sdbuf[sdlen++]=(a)
#define SDADD2(a) sdbuf[sdlen++]=(a)&0xff;sdbuf[sdlen++]=(a)>>8
//#define SDPLUS(sd,cmd) sdret=sd_protplus((sd),(cmd),sdbuf,&sdlen)

#define SDMAXLEN 300
#define SDFCE   1
#define SDADR   2
#define SDLEN   3

enum conntype{
    CT_TTYS, CT_UDP, CT_TCP, CT_FTDI
};

enum sprotocol{
	SPROT_NONE,
	SPROT_ROTAR
};

enum SCONN_CMD{
    SCONN_ROT_AZIM
};

struct sconn_job{
    struct sconn_job *next;
    struct sconn_job *prev;
    enum SCONN_CMD cmd;
    struct sdev *sdev;
    int azim, elev;
};

struct sdev{
    struct sdev *next;
    struct sdev *prev;

    struct sconn *sconn;
    unsigned char saddr;
    int timeout_ms;

    int (*sdev_main)(struct sdev *sdev);
    void *arg;
};

struct sconn{
    struct sconn *next;
    struct sconn *prev;

    enum conntype type;
    int opened;
    int refcnt;

    gchar *ttys_filename;
    gchar *ip_hostname;
    int ip_port;
    int usb_port;
    GThread *thread;
    int thread_break;
    int give_me_chance;
    struct sconn_job jobs;
    MUTEX_DEFINE(jobs);
    struct sdev sdevs;
    MUTEX_DEFINE(sdevs);
    int sdevi;
	enum sprotocol sprotocol;
    struct zserial *zser; /* valid only in child process! */
	//unsigned char ftdi_state;
    int ftdi_vid, ftdi_pid;
    char *ftdi_serial; 
    int freeing;
};


extern struct sconn sconns;
extern MUTEX_DEFINE(sconns);

void init_sconns(void);
struct sdev *sd_open_ttys(char saddr, char *filename, int timeout_ms);
struct sdev *sd_open_udp(char *hostname, int udpport);
struct sdev *sd_open_tcp(char *hostname, int tcpport);
struct sdev *sd_open_ftdi(char saddr, int vid, int pid, char *serial, int timeout_ms);

void sc_open_common(struct sconn *sconn);
int free_sd(struct sdev *sd);

int sconn_file_open(struct sconn *sconn, int verbose);
int sconn_file_close(struct sconn *sconn);
int sconn_file_read(struct sconn *sconn, void *data, size_t len, int timeout_ms);
int sconn_file_write(struct sconn *sconn, void *data, size_t len);

#ifdef Z_HAVE_LIBFTDI
int sconn_ftdi_open(struct sconn *sconn, int verbose);
int sconn_ftdi_close(struct sconn *sconn);
int sconn_ftdi_read(struct sconn *sconn, void *data, size_t len, int timeout_ms);
int sconn_ftdi_write(struct sconn *sconn, void *data, size_t len);
#endif
    
gpointer sc_main(gpointer xxx);
char *sd_err(int err);          
int sd_prot(struct sconn *sconn, char saddr, char fce, char *data, int *len, int timeout);

void sconn_job_add(struct sconn *sconn, struct sconn_job *job);
struct sconn_job *sconn_job_get(struct sconn *sconn);




#endif
