<repo_name>hoog1511/Project-Domotica<file_sep>/beveiliging.ino
int kalibratietijd = 30;
long unsigned int LowIn ;   // tijd wanneer sensor outputs laag impuls
long unsigned int pauze = 30000; // na deze tijd mag de arduino aannemen dat er geen beweging meer is
boolean lockLow = true;
boolean takeLowTime;
#define irLedPin 5
#define irSensorPin 4
#define echoPin 3
#define triggerPin 2
#define ledPin 1

int maximumRange = 100;
int minimumRange = 0;
long duration, distance;
int tijden[20];
int y = 0;
int tijdvannu = 0;
bool melding = false;
int aantal = 0;

volatile unsigned long seconden = 0;
unsigned long seconden_oud = 0;

int seco;
int minu;
int uren;

unsigned int ethPort = 3300;
byte mac [] = { 0x40, 0x6c, 0x8f, 0x36, 0x84, 0x8a };
//IPAddress ip(192, 168, 1, 102);

ISR(TIMER1_OVF_vect) {
  TCNT1 = 0xBDC;
  seconden = seconden + 1;
};

#include <SPI.h>
#include <Ethernet.h>
EthernetServer server(ethPort);


void setup() {
  Serial.begin(9600);

  TIMSK1 = 0x01; // enabled global and timer overflow interrupt;
  TCCR1A = 0x00; // normal operation page 148 (mode0);
  TCNT1 = 0xBDC; // set initial value to remove time error (16bit counter register)
  TCCR1B = 0x04; // start timer/ set clock

  zetTijd();

  if (Ethernet.begin(mac) == 0)
  {
    Serial.print("Geen address te vinden!");
    while (true) {}
  }


  Serial.println("IP address ");
  Serial.print(Ethernet.localIP());
  //Serial.print("192.168.1.102")
  Ethernet.begin(mac, Ethernet.localIP());
  server.begin();

  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(ledPin, OUTPUT);

  pinMode(irSensorPin, INPUT);
  pinMode(irLedPin, OUTPUT);
  digitalWrite(irSensorPin, LOW);

  //kalibratie tijd
  Serial.println("---");
  Serial.println("Kalibratie van sensor is bezig");
  for (int i = 0; i < kalibratietijd; i++) {
    Serial.print(".");
    delay(200);
  }
  Serial.println("");
  Serial.println("Klaar ");
  Serial.println("Sensor actief!");
  delay(50);
}

