Hi, I have this working code:
Every 30s it check state of inputs and send result to http server. Communication is secured by sha1hmac hash.
#include <sha1.h>
#include <EtherCard.h>
static byte mymac[] = { 0x00, 0x00, 0x6C, 0x01, 0x02, 0x03 };
char website[] PROGMEM = "server.example.net";
const byte hmacKey[] PROGMEM = { 'p', 'a', 's', 's', '\n' };
byte Ethernet::buffer[800];
static uint32_t timer; // http://mbed.org/handbook/C-Data-Types (0 .. 4,294,967,295)
const int inputButton1 = 5;
const int inputButton2 = 7;
const int output1 = 9;
const int output2 = 10;
static void response_callback (byte status, word off, word len) {
Serial.print((const char*) Ethernet::buffer + off + 207);
}
long previousMillis = 0;
long interval = 30000; // [ms]
void setup () {
Serial.begin(9600);
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println( "Failed to access Ethernet controller");
if (!ether.dhcpSetup())
Serial.println("DHCP failed");
if (!ether.dnsLookup(website))
Serial.println("DNS failed");
pinMode(inputButton1, INPUT);
pinMode(inputButton2, INPUT);
pinMode(output1, OUTPUT);
pinMode(output2, OUTPUT);
}
void loop() {
ether.packetLoop(ether.packetReceive());
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
previousMillis = currentMillis;
int buttonState1 = digitalRead(inputButton1);
int buttonState2 = digitalRead(inputButton1);
char stringToSend[70];
char tmp[41];
memset(tmp, 0, 41);
sprintf(stringToSend, "?btn1=%s&btn2=%s&sha1=",
digitalRead(inputButton1) ? "ON" : "OFF",
digitalRead(inputButton2) ? "ON" : "OFF"
);
Sha1.initHmac(hmacKey,(sizeof(hmacKey)-1) );
Sha1.print(stringToSend);
uint8_t *hash = Sha1.resultHmac();
for (int i=0; i<20; i++) {
tmp[i*2] = "0123456789abcdef"[hash[i]>>4];
tmp[i*2+1] = "0123456789abcdef"[hash[i]&0xf];
}
Serial.println(stringToSend);
strcat(stringToSend, tmp);
Serial.println(stringToSend);
if (millis() > timer) {
timer = millis() + 5000;
ether.browseUrl(PSTR("/arduino.php"), stringToSend, website, response_callback);
}
}
}
# cat /var/log/apache2/access.log
192.168.1.44 - - [01/Sep/2013:17:11:21 +0200] "GET /arduino.php?btn1=OFF&btn2=ON&sha1=a5b5da1c91aa2ea0c7e630db6c8e3175058e907f HTTP/1.0" 200 211 "-" "-"
Now I need control outputs. On server I have php script. Should I send response from server as header or as text? Or differently?
<?php
header('out1: ON');
header('out1: OFF');
header('sha1: a5b5da1c91aa2ea0c7e630db6c8e3175058e907f');
?>
<?php
header('outs: 01'); // out1=off out2=on
header('sha1: a5b5da1c91aa2ea0c7e630db6c8e3175058e907f');
?>
<?php
echo 'out1: ON\n';
echo 'out1: OFF\n';
echo 'sha1: a5b5da1c91aa2ea0c7e630db6c8e3175058e907f\n';
?>
On Arduino, what is better way to parse response and set variables?
Thank you for your help!