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.
Related
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,,,,
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'm using Android to toggle my led light with Arduino and ethernet shield. It didn't work despite having no problems during compilation neither on Android nor Arduino. I connected the ethernet shield with my computer and I gave it the same address as my computer.
This is my Android code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.ToggleButton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/********************************/
/* Define all the buttons */
/********************************/
Switch led1 = (Switch) findViewById(R.id.Led1);
/*******************************************************/
/* Set an onclick/onchange listener for every button */
/*******************************************************/
led1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/* Switch is led 1 */
new Background_get().execute("led1=1");
} else {
new Background_get().execute("led1=0");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*****************************************************/
/* This is a background process for connecting */
/* to the arduino server and sending */
/* the GET request withe the added data */
/*****************************************************/
private class Background_get extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
/* Change the IP to the IP you set in the arduino sketch */
URL url = new URL("http://169, 254, 128, 184/?" + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
result.append(inputLine).append("\n");
in.close();
connection.disconnect();
return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
And this is the Arduino code:
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(169, 254, 128, 184);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
// Pin 5
pinMode(5, OUTPUT);
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
String buffer = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
buffer += c;
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
// the connection will be closed after completion of the response
client.println("Refresh: 5");
// refresh the page automatically every 5 sec
client.println();
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
buffer = "";
} else if (c != '\r') {
if (buffer.indexOf("GET /?led1=1") >= 0) { // If led1 = 1
digitalWrite(5, HIGH); // led 1 > on
}
if (buffer.indexOf("GET /?led1=0") >= 0) { // If led1 = 0
digitalWrite(5, LOW); // led 1 > off
}
} else {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
Program your Arduino:
#include "etherShield.h"
#include "ETHER_28J60.h"
int led2 = 7;
int led1 = 6;
static uint8_t mac[6] = {0xAA, 0xBB, 0xCC, 0xDD, 0xBB, 0xAA}; // this just needs to be unique for your network,
// so unless you have more than one of these boards
// connected, you should be fine with this value.
static uint8_t ip[4] = {192, 168, 0, 15}; // the IP address for your board. Check your home hub
// to find an IP address not in use and pick that
// this or 10.0.0.15 are likely formats for an address
// that will work.
static uint16_t port = 80; // Use port 80 - the standard for HTTP
ETHER_28J60 e;
void setup(){
e.setup(mac, ip, port);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}
void loop(){
char* params;
if (params = e.serviceRequest()){
if (strcmp(params, "?cmd=1") == 0){digitalWrite(led1, HIGH);}
if (strcmp(params, "?cmd=2") == 0){digitalWrite(led1, LOW); }
if (strcmp(params, "?cmd=3") == 0){digitalWrite(led2, HIGH);}
if (strcmp(params, "?cmd=4") == 0){digitalWrite(led2, LOW); }
e.respond();
}
}
Program your APP
Add Permission to Your Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View led1on = findViewById(R.id.led_1on);
View led1off = findViewById(R.id.led_1off);
View led2on = findViewById(R.id.led_2on);
View led2off = findViewById(R.id.led_2off);
led1on.setOnClickListener(this);
led1off.setOnClickListener(this);
led2on.setOnClickListener(this);
led2off.setOnClickListener(this);
}
public void commandArduino(String url){
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(new HttpGet(url));
} catch (Exception e) {}
}
public void onClick(View thisView) {
switch(thisView.getId()){
case R.id.led_1on: commandArduino("http://192.168.0.15/?cmd=1"); break;
case R.id.led_1off: commandArduino("http://192.168.0.15/?cmd=2"); break;
case R.id.led_2on: commandArduino("http://192.168.0.15/?cmd=3"); break;
case R.id.led_2off: commandArduino("http://192.168.0.15/?cmd=4"); break;
}
}
}
Reference:
http://www.instructables.com/id/Arduino-Android-LED-control-Using-Ethernet-Shield/
I am trying to make a port scanner on Android and I am a little stuck. I want to see if a port is open on the router/default gateway, but nothing seems to be working. I tried using is reachable, but I feel like that may be the wrong thing.
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;
public class portscan extends Activity {
String targetHost;
public int startPort = 1; //(for uses in later programming)
public int endPort = 1000;
private Intent scanIntent;
InetAddress targetAddress;
String targetHostName;
WifiManager networkd;
DhcpInfo details;
public String gateway;
TextView GW;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.port);
GW = (TextView)findViewById(R.id.gateway);
networkd = (WifiManager) getSystemService(Context.WIFI_SERVICE);
details = networkd.getDhcpInfo();
String test = intToIp(details.gateway);
gateway = "Default Gateway: "+String.valueOf(details.gateway);
boolean isAvailable = false;
isAvailable = InetAddress.getByName(test).isReachable(80); //trying to see if port open
if (isAvailable == true) {
GW.setText("port 21 is up");
}
} catch (Exception e) {
}
}
public String intToIp(int i) { //this converts the DHCP information (default gateway) into a readable network address
return ( i & 0xFF)+ "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF)+ "." +
((i >> 24 ) & 0xFF );
}
Using the code below you can add a timeout.
try {
Socket socket = new Socket();
SocketAddress address = new InetSocketAddress(ip, port);
socket.connect(address, TIMEOUT);
//OPEN
socket.close();
} catch (UnknownHostException e) {
//WRONG ADDRESS
} catch (SocketTimeoutException e) {
//TIMEOUT
} catch (IOException e) {
//CLOSED
}
Do not use isReachable, it is not meant for port scanning (and is unreliable for anything else too, really).
For port scanning, you use sockets. Pseudo-example:
for (int port = 0; port <= 9999; port++)
{
try
{
// Try to create the Socket on the given port.
Socket socket = new Socket(localhost, port);
// If we arrive here, the port is open!
GW.setText( GW.getText() + String.Format( "Port %d is open. Cheers!\n", port ));
// Don't forget to close it
socket.close();
}
catch (IOException e)
{
// Failed to open the port. Booh.
}
}
I'm trying to connect an application between the computer and an android app. The app will be the client and the computer will be the server.
Using BlueZ (C library for bluetooth on linux) for server:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
int s, client, bytes_read;
socklen_t opt = sizeof(rem_addr);
// allocate socket
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
// bind socket to port 1 of the first available
// local bluetooth adapter
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 1;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
// put socket into listening mode
listen(s, 1);
// accept one connection
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
// close connection
close(client);
close(s);
return 0;
}
The source of this example is : http://people.csail.mit.edu/albert/bluez-intro/x502.html
And the class of the app that i'm using to connect is:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Message;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.UUID;
public class ConnectionThread extends Thread {
BluetoothSocket btSocket = null;
BluetoothServerSocket btServerSocket = null;
InputStream input = null;
OutputStream output = null;
String btDevAddress = null;
String myUUID = "00000101-0000-1000-8000-00805F9C34BF";
boolean server;
boolean running = false;
public ConnectionThread() {
this.server = true;
}
public ConnectionThread(String btDevAddress) {
this.server = false;
this.btDevAddress = btDevAddress;
}
public void run() {
this.running = true;
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if(this.server) {
try {
btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord("Super Bluetooth", UUID.fromString(myUUID));
btSocket = btServerSocket.accept();
if(btSocket != null) {
btServerSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
toMainActivity("---N".getBytes());
}
} else {
try {
BluetoothDevice btDevice = btAdapter.getRemoteDevice(btDevAddress);
btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));
btAdapter.cancelDiscovery();
if (btSocket != null)
btSocket.connect();
} catch (IOException e) {
e.printStackTrace();
toMainActivity("---N".getBytes());
}
}
if(btSocket != null) {
toMainActivity("---S".getBytes());
try {
input = btSocket.getInputStream();
output = btSocket.getOutputStream();
byte[] buffer = new byte[1024];
int bytes;
while(running) {
bytes = input.read(buffer);
toMainActivity(Arrays.copyOfRange(buffer, 0, bytes));
}
} catch (IOException e) {
e.printStackTrace();
toMainActivity("---N".getBytes());
}
}
}
private void toMainActivity(byte[] data) {
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putByteArray("data", data);
message.setData(bundle);
MainActivity.handler.sendMessage(message);
}
public void write(byte[] data) {
if(output != null) {
try {
output.write(data);
} catch (IOException e) {
e.printStackTrace();
}
} else {
toMainActivity("---N".getBytes());
}
}
public void cancel() {
try {
running = false;
btServerSocket.close();
btSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
running = false;
}
}
To send a data to the server I do:
ConnectionThread connect = new ConnectionThread(data.getStringExtra("Address_server"));
connect.start();
byte[] data = "20".getBytes();
connect.write(data);
The problem is not that the connection is occurring. I believe it's because the server is out of UUID.
How can I insert the UUID into the server so that it can receive the data sent?
This question may be slightly old, but seeing as I faced the same problem recently, I want to share one possible solution I came up with. The solution is essentially two projects (skeletal examples): a CMake project (Linux side) and an Android Studio project (APK). To avoid sharing winded explanations, I'll embed the Github repository here. Im open to questions should the need arise, and good luck to the next person who tackles this problem!
I don't know how to do this in libbluetooth/raw socket based. But you can use profile manager interface provided by Bluez to create your own custom profile and register this with bluetoothd.
Below is the sample slide directly copied from this presentation.
To explain in detail, you need to define the methods described in Profile1 interface and register it with Bluetoothd using "RegisterProfile" method.
I don't have any custom profile implementation example, but you can always refer bluez-alsa repository for AG/HFP/HS based profile implementations, which is implemented as external profiles using this interface.
Most interesting part for you in this repository is, "register_profile" API, which take UUID and other required parameters. You can copy the same implementation and register your own UUID and implement,
NewConnection: Action which needs to be performed when new device is connected with server. You can find how to connect using DBUS in Linux here with explanation here.
RequestDisconnection: Which will be called by Bluetoothd when device is disconnected. You can perform cleanup for device based allocation/resources.
Release: Which will be called when Bluetoothd exits. You can perform the profile complete cleanup and UnregisterProfile for graceful exit.