Lab_interaccio/2011/Intact/Test/ArduinoEthernetDHCP_UDP/ArduinoEthernetDHCP_UDP.pde
2025-02-25 21:29:42 +01:00

393 lines
9.5 KiB
Plaintext

// Just a quick demo that basically combines the samples shipping individually within the
// Arduino DHCP, DNS and Bonjour libraries. This sketch will do 3 things:
// 1. Attempt to get network configuration data via DHCP.
// 2. Allow for DNS name resolution via the serial line, using the DNS server from the
// the DHCP lease.
// 3. Announce its IP address on link-local Bonjour as "arduino.local", once an IP has
// been received via DHCP.
//
// For detailed code comments on how everything works, please look at the individual
// sample code shipping with each of the libraries.
#if defined(ARDUINO) && ARDUINO > 18
#include <SPI.h>
#endif
#include <Ethernet.h>
#include <EthernetDHCP.h>
#include <EthernetDNS.h>
#include <Udp.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
#define MESSAGE_SIZE 20
#define ARDUINO_ID 1
static char incomming_message[MESSAGE_SIZE] = { // Message template
'/', 'a', 'r', 'd',
'/', B0,
'/', 'o', 'p',
'/', B0, '\0',
',', 'i', '\0', '\0',
B0, B0, B0, B0
};
static int incomming_value = 0;
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte server[] = {
0,0,0,0 }; // TEMPORAL SERVER
unsigned int localPort = 8888; // local port to listen on
// the next two variables are set when a packet is received
byte remoteIp[4]; // holds received packet's originating IP
unsigned int remotePort; // holds received packet's originating port
//byte remoteIp[4] = {
// 172,26,0,46 }; // holds received packet's originating IP
//unsigned int remotePort = 8889; // holds received packet's originating port
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged!!!!"; // a string to send back
char serverHostname[] = "kn.sofiethic.org";
const char* ip_to_str(const uint8_t*);
boolean dhcpReady = 0;
boolean flagConnect = 0;
void setup()
{
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
DHCP_begin();
DNS_resolve();
Udp.begin(localPort);
}
Client client(server, 80);
void loop()
{
EthernetDHCP.maintain();
int packetSize = Udp.available(); // note that this includes the UDP header
if(packetSize)
{
packetSize = packetSize - 8; // subtract the 8 byte header
Serial.print("Received packet of size: ");
Serial.println(packetSize);
// read the packet into packetBufffer and get the senders IP addr and port number
Udp.readPacket(packetBuffer,UDP_TX_PACKET_MAX_SIZE, remoteIp, remotePort);
Serial.print("Contents: ");
Serial.println(packetBuffer);
//Udp.sendPacket( ReplyBuffer, remoteIp, 8889);
//Udp.sendPacket( packetBuffer, remoteIp, 8889);
char osc_packet[32] =
{
'/','a','r','d','u','i','n','o','/','s','1',0,',','i',0,0,0,0,0,100 };
Udp.sendPacket( osc_packet , remoteIp, 8889);
/*
// Broadcast the value
Serial.write("/ard/"); //OSC Address Pattern
Serial.print(BAHIA_ID, DEC);
Serial.write('/');
Serial.print(pin_n, DEC);
Serial.write("\0\0\0\0");
Serial.write(",i\0\0"); //OSC Type Tag String
Serial.write("\0\0"); //OSC Arguments
Serial.write(reported_value);
// For debug only
Serial.println("");
*/
}
delay(10);
}
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
void dhcp()
{
static DhcpState prevState = DhcpStateNone;
static unsigned long prevTime = 0;
DhcpState state = EthernetDHCP.poll();
if (prevState != state) {
Serial.println();
switch (state) {
case DhcpStateDiscovering:
Serial.print("Discovering servers.");
dhcpReady=0;
break;
case DhcpStateRequesting:
Serial.print("Requesting lease.");
dhcpReady=0;
break;
case DhcpStateRenewing:
Serial.print("Renewing lease.");
dhcpReady=0;
break;
case DhcpStateLeased:
{
Serial.println("Obtained lease!");
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
Serial.println('\n');
EthernetDNS.setDNSServer(dnsAddr);
//////////////////////////////////////////////////////////////
// DETECCION DE LA IP DEL SERVIDOR
//////////////////////////////////////////////////////////////
Serial.print("Resolving ");
Serial.print(serverHostname);
Serial.print("...");
//byte ServerIpAddr[4];
//DNSError err = EthernetDNS.sendDNSQuery("kn.sofiethic.org");
DNSError err = EthernetDNS.sendDNSQuery(serverHostname);
if (DNSSuccess == err) {
do {
err = EthernetDNS.pollDNSReply(server);
if (DNSTryLater == err) {
delay(20);
Serial.print(".");
}
}
while (DNSTryLater == err);
}
Serial.println();
if (DNSSuccess == err) {
Serial.print("The IP address is ");
Serial.print(ip_to_str(server));
Serial.println(".");
dhcpReady=1;
}
else if (DNSTimedOut == err) {
Serial.println("Timed out.");
}
else if (DNSNotFound == err) {
Serial.println("Does not exist.");
}
else {
Serial.print("Failed with error code ");
Serial.print((int)err, DEC);
Serial.println(".");
}
break;
}
}
}
else if (state != DhcpStateLeased && millis() - prevTime > 300) {
prevTime = millis();
Serial.print('.');
}
else if (state == DhcpStateLeased) {
dhcpReady = 1;
}
prevState = state;
}
void DHCP_begin()
{
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
}
void DNS_resolve()
{
//////////////////////////////////////////////////////////////
// DETECCION DE LA IP DEL SERVIDOR
//////////////////////////////////////////////////////////////
Serial.print("Resolving ");
Serial.print(serverHostname);
Serial.print("...");
//byte ServerIpAddr[4];
//DNSError err = EthernetDNS.sendDNSQuery("kn.sofiethic.org");
DNSError err = EthernetDNS.sendDNSQuery(serverHostname);
if (DNSSuccess == err) {
do {
err = EthernetDNS.pollDNSReply(server);
if (DNSTryLater == err) {
delay(20);
Serial.print(".");
}
}
while (DNSTryLater == err);
}
Serial.println();
if (DNSSuccess == err) {
Serial.print("The IP address is ");
Serial.print(ip_to_str(server));
Serial.println(".");
dhcpReady=1;
}
else if (DNSTimedOut == err) {
Serial.println("Timed out.");
}
else if (DNSNotFound == err) {
Serial.println("Does not exist.");
}
else {
Serial.print("Failed with error code ");
Serial.print((int)err, DEC);
Serial.println(".");
}
}
// Check Incomming Messages
void checkIncomming() {
// Check for new configuration messages
if(Serial.available() >= MESSAGE_SIZE) {
// Get the message
for(byte i = 0; i < MESSAGE_SIZE; i++) {
incomming_message[i] = Serial.read();
}
// Check OSC Message
if(incomming_message[0] != '/') {
return;
}
// Check namespace
if(
(incomming_message[1] != 'a') ||
(incomming_message[2] != 'r') ||
(incomming_message[3] != 'd')
) {
return;
}
// Check id
if(incomming_message[5] != ARDUINO_ID) {
return;
}
// Check instruction type and perform action
char instruction_type = incomming_message[7];
byte pin_n = incomming_message[10];
int argument = int(word(byte(incomming_message[18]), byte(incomming_message[19])));
switch(instruction_type) {
case 'w': // Write value
//instructionWrite(pin_n, argument);
break;
case 'e': // Enable/disable sensor
//instructionEnable(pin_n, argument == 0 ? true : false);
break;
case 'c': // Configure pin funtion
//instructionConfigure(pin_n, argument);
break;
default:
return; // Unknown instruction, ignoring
}
}// If not enough bytes in buffer, then do nothing
}