void loop() {
  EthernetClient ethernetClient = server.available();

  if (seconden_oud != seconden) {
    seconden_oud = seconden;
    seco++;
    if (seco == 60) {
      seco = 0;
      minu++;
      if (minu == 60) {
        minu = 0;
        uren++;
        if (uren == 24) {
          uren = 0;
        }
      }
    }
  }

  while (ethernetClient.available())
  {
    char inByte = ethernetClient.read();
    executeCommand(inByte);
    inByte = NULL;
  }

  if (digitalRead(irSensorPin) == HIGH) {
    digitalWrite(irLedPin, HIGH);   //als de sensor hoog is moet de pin ook hoog zijn
    if (lockLow) {
      while (ethernetClient.available())
      {
        char inByte = ethernetClient.read();
        executeCommand(inByte);
        inByte = NULL;
      }
      lockLow = false;
      Serial.println("---");
      Serial.println("motion gedetecteerd bij ");
      if (uren < 10)
      {
        Serial.print("0");
      }
      Serial.print(uren);
      Serial.print(":");
      if (minu < 10)
      {
        Serial.print("0");
      }
      Serial.print(minu);
      digitalWrite(triggerPin, LOW);
      delayMicroseconds(2);

      digitalWrite(triggerPin, HIGH);
      delayMicroseconds(10);

      digitalWrite(triggerPin, LOW);
      duration = pulseIn(echoPin, HIGH);

      distance = (duration / 2) / 29.2;
      if (distance >= maximumRange || distance <= minimumRange) {
        //Serial.println("-1");
        digitalWrite(ledPin, HIGH);
      }
      else {
        Serial.println(distance);
        Serial.print(" cm ");
        digitalWrite(ledPin, LOW);
      }
      delay(50);
    }
  }
  melding = true;
  if (melding == true && distance >= maximumRange || distance <= minimumRange) {
    if (y < 20) {
      {
        if (((uren * 100) + minu) != tijden[y - 1])
        { tijden[y] = ((uren * 100) + minu);
          Serial.println(tijden[y]);
          y++;
          melding = false;
        }
      }
    }
    else {
      if (((uren * 100) + minu) != tijden[y - 1] && ((uren * 100) + minu) != tijden[19])
      { y = 0;
        tijden[y] = ((uren * 100) + minu);
        Serial.println(tijden[y]);
        melding = false;
      }
    }
  }
  takeLowTime = true;


  if (digitalRead(irSensorPin) == LOW) {
    digitalWrite(irLedPin, LOW);  //als de sensor laag is moet de pin ook laag zijn

    if (takeLowTime) {
      LowIn = millis();          //tijd van hoog naar laag
      takeLowTime = false;
    }
    //als de sensor langer laag blijft dan de pauze is er nieuwe motion
    if (!lockLow && millis() - LowIn > pauze) {
      lockLow = true;
      Serial.println("motion gestopt bij ");
      if (uren < 10)
      {
        Serial.print("0");
      }
      Serial.print(uren);
      Serial.print(":");
      if (minu < 10)
      {
        Serial.print("0");
      }
      Serial.print(minu);
      delay(50);
    }
    digitalWrite(triggerPin, LOW);
  }
}
void zetTijd() {
  String tijd = __TIME__;
  uren = (tijd.charAt(0) - 48) * 10 + tijd.charAt(1) - 48;
  minu = (tijd.charAt(3) - 48) * 10 + tijd.charAt(4) - 48;
  seco = (tijd.charAt(6) - 48) * 10 + tijd.charAt(7) - 48;
}

