mardi 2 juin 2015

Send data from Arduino to a Web Server through Ethenet shield

I have an Arduino with an Ethernet shield, it connected to the same hub with my computer. I tried to let this Arduino send some HTTP Request Get to my web server written in Python.

I fixed the IP for my computer at 192.168.1.2 and the Arduino will get its IP automatically through a DHCP server or if it fails to get a new IP, it would get a static IP.

Web server part: I tested my Web server and it worked as whenever I called that request, it would save for me the record into the database(I am using mongodb as my database)

Arduino part: I tested and I saw it could connect to my DHCP server, not my web server as it sent a Request and get a Response from the DHCP server.

How to config so my DHCP server can transfer Arduino's request directly to my web server? Or other solution like let my Arduino send data directly to my web server?

Small code of my web server:

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

from bottle import *
from pymongo import *
import datetime


@route('/hello')
def hello():
    return "Hello World!"


@get('/receiver', method = 'GET')
def receiver():
    # Get data from http request and save it into db
    print 'Inserting data'
    receiver_id = request.query.getall('id')
    broadcaster_id = request.query.getall('bid')
    signal_strength = request.query.getall('s')
    client = MongoClient('localhost', 27017)
    db = client['arduino']
    collection = db['arduino']
    record = {'receiver_id':receiver_id,
              'broadcaster_id':broadcaster_id,
              'signal_strength':signal_strength,
              'date': datetime.datetime.utcnow()}
    print record
    collection.insert_one(record)
    return template('Record: {{record}}', record = record)

@get('/db')
def db():
    # Display all data
    client = MongoClient('localhost', 27017)
    db = client['arduino']
    collection = db['arduino']
    for record in collection.find():
        return template('<div>{{receiver_id}}</div>',receiver_id = record)

@error(404)
def error404(error):
    return 'Something wrong, try again!'

run(host='localhost', port=80, debug=True)

Small code of my Arduino program:

 /*
Connect to Ethernet Using DHCP
Author:- Embedded Laboratory
*/

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

#define ETH_CS    10
#define SD_CS  4

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {0xCA,0xFE,0x00,0x00,0x00,0x15};

IPAddress ip(192,168,1,15);

IPAddress server(192,168,1,2); 
//char server[] = "localhost";
EthernetClient client;

void setup()
{
  Serial.begin(9600);
  Serial.println("Starting Ethernet Connection");
  pinMode(ETH_CS,OUTPUT);
  pinMode(SD_CS,OUTPUT);
  digitalWrite(ETH_CS,LOW); // Select the Ethernet Module.
  digitalWrite(SD_CS,HIGH); // De-Select the internal SD Card
  if (Ethernet.begin(mac) == 0)  // Start in DHCP Mode
  {
    Serial.println("Failed to configure Ethernet using DHCP, using Static Mode");
    // If DHCP Mode failed, start in Static Mode
    Ethernet.begin(mac, ip);
  }

  Serial.print("My IP address: ");

  for (byte thisByte = 0; thisByte < 4; thisByte++)
  {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print("."); 
  }
  Serial.println();

  // give the Ethernet shield a second to initialize:
  delay(1000);
  Serial.println("connecting...");
  for(int i =1; i < 6; i++){
    Serial.print("Test number ");
    Serial.println(i);
    // if you get a connection, report back via serial:
    if (client.connect(server, 80))
    {
      Serial.println("connected");
      // Make a HTTP request:      
      //client.println("GET /receiver?id=4&bid=3&s=70 HTTP/1.1");
      client.println("GET / HTTP/1.1");
      client.println("Host: localhost");
      client.println("Connection: close");
      client.println();
      delay(1000);
    }
    else
    {
      // if you didn't get a connection to the server:
      Serial.println("connection failed");
    }    
  } 

}

void loop()
{
  // if there are incoming bytes available 
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    client.write(c);
    Serial.print("Read the client:");
    Serial.print(c);
  }

  // as long as there are bytes in the serial queue,
  // read them and send them out the socket if it's open:
  while (Serial.available() > 0)
  {
    char inChar = Serial.read();
    if (client.connected())
    {
      client.print(inChar); 
    }
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    // do nothing:
    while(true);
  }
}




Aucun commentaire:

Enregistrer un commentaire