/*
 * outputsocket.c: Network output for the Atmolight-plugin
 *
 * See the README file for copyright information and how to reach the author.
 *
 * $Id$
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <vdr/tools.h>

#include "defs.h"
#include "output.h"
#include "outputnetwork.h"

// --- cOutputNetwork -----------------------------------------------------------

cOutputNetwork::cOutputNetwork()
{
 address.sin_port = 0;
}

bool cOutputNetwork::Open(const char* param)
{
 char ip[16];
 int port;
 if (2 != sscanf(param, "%15[^:]:%d", ip, &port))
 {
   esyslog("Atmolight: Wrong number of network parameters!");
   return false;
 }
 address.sin_family = AF_INET;
 address.sin_port = htons(port);
 if (0 == inet_aton(ip, &address.sin_addr))
 {
   address.sin_port = 0;
   esyslog("Atmolight: Wrong network parameters!");
   return false;
 }
 return true;
}

bool cOutputNetwork::Close()
{
 return true;
}

bool cOutputNetwork::OutputColors(const tColorPacket col)
{
 static char msg[20];
 static int  msg_len = 19;
 bool retcode = false;

 // create string to send
 msg[0] = 0xFF; // startbyte
 msg[1] = 0x00; // startchannel low byte
 msg[2] = 0x00; // startchannel high byte
 msg[3] = 0x0F; // number of channels

 for (int i = 0; i < 5; i++) // 5 channels (c, l, r, t, b)
 {
   msg[i*3+4] = col.channel[i].r;
   msg[i*3+5] = col.channel[i].g;
   msg[i*3+6] = col.channel[i].b;
 }

 // send data to target
 if (0 != address.sin_port)
 {
   int create_socket;

   if (0 < (create_socket = socket(AF_INET, SOCK_STREAM, 0)))
   {
     if (0 == connect(create_socket, (struct sockaddr *) &address, sizeof(address)))
     {
       retcode = (msg_len == send(create_socket, msg, msg_len, 0));
     }
     else
     {
       retcode = false;
       // esyslog("Atmolight: Could not connect to socket!");
     }
     close(create_socket);
   }
   else
   {
     retcode = false;
     // esyslog("Atmolight: Could not open socket!");
   }
 }

 return retcode;
}