void executeCommand(char cmd)
{
  switch (cmd) {
    case 'q': //update log
      for (int i = 0; i <= y; i++)
      {
        if (tijden[i] != 0 && tijden[i] != tijden[i - 1])
        {
          String tijd = String(tijden[i]);

          if (tijden[i] < 1000)
          {
            tijd = "0" + tijd;
          }
          for (int x = 0; x < 4; x++)
          {
            char c = tijd.charAt(x);
            server.write(c);
            Serial.println("{" + String(c) + "} + ");
          }
          Serial.println("{" + tijd + "} ");
        }

      }
    /*case 'q': //melding van motion
      if (tijdvannu > 19)
      {
        tijdvannu = 0;
      }
      String tijd = String(tijden[tijdvannu]);

      if (tijden[tijdvannu] < 1000)
      {
        tijd = "0" + tijd;
      }

      for (int a = 0; a < 4; a++)
      { char n = tijd.charAt(a);
        server.write(n);
        Serial.println("{" + String(n) + "} + ");
      }
      Serial.println("{" + tijd + "} ");
      tijdvannu++;
  }*/
}

<file_sep>/DomoticaServer_groep20.ino

#include <NewRemoteReceiver.h>
#include <NewRemoteTransmitter.h>
#include <RemoteTransmitter.h>
//  Domotica server with KAKU-controller
//
// By <NAME>, Student Computer Science NHL.
// V0.1, 19/1/2017. Works with Xamarin

// kaku, Gamma, APA3, codes based on Arduino -> Voorbeelden -> NewRemoteSwitch -> ShowReceivedCode
// 1 Addr 21177114 unit 0 on/off, period: 270us   replace with your own code
// Supported KaKu devices -> find, download en install corresponding libraries

#define unitCodeApa3      20144854  // replace with your own code

// Include files.
#include <time.h>
#include <SPI.h>                  // Ethernet shield uses SPI-interface
#include <Ethernet.h>             // Ethernet library (use Ethernet2.h for new ethernet shield v2)
#include <NewRemoteTransmitter.h> // Remote Control, Gamma, APA3


// Set Ethernet Shield MAC address  (check yours)
byte mac[] = { 0x40, 0x6c, 0x3f, 0x36, 0x64, 0x6a }; //Random mac adres
int ethPort = 3300;                                  // Take a free port (check your router)

#define RFPin        3  // output, pin to control the RF-sender (and Click-On Click-Off-device)
#define lowPin       5  // output, always LOW
#define highPin      6  // output, always HIGH
#define switchPin    7  // input, connected to some kind of inputswitch
#define analogPin    0  // sensor value

EthernetServer server(ethPort);              // EthernetServer instance (listening on port <ethPort>).
NewRemoteTransmitter apa3Transmitter(unitCodeApa3, RFPin, 270, 3);  // APA3 (Gamma) remote, use pin <RFPin>
//Is for the socket's
int socket = 0;                          // output, defines the socket 0 or 1
bool pinState = false;                   // Variable to store actual pin state
bool pinChange = false;                  // Variable to store actual pin change
bool pinState1 = false;                  // Variable to store actual pin state
bool pinChange1 = false;                 // Variable to store actual pin change


// distance sensor
int triggerPin = 4;
int echoPin = 5;
bool disstate = false;
long Distance = 0;
long duration = 0;



//Is for the timer
char Time[4];
int Clock = 0;
char Time1[4];
int Clock1 = 0;
volatile unsigned long seconds = 0;
unsigned long seconds_old = 0;
int Sec;
int Min;
int Hours;

ISR(TIMER1_OVF_vect) {
  TCNT1 = 0xBDC;
  seconds = seconds + 1;
}

//  for the Photoresistor
const int pResistor = A0; // Photoresistor at Arduino analog pin A0
const int ledPin = 9;     // Led pin at Arduino pin 9
int pRvalue = 0;          // Store value from photoresistor (0-1023)
bool onoff = false;
bool onoff1 = false;


void setup()
{
  Serial.begin(9600);
  Serial.println("Domotica project, Arduino Domotica Server\n");

  //Init I/O-pins
  pinMode(switchPin, INPUT);            // hardware switch, for changing pin state
  pinMode(lowPin, OUTPUT);
  pinMode(highPin, OUTPUT);
  pinMode(RFPin, OUTPUT);
  pinMode(ledPin, OUTPUT);             // Set lepPin - 9 pin as an output
  pinMode(pResistor, INPUT);              // Set pResistor - A0 pin as an input
  pinMode(triggerPin, OUTPUT);
  pinMode(echoPin, INPUT);

  //Default states
  digitalWrite(switchPin, HIGH);        // Activate pullup resistors (needed for input pin)
  digitalWrite(lowPin, LOW);
  digitalWrite(highPin, HIGH);
  digitalWrite(RFPin, LOW);

  // for the internal timer
  TIMSK1 = 0x01; // enabled global and timer overflow interrupt;
  TCCR1A = 0x00; // normal operation page 148 (mode0);
  TCNT1 = 0xBDC; // set initial value to remove time error (16bit counter register)
  TCCR1B = 0x04; // start timer/ set clock


  settime();
  //Try to get an IP address from the DHCP server.
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("Could not obtain IP-address from DHCP -> do nothing");
    while (true) {    // no point in carrying on, so do nothing forevermore; check your router
    }
  }

  Serial.print("Input switch on pin "); Serial.println(switchPin);
  Serial.println("Ethernetboard connected (pins 10, 11, 12, 13 and SPI)");
  Serial.println("Connect to DHCP source in local network");

  //Start the ethernet server.
  server.begin();

  // Print IP-address
  Serial.print("Listening address: ");
  Serial.print(Ethernet.localIP());

  // for hardware debug
  int IPnr = getIPComputerNumber(Ethernet.localIP());   // Get computernumber in local network 192.168.1.3 -> 3)
  Serial.print(" ["); Serial.print(IPnr); Serial.print("] ");
  Serial.print("  [Testcase: telnet "); Serial.print(Ethernet.localIP()); Serial.print(" "); Serial.print(ethPort); Serial.println("]");

}

void loop()
{




  pRvalue = analogRead(pResistor);         // update pRsensor value
  Photoresistor(pRvalue);
  checks();


  // Internal Timer
  if (seconds_old != seconds) {
    seconds_old = seconds;
    Sec++;
    if (Sec == 60) {
      Sec = 0;
      Min++;
      if (Min == 60) {
        Min = 0;
        Hours++;
        if (Hours == 24) {
          Hours = 0;
        }
      }
    }
    Serial.print(Hours);
    Serial.print(':');
    Serial.println(Min);
    Serial.println(pRvalue);

    // Listen for incomming connection (app)
    EthernetClient ethernetClient = server.available();
    if (!ethernetClient) {
      return; // wait for connection
    }


    Serial.println("Application connected");

    // Do what needs to be done while the socket is connected.
    while (ethernetClient.connected())
    {
      checks();

      if (disstate == true) {
        distance();
        Serial.println(Distance);
        if (Distance < 300)
        {
          executeCommand('u');
        }





      }

      // Execute when byte is received.
      while (ethernetClient.available())
      {
        char inByte = ethernetClient.read();   // Get byte from the client
        executeCommand(inByte);                // Wait for command to execute
        inByte = NULL;                         // Reset the read byte.
      }
    }
    Serial.println("Application disonnected");
  }
}

// Choose and switch your Kaku device, state is true/false (HIGH/LOW)
void switchDefault(bool state)
{
  if (socket == 0) {
    Serial.println("code send 0");
  }
  if (socket == 1) {
    Serial.println("code send 1");
  }
  apa3Transmitter.sendUnit(socket, state);          // APA3 Kaku (Gamma)
  delay(50);
}

// Implementation of (simple) protocol between app and Arduino
// Request (from app) is single char ('a', 'u', 't' etc.)
// Response (to app) is 6 chars  (not all commands demand a response)
void executeCommand(char cmd)
{
  char buf[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};

  // Command protocol
  Serial.print("["); Serial.print(cmd); Serial.println("] -> ");
  switch (cmd) {
    /*case 'a': // Report sensor value to the app
       intToCharBuf(sensorValue, buf, 4);                // convert to charbuffer
       server.write(buf, 4);                             // response is always 4 chars (\n included)


       break;*/
    case 'u': // Toggle state of socket1; If state is already ON then turn it OFF
      socket = 1;
      if (pinState1) {
        pinState1 = false;
        Serial.println("Set pin state to \"OFF\"");
      }
      else {
        pinState1 = true;
        Serial.println("Set pin state to \"ON\"");
      }
      pinChange1 = true;
      break;
    case 't': // Toggle state; If state is already ON then turn it OFF
      socket = 0;
      if (pinState) {
        pinState = false;
        Serial.println("Set pin state to \"OFF\"");
      }
      else {
        pinState = true;
        Serial.println("Set pin state to \"ON\"");
      }
      pinChange = true;
      break;
    case 'd': // distance sensor
      if (disstate = false) {
        disstate = true;
      }
      else {
        disstate = false;
      }
      break;
  }

}

// checks if there is any changes in
void checks()
{

  checkEvent(switchPin, pinState);          // update pin state
  checkEvent(switchPin, pinState1);         // update pin1 state


  // Activate pin based op pinState
  if (pinChange) {
    if (pinState) {
      switchDefault(true);
    }
    else {
      switchDefault(false);
    }
    pinChange = false;
  }
  if (pinChange1) {
    if (pinState1) {
      switchDefault(true);
    }
    else {
      switchDefault(false);
    }
    pinChange1 = false;
  }
}

//checks for light value
void Photoresistor (int value)
{
  if (onoff == false && value > 681)
  {
    digitalWrite(ledPin, LOW);  //Turn led off
    if (pinState == true) {
      executeCommand('t');
      onoff = true;
    }
  }
  if (onoff1 == false && value > 681)
  {
    digitalWrite(ledPin, LOW);  //Turn led off
    if (pinState1 == true) {
      executeCommand('u');
      onoff1 = true;
    }
  }

  if (onoff == true && value < 680)
  {
    digitalWrite(ledPin, HIGH); //Turn led on
    if (pinState == false) {
      executeCommand('t');
      onoff = false;
    }
  }
  if (onoff1 == true && value < 680)
  {
    digitalWrite(ledPin, HIGH); //Turn led on
    if (pinState1 == false) {
      executeCommand('u');
      onoff1 = false;
    }
  }

}


