#include <SoftwareSerial.h> // Library for software serial
#define DEBUG true
#define APConnectLED 2
#define CalibrateLED 3
#define StationConnectLED 4
#define newRx 9
#define newTx 10
#define trigPin 5
#define echoPin 6
#define timeout 10000 //in milli-seconds
#define error 1
/*
Esp Tx -> newRx
Esp Rx -> newTx
*/
double thresh;
double empty;
String wifiName = "";
String wifiPswd = "";
SoftwareSerial esp8266(newRx, newTx); // Pins for ESP8266, Rx,Tx
void setup()
{
Serial.begin(9600); // Setting the baudrate for debugging
esp8266.begin(9600); //Start Serial port communication with ESP8266
pinMode(trigPin, OUTPUT); // Setting the trigPin as Output pin
pinMode(echoPin, INPUT); // Setting the echoPin as Input pin
digitalWrite(trigPin, LOW);
pinMode(APConnectLED, OUTPUT); //Set LED pin direction
pinMode(CalibrateLED, OUTPUT); //Set LED pin direction
pinMode(StationConnectLED, OUTPUT); //Set LED pin direction
esp8266.print("AT+RST\r\n");//Reset the module
String response = ""; //Accumulator variable for response
while(1) //Read till the end of response
{
while(esp8266.available()) // Check if ESP is available
{
char c = esp8266.read(); // Read the values of ESP in c variable
if(c!=0) //Neglect NULL
response+=c; // Increase the value of c variable
}
if((response.indexOf("ready\r\n")>0) )// end of reset state
break;
}
//Serial.println(response); //DEBUG purposes
sendData("AT+CWMODE=2\r\n",DEBUG); // This will configure the mode as access point
sendData("AT+CIFSR\r\n",DEBUG); // This command will get the ip address
sendData("AT+CIPMUX=1\r\n",DEBUG); // This will configure the esp for multiple connections
sendData("AT+CIPSERVER=1,80\r\n",DEBUG); // This command will turn on the server on port 80
}
/* This Particular Function is used for Repeated Execution of the Circuit until Specified. */
int state = -1;
void loop()
{
if(esp8266.available() && state != 6)
{
String response = "";
while(1)
{
while(esp8266.available()) // Check if ESP is available
{
char c = esp8266.read(); // Read the values of ESP in c variable
if(c!=0)
response+=c; // Increase the value of c variable
}
if((response.indexOf("\n")>0) )//&& !found)
break;
}
Serial.println("response is:");
Serial.print(response);
if(response.indexOf("CONNECT")>0)
digitalWrite(APConnectLED, HIGH);
if(response.indexOf("IPD")>0 && (response.indexOf("PSEND")<0))
{
char port = response[response.indexOf("IPD,") + 4];
String request = "";
int start = response.indexOf(':') + 1;
while(response[start] != '\0')
{
request += response[start];
start++;
}
//Serial.print("request is:");
//Serial.println(request);
if(request.equals("mac\r\n"))
state = 1;
else if(request.equals("ok\r\n"))
state = 2;
else if(request.equals("empty\r\n"))
state = 3;
else
{
state = 4;
String threshString = request;
int index = threshString.indexOf("threshold");
char c = request[index + 10];
//Serial.print(request[index + 10]);
//Serial.println(request[index + 11]);
thresh = (c - 48) * 10;
c = request[index + 11];
thresh += c - 48;
}
//Serial.print("State is:");
//Serial.println(state);
//Serial.print("Req was: ");
//Serial.println(request);
switch(state)
{
case 1:
{
//Serial.println("Fetching MAC");
esp8266.print("AT+CIFSR\r\n");
String macData = "";
while(1)
{
while(esp8266.available()) // Check if ESP is available
{
char c = esp8266.read(); // Read the values of ESP in c variable
if(c!=0)
macData+=c; // Increase the value of c variable
}
if((macData.indexOf("OK\r\n")>0) )//&& !found)
break;
}
String mac = "";
int start = macData.indexOf("APMAC,") + 7;
while(macData[start] != '"')
{
mac += macData[start];
start++;
}
String msg = "";
msg += "AT+CIPSEND=";
msg += port;
msg += ',';
msg += mac.length();
msg += "\r\n";
sendData(msg,DEBUG);
sendData(mac,DEBUG);
//Serial.print("mac is:");
//Serial.println(mac);
//Serial.println("Sent");
break;
}
case 2:
{
//Serial.println("Got ok");
digitalWrite(CalibrateLED, HIGH);
break;
}
case 3:
{
//Serial.println("Got empty cal");
empty = calcDist();
digitalWrite(CalibrateLED, LOW);
delay(20);
digitalWrite(CalibrateLED, HIGH);
delay(20);
digitalWrite(CalibrateLED, LOW);
delay(20);
digitalWrite(CalibrateLED, HIGH);
String CIP = "AT+CIPSEND=";
CIP += port;
CIP += ",";
CIP += "2\r\n";
sendData(CIP,DEBUG);
sendData("ok",DEBUG);
break;
}
case 4:
{
//Serial.println("Got threshold");
//Serial.println(empty);
thresh = (empty*thresh)/100;
//Serial.println(thresh);
digitalWrite(CalibrateLED, LOW);
String CIP = "AT+CIPSEND=";
CIP += port;
CIP += ",";
CIP += "2\r\n";
sendData(CIP,DEBUG);
sendData("ok",DEBUG);
state = 5;
//Serial.println("SSID req");
CIP = "AT+CIPSEND=";
CIP += port;
CIP += ",";
CIP += "12\r\n";
sendData(CIP,DEBUG);
sendData("Give details",DEBUG);
String details = "";
while(1)
{
while(esp8266.available()) // Check if ESP is available
{
char c = esp8266.read(); // Read the values of ESP in c variable
if(c!=0)
details+=c; // Increase the value of c variable
}
if(details.indexOf(";")>0)
break;
}
//Serial.print("response is:");
//Serial.println(details);
int start = details.indexOf(":")+ 1;
//Serial.print(start);
//Serial.println(details[start]);
//while(1);
char c = details[start];
while(c != ',')
{
//Serial.println(details[start]);
c = details[start];
if(c != ',')
wifiName += c;
start++;
}
c = details[start];
while(c != ';')
{
c = details[start];
if(c != ';')
wifiPswd += c;
start++;
}
state = 6;
CIP = "AT+CIPSEND=";
CIP += port;
CIP += ",";
CIP += "2\r\n";
sendData(CIP,DEBUG);
sendData("ok",DEBUG);
CIP = "AT+CIPCLOSE=";
CIP += port;
CIP += "\r\n";
sendData(CIP, DEBUG);
break;
}
}
}
//Serial.print("State is: ");
//Serial.print(state);
}
if(state == 6)
{
digitalWrite(APConnectLED, LOW);
digitalWrite(CalibrateLED, LOW);
Serial.println("PAGE TWO");
Serial.println(wifiName);
Serial.println(wifiPswd);
sendData("AT+CWMODE=1\r\n", DEBUG);
String JAP = "AT+CWJAP=";
JAP += '"';
JAP += wifiName;
JAP += '"';
JAP += ",";
JAP += '"';
JAP += wifiPswd;
JAP += '"';
JAP += "\r\n";
sendData(JAP, DEBUG);
sendData("AT+CIPMUX=1\r\n", DEBUG);
sendData("AT+CIPSERVER=1,80\r\n", DEBUG);
//Serial.println("Server up");
digitalWrite(StationConnectLED, HIGH);
double next_dist, dist;
next_dist = calcDist();
while(next_dist > empty)
next_dist = calcDist();
dist = next_dist;
long int t = millis();
while(1)
{
if(esp8266.available())
{
Serial.println("Available");
String response = "";
while(1) //Read till the end of response
{
while(esp8266.available()) // Check if ESP is available
{
char c = esp8266.read(); // Read the values of ESP in c variable
if(c!=0) //Neglect NULL
response+=c; // Increase the value of c variable
}
if((response.indexOf("\n")>0) )// end of reset state
break;
}
Serial.println(response);
if(response.indexOf("IPD"))
{
char port = response[0];
Serial.println(port);
if((millis() - t)> timeout)
dist = next_dist;
String data = "AT+CIPSEND=";
data += port;
data += ",";
data += "1";
data += "\r\n";
sendData(data, true);
if( dist > thresh)
sendData("1", true);
else
sendData("0", true);
data = "AT+CIPCLOSE=";
data += port;
data += "\r\n";
sendData(data, true);
}
}
else
{
Serial.println("No req");
double temp = calcDist();
if(temp <= empty)
{
double delta = temp - dist;
if((temp >= error) && ((-1 * error) >= temp))
{
next_dist = temp;
t = millis();
}
}
}
}
}
}
bool sendData(String command, boolean debug)
{
String response = ""; // Initialize response
esp8266.print(command); // Print the command
long int time = millis();
while(1)
{
while(esp8266.available()) // Check if ESP is available
{
char c = esp8266.read(); // Read the values of ESP in c variable
if(c!=0)
response+=c; // Increase the value of c variable
}
if((response.indexOf("ERROR")>0) )//&& !found)
return false;
if((response.indexOf("OK\r\n")>0) || (response.indexOf(">")>0) )//&& !found)
break;
}
if(debug)
{
Serial.print(response); // Print the Response
}
return true; // Return response
}
double calcDist()
{
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//return (pulseIn(echoPin, HIGH);/2) / 29.1;
return 50.0;
}
#include <Servo.h>
#define leftArm 3
#define rightArm 5
#define leftBack 6
#define rightBack 9
#define motorA 2
#define motorB 4
#define backRecline 7
#define frontRecline 8
#define longSitting 10
#define backSensor 11
#define seatSensor 12
#define reclineSensor 13
#define reclineBackTimeout 10000
#define reclineFrontTimeout 10000
#define sittingTimeout 30000
#define windTime 1600
#define unwindTime 1400
#define slideTime 2800
#define armTime 10000
#define relaxTime 10000
Servo left;
Servo right;
Servo rBack;
Servo lBack;
long reclineBackTime = millis();
long sittingTime = millis();
long reclineFrontTime = millis();
void setup()
{
Serial.begin(9600);
left.attach(leftArm);
right.attach(rightArm);
rBack.attach(leftBack);
lBack.attach(rightBack);
digitalWrite(motorA, OUTPUT);
digitalWrite(motorB, OUTPUT);
digitalWrite(backRecline, OUTPUT);
digitalWrite(frontRecline, OUTPUT);
digitalWrite(longSitting, OUTPUT);
digitalWrite(backSensor, INPUT);
digitalWrite(reclineSensor, INPUT);
digitalWrite(seatSensor, INPUT);
//Default states
lBack.write(0);
rBack.write(0);
left.write(180);
right.write(0);
}
void loop()
{
delay(10);
Serial.print(millis());
Serial.print(" ");
Serial.print(digitalRead(backSensor));
Serial.print(":");
Serial.print(reclineFrontTime);
Serial.print(" ");
Serial.print(digitalRead(reclineSensor));
Serial.print(":");
Serial.print(reclineBackTime);
Serial.print(" ");
Serial.print(digitalRead(seatSensor));
Serial.print(":");
Serial.println(sittingTime);
//Apply NOT-----------------------------------
//Front recline
if(!digitalRead(backSensor)) //Update if in correct posture //front recline -> 1
reclineFrontTime = millis();
//---------------------------------------------
//Back recline
if(digitalRead(reclineSensor)) //Update if not reclining //recline -> 0
reclineBackTime = millis();
//Sitting
if(digitalRead(seatSensor)) //Update if not sitting //Sitting -> 0
sittingTime = millis();
//Front recline
if((millis() - reclineFrontTime) >= reclineFrontTimeout)
{
//ON
Serial.print(millis());
Serial.print(" ");
Serial.print(reclineFrontTime);
Serial.print(" ");
Serial.println("front TO");
digitalWrite(frontRecline, HIGH);
left.write(90);
right.write(90);
delay(armTime);
left.write(180);
right.write(0);
Serial.print("Relaxing...");
delay(relaxTime);
Serial.println("Done!");
reclineBackTime = millis();
reclineFrontTime = millis();
sittingTime = millis();
}
else
{
digitalWrite(frontRecline, LOW);
left.write(180);
right.write(0);
}
//Back recline
if((millis() - reclineBackTime) >= reclineBackTimeout)
{
//
Serial.print(millis());
Serial.print(" ");
Serial.print(reclineBackTime);
Serial.print(" ");
Serial.println("back TO");
digitalWrite(backRecline, HIGH);
lBack.write(90);
rBack.write(70);
Serial.print("Relaxing...");
delay(relaxTime);
Serial.println("Done!");
reclineBackTime = millis();
reclineFrontTime = millis();
sittingTime = millis();
}
else
{
digitalWrite(backRecline, LOW);
lBack.write(0);
rBack.write(0);
}
//Long sitting
if((millis() - sittingTime) >= sittingTimeout)
{
//ON
Serial.print(millis());
Serial.print(" ");
Serial.print(sittingTime);
Serial.print(" ");
Serial.println("sit TO");
digitalWrite(longSitting, HIGH);
digitalWrite(motorA, HIGH);
digitalWrite(motorB, LOW);
delay(windTime);
digitalWrite(motorA, LOW);
digitalWrite(motorB, LOW);
delay(slideTime);
digitalWrite(motorA, LOW);
digitalWrite(motorB, HIGH);
delay(unwindTime);
digitalWrite(motorA, LOW);
digitalWrite(motorB, LOW);
Serial.print("Relaxing...");
delay(relaxTime);
Serial.println("Done!");
reclineBackTime = millis();
reclineFrontTime = millis();
sittingTime = millis();
}
else
{
digitalWrite(longSitting, LOW);
digitalWrite(motorA, LOW);
digitalWrite(motorB, LOW);
}
}
package com.example.myapplication2;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.Toast;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
private TelnetClient telnet;
private ArrayList<Node> listNote;
private String myMac;
private String myIP;
private Button refreshButton;
private ListView itemList;
private ArrayAdapter<String> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addButton = findViewById(R.id.add_button);
refreshButton = findViewById(R.id.refresh_button);
itemList = findViewById(R.id.item_listView);
refreshButton.setClickable(false);
telnet = new TelnetClient();
mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
itemList.setAdapter(mAdapter);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new connection().execute();
}
});
refreshButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(myIP==null){
setPermanentConnection();
}
else{
mAdapter.clear();
mAdapter.notifyDataSetChanged();
new checkBox().execute(myIP);
}
}
});
}
private class checkBox extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... arg0) {
try{
telnet.connect(arg0[0], 80);
Log.v("TelnetExample", "Connection Successful");
byte[] b = new byte[1];
telnet.getInputStream().read(b,0,1);
telnet.disconnect();
String s = new String(b, "ISO-8859-1");
if(s.charAt(0) == '1'){
return true;
}
else return false;
}
catch (IOException t){
Log.e("TelnetExample", t.getMessage());
}
return false;
}
protected void onPostExecute(Boolean boo){
if(boo == true){
String item = "coffee";
mAdapter.add(item);
mAdapter.notifyDataSetChanged();
}
}
}
private class connection extends AsyncTask<Object, Integer, Boolean> {
@Override
protected Boolean doInBackground(Object... arg0) {
try{
telnet.connect("192.168.4.1", 80);
Log.v("TelnetExample", "Connection Successful");
return true;
}
catch (IOException t){
Log.e("TelnetExample", t.getMessage());
}
return false;
}
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
new getMac().execute();
}
else{
Toast.makeText(getApplicationContext(), "Connection Error", Toast.LENGTH_SHORT).show();
}
}
}
private class getMac extends AsyncTask<Object, Integer, String> {
@Override
protected String doInBackground(Object... arg0) {
String s = null;
String command = "mac\n";
try{
telnet.getOutputStream().write(command.getBytes());
telnet.getOutputStream().flush();
try{
byte[] b = new byte[17];
telnet.getInputStream().read(b,0,17);
s = new String(b, "ISO-8859-1");
myMac = s;
command = "ok\n";
telnet.getOutputStream().write(command.getBytes());
telnet.getOutputStream().flush();
}
catch (IOException t){
Log.e("TelnetExample", t.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
protected void onPostExecute(String s) {
if(s == null){
Log.e("TelnetExample", "Mac not received");
}
else{
Log.v("TelnetExample", "Mac received: " + s);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Please Empty the Smart Box and Press OK")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new calibrate().execute();
}
});
// Create the AlertDialog object and return it
builder.create();
builder.show();
}
}
}
private class calibrate extends AsyncTask<Object, Integer, Boolean> {
@Override
protected Boolean doInBackground(Object... arg0) {
String s = null;
String command = "empty\n";
try {
telnet.getOutputStream().write(command.getBytes());
telnet.getOutputStream().flush();
try {
byte[] b = new byte[2];
telnet.getInputStream().read(b, 0, 2);
s = new String(String.valueOf(b));
return true;
} catch (IOException t) {
Log.e("TelnetExample", t.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result) {
final NumberPicker numberPicker = new NumberPicker(MainActivity.this);
numberPicker.setMaxValue(99);
numberPicker.setMinValue(10);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setView(numberPicker);
builder.setTitle("Set Threshold");
builder.setMessage("Choose threshold percentage:");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int i = numberPicker.getValue();
System.out.println(i);
new setThreshold().execute(i);
}
});
builder.create();
builder.show();
}
}
}
private class setThreshold extends AsyncTask<Integer, Integer, Boolean> {
@Override
protected Boolean doInBackground(Integer... threshold) {
String s = null;
String command = "threshold " + threshold[0] + "\n";
try{
Log.v("TelnetExample", "setThreshold: " + command);
telnet.getOutputStream().write(command.getBytes());
telnet.getOutputStream().flush();
byte[] b = new byte[14];
telnet.getInputStream().read(b,0,14);
s = Arrays.toString(b);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
if (result) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Enter Wifi SSID and Password, seperated by a comma");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new setWifi().execute(input.getText().toString());
}
});
builder.show();
}
}
}
private class setWifi extends AsyncTask<String, Integer, Boolean> {
@Override
protected Boolean doInBackground(String... arg0) {
String command = arg0[0] + ";\n";
try {
Log.v("Telnet Example", "setWifi: " + arg0[0]);
telnet.getOutputStream().write(command.getBytes());
telnet.getOutputStream().flush();
telnet.disconnect();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
// protected void onPostExecute(Boolean result) {
// new CountDownTimer(10000, 1000) {
// @Override
// public void onTick(long millisUntilFinished) {
//
// }
// public void onFinish() {
// setPermanentConnection();
// }
// }.start();
// }
}
private void setPermanentConnection(){
listNote = new ArrayList<>();
readAddresses();
String ip =listNote.get(0).ip;
new buildArp().execute(ip);
}
private class buildArp extends AsyncTask<String, Boolean, Boolean> {
@Override
protected Boolean doInBackground(String... arg0) {
String ip = arg0[0];
int index = ip.lastIndexOf('.');
String allip = ip.substring(0, index + 1);
System.out.println(allip);
for(int i = 1; i <= 255; i++){
ip = allip + i;
InetAddress in = null;
try {
in = InetAddress.getByName(ip);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
if(in.isReachable(500)) {
String tempMac = null;
byte[] mac = NetworkInterface.getByInetAddress(in).getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int j = 0; j < mac.length; j++) {
sb.append(String.format("%02X%s", mac[j], (j < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
tempMac = sb.toString();
if(myMac.equals(tempMac)){
myIP = ip;
}
Log.v("Telnet","Responde OK: " + ip);
} else {
Log.v("Telnet","No responde: Time out " + ip);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(Boolean b){
Log.v("Telnet", "DONE");
readAddresses();
findIP();
}
}
private void findIP(){
myIP = null;
Log.v("Telnet", "My mac: " + myMac);
for(int i = 0; i < listNote.size(); i++){
Log.v("Telnet", listNote.get(i).ip + " "+ listNote.get(i).mac);
if(myMac.equals(listNote.get(i).mac)){
Log.v("Telnet", "Found");
myIP = listNote.get(i).ip;
}
}
if(myIP == null){
Log.v("Telnet", "Mac not found");
Toast.makeText(getApplicationContext(), "SetUp Failed!!", Toast.LENGTH_SHORT).show();
}
else{
Log.v("Telnet", "MAC found, IP is " + myIP);
Toast.makeText(getApplicationContext(), "SetUp Completed!!", Toast.LENGTH_SHORT).show();
refreshButton.setClickable(true);
}
}
private void readAddresses() {
listNote.clear();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] splitted = line.split(" +");
if (splitted != null && splitted.length >= 4) {
String ip = splitted[0];
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
Node thisNode = new Node(ip, mac);
listNote.add(thisNode);
}
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Node {
String ip;
String mac;
Node(String ip, String mac){
this.ip = ip;
this.mac = mac;
}
@Override
public String toString() {
return ip + " " + mac;
}
}
}