Created
December 1, 2013 03:51
-
-
Save flaviocdc/7728302 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.brauto.automacao.device.usb; | |
import android.app.Service; | |
import android.content.Intent; | |
import android.os.Handler; | |
import android.os.IBinder; | |
import android.util.Log; | |
import com.brauto.automacao.MyApp; | |
import com.googlecode.androidannotations.annotations.EService; | |
import com.physicaloid.lib.Physicaloid; | |
import com.physicaloid.lib.usb.driver.uart.ReadLisener; | |
@EService | |
public class USBDeviceService extends Service { | |
private static final String TAG = USBDeviceService.class.getSimpleName(); | |
private Physicaloid mPhysicaloid; | |
@Override | |
public IBinder onBind(Intent intent) { | |
return null; | |
} | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
openDevice(); | |
((MyApp) getApplication()).setUsbDeviceService(this); | |
} | |
private void openDevice() { | |
mPhysicaloid = new Physicaloid(this); | |
if (!mPhysicaloid.isOpened()) { | |
if (mPhysicaloid.open()) { // default 9600bps | |
mPhysicaloid.addReadListener(new ReadListener()); | |
new Handler().postDelayed(new Runnable() { | |
@Override | |
public void run() { | |
write(new byte[] { 'H', 'e', 'l', 'l', 'o', '$' }); | |
} | |
}, 5000); | |
} | |
} | |
} | |
private final class ReadListener implements ReadLisener { | |
StringBuffer buffer; | |
// callback when reading one or more size buffer | |
@Override | |
public synchronized void onRead(int size) { | |
byte[] buf = new byte[size]; | |
mPhysicaloid.read(buf, size); | |
for (byte b : buf) { | |
if (b == '#') | |
{ | |
buffer = new StringBuffer(); | |
} | |
else if (b == '$') | |
{ | |
Log.i(TAG, "MSG: " + buffer.toString()); | |
buffer = null; | |
} | |
else | |
{ | |
if (buffer == null) | |
{ | |
Log.i(TAG, "Ignorando, mensagem nao comecou..." + (char) b); | |
continue; | |
} | |
buffer.append((char) b); | |
} | |
} | |
} | |
} | |
public void write(byte[] buf) | |
{ | |
mPhysicaloid.write(buf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment