Skip to content

Instantly share code, notes, and snippets.

@gutugutu3030
Created February 2, 2017 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gutugutu3030/e3db82bb5cffbe94db5c96f05162149b to your computer and use it in GitHub Desktop.
Save gutugutu3030/e3db82bb5cffbe94db5c96f05162149b to your computer and use it in GitHub Desktop.
//use StandardFirmata
String port="COM8";
int motorPin=12;
String ip="127.0.0.1";
//---------------------------------
import processing.serial.*;
import cc.arduino.*;
import java.io.IOException;
import java.net.InetAddress;
import java.lang.reflect.*;
Arduino arduino;
void setup() {
arduino = new Arduino(this, port, 57600);
arduino.pinMode(motorPin, Arduino.OUTPUT);
NetworkListenner nl=new NetworkListenner(this,ip);
nl.setConnectedListenner("connectedNetwork");
nl.setDisconnectedListenner("disconnectedNetwork");
nl.start();
}
void draw() {
}
void connectedNetwork() {
arduino.digitalWrite(motorPin,Arduino.LOW);
}
void disconnectedNetwork() {
arduino.digitalWrite(motorPin,Arduino.HIGH);
}
class NetworkListenner extends Thread {
Object parent;
Method connected, disconnected;
String port;
NetworkListenner(Object parent,String port) {
this.parent=parent;
this.port=port;
}
void setConnectedListenner(String name) {
try {
connected=parent.getClass().getMethod(name, null);
}
catch(Exception e) {
e.printStackTrace();
}
}
void setDisconnectedListenner(String name) {
try {
disconnected=parent.getClass().getMethod(name, null);
}
catch(Exception e) {
e.printStackTrace();
}
}
void run() {
boolean oldData;
while (true) {
try {
oldData=isOnline();
break;
}
catch(Exception e) {
try {
Thread.sleep(10);
}
catch(Exception e1) {
e1.printStackTrace();
}
}
}
while (true) {
try {
boolean newData=isOnline();
//println(newData);
if (newData!=oldData) {
Method m=(newData?connected:disconnected);
m.setAccessible(true);
m.invoke(parent, null);
}
Thread.sleep(1);
oldData=newData;
}
catch(Exception e) {
e.printStackTrace();
}
}
}
boolean isOnline() throws Exception {
InetAddress inetAddress = InetAddress.getByName(port);
boolean pingdata = inetAddress.isReachable( 1200 );
return pingdata;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment