I'm making a smart interphone.
If button(raspberryPi) is pressed, smartphone(app) rings.
So I need to Socket Communication.
Because I don't know socket... , I copied it.
I should use Java (android), I found Java pi4v library.
I have server(RaspberryPi) code, client(Android) code, and button code.
But, they're respective and I don't know how to combine them.
I want to send any signal pi to android using button!
Here is Server code.
import java.io.*;
import java.net.*;
public class JavaSocketServer{
public static void main(String[] args){
try{
int portNumber = 10001;
System.out.println("Start Server...");
ServerSocket aServerSocket = new ServerSocket(portNumber);
System.out.println("Listening at port " + portNumber + ",,,");
while(true){
Socket sock = aServerSocket.accept();
InetAddress clientHost = sock.getLocalAddress();
int clientPort = sock.getPort();
System.out.println("A client connected.");
System.out.println("(host : " + clientHost + ", port : " + clientPort);
ObjectInputStream instream = new ObjectInputStream(sock.getInputStream());
Object obj = instream.readObject();
System.out.println("Input : " + obj);
ObjectOutputStream outstream = new ObjectOutputStream(sock.getOutputStream());
outstream.writeObject(obj + " from Server.");
outstream.flush();
sock.close();
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
Here is Android Client Code.
package org.techtown.socket;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
/**
*
*
* #author Mike
*
*/
public class MainActivity extends AppCompatActivity {
EditText input01;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input01 = (EditText) findViewById(R.id.input01);
// 버튼 이벤트 처리
Button button01 = (Button) findViewById(R.id.button01);
button01.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String addr = input01.getText().toString().trim();
ConnectThread thread = new ConnectThread(addr);
thread.start();
}
});
}
/**
* 소켓 연결할 스레드 정의
*/
class ConnectThread extends Thread {
String hostname;
public ConnectThread(String addr) {
hostname = addr;
}
public void run() {
try {
int port = 11001;
Socket sock = new Socket(hostname, port);
ObjectOutputStream outstream = new ObjectOutputStream(sock.getOutputStream());
outstream.writeObject("Hello AndroidTown on Android");
outstream.flush();
ObjectInputStream instream = new ObjectInputStream(sock.getInputStream());
String obj = (String) instream.readObject();
Log.d("MainActivity", "서버에서 받은 메시지 : " + obj);
sock.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
}
Here is Button code.
import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
/**
* This example code demonstrates how to setup a listener
* for GPIO pin state changes on the Raspberry Pi.
*
* #author Robert Savage
*/
public class ListenGpioExample {
public static void main(String args[]) throws InterruptedException {
System.out.println("<--Pi4J--> GPIO Listen Example ... started.");
// create gpio controller
final GpioController gpio = GpioFactory.getInstance();
// provision gpio pin #02 as an input pin with its internal pull down resistor enabled
final GpioPinDigitalInput myButton = gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, PinPullResistance.PULL_DOWN);
// set shutdown state for this input pin
myButton.setShutdownOptions(true);
// create and register gpio pin listener
myButton.addListener(new GpioPinListenerDigital() {
#Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
// display pin state on console
System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
}
});
System.out.println(" ... complete the GPIO #02 circuit and see the listener feedback here in the console.");
// keep program running until user aborts (CTRL-C)
while(true) {
Thread.sleep(500);
}
// stop all GPIO activity/threads by shutting down the GPIO controller
// (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
// gpio.shutdown(); <--- implement this method call if you wish to terminate the Pi4J GPIO
controller
}
}
I have no Idea,,,,
Related
I have an ESP8266 12F in Soft AP mode(Server) and trying to connect my Android App to it in persistent mode(TCP).
I'm trying with this code and I can send data but not receive the answer an I know that the answer is being sent because I'm sniffing the ESP8266 connection.
The goal is to start a TCP client connection against the ESP8266 and send packets to it depending on what button is pressed in the App and the IoT device can be busy to answer so I can't wait halting the App GUI; that's why I need a persistent connection.
I tried different approaches without success.
package com.coolio.tcptest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.net.*;
import java.io.*;
public class ClientActivity extends AppCompatActivity {
Socket myClient = new Socket();
Boolean Connected = false;
String serverName;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
}
public class client extends AsyncTask<Void,Void,Void>
{
String received;
protected Void doInBackground(Void... Params)
{
//String serverName = "10.7.48.108";
int port = 1100;
try {
//updateText.setText("Connecting to " + serverName + " on port " + port);
// Socket client = new Socket(serverName, port);
if(!Connected)
{
//myClient.addListener();
myClient = new Socket(serverName, port);
myClient.setTcpNoDelay(true);
//myClient.on("new message", onNewMessage);
Connected=true;
}
//updateText.setText("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = myClient.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
InputStream inFromServer = myClient.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
out.writeBytes("Connected!\r\n");
received = in.readUTF();//Stuck here
myClient.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid)
{
//Never reach here
TextView updateText = (TextView) findViewById(R.id.update);
updateText.setText("in post");
TextView receivedText = (TextView) findViewById(R.id.received);
receivedText.setText("Server says: " + received);
}
}
public void onSendClicked(View view)
{
//EditText messageView= (EditText) findViewById(R.id.ip);
//serverName=messageView.getText().toString();
serverName="192.168.4.1";
new client().execute();
}
}
I need your help!
First: I am from austria , so my english is not so good. So I apologize for the mistakes I will make!
This is my first project I try with Android Studio. I am a newbie in programming. I have not much skill in Arduino and Android program language, but I need it for my bachelor project, so I have to learn it!
I worked with a tutorial video, which was in spanish, so I have no clue what that guy was talking about, but I understood the code all in all.
My problem is, when I start the app on my phone, the first screen (paired devices) works fine. But when I press on the paired device...
This following error occurs :
Capturing and displaying logcat messages from application. This
behavior can be disabled in the "Logcat output" section of the
"Debugger" settings page. D/OpenGLRenderer:
ProgramCache.generateProgram: 103079215104 D/AndroidRuntime: Shutting
down VM E/AndroidRuntime: FATAL EXCEPTION: main
Process: bachelor_projekt.bluetoothcontroller, PID: 11061
java.lang.RuntimeException: Unable to resume activity
{bachelor_projekt.bluetoothcontroller/bachelor_projekt.bluetoothcontroller.UserInterface}:
java.lang.IllegalArgumentException: null is not a valid Bluetooth
address
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3506)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: java.lang.IllegalArgumentException: null is not a valid Bluetooth address
at android.bluetooth.BluetoothDevice.(BluetoothDevice.java:668)
at android.bluetooth.BluetoothAdapter.getRemoteDevice(BluetoothAdapter.java:553)
at bachelor_projekt.bluetoothcontroller.UserInterface.onResume(UserInterface.java:122)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1272)
at android.app.Activity.performResume(Activity.java:6917)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3477)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6247)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
I/Process: Sending signal. PID: 11061 SIG: 9 Application terminated.
After that message, the app shuts down :
I divided my app in:
Bluetooth - for the bluetooth connection
Here is the code:
package bachelor_projekt.bluetoothcontroller;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.Set;
public class Bluetooth extends AppCompatActivity {
// Cleaning of the Logcat (Systemlog)
private static final String TAG = "Bluetooth";
// Declaration of ListView
ListView IdList;
// String which will be sended to the main frame
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Declaration of the fields
private BluetoothAdapter myBluetooth;
private ArrayAdapter<String> myPairedDevicesArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
}
#Override
public void onResume()
{
super.onResume();
//----------------------------
VerificationBT();
// Initialze the array which keeps the bluetooth devices
myPairedDevicesArray=new ArrayAdapter<String>(this, R.layout.device_name);
IdList = findViewById(R.id.idList);
IdList.setAdapter(myPairedDevicesArray);
IdList.setOnItemClickListener(myDeviceClickListener);
// Get local default bluetooth adapter
myBluetooth = BluetoothAdapter.getDefaultAdapter();
// Includes the bluetooth member which is paired with the device
Set<BluetoothDevice> pairedDevices =myBluetooth.getBondedDevices();
// Pair with an already in the array included device.
if (pairedDevices.size()>0)
{
for (BluetoothDevice device : pairedDevices){
myPairedDevicesArray.add(device.getName() + "\n" + device.getAddress());
}
}
}
// Configuration for the "on click" ability for the liste
private AdapterView.OnItemClickListener myDeviceClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView av , View v, int arg2, long arg3) {
// Detect the MAC-Adress of the device ( last 17 caracters)
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// 1 Try to connect if MAC adress is the same
Intent i = new Intent(Bluetooth.this, UserInterface.class);
startActivity(i);
}
};
private void VerificationBT(){
// Checks if the device has bluetooth and if it is activated
myBluetooth=BluetoothAdapter.getDefaultAdapter();
if(myBluetooth==null) {
Toast.makeText(getBaseContext(), "Device doesn't have bluetooth", Toast.LENGTH_SHORT).show();
} else{
if (myBluetooth.isEnabled()) {
Log.d(TAG, "...Bluetooth Avtivated...");
} else{
// Ask the user to activate bluetooth
Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBt,1);
}
}
}
}
The second part is the user interface - Here should be the actual project which is just for start (3 Buttons, 1 for LED on, 1 for LED off, 1 for disconnect).
Here is the code:
package bachelor_projekt.bluetoothcontroller;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
public class UserInterface extends AppCompatActivity {
Button IdLedON, IdLedOFF, IdDisconnect;
TextView IdBuffer;
//-------------------------------------------------
Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConnection;
// Special service - SPP UUID
private static final UUID BTMODULE_UUID = UUID.fromString
("00001101-0000-1000-8000-00211300ACCD"); //805F9B34FB
// String direction of the MAC
private static String address = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_interface);
// Connection between inferface and variables
IdLedON = (Button) findViewById(R.id.IdLedON);
IdLedOFF = (Button) findViewById(R.id.IdLedOFF);
IdDisconnect = (Button) findViewById(R.id.IdDisconnect);
IdBuffer = findViewById(R.id.IdBuffer);
bluetoothIn = new Handler(){
public void handleMessage(android.os.Message msg){
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
DataStringIN.append(readMessage);
int endOfLineIndex = DataStringIN.indexOf("#");
if (endOfLineIndex > 0) {
String dataInPrint = DataStringIN.substring(0, endOfLineIndex);
IdBuffer.setText("Data: " + dataInPrint);
DataStringIN.delete(0, DataStringIN.length());
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter();
VerificationBT();
IdLedON.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyConnection.write("1");
}
});
IdLedOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MyConnection.write("0");
}
});
IdDisconnect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (btSocket != null)
{
try {
btSocket.close();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();;}
}
finish();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
// Creates a save Connection for the device
return device.createRfcommSocketToServiceRecord(BTMODULE_UUID);
}
#Override
public void onResume()
{
super.onResume();
// Receives MAC Adress Direction out of DeviceListActivity via intent
Intent intent = getIntent();
// Receives MAC Adress Direction out of DeviceListActivity via EXTRA
address = intent.getStringExtra(Bluetooth.EXTRA_DEVICE_ADDRESS);
// adjust MAC Adress
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try
{
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Error while Connection with device accured ", Toast.LENGTH_SHORT).show();
}
// Creates a connection with bluetooth
try
{
btSocket.connect();
} catch (IOException e){
try{
btSocket.close();
} catch (IOException e2){}
}
MyConnection = new ConnectedThread(btSocket);
MyConnection.start();
}
#Override
public void onPause()
{
super.onPause();
try
{
// If you leave the application there can be no access to the bluetooth adapter
btSocket.close();
} catch (IOException e2){}
}
// Check if bluetooth device is available and connect with it
private void VerificationBT()
{
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device doesn't support bluetooth", Toast.LENGTH_LONG);
} else {
Intent enableBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBt, 1);
}
}
// class for making a connection
private class ConnectedThread extends Thread
{
private final InputStream myInStream;
private final OutputStream myOutStream;
public ConnectedThread(BluetoothSocket socket)
{
InputStream tmpIn=null;
OutputStream tmpOut=null;
try
{
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {}
myInStream=tmpIn;
myOutStream=tmpOut;
}
public void run()
{
byte[] buffer = new byte[256];
int bytes;
// Device stays in the "try to connect" mode
while(true) {
try {
bytes = myInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
} catch (IOException e) {
break;
}
}
}
public void write(String input)
{
try{
myOutStream.write(input.getBytes());
} catch (IOException e)
{
// If it is not possible to send data
Toast.makeText(getBaseContext(), " Connection failed", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
So if you need for information, just tell me.
Hopefully someone of you understands my problem and can help me :)
Best wishes
Semi
Seems like there is an error in the code.
This error:
android.app.ActivityThread.handleResumeActivity
Appeared way too many times which means and activity froze or crashed and then tried to restart but kept on failing so many times it just gave up in the end.
Also, it looks like your using a VM to test the code so try using it with a real device.
If you cant find out the problem try writing the code from the start again or run it through a bug interpreter.
Best of luck,
Paul!
I want to build an app that can connect with a single click of button which will create a vpn profile and connect to the vpn profile by parsig the username and password of the vpn server.
The code that is developed and modified is good to create and connect vpn but my vpn requires username and password to be entered so i want to do that programatically.
Here is my project
VpnClient.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class VpnClient extends AppCompatActivity{
public interface Prefs {
String NAME = "connection";
String SERVER_ADDRESS = "server.address";
String SERVER_PORT = "server.port";
String SHARED_SECRET = "shared.secret";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button disconnect = (Button) findViewById(R.id.disconnect);
Button connect = (Button) findViewById(R.id.connect);
// final TextView serverAddress = (TextView) findViewById(R.id.address);
//final TextView serverPort = (TextView) findViewById(R.id.port);
// final TextView sharedSecret = (TextView) findViewById(R.id.secret);
final SharedPreferences prefs = getSharedPreferences(Prefs.NAME, MODE_PRIVATE);
final String serverAddress = ""; !!I insert my vpnserver address in here which is my.vpnserver.com
final String serverPort = ""; !!As server port i am using 1723 for PPTP connection
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefs.edit()
.putString(Prefs.SERVER_ADDRESS,"")
.putString(Prefs.SERVER_PORT, "")
.putString(Prefs.SHARED_SECRET, "")
.commit();
Intent intent = VpnService.prepare(VpnClient.this);
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}
});
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(getServiceIntent().setAction(MyVpnService.ACTION_DISCONNECT));
}
});
}
#Override
protected void onActivityResult(int request, int result, Intent data) {
if (result == RESULT_OK) {
startService(getServiceIntent().setAction(MyVpnService.ACTION_CONNECT));
}
}
private Intent getServiceIntent() {
return new Intent(this, MyVpnService.class);
}
}
MyVpnService.java
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.support.annotation.RequiresApi;
import android.support.v4.util.Pair;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.LogRecord;
public class MyVpnService extends andenter code hereroid.net.VpnService implements android.os.Handler.Callback {
private static final String TAG = MyVpnService.class.getSimpleName();
public static final String ACTION_CONNECT = "com.yaksh.vpn.START";
public static final String ACTION_DISCONNECT = "com.yaksh.vpn.STOP";
private Handler mHandler;
private static class Connection extends Pair<Thread, ParcelFileDescriptor> {
public Connection(Thread thread, ParcelFileDescriptor pfd) {
super(thread, pfd);
}
}
private final AtomicReference<Thread> mConnectingThread = new AtomicReference<>();
private final AtomicReference<Connection> mConnection = new AtomicReference<>();
private AtomicInteger mNextConnectionId = new AtomicInteger(1);
private PendingIntent mConfigureIntent;
#Override
public void onCreate() {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Create the intent to "configure" the connection (just start ToyVpnClient).
mConfigureIntent = PendingIntent.getActivity(this, 0, new Intent(this, VpnClient.class),
PendingIntent.FLAG_UPDATE_CURRENT);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_DISCONNECT.equals(intent.getAction())) {
disconnect();
return START_NOT_STICKY;
} else {
connect();
return START_STICKY;
}
}
#Override
public void onDestroy() {
disconnect();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public boolean handleMessage(Message message) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
if (message.what != R.string.disconnected) {
updateForegroundNotification(message.what);
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void connect() {
// Become a foreground service. Background services can be VPN services too, but they can
// be killed by background check before getting a chance to receive onRevoke().
updateForegroundNotification(R.string.connecting);
mHandler.sendEmptyMessage(R.string.connecting);
// Extract information from the shared preferences.
final SharedPreferences prefs = getSharedPreferences(VpnClient.Prefs.NAME, MODE_PRIVATE);
final String server = prefs.getString(VpnClient.Prefs.SERVER_ADDRESS, "");
final byte[] secret = prefs.getString(VpnClient.Prefs.SHARED_SECRET, "").getBytes();
final int port;
try {
port = Integer.parseInt(prefs.getString(VpnClient.Prefs.SERVER_PORT, ""));
} catch (NumberFormatException e) {
Log.e(TAG, "Bad port: " + prefs.getString(VpnClient.Prefs.SERVER_PORT, null), e);
return;
}
// Kick off a connection.
startConnection(new VpnConnection(
this, mNextConnectionId.getAndIncrement(), server, port, secret));
}
private void startConnection(final VpnConnection connection) {
// Replace any existing connecting thread with the new one.
final Thread thread = new Thread(connection, "ToyVpnThread");
setConnectingThread(thread);
// Handler to mark as connected once onEstablish is called.
connection.setConfigureIntent(mConfigureIntent);
connection.setOnEstablishListener(new VpnConnection.OnEstablishListener() {
public void onEstablish(ParcelFileDescriptor tunInterface) {
mHandler.sendEmptyMessage(R.string.connected);
mConnectingThread.compareAndSet(thread, null);
setConnection(new Connection(thread, tunInterface));
}
});
thread.start();
}
private void setConnectingThread(final Thread thread) {
final Thread oldThread = mConnectingThread.getAndSet(thread);
if (oldThread != null) {
oldThread.interrupt();
}
}
private void setConnection(final Connection connection) {
final Connection oldConnection = mConnection.getAndSet(connection);
if (oldConnection != null) {
try {
oldConnection.first.interrupt();
oldConnection.second.close();
} catch (IOException e) {
Log.e(TAG, "Closing VPN interface", e);
}
}
}
private void disconnect() {
mHandler.sendEmptyMessage(R.string.disconnected);
setConnectingThread(null);
setConnection(null);
stopForeground(true);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void updateForegroundNotification(final int message) {
startForeground(1, new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_vpn)
.setContentText(getString(message))
.setContentIntent(mConfigureIntent)
.build());
}
}
VpnConnection.java
import android.app.PendingIntent;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.support.annotation.RequiresApi;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.concurrent.TimeUnit;
/**
* Created by Yaksh on 11/3/2017.
*/
public class VpnConnection implements Runnable{
/**
* Callback interface to let the {#link MyVpnService} know about new connections
* and update the foreground notification with connection status.
*/
public interface OnEstablishListener {
void onEstablish(ParcelFileDescriptor tunInterface);
}
/** Maximum packet size is constrained by the MTU, which is given as a signed short. */
private static final int MAX_PACKET_SIZE = Short.MAX_VALUE;
/** Time to wait in between losing the connection and retrying. */
private static final long RECONNECT_WAIT_MS = TimeUnit.SECONDS.toMillis(3);
/** Time between keepalives if there is no traffic at the moment.
*
* TODO: don't do this; it's much better to let the connection die and then reconnect when
* necessary instead of keeping the network hardware up for hours on end in between.
**/
private static final long KEEPALIVE_INTERVAL_MS = TimeUnit.SECONDS.toMillis(15);
/** Time to wait without receiving any response before assuming the server is gone. */
private static final long RECEIVE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(20);
/**
* Time between polling the VPN interface for new traffic, since it's non-blocking.
*
* TODO: really don't do this; a blocking read on another thread is much cleaner.
*/
private static final long IDLE_INTERVAL_MS = TimeUnit.MILLISECONDS.toMillis(100);
/**
* Number of periods of length {#IDLE_INTERVAL_MS} to wait before declaring the handshake a
* complete and abject failure.
*
* TODO: use a higher-level protocol; hand-rolling is a fun but pointless exercise.
*/
private static final int MAX_HANDSHAKE_ATTEMPTS = 50;
private final MyVpnService mService;
private final int mConnectionId;
private final String mServerName;
private final int mServerPort;
private final byte[] mSharedSecret;
private PendingIntent mConfigureIntent;
private OnEstablishListener mOnEstablishListener;
public VpnConnection(final MyVpnService service, final int connectionId,
final String serverName, final int serverPort, final byte[] sharedSecret) {
mService = service;
mConnectionId = connectionId;
mServerName = serverName;
mServerPort= serverPort;
mSharedSecret = sharedSecret;
}
/**
* Optionally, set an intent to configure the VPN. This is {#code null} by default.
*/
public void setConfigureIntent(PendingIntent intent) {
mConfigureIntent = intent;
}
public void setOnEstablishListener(OnEstablishListener listener) {
mOnEstablishListener = listener;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void run() {
try {
Log.i(getTag(), "Starting");
// If anything needs to be obtained using the network, get it now.
// This greatly reduces the complexity of seamless handover, which
// tries to recreate the tunnel without shutting down everything.
// In this demo, all we need to know is the server address.
final SocketAddress serverAddress = new InetSocketAddress(mServerName, mServerPort);
// We try to create the tunnel several times.
// network is available.
// Here we just use a counter to keep things simple.
for (int attempt = 0; attempt < 10; ++attempt) {
// Reset the counter if we were connected.
if (run(serverAddress)) {
attempt = 0;
}
// Sleep for a while. This also checks if we got interrupted.
Thread.sleep(3000);
}
Log.i(getTag(), "Giving up");
} catch (IOException | InterruptedException | IllegalArgumentException e) {
Log.e(getTag(), "Connection failed, exiting", e);
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private boolean run(SocketAddress server)
throws IOException, InterruptedException, IllegalArgumentException {
ParcelFileDescriptor iface = null;
boolean connected = false;
// Create a DatagramChannel as the VPN tunnel.
try (DatagramChannel tunnel = DatagramChannel.open()) {
// Protect the tunnel before connecting to avoid loopback.
if (!mService.protect(tunnel.socket())) {
throw new IllegalStateException("Cannot protect the tunnel");
}
// Connect to the server.
tunnel.connect(server);
// For simplicity, we use the same thread for both reading and
// writing. Here we put the tunnel into non-blocking mode.
tunnel.configureBlocking(false);
// Authenticate and configure the virtual network interface.
iface = handshake(tunnel);
// Now we are connected. Set the flag.
connected = true;
// Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(iface.getFileDescriptor());
// Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(iface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(MAX_PACKET_SIZE);
// Timeouts:
// - when data has not been sent in a while, send empty keepalive messages.
// - when data has not been received in a while, assume the connection is broken.
long lastSendTime = System.currentTimeMillis();
long lastReceiveTime = System.currentTimeMillis();
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
// Write the outgoing packet to the tunnel.
packet.limit(length);
tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
lastReceiveTime = System.currentTimeMillis();
}
// Read the incoming packet from the tunnel.
length = tunnel.read(packet);
if (length > 0) {
// Ignore control messages, which start with zero.
if (packet.get(0) != 0) {
// Write the incoming packet to the output stream.
out.write(packet.array(), 0, length);
}
packet.clear();
// There might be more incoming packets.
idle = false;
lastSendTime = System.currentTimeMillis();
}
// If we are idle or waiting for the network, sleep for a
// fraction of time to avoid busy looping.
if (idle) {
Thread.sleep(IDLE_INTERVAL_MS);
final long timeNow = System.currentTimeMillis();
if (lastSendTime + KEEPALIVE_INTERVAL_MS <= timeNow) {
// We are receiving for a long time but not sending.
// Send empty control messages.
packet.put((byte) 0).limit(1);
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
lastSendTime = timeNow;
} else if (lastReceiveTime + RECEIVE_TIMEOUT_MS <= timeNow) {
// We are sending for a long time but not receiving.
throw new IllegalStateException("Timed out");
}
}
}
} catch (SocketException e) {
Log.e(getTag(), "Cannot use socket", e);
} finally {
if (iface != null) {
try {
iface.close();
} catch (IOException e) {
Log.e(getTag(), "Unable to close interface", e);
}
}
}
return connected;
}
private ParcelFileDescriptor handshake(DatagramChannel tunnel)
throws IOException, InterruptedException {
// To build a secured tunnel, we should perform mutual authentication
// and exchange session keys for encryption. To keep things simple in
// this demo, we just send the shared secret in plaintext and wait
// for the server to send the parameters.
// Allocate the buffer for handshaking. We have a hardcoded maximum
// handshake size of 1024 bytes, which should be enough for demo
// purposes.
ByteBuffer packet = ByteBuffer.allocate(1024);
// Control messages always start with zero.
packet.put((byte) 0).put(mSharedSecret).flip();
// Send the secret several times in case of packet loss.
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
// Wait for the parameters within a limited time.
for (int i = 0; i < MAX_HANDSHAKE_ATTEMPTS; ++i) {
Thread.sleep(IDLE_INTERVAL_MS);
// Normally we should not receive random packets. Check that the first
// byte is 0 as expected.
int length = tunnel.read(packet);
if (length > 0 && packet.get(0) == 0) {
return configure(new String(packet.array(), 1, length - 1).trim());
}
}
throw new IOException("Timed out");
}
private ParcelFileDescriptor configure(String parameters) throws IllegalArgumentException {
// Configure a builder while parsing the parameters.
MyVpnService.Builder builder = mService.new Builder();
for (String parameter : parameters.split(" ")) {
String[] fields = parameter.split(",");
try {
switch (fields[0].charAt(0)) {
case 'm':
builder.setMtu(Short.parseShort(fields[1]));
break;
case 'a':
builder.addAddress(fields[1], Integer.parseInt(fields[2]));
break;
case 'r':
builder.addRoute(fields[1], Integer.parseInt(fields[2]));
break;
case 'd':
builder.addDnsServer(fields[1]);
break;
case 's':
builder.addSearchDomain(fields[1]);
break;
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Bad parameter: " + parameter);
}
}
// Create a new interface using the builder and save the parameters.
final ParcelFileDescriptor vpnInterface;
synchronized (mService) {
vpnInterface = builder
.setSession(mServerName)
.setConfigureIntent(mConfigureIntent)
.establish();
if (mOnEstablishListener != null) {
mOnEstablishListener.onEstablish(vpnInterface);
}
}
Log.i(getTag(), "New interface: " + vpnInterface + " (" + parameters + ")");
return vpnInterface;
}
private final String getTag() {
return VpnConnection.class.getSimpleName() + "[" + mConnectionId + "]";
}
}
hello im having stuck after i sending data from esp8266
i connected esp8266 with my arduino
this is my arduino code
#include <SoftwareSerial.h>
//#include <OneWire.h>
//#include <DallasTemperature.h>
//#include <stdlib.h>
//#include "Wire.h"
//#define DS3231_I2C_ADDRESS 0x68
//#define ONE_WIRE_BUS 5
//WIFI
#include <SPI.h>
#include <WiFi.h>
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
//OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
//DallasTemperature sensors(&oneWire);
int wifiTx = 4;
int wifiRx = 3;
#define DEBUG true
char com;
String data;
SoftwareSerial wifi(wifiTx, wifiRx);
//wifi
char ssid[] = "waifu"; // your network SSID (name)
char pass[] = "chronoangel"; // your network password
//int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
// put your setup code here, to run once:
Wire.begin();
Serial.begin(9600);
wifi.begin(115200);
sensors.begin();
//sekon, menit,jam, day of week, hari, bulan taun
//setDS3231time(0,15,2,1,13,7,16);
//\start_wifi();
esp();
}
void loop() {
test_wifi();
//loop_esp();
}
void esp()
{
sendCommand("AT\r\n",2000,DEBUG);
sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
sendCommand("AT+CWJAP=\"waifu\",\"chronoangel\"\r\n",3000,DEBUG);
delay(10000);
//Serial.println("\nCek IP");
//sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
Serial.println("\nGet PORT");
sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
Serial.println("\nSet IP");
sendCommand("AT+CIPSTA=\"192.168.1.7\"\r\n",1000,DEBUG); // set ip address
sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
Serial.println("\nServer Ready");
}
void test_wifi()
{
if(wifi.available())
{
char toSend = (char)wifi.read();
Serial.print(toSend);
}
//Read from usb serial to wifi
if(Serial.available())
{
char toSend = (char)Serial.read();
wifi.print(toSend);
}
}
and this is my android studio code
package com.example.chronoangel.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.IP);
editTextPort = (EditText) findViewById(R.id.Port);
buttonConnect = (Button) findViewById(R.id.connect);
//buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView) findViewById(R.id.textData);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(editTextAddress.getText().toString(), Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
//class to get data from esp8266
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
this is my view of my program :
my problem is similiar to this page :
http://stackoverflow.com/questions/34274774/esp8266-wifi-server-to-android-client
but i think in there didnt have clue either how to reconnected after send a data
the program run after i click connect on android app
in my serial arduino after i send AT+ COMMAND
AT+CIPSEND = 0,2
then i send data "ab" to my android
the data was not send, but if ii send AT+COMMAND
AT+CIPCLOSE=0
the data was send,but i must click connect again to get the data from esp
my question is can we get continous data after click connect ?
how suppose i do with the android to connect again after arduino send a message ?
This is more an advice than an answer, because I think there is no other way than to close the connection everytime.
But i highly recommend to use your own Software for your ESP8266 rather than to use the AT-Commands. They are nice for the start, to connect to a network and so on. But they are limited. Since you're using arduino allready, i would suggest to use the IDE to write some code for your ESP.
You can find a lot of code and help here.
https://create.arduino.cc/projecthub/Metavix/programming-the-esp8266-with-the-arduino-ide-in-3-simple-601c16
And the ESP8266WiFi.h offers a lot of functions that are ready to use.
I am creating an Android application that allows client to server messaging at the moment but I am looking for a way to also allow server to client messaging, so both client and server can message back and forth. Any suggestion on how I could do this would be appreciated. I know that I will need to edit my ChatServer class, which is as follows;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
public class ChatServer {
private static final String USAGE = "Usage: java ChatServer";
/** Default port number on which this server to be run. */
private static final int PORT_NUMBER = 8008;
/**
* List of print writers associated with current clients, one for each.
*/
private List<PrintWriter> clients;
/** Creates a new server. */
public ChatServer() {
clients = new LinkedList<PrintWriter>();
}
/** Starts the server. */
public void start() {
System.out.println("AndroidChatApplication server started on port "
+ PORT_NUMBER + "!");
try {
ServerSocket s = new ServerSocket(PORT_NUMBER);
for (;;) {
Socket incoming = s.accept();
new ClientHandler(incoming).start();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("AndroidChatApplication server stopped.");
}
/** Adds a new client identified by the given print writer. */
private void addClient(PrintWriter out) {
synchronized (clients) {
clients.add(out);
}
}
/** Adds the client with given print writer. */
private void removeClient(PrintWriter out) {
synchronized (clients) {
clients.remove(out);
}
}
/** Broadcasts the given text to all clients. */
private void broadcast(String msg) {
for (PrintWriter out : clients) {
out.println(msg);
out.flush();
}
}
public static void main(String[] args) {
if (args.length > 0) {
System.out.println(USAGE);
System.exit(-1);
}
new ChatServer().start();
}
/**
* A thread to serve a client. This class receive messages from a client and
* broadcasts them to all clients including the message sender.
*/
private class ClientHandler extends Thread {
/** Socket to read client messages. */
private Socket incoming;
/** Creates a hander to serve the client on the given socket. */
public ClientHandler(Socket incoming) {
this.incoming = incoming;
}
/** Starts receiving and broadcasting messages. */
public void run() {
PrintWriter out = null;
try {
out = new PrintWriter(new OutputStreamWriter(
incoming.getOutputStream()));
// inform the server of this new client
ChatServer.this.addClient(out);
out.print("Welcome to AndroidChatApplication! ");
out.println("Enter BYE to exit.");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
for (;;) {
String msg = in.readLine();
if (msg == null) {
break;
} else {
if (msg.trim().equals("BYE"))
break;
System.out.println("Received: " + msg);
// broadcast the receive message
ChatServer.this.broadcast(msg);
}
}
incoming.close();
ChatServer.this.removeClient(out);
} catch (Exception e) {
if (out != null) {
ChatServer.this.removeClient(out);
}
e.printStackTrace();
}
}
}
}
You can just use the push notification service from Google, check GoogleCloudMessaging and friends for more details. And here's some simple tutorial on how to use it.