Connect to ELM327 // Select protocol - android

I am trying to connect to a ELM327 device via bluetooth.
The library I am using:
https://github.com/eltonvs/java-obd-api
Establishing a bluetooth connection works fine and I can reset the device:
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
final BluetoothSocket socket;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
socket.connect();
Log.d("xx", "1. Reset");
ObdResetCommand obdResetCommand = new ObdResetCommand();
obdResetCommand.run(socket.getInputStream(), socket.getOutputStream());
System.out.println(obdResetCommand.getFormattedResult());
Log.d("xx", "2. Echo Off");
EchoOffCommand echoOffCommand = new EchoOffCommand();
echoOffCommand.run(socket.getInputStream(), socket.getOutputStream());
System.out.println(echoOffCommand.getFormattedResult());
Log.d("xx", "3. LineFeed Off");
LineFeedOffCommand lineFeedOffCommand = new LineFeedOffCommand();
lineFeedOffCommand.run(socket.getInputStream(), socket.getOutputStream());
System.out.println(lineFeedOffCommand.getFormattedResult());
}
Output:
D/xx: 1. Reset
I/System.out: ELM327v1.5
D/xx: 2. Echo Off
I/System.out: OK
D/xx: 3. LineFeed Off
I/System.out: OK
The part that is not working is to select the protocol and read a voltage value:
SelectProtocolCommand selectProtocolCommand = new SelectProtocolCommand(ObdProtocols.AUTO);
try {
selectProtocolCommand.run(socket.getInputStream(), socket.getOutputStream());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
ModuleVoltageCommand moduleVoltageCommand = new ModuleVoltageCommand();
try {
moduleVoltageCommand.run(socket.getInputStream(), socket.getOutputStream());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
What I observe is that the protocol selection is finished very quickly without any output. When I compare the protocol selection part to other apps like "torque lite", this takes much longer and I see flashing lights on my ELM327 device, which is not the case when running my code.
The ModuleVoltageCommand crashes then with:
br.ufrn.imd.obd.exceptions.UnableToConnectException: Error running
Control Module Power Supply [01 42], response: ...UNABLETOCONNECT
I verified the dongle is working with other apps, so this must be an issue with my code.
What am I doing wrong?

I'm the creator of this library, thanks for using my project!
This is an issue with the ECU, when you change the protocol, the next command will usually fail. What I usually do is sending a dump command that's expected to fail (so you just ignore any raised exception for this command) and then I send the commands I really want to run.
Hope it solves your issue!

Related

LuaSocket server don't accept clients

Im making a lua script running at my pc, and need to connect from my android.
So in the lua script I just put this:
local socket = require 'socket'
local server = socket.tcp()
print("createdserver")
server:bind('*',7070)
print("binded")
while 1 do
server:listen(32)
local client = server:accept()
-- make sure we don't block waiting for this client's line
client:settimeout(10)
-- receive the line
local line, err = client:receive()
-- if there was no error, send it back to the client
if not err then client:send(line .. "\n") end
-- done with client, close the object
client:close()
end
And at android I got a really simple socket connection:
public Connection(String ip, int _port) {
//inMessage = new NetworkMessage();
buffer = new byte[16394];
try {
serverAddres = InetAddress.getByName(ip);
socket = new Socket(serverAddres, _port);
socketOut = socket.getOutputStream();
} catch (IOException e) {
Log.e("Connect", e.getMessage());
}
}
At android it just stays at "new Socket" and dont connect.
Im not familiar with lua but my understanding is that you are writing a new line to the socket and you want to receive on the Android side.
Normally if that is the case you need to get the inputStream not the output one since you are waiting for results. Furthermore you need to indefinitely (or till some conditions are met) to listen to the input stream for data on a separate thread (a standard in):
while(true){
if (inputStreamReader().read() != -1){
// do you processing
}
}
My notebook was changing its IP address so I couldnt reach it from the android, already solved!

Problems with specific unix commands while using Jsch (Exec) on Android

Hello i was doing a couple of days and research and some problem analysis, but i have no clue how to solve my Problem right now.
Maybe someone can help....
I am using Jsch for Android devices to access my raspberry pi in order to set some specific commands.
I began with Jsch shell command and everything worked fine besides the fact that i was never able to close a connection due to an infinite loop.
I tried to switch to Exec especially because i just want to send a couple of commands and do not really need to nood what happens on the shell.
Anyways... here is my code:
The intention is to send a cec sleep signal to my tv...
public c_jsch(String userName, String password,
String connectionIP, String knownHostsFileName)
{
JSch jsch = new JSch();
System.out.println("com.jcraft.jsch BBÄÄÄHHMM");
try
{
Session session = jsch.getSession("pi", "192.168.188.23", 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword("raspberry");
session.connect();
String command = "/home/pi/.xbmc-current/xbmc-bin/bin/cec-client -s -d 1";
String command2 = "tx 10 36 \r \n";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
channel.setCommand(command);
channel.setInputStream(null);
channel.connect();
InputStream in = channel.getInputStream();
//NOT YET USEFUL
OutputStream out = channel.getOutputStream();
System.out.println("com.jcraft.jsch Unix system connected...");
byte[] tmp = new byte[1024];
while (true)
{
while (in.available() > 0)
{
int i = in.read(tmp, 0, 1024);
if (i < 0){
break;
}
System.out.print("com.jcraft.jsch Feedback: " + new String(tmp, 0, i));
// NOT WORKING
out.write(command2.getBytes());
out.flush();
System.out.println("com.jcraft.jsch Command flushed");
}
if (channel.isClosed())
{
System.out.println("com.jcraft.jsch exit-status: " + channel.getExitStatus());
break;
}
try
{
Thread.sleep(1000);
}
catch (Exception ee)
{
}
}
channel.disconnect();
session.disconnect();
System.out.println("com.jcraft.jsch exit-status: DONE");
}
catch (Exception e)
{
System.out.println("com.jcraft.jsch exit-status: " + e.getMessage());
}
}
Trying this code throws no error messages but a disappointing exit status-message: 127.
This means command not found.... so i assume there is a big difference between shell and exec commands ... with shell i works like a charm on ssh.
I hope you can help me.
:::Update, as i was first working with Pipes | that are not sufficient for exec and had to add Outputstream in order to send commands after connected to the channel i was able to realise sending commands to my Tv... thank you
I updated my code above and added /r /n to the string that i was going to flush. this was actually the open issue. – DerKai

Connecting Bluetooth in Android

I have done a simple app to connect my phone with an Arduino via BT and all goes right. My phone have Android 2.3.6... But, when I try the app on my tablet (with android 4.0.3), I can't connect. I post here the specific piece of code:
try {
BluetoothSocket socket = mydevice.createRfcommSocketToServiceRecord(UUID.fromString(ARDUINO_STANDAR_UUID));
socket.connect();
OutputStream output = socket.getOutputStream();
InputStream input = socket.getInputStream();
Log.d(TAG, "Connected");
}
catch (IOException e) { Log.e(TAG, e.getMessage()); }
}
Using the Log, the problem is at socket.connect(); at that point, I have to enter the PIN of the device, but it don't connect anyway... The error is "Connection refused"...
What can be wrong?
Try something like this to take care of the connection. I just updated an old android-10 app the other day to android-17 and dealt with exactly this.
BluetoothDevice yourDevice;
try {
Method m = yourDevice.getClass().getMethod( "createInsecureRfcommSocket", new Class[] { int.class } );
selectedDeviceSocket = (BluetoothSocket) m.invoke( yourDevice, Integer.valueOf( 1 ) );
selectedDeviceSocket.connect();
}

connection between server running perl skript and android

I am trying to send data from my Android phone to my home-server by using sockets. My server runs Linux so I used Perl to code the script for my server. The connection works fine and I can send data to my client running on the phone.
Problem is, when I send something (first try was a simple string) to the server, I don't receive anything at the servers side. Everything works fine if I use telnet to send a string to the server.
I am sitting here for some time now and I looked if there was a similar question to mine and could not find any in which the problem is discussed for Android to Perl-script. Here is my code for the Android app:
try {
Socket socket = new Socket("192.168.178.22", 22222);
Statusinformation("connection with server succeed");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Statusinformation(input.readLine());
OutputStream outstream =socket.getOutputStream();
PrintWriter out = new PrintWriter(outstream);
out.println("This is a test message from client on phone!\n");
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Statusinformation("connection unsucsessfull");
e.printStackTrace();
}
on my phone I receive this if i execute the above code:
connection with server succeed!
and on the server side I'm using this code to receive the string from socket clients:
use IO::Socket;
my $server = IO::Socket::INET -> new(
Proto => 'tcp',
LocalPort => 22222,
Listen => SOMAXCONN,
);
print "Server started..\n";
while (1) {
next unless my $conect = $server -> accept();
my $childconection = fork;
if ($childconection == 0) {
handle_connection($conect);
}
}
sub handle_connection
{
my $sock = shift;
my $client_message="";
my $client_addr = $sock -> peerhost;
print "connection: $client_addr connected\n";
print $sock "hi $client_addr, you are connected!\n";
while (1) {
open (Tempfile, '>>tempfile.txt');
while ($client_message = <$sock>) {
print Tempfile $client_message;
print $client_message;
}
close (Tempfile);
}
close($sock);
exit(0);
}
ok now I am a little ashamed.
I solved the problem by adding:
out.flush();
the flush() method assures that all pending data is send to the target and flushs the target.

Android Connection to WebSocket hang

In my Android project I implemented a Faye client. But, when I call SocketChannel.socket().connect(...), the connection hangs and the next line does not run. It is as if I don`t set the timeout, or disconnect for timeout.
Thread.currentThread().setName("WebSocketConnector");
try {
// "java.net.SocketException: Address family not supported by protocol"
System.setProperty("java.net.preferIPv6Addresses", "false");
mTransportChannel = SocketChannel.open();
// mTransportChannel.configureBlocking(false);
// the following will block until connection was established or
// an error occurred!
mTransportChannel.socket().connect(
new InetSocketAddress(mWsHost, mWsPort), mOptions.getSocketConnectTimeout());
Log.i(TAG, "Socket connected");
// before doing any data transfer on the socket, set socket
// options
mTransportChannel.socket().setSoTimeout(
mOptions.getSocketReceiveTimeout());
mTransportChannel.socket().setTcpNoDelay(
mOptions.getTcpNoDelay());
return null;
} catch (IOException e) {
Log.e(TAG, e.getMessage());
return e.getMessage();
}
If I did so:
mTransportChannel = SocketChannel.open();
mTransportChannel.configureBlocking(false);
mTransportChannel.connect(socketAddress);
SocketChannel .isConnected() return false
What is the problem I don't understand?
DNS resolution might be blocking even before the connect() call. Put new InetSocketAddress(mWsHost, mWsPort) on a separate line, and print out its results. Chances are you are stuck there.
If that's not the case, check if you can connect to the target host/port with telnet:
~$ telnet host port
This problem is resolved. My wifi connection didn`t have access to private resource. But how I have other problem with web socket. It is
Android socket read method return -1

Categories

Resources