void distance() {
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);

  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);

  digitalWrite(triggerPin, LOW);
  duration = pulseIn(echoPin, HIGH);

  Distance = duration / 58.2;
  Serial.println(Distance);
  Serial.print(" cm ");

}


// Convert int <val> char buffer with length <len>
void intToCharBuf(int val, char buf[], int len)
{
  String s;
  s = String(val);                        // convert tot string
  if (s.length() == 1) s = "0" + s;       // prefix redundant "0"
  if (s.length() == 2) s = "0" + s;
  s = s + "\n";                           // add newline
  s.toCharArray(buf, len);                // convert string to char-buffer
}

// Check switch level and determine if an event has happend
// event: low -> high or high -> low
void checkEvent(int p, bool &state)
{
  static bool swLevel = false;       // Variable to store the switch level (Low or High)
  static bool prevswLevel = false;   // Variable to store the previous switch level

  swLevel = digitalRead(p);
  if (swLevel)
    if (prevswLevel) delay(1);
    else {
      prevswLevel = true;   // Low -> High transition
      state = true;
      pinChange = true;
      pinChange1 = true;
    }
  else // swLevel == Low
    if (!prevswLevel) delay(1);
    else {
      prevswLevel = false;  // High -> Low transition
      state = false;
      pinChange = true;
      pinChange1 = true;
    }
}

// Convert IPAddress tot String (e.g. "192.168.1.105")
String IPAddressToString(IPAddress address)
{
  return String(address[0]) + "." +
         String(address[1]) + "." +
         String(address[2]) + "." +
         String(address[3]);
}

// Returns B-class network-id: 192.168.1.3 -> 1)
int getIPClassB(IPAddress address)
{
  return address[2];
}

// Returns computernumber in local network: 192.168.1.3 -> 3)
int getIPComputerNumber(IPAddress address)
{
  return address[3];
}

// Returns computernumber in local network: 192.168.1.105 -> 5)
int getIPComputerNumberOffset(IPAddress address, int offset)
{
  return getIPComputerNumber(address) - offset;
}

void settime() {
  String Time = __TIME__;
  Hours = (Time.charAt(0) - 48) * 10 + Time.charAt(1) - 48;
  Min = (Time.charAt(3) - 48) * 10 + Time.charAt(4) - 48;
  Sec = (Time.charAt(6) - 48) * 10 + Time.charAt(7) - 48;
}
<file_sep>/servo map/master/README.md
# Slagboom master

Library die basis vormt voor de interactie tussen de app en de Arduino.

pls no copy<file_sep>/servo map/slave/slave.ino
#include <VirtualWire.h>
#include <ServoTimer2.h>

const int KEY = 81;

const int RF_RECEIVE_PIN = 7;

const int ULTRA_ECHO_PIN = 6;
const int ULTRA_TRIGGER_PIN = 11;
const int ULTRA_MIN_DISTANCE = 2; // inch
const int ULTRA_MAX_DISTANCE = 6; // inch

const int SERVO_PIN = 5;
const int SERVO_MIN_POS = 544;
const int SERVO_MAX_POS = 1472;
const int SERVO_STEP_SIZE = 32;

const int MAX_SWEEPS = 4;

bool start_signal = false;
int distance = 0;
int old_distance = distance;
bool alternate = true;
int sweep_count = 0;
ServoTimer2 myservo;

void setup() {
  Serial.begin(9600);
  Serial.setTimeout(100);
  // RF communication
  vw_set_rx_pin(RF_RECEIVE_PIN);
  vw_set_ptt_inverted(true);
  vw_setup(2000);
  vw_rx_start();

  pinMode(ULTRA_ECHO_PIN, INPUT);
  pinMode(ULTRA_TRIGGER_PIN, OUTPUT);

  // Set start position
  open_servo();
}

