/*
 * rio_tcp.c
 *
 *  Created on: 24-Apr-2024
 *  Author: Lab To Market
 *
 * Implementation of TCP functions for Remote I/O
 */

#include "lwip/tcp.h"
#include "HL_sci.h"

struct tcp_pcb *pcb_test;
#define SERVER_PORT 6666
#define sciREGx sciREG1

void    sciDisplayTexttcp      (sciBASE_t *sci, uint8_t *text,uint32_t length);
uint8_t     tcpTitle[]          = {" ******************* Into TCP ************************"};

void on_connect_callback()
{

      const char *message = "Hello, server!";
      tcp_write(pcb_test, message, strlen(message), TCP_WRITE_FLAG_COPY);
      tcp_output(pcb_test);
}

void tcp_communicate(){

      sciInit();
      sciDisplayTexttcp(sciREGx, tcpTitle, sizeof(tcpTitle));
      ip_addr_t server_ip;
      err_t err_test;

      pcb_test = tcp_new();
      LWIP_ASSERT("httpd_init: tcp_new failed", pcb_test != NULL);
      //tcp_setprio(pcb_test, HTTPD_TCP_PRIO);

      if(pcb_test != NULL){
          IP4_ADDR(&server_ip, 192,168,2,10);
          tcp_connect(pcb_test, &server_ip, SERVER_PORT, on_connect_callback);

      }
}

void sciDisplayTexttcp(sciBASE_t *sci, uint8_t *text,uint32_t length)
{
    while(length--)
    {
        while ((sci->FLR & 0x4) == 4);
       sciSendByte(sci,*text++);
    };
}

