2014-01-22 9 views
3

У меня есть проект в школе, который состоит из RC-автомобиля, который управляется через WiFi. Он работает отлично в течение нескольких секунд, но затем он просто останавливает соединение и пытается снова подключиться. Дело в том, что если я делаю автомобиль, который полагается на эту нестабильную связь, это может привести к несчастным случаям. Либо к себе, либо к человеку.Поддержание связи между программой Arduino и Java

Возможно, я что-то не так? Мой вопрос: как я постоянно поддерживаю это соединение? Вот моя программа до сих пор:

Arduino Клиент:

#include <SPI.h> 
#include <WiFi.h> 

int status = WL_IDLE_STATUS; 
char ssid[] = "mynet"; 
char pass[] = "password"; 

IPAddress remoteIp(192,168,80,165); 
int port = 37899; 

String message = ""; 

WiFiClient client; 

void setup() 
{ 
    // start the serial for debugging 
    Serial.begin(9600); 
    pinMode(9, OUTPUT); 
    digitalWrite(9, LOW); 

    //check if the wifi shield is present 
    if(WiFi.status() == WL_NO_SHIELD){ 
     Serial.println("WiFi shield not present! Press reset to try again."); 
     while(true); //stops the program 
    } 

    connectWiFi(); 
    printWifiStatus(); 
    connectClient(3); 
} 

void loop(){ 

    if(client){ 
     if(client.available()){ 

      char c = client.read(); 

      if(c != '\n'){ 
       message += c; 
      } 
      else{ 
       Serial.println("Received message: "+message); 
       checkMessage(); 
       sendMessage(message); 
       message = ""; 
      } 
     } 
    } 
} 

void printWifiStatus() { 
    // print the SSID of the network you're attached to: 
    Serial.print("SSID: "); 
    Serial.println(WiFi.SSID()); 

    // print your WiFi shield's IP address: 
    IPAddress ip = WiFi.localIP(); 
    Serial.print("IP Address: "); 
    Serial.println(ip); 
} 

void connectWiFi(){ 

    if(status != WL_CONNECTED){ 
     while(status != WL_CONNECTED){ 

      Serial.print("Attempting connection to network..."); 

      status = WiFi.begin(ssid, pass); 
      delay(3000); 

      if(status == WL_CONNECTED){ 
       Serial.println(" SUCSESS"); 
      } 
      else{ 
       Serial.println(" FAILED"); 
       delay(3000); 
       connectWiFi(); 
      } 
     } 
    } 
} 

void connectClient(int retries){ 

    //Attempt connection to server 

    if(retries <= 0){ 
     Serial.println("FAILED"); 
     Serial.println("Connection to server failed."); 
     while(true); 
    } 

    Serial.print("Attempting conenction to server... "); 

    if(client.connect(remoteIp, port)){ 
     Serial.println("SUCSESS"); 
     sendMessage("Hello server!"); 
    } 
    else if(retries > 0){ 
     Serial.println("FAILED"); 
     connectClient(retries - 1); 
    } 

} 

void checkMessage(){ 

    if(message == "on"){ 
     digitalWrite(9, HIGH); 
    } 

    if(message == "off"){ 
     digitalWrite(9, LOW); 
    } 
} 

void sendMessage(String toSend){ 

    if(client){ 
     client.println(toSend+'\n'); 
     client.flush(); 
     Serial.println("Sendt message: "+toSend); 
    } 
    else{ 
     Serial.println("Could not send message; Not connected."); 
    } 
} 