void loop() {
  // RF start signal received
  uint8_t id = receive_id();
  if (id && id == KEY) {
    start_signal = true;
    sweep_count = 0;
  }

  // For old vs new distance comparison
  old_distance = distance ? distance : old_distance;
  distance = ping_distance();

  // Movement detected
  if ((old_distance > 0) &&
      (distance != old_distance) &&
      (distance <= ULTRA_MAX_DISTANCE) &&
      (distance >= ULTRA_MIN_DISTANCE) &&
      (sweep_count < MAX_SWEEPS) || start_signal) {
    if (start_signal) start_signal = false;

    // Move servo
    if (alternate) close_servo();
    else open_servo();

    sweep_count++;

    alternate = !alternate;
    delay(250);
  }
}

String receive_msg() {
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  String msg = "";
  
  if (vw_get_message(buf, &buflen)) {
    for (int i = 0; i < buflen; i++) {
      msg += char(buf[i]);
    }
  }
  return msg;
}

uint8_t receive_id() {
  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;
  
  if (vw_get_message(buf, &buflen)) {
    for (int i = 0; i < buflen; i++) {
      Serial.print("R: ");
      Serial.println(buf[i]);
    }

    return buf[0];
  }

  return 0;
}

unsigned int ping_distance() {
  delay(50);
  unsigned long duration, distance;
  digitalWrite(ULTRA_TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(ULTRA_TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(ULTRA_TRIGGER_PIN, LOW);
  duration = pulseIn(ULTRA_ECHO_PIN, HIGH);
  return (duration/58.138) * .39; // remove *.39 for cm
}

void open_servo() {
  // Attach/detach to prevent RF interference
  myservo.attach(SERVO_PIN);
  for (int pos = SERVO_MAX_POS; pos >= SERVO_MIN_POS; pos -= SERVO_STEP_SIZE) {
    myservo.write(pos);
    delay(10);
  }
  myservo.detach();
}

void close_servo() {
  // Attach/detach to prevent RF interference
  myservo.attach(SERVO_PIN);
  for (int pos = SERVO_MIN_POS; pos <= SERVO_MAX_POS; pos += SERVO_STEP_SIZE) {
    myservo.write(pos);
    delay(10);
  }
  myservo.detach();
}


<file_sep>/servo map/master/src/CommandServer.h
#pragma once

#include <SPI.h>
#include <Ethernet.h>

typedef bool (*handler)(EthernetClient client, uint8_t * args, int length);
typedef void (*event)(EthernetClient client);

class CommandServer 
{
	public:
		CommandServer(unsigned int port = 3000);
		bool begin(void);
		void update(void);
		void addCommand(uint8_t id, handler callback);
		void setOnErrorHandler(event callback);
		void setOnConnectHandler(event callback);
		void setOnDisconnectHandler(event callback);
	private:
		handler commands[255];
		event errorHandler;
		event connectHandler;
		event disconnectHandler;
		EthernetServer server;
};<file_sep>/servo map/master/src/CommandServer.cpp
#include "CommandServer.h"

CommandServer::CommandServer(unsigned int port) : server(port) { }

bool CommandServer::begin() {
	server.begin();
}

void CommandServer::update() {
	EthernetClient client = server.available();
	while (client.connected()) {
		if (connectHandler) connectHandler(client);
		
		uint8_t command;		
		if (client.available()) {
			command = client.read();
			
			if (!commands[command]) {
				if (errorHandler) errorHandler(client);
				if (disconnectHandler) disconnectHandler(client);
				client.stop();
				return;
			}
		} else {
			if (errorHandler) errorHandler(client);
			if (disconnectHandler) disconnectHandler(client);
			client.stop();
			return;
		}
		
		uint8_t buffer[client.available()];
		int i = 0;
		while (client.available()) {
		  buffer[i++] = client.read();
		}
		
		commands[command](client, buffer, i);
		if (disconnectHandler) disconnectHandler(client);
		client.stop();
	}
}

void CommandServer::addCommand(uint8_t id, handler callback) {
	commands[id] = callback;
}

void CommandServer::setOnErrorHandler(event callback) {
	errorHandler = callback;
}

void CommandServer::setOnConnectHandler(event callback) {
	connectHandler = callback;
}

void CommandServer::setOnDisconnectHandler(event callback) {
	disconnectHandler = callback;
}<file_sep>/servo map/master/examples/SlagboomServer/SlagboomServer.ino
#include <SPI.h>
#include <Ethernet.h>
#include <CommandServer.h>
#include <VirtualWire.h>

#define PORT 3000
#define STATUS_LED_PIN 7
#define TRANSMITTER_PIN 3
#define RECEIVER_PIN 2

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD };

CommandServer server(PORT);

void setup() {
  Serial.begin(9600);
  
  Serial.println(F("Setting up transmitter"));
  vw_set_tx_pin(TRANSMITTER_PIN);
  vw_set_ptt_inverted(true);
  vw_setup(2000);
  Serial.println(F("Transmitter ready for action"));

  Serial.println(F("Starting server"));
  if (!Ethernet.begin(mac)) {
    Serial.println(F("Failed to obtain DHCP address"));
    Serial.println(F("Foute boel. Tijd om niks te doen."));
    while (true) ;
  }

  server.begin();
  server.setOnErrorHandler(&onError);
  server.setOnConnectHandler(&onConnect);
  server.setOnDisconnectHandler(&onDisconnect);
  server.addCommand('p', &handlePing);
  server.addCommand('a', &handleBroadcast);

  Serial.print(F("Listening to connections on "));
  Serial.print(Ethernet.localIP());
  Serial.print(":");
  Serial.println(PORT);
}

void loop() {
  server.update();
}

void onError(EthernetClient client) {
  Serial.println(F("Error!"));
}

void onConnect(EthernetClient client) {
  Serial.println(F("Incoming connection"));
}

void onDisconnect(EthernetClient client) {
  Serial.println(F("Disconnected"));
}

bool handlePing(EthernetClient client, uint8_t * args, int length) {
  Serial.println(F("Pong!"));
  client.write("pong");
  
  return true;
}

bool handleBroadcast(EthernetClient client, uint8_t * args, int length) {
  vw_send(args, length);
  vw_wait_tx();

  Serial.print(F("Broadcasted: "));
  for (int i = 0; i < length; i++) {
    Serial.println(args[i]);
  }
  
  return true;
}

<file_sep>/servo map/master/extras/tester/main.js
var net = require('net');

var client = new net.Socket();
client.connect(3000, '192.168.1.100', function () {
	console.log('Connected');
	client.write(new Buffer([97, 4, 5]));
});

client.on('data', function (data) {
	console.log('Received: ' + data);
});

client.on('close', function () {
	console.log('Bye!');
});<file_sep>/servo map/master/library.properties
name=CommandServer
version=1.0
author=<NAME> <<EMAIL>>, <NAME> <<EMAIL>>
maintainer=Obe Attema <<EMAIL>>
sentence=Handelt commando's af via TCP.
paragraph=Dingen
category=Communication
url=http://frikandellen.party
architectures=avr
includes=CommandServer.h<file_sep>/servo map/master/master.ino
#include <VirtualWire.h>

const int RF_TRANSMIT_PIN = 7;

void setup() {
  // RF communication
  vw_set_tx_pin(RF_TRANSMIT_PIN);
  vw_set_ptt_inverted(true);
  vw_setup(2000);
}

void loop() {
  // Read from serial for testing purposes
  if (Serial.available() > 0) {
    String msg = Serial.readString();
    if (msg.length() > 0)
      transmit_msg(msg);
  }
}

void transmit_msg(String msg) {
  char buf[msg.length()+1];
  msg.toCharArray(buf, msg.length()+1);
  vw_send((uint8_t *)buf, msg.length()+1);
  vw_wait_tx();
}