Java Server:

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Car_Client extends JFrame { 

    private JTextField userText; 
    private JTextArea chatWindow; 

    private static final int serverPort = 37899; 

    private ServerSocket server; 
    private Socket connection; 
    private BufferedWriter output; 
    private BufferedReader input; 

    private String message = ""; 

    public Car_Client() { 

     userText = new JTextField(); 
     userText.setEditable(false); 
     userText.addActionListener(
       new ActionListener() { 
        public void actionPerformed(ActionEvent event) { 
         sendMessage(event.getActionCommand()); 
         userText.setText(""); 
        } 
       } 
     ); 
     add(userText, BorderLayout.NORTH); 
     chatWindow = new JTextArea(); 
     add(new JScrollPane(chatWindow), BorderLayout.CENTER); 
     setSize(400, 300); 
     setVisible(true); 

    } 

    public void startRunning() { 
     try { 

      server = new ServerSocket(serverPort, 100); 
      while (true) { 
       try { 
        waitForConnection(); 
        setupStreams(); 
        whileConnected(); 
       } catch (EOFException eofException) { 
        showMessage("Client terminated connection"); 
       } catch (IOException ioException) { 
        showMessage("Could not connect..."); 
       } finally { 
        closeStreams(); 
       } 
      } 

     } catch (IOException ioException) { 
      ioException.printStackTrace(); 
     } 

    } 

    private void waitForConnection() throws IOException { 

     showMessage("Waiting for someone to connect..."); 
     connection = server.accept(); //once someone asks to connect, it accepts the connection to the socket this gets repeated fast 
     showMessage("Now connected to " + connection.getInetAddress().getHostName()); //shows IP adress of client 

    } 

    private void setupStreams() throws IOException { 

     showMessage("creating streams..."); 
     output = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); 
     output.flush(); 
     input = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     showMessage("Streams are setup!"); 

    } 

    private void whileConnected() throws IOException { 

     ableToType(true); //makes the user able to type 

     do { 

      char x = (char) input.read(); 
      while (x != '\n') { 
       message += x; 
       x = (char) input.read(); 
      } 
      showMessage(message); 
      message = ""; 

     } while (!message.equals("END")); //if the user has not disconnected, by sending "END" 

    } 

    private void closeStreams() { 

     ableToType(false); 

     showMessage("Closing streams..."); 
     try { 
      output.close(); 
      input.close(); 
      connection.close(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 

    private void sendMessage(String message) { 
     try { 
      output.write(message + '\n'); 
      output.flush(); 
      showMessage("Sent: " + message); 
     } catch (IOException ex) { 
      chatWindow.append("\nSomething messed up whilst sending messages..."); 
     } 

    } 

    private void showMessage(final String message) { 
     SwingUtilities.invokeLater(
       new Runnable() { 
        public void run() { 
         chatWindow.append('\n' + message); 
        } 
       } 
     ); 

    } 

    private void ableToType(final boolean tof) { 
     SwingUtilities.invokeLater(
       new Runnable() { 
        public void run() { 
         userText.setEditable(tof); 
        } 
       } 
     ); 
    } 

} 

Ура!
-kad

+0

Возможно, вы могли бы вставить свой собственный код - было бы полезно ... –

+0

Прошу прощения, но у меня нет кода, потому что мой жесткий диск сломался, и я потерял свои файлы. Я действительно ищу больше примеров того, как правильно общаться между java и arduino. В то же время я попытаюсь переделать свою программу:/ – Kad

+0

SO не предназначен для публикации примеров на основе описания проблемы, но для устранения возможных проблем, которые могут иметь ваш код. Вы, вероятно, захотите пойти куда-нибудь еще (google?), Чтобы получить помощь. – luanjot

ответ

1

Я решил, что сделал это так, чтобы Arduino отправлял данные в программу Java каждые 15 секунд. Все, что потребовалось было несколько строк по программе Arduino:

переменные: функция

long lastSendt; 

Loop: функция

void loop(){ 

    if(client){ 

     if(millis() >= (lastSendt + 15000)){ 
      sendCharacter('*') 
     } 

     if(client.available()){ 

      char c = client.read(); 

      if(c != '\n'){ 
       message += c; 
      } 
      else{ 
       Serial.println("Received message: "+message); 
       checkMessage(); 
       sendMessage(message); 
       message = ""; 
      } 
     } 
    } 
} 

sendCharacter:

void sendCharacter(char toSend){ 

    if(client){ 
     client.println(toSend){ 
     lastSendt = millis(); 
    }else{ 
     Serial.println("Could not send character!"); 
    } 
} 
Смежные вопросы