AIR android serversocket works only in ADL (air debug launcher) - android

My problem is that I am working on an air app that communicates with each other through serversocket (server) socket (client)
When I test it in Air debug launcher everything works on the server side (I can see the server from a different internet connection)
But when I try to host from Android device it only works on LAN (can't see hosted server from the different connection)
My question is why it works in the Test environment but not in the built APP.. soo frustrating.
here is my serverside code:
package AS {
import flash.display.MovieClip;
import AS.Constants;
import flash.net.ServerSocket;
import flash.net.Socket;
import flash.events.ServerSocketConnectEvent;
import flash.events.ProgressEvent;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.text.TextFieldType;
import flash.net.SharedObject;
import fl.data.DataProvider;
import flash.net.URLRequest;
import flash.media.Sound;
import flash.desktop.NativeApplication;
import flash.desktop.SystemIdleMode;
import flash.text.TextFormat;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class chatPage extends MovieClip {
private var server:ServerSocket;
private var clients:Vector.<Socket> = new Vector.<Socket>;
private var clientUsernames:Array = new Array();
private var autoScroll:Boolean=true;
private var autoClean:Boolean=false;
private var counter:int=900;
private var soundwarn:Boolean=true;
private var myformat:TextFormat=new TextFormat();
public function chatPage(address:String="0.0.0.0",port:uint=8888):void {
server = new ServerSocket();
server.bind(port,address);
server.addEventListener(ServerSocketConnectEvent.CONNECT, serverConnectHandler);
server.listen();
if(!server.listening){
die();
Constants.mainRef.initLoginScreen("not listening");
}else if(!server.bound){
die();
Constants.mainRef.initLoginScreen("not bound");
}
myformat.color=0xffffff;
client_list.setRendererStyle("textFormat",myformat);
soundButton.gotoAndStop(1);
chat_txt.text = String("");
chat_txt.scrollV=chat_txt.maxScrollV;
scrollBar.update();
scrollBar.addEventListener(Event.SCROLL, scrollingListener);
send_txt.addEventListener(KeyboardEvent.KEY_DOWN, commandHandler);
autoClean_btn.addEventListener(Event.CHANGE, autoCleanHandler);
soundButton.addEventListener(MouseEvent.CLICK, soundClickHandler);
close_btn.addEventListener(MouseEvent.CLICK, closeHandler);
kick_btn.addEventListener(MouseEvent.CLICK, kickHandler);
ban_btn.addEventListener(MouseEvent.CLICK, banHandler);
burn_btn.addEventListener(MouseEvent.CLICK, burnHandler);
share_btn.addEventListener(MouseEvent.CLICK, shareHandler);
scroll_down_btn.addEventListener(MouseEvent.CLICK, scrollDownHandler);
preventSleep_check.addEventListener(Event.CHANGE, sleepChangeHandler);
}
private function burnHandler(e:MouseEvent):void {
//burn all evidence for you and all your clients
if(chat_txt.length > 0){
send(4,Constants.mainRef.encrypt("burn"));
chat_txt.text = String("");
chat_txt.scrollV=chat_txt.maxScrollV;
scrollBar.update();
}
}
private function shareHandler(e:MouseEvent):void {
//share the contents of your chat_txt to all your clients
if(chat_txt.length > 0){
send(5,Constants.mainRef.encrypt(chat_txt.text));
}
}
private function banHandler(e:MouseEvent):void {
var tempIpArr:Array = new Array();
for (var i: uint = 0; i < clients.length; i++) {
tempIpArr.push(clients[i].remoteAddress);
}
Constants.STAGE.addChild(new listDialog(clientUsernames, tempIpArr, this) );
}
private function sleepChangeHandler(e:Event):void{
if(this.preventSleep_check.selected){
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.KEEP_AWAKE;
}else{
NativeApplication.nativeApplication.systemIdleMode = SystemIdleMode.NORMAL;
}
}
private function kickHandler(e:MouseEvent):void {
if(client_list.selectedIndex > -1){
clients[client_list.selectedIndex].close();
clients[client_list.selectedIndex].removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
clients[client_list.selectedIndex].removeEventListener(Event.CLOSE, socketDisconnectHandler);
clients.splice(client_list.selectedIndex,1);
//send("▼"+clientUsernames[client_list.selectedIndex]);
send(3,String(clientUsernames[client_list.selectedIndex]));
clientUsernames.splice(client_list.selectedIndex,1);
client_list.dataProvider = new DataProvider( clientUsernames );
}
}
public function remoteKick(index:uint):void{
clients[index].close();
clients[index].removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
clients[index].removeEventListener(Event.CLOSE, socketDisconnectHandler);
clients.splice(index,1);
send(3,String(clientUsernames[index]));
clientUsernames.splice(index,1);
client_list.dataProvider = new DataProvider( clientUsernames );
}
private function scrollDownHandler(e:MouseEvent):void {
autoScroll=true;
chat_txt.scrollV=chat_txt.maxScrollV;
scrollBar.update();
}
private function closeHandler(e:MouseEvent):void {
die();
Constants.mainRef.initLoginScreen("Chat room terminated!");
//Constants.STAGE.addChild(new logInScreen("Chat room terminated!"));
}
private function soundClickHandler(e:MouseEvent):void {
if(soundButton.currentFrame == 1){
soundwarn=false;
soundButton.gotoAndStop(2);
}else{
soundwarn=true;
soundButton.gotoAndStop(1);
}
}
private function autoCleanFrameListener(e:Event):void {
if(autoClean){
counter--;
counter_txt.text = String( Math.floor( counter / 30 ) + "s" );
if(counter <= 0){
counter_txt.text = String("30s");
chat_txt.text = String("");
chat_txt.scrollV=chat_txt.maxScrollV;
scrollBar.update();
currentDataStr = String("");
counter=900;
}
}
}
private function autoCleanHandler(e:Event):void {
if(autoClean_btn.selected){
autoClean=true;
counter_txt.text = String("30s");
this.addEventListener(Event.ENTER_FRAME, autoCleanFrameListener);
}else{
this.removeEventListener(Event.ENTER_FRAME, autoCleanFrameListener);
autoClean=false;
counter_txt.text = String("");
counter=900;
}
}
private function scrollingListener(e:Event):void {
if(chat_txt.scrollV!=chat_txt.maxScrollV){
autoScroll=false;
}
}
private function serverConnectHandler(e:ServerSocketConnectEvent):void {
var socket:Socket = e.socket;
var banned:Boolean;
if(Constants.banList.length > 0){
for (var i: uint = 0; i < Constants.banList.length; i++) {
if(Constants.banList[i] == socket.remoteAddress){
banned=true;
break;
}else{
banned=false;
}
}
}else{
banned=false;
}
if(!banned){
clients.push(socket);
clients[clients.length-1].addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
clients[clients.length-1].addEventListener(Event.CLOSE, socketDisconnectHandler);
send(2,Constants.mainRef.encrypt(Constants.mainRef.username));
}else{
socket.close();
}
}
private function socketDisconnectHandler(e:Event):void {
send(3,Constants.mainRef.encrypt( clientUsernames[clients.indexOf(e.target)] ) );
clientUsernames.splice(clients.indexOf(e.target),1);
client_list.dataProvider = new DataProvider( clientUsernames );
clients.splice(clients.indexOf(e.target),1);
e.target.close();
e.target.removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
e.target.removeEventListener(Event.CLOSE, socketDisconnectHandler);
}
private var currentDataStr:String;
private var currentDataType:uint;
private function socketDataHandler(e:ProgressEvent):void {
var socket:Socket = e.currentTarget as Socket;
currentDataType = socket.readUnsignedInt();
currentDataStr = socket.readUTFBytes(socket.bytesAvailable);
send(currentDataType, currentDataStr);
if(currentDataType == 1){
chat_txt.appendText(Constants.mainRef.decrypt(currentDataStr) );
if(autoScroll){
chat_txt.scrollV=chat_txt.maxScrollV;
}
scrollBar.update();
if(soundwarn){
//give sound warning
var snd:Sound = new Sound(new URLRequest("sound/ding.mp3"));
snd.play();
}
}else if(currentDataType == 2){
var tempString:String = Constants.mainRef.decrypt(currentDataStr);
clientUsernames.push(tempString);
client_list.dataProvider = new DataProvider( clientUsernames );
}
tempString=String("");
currentDataStr=String("");
currentDataType=0;
}
private function commandHandler(e:KeyboardEvent):void {
if(e.keyCode==13){
//ENTER GOT PRESSED
var commandStr:String = send_txt.text;
if(commandStr.indexOf(".") == 0){
if(commandStr.indexOf(".del") > -1 ){
chat_txt.text = String("");
currentDataStr = String("");
chat_txt.scrollV=chat_txt.maxScrollV;
scrollBar.update();
}else if(commandStr.indexOf(".burn") > -1 ){
if(chat_txt.length > 0){
send(4,Constants.mainRef.encrypt("burn"));
chat_txt.text = String("");
chat_txt.scrollV=chat_txt.maxScrollV;
scrollBar.update();
}
}else if(commandStr.indexOf(".share") > -1 ){
if(chat_txt.length > 0){
send(5,Constants.mainRef.encrypt(chat_txt.text));
}
}else if(commandStr.indexOf(".ip") > -1 ){
getIpOnline();
}else if(commandStr.indexOf(".roll") > -1 ){
var rngMax:int = parseInt( commandStr.slice(commandStr.indexOf(" ")) );
if(rngMax > 0){
var rawString:String = Constants.mainRef.username + " rolled " + String(Constants.mainRef.randomNum(1,rngMax)) + " out of " + String(rngMax) + "\n";
send(1, Constants.mainRef.encrypt( rawString ) );
chat_txt.appendText( rawString );
if(autoScroll){
chat_txt.scrollV=chat_txt.maxScrollV;
}
scrollBar.update();
}
}else if(commandStr.indexOf(".kick") > -1 && client_list.selectedIndex > -1){
clients[client_list.selectedIndex].close();
clients[client_list.selectedIndex].removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
clients[client_list.selectedIndex].removeEventListener(Event.CLOSE, socketDisconnectHandler);
clients.splice(client_list.selectedIndex,1);
send(3,Constants.mainRef.encrypt( clientUsernames[client_list.selectedIndex] ) );
clientUsernames.splice(client_list.selectedIndex,1);
client_list.dataProvider = new DataProvider( clientUsernames );
}
}else if(commandStr.length > 0){
send(1, Constants.mainRef.encrypt(Constants.mainRef.username + ": " + commandStr + "\n"));
chat_txt.appendText(Constants.mainRef.username + ": " + commandStr + "\n");
if(autoScroll){
chat_txt.scrollV=chat_txt.maxScrollV;
}
scrollBar.update();
}
send_txt.text = String("");
commandStr = String("");
Constants.STAGE.focus = null;
}
}
public function send(typeIndex:uint, data:String):void {
for each(var client:Socket in clients){
client.writeUnsignedInt(typeIndex);
client.writeUTFBytes(data);
client.flush();
}
}
private function getIpOnline():void{
var phpFileRequest:URLRequest = new URLRequest("https://api.ipify.org/");
phpFileRequest.method = URLRequestMethod.GET;
var phpLoader:URLLoader = new URLLoader();
phpLoader.addEventListener(Event.COMPLETE, showResult);
phpLoader.load(phpFileRequest);
}
private function showResult(e:Event):void{
send_txt.text = String(e.target.data);
e.target.removeEventListener(Event.COMPLETE, showResult);
}
public function die():void{
var i:uint
for(i = 0; i < clients.length; i++) {
clients[i].close();
clients[i].removeEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
clients[i].removeEventListener(Event.CLOSE, socketDisconnectHandler);
}
server.removeEventListener(ServerSocketConnectEvent.CONNECT, serverConnectHandler);
server.close();
chat_txt.text = String("");
send_txt.text = String("");
kick_btn.removeEventListener(MouseEvent.CLICK, kickHandler);
ban_btn.removeEventListener(MouseEvent.CLICK, banHandler);
preventSleep_check.removeEventListener(Event.CHANGE, sleepChangeHandler);
close_btn.removeEventListener(MouseEvent.CLICK, closeHandler);
burn_btn.removeEventListener(MouseEvent.CLICK, burnHandler);
share_btn.removeEventListener(MouseEvent.CLICK, shareHandler);
scroll_down_btn.removeEventListener(MouseEvent.CLICK, scrollDownHandler);
soundButton.removeEventListener(MouseEvent.CLICK, soundClickHandler);
autoClean_btn.removeEventListener(Event.CHANGE, autoCleanHandler);
this.removeEventListener(Event.ENTER_FRAME, autoCleanFrameListener);
scrollBar.removeEventListener(Event.SCROLL, scrollingListener);
send_txt.removeEventListener(KeyboardEvent.KEY_DOWN, commandHandler);
clients.length=0;
clientUsernames.length=0;
if(Constants.cardIndexer.length > 0){
for (i = 0; i < Constants.cardIndexer.length; i++) {
Constants.cardIndexer[i].die(4);
}
Constants.cardIndexer.length=0;
Constants.deckRef.length=0;
}
this.parent.removeChild(this);
}
private function chatText(texty:String,chat:Boolean=true):void{
if(chat){
send(1, Constants.mainRef.encrypt(Constants.mainRef.username + ": " + texty + "\n"));
chat_txt.appendText(Constants.mainRef.username + ": " + texty + "\n");
if(autoScroll){
chat_txt.scrollV=chat_txt.maxScrollV;
}
scrollBar.update();
}else{
send(1, Constants.mainRef.encrypt(texty + "\n"));
chat_txt.appendText(texty + "\n");
if(autoScroll){
chat_txt.scrollV=chat_txt.maxScrollV;
}
scrollBar.update();
}
}
}
}

For those who will struggle with this problem in the future.
Mainly 2 things required to be able to host a socket server successfully visible from
the internet:
-port forwarding.
-put your air app in firewall "allow" list.
(in my situation this was the missing part. ouch!)
Now everything works as it should.

Related

When using setOnGroupClickListener method report an error “cannot find symbol”

When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}

Remove Unknown tags (C3, BF40, C2) from TLV using TLVUtility on terminalSdk-2.0.3.jar

I am trying to remove some Unknown tags (C3, BF40, C2,.. etc) from ByteArray using TLVUtility (mastercard class from terminalSdk-2.0.3.jar), Tags was not removing from the ByteArray. I am trying like this,
Here is my TLV Data I have,
ppseResponse = ByteUtility.hexStringToByteArray("6F54840E325041592E5359532E4444463031C30F4920414D2054484520424553542033BF4003C20101A52BBF0C28610C4F07A0000000041010870101610C4F07A0000000043060870103610A4F05B0123456788701099000")
I am trying this to remove the Unknown tags like,
"BEFORE << ${ByteUtility.byteArrayToHexString(ppseResponse)}".toLog(activity, TAG) //To print Log
val unknownTags = byteArrayOf((0x00C3).toByte(),(0xBF40).toByte(), (0x00C2).toByte())
var removed = TLVUtility.removeTag(ppseResponse, ContentType.TLV,unknownTags)
"AFTER << ${ByteUtility.byteArrayToHexString(removed)}".toLog(activity, TAG) //To print Log
Here is the function removeTag on terminalSdk-2.0.3.jar function look likes,
public static byte[] removeTag(byte[] var0, ContentType var1, byte[] var2) {
int var10000;
Throwable var10001;
String var28;
label698: {
var10000 = 2 % 2;
if (var0 != null) {
label691: {
var10000 = g + 85;
f = var10000 % 128;
if (var10000 % 2 == 0) {
byte[] var26 = var2;
byte var27;
label676: {
label675: {
try {
null.hashCode();
if (var26 == null) {
break label675;
}
} catch (Throwable var25) {
throw var25;
}
var27 = 42;
break label676;
}
var27 = 74;
}
switch(var27) {
case 42:
break;
case 74:
default:
break label691;
}
} else if (var2 == null) {
break label691;
}
var10000 = f + 55;
g = var10000 % 128;
switch(var10000 % 2 != 0 ? 0 : 1) {
case 0:
default:
if (var2.length >= 1) {
break label698;
}
break;
case 1:
if (var2.length >= 1) {
break label698;
}
}
}
}
var28 = e(31, '卆', 490).intern();
try {
((Class)q.b(38, 8595, '\ue0f7')).getMethod("e", String.class).invoke((Object)null, var28);
} catch (Throwable var22) {
var10001 = var22.getCause();
if (var10001 != null) {
throw var10001;
}
throw var22;
}
throw new LibraryUncheckedException(ExceptionCode.X6F44);
}
label700: {
if (var1 == ContentType.T) {
var10000 = g + 15;
f = var10000 % 128;
if (var10000 % 2 == 0) {
if (var0.length < 0) {
break label700;
}
} else if (var0.length < 1) {
break label700;
}
}
switch(var1 != ContentType.TLV ? 81 : 64) {
case 81:
if (var1 != ContentType.TDO) {
break;
}
case 64:
default:
if (var0.length < 3) {
var28 = e(47, '\u0000', 560).intern();
try {
((Class)q.b(38, 8595, '\ue0f7')).getMethod("e", String.class).invoke((Object)null, var28);
} catch (Throwable var23) {
var10001 = var23.getCause();
if (var10001 != null) {
throw var10001;
}
throw var23;
}
throw new LibraryUncheckedException(ExceptionCode.X6F43);
}
}
ArrayList var3 = conditionalTlvParsing(var0, var1, e(1, '\u0000', 140).intern(), true);
Iterator var4 = var3.iterator();
while(var4.hasNext()) {
BerTlv var5 = (BerTlv)var4.next();
switch(var5.getTagObject().getNTag() == ByteUtility.byteArrayToInt(var2) ? 39 : 84) {
case 39:
default:
var4.remove();
case 84:
}
}
return formByteArrayFromTlvList(var3, var1);
}
var28 = e(39, '\u0000', 521).intern();
try {
((Class)q.b(38, 8595, '\ue0f7')).getMethod("e", String.class).invoke((Object)null, var28);
} catch (Throwable var24) {
var10001 = var24.getCause();
if (var10001 != null) {
throw var10001;
}
throw var24;
}
throw new LibraryUncheckedException(ExceptionCode.X6F43);
}
I fixed this issue by creating new custom function. Here is the function. Now on this function I am removing all the Unknown Tags and its Skipping all Known Tags and Third party data and Optional Tags Tags
First we need to define optional Tag,
private var optionalTags: ArrayList<ByteArray> = getOptionalTags()
Here is the function I am adding Optional Tags,
private fun getOptionalTags(): ArrayList<ByteArray> {
optionalTags = ArrayList()
optionalTags.add(ByteUtility.hexStringToByteArray("9F3E")) //Terminal Categories Supported List
optionalTags.add(ByteUtility.hexStringToByteArray("9F3F")) //Selection Data Object List
optionalTags.add(ByteUtility.hexStringToByteArray("9F2A")) //Kernel Identifier
optionalTags.add(ByteUtility.hexStringToByteArray("9F0A")) //Application Selection Registered Proprietary Data
return optionalTags
}
Here is the function to remove the Unknown tags,
private fun removeUnknownTags(ppseResponse: ByteArray): ByteArray {
var parentTags: MutableMap<ByteArray, Int> = LinkedHashMap()
var ppseResp = ppseResponse;
var i = 0
"PPSE (Length: ${ppseResp.size}) : HexString: ${ByteUtility.byteArrayToHexString(ppseResp)} \n ByteArray: ${ppseResp.toList()}".toLog()
while (i < ppseResp.size - 1) {
var removeTag = false;
var currentTag = TLVUtility.getCurrentTag(ppseResp, i);
var nextIndex = i + currentTag.size;
var tLVLengthInfo = TLVUtility.getTLVLengthInfo(ppseResp, nextIndex);
val tagLength = tLVLengthInfo.expectedNumberOfBytes
var tagValueSize = tLVLengthInfo.lengthBytes.size
var tagValue = ByteUtility.getSubByteArray(ppseResp, nextIndex + tagValueSize, tagLength)
"<==- ${i} : ${ByteUtility.byteArrayToHexString(currentTag)} (${TLVUtility.getReferenceTagDetails(currentTag).name}) , Length:${tagLength} (${tLVLengthInfo.lengthBytes.toList()} : ${ByteUtility.byteArrayToHexString(tLVLengthInfo.lengthBytes)}) , Max:${TLVUtility.getReferenceTagDetails(currentTag).maxLen} , Min:${TLVUtility.getReferenceTagDetails(currentTag).minLen} -==>".toLog()
"Value : ${ByteUtility.byteArrayToHexString(tagValue)} , Bytes:${tagValue.toList()}".toLog()
var tagNameLengthValue = ByteUtility.getSubByteArray(ppseResp, i, currentTag.size + tagValueSize + tagLength)
if (TLVUtility.getReferenceTagDetails(currentTag).name.contentEquals("Unknown Tag")) {
var optionalTag = false;
for (optTag in optionalTags) {
if (currentTag.contentEquals(optTag)) {
"${ByteUtility.byteArrayToHexString(currentTag)} is Optional Tag".toLog()
i = nextIndex + tagValueSize + tagLength;
optionalTag = true;
break
}
}
if (!optionalTag)
removeTag = true
} else if (TLVUtility.getReferenceTagDetails(currentTag).name.contentEquals("Third Party Data")) {
i = nextIndex + tagValueSize + tagLength;
} else {
if (!removeTag) {
if (TLVUtility.isTLVEncoded(tagValue)) {
parentTags.put(currentTag, i)
parentTags.entries.stream()
.sorted(Map.Entry.comparingByValue<ByteArray, Int>().reversed())
.forEachOrdered { x -> parentTags.put(x.key, x.value) }
if (tagValue.contentEquals(ByteUtility.hexStringToByteArray("00"))) {
i = nextIndex + tagValueSize + tagLength;
} else
i = nextIndex + tagValueSize
} else {
i = nextIndex + tagValueSize + tagLength;
}
}
}
if (removeTag) {
"-*-*-*-Removing TAG ${ByteUtility.byteArrayToHexString(currentTag)}-*-*-*-".toLog()
ppseResp = ByteUtility.getSubByteArray(ppseResp, 0, i) + ByteUtility.getSubByteArray(ppseResp, i + tagNameLengthValue.size)
var byteDiff = tagNameLengthValue.size
"--Updating Tag Length (Removed Bytes ${byteDiff})--".toLog()
for (tag in parentTags.entries.reversed()) {
var parentBytes = tag.key
var index = tag.value
var sizeIndex = index + parentBytes.size
var unknownTLVLengthInfo = TLVUtility.getTLVLengthInfo(ppseResp, sizeIndex);
val length = unknownTLVLengthInfo.expectedNumberOfBytes
if (i > index && i <= index + length) { //To Check is Parent Tag
"Parent Tag ${ByteUtility.byteArrayToHexString(tag.key)} (Bytes:${tag.key.toList()}) , Position:${tag.value}".toLog()
var lengthByteArray = unknownTLVLengthInfo.lengthBytes
var newLengthByteArray = ByteUtility.intToBerEncodedLength(length - byteDiff).bytes
var lengthDiff = lengthByteArray.size - newLengthByteArray.size;
byteDiff = byteDiff + lengthDiff
ppseResp = ByteUtility.getSubByteArray(ppseResp, 0, sizeIndex) + newLengthByteArray + ByteUtility.getSubByteArray(ppseResp, sizeIndex + lengthByteArray.size)
if (lengthDiff > 0) {
i = i - lengthDiff
for (child in parentTags.entries) {
if (child.value > tag.value) {
parentTags.replace(child.key, child.value - lengthDiff)
}
}
}
// "PPSE After (Length: ${ppseResp.size}): ${ByteUtility.byteArrayToHexString(ppseResp)} \n ByteArray: ${ppseResp.toList()}".toLog()
}
}
}
}
return ppseResp;
}

Exchange rate currency format setting in Flutter

I have an exchange rate application in flutter, but I want to make the currency format the same as below, how can I do it?
My Code :
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import '../Utils.dart';
class CurrencyInputFormatter extends TextInputFormatter {
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.selection.baseOffset == 0) {
print(true);
return newValue;
}
double value = double.parse(newValue.text);
final formatter = NumberFormat("#,##0", "tr-TR");
String newText = formatter.format(value);
print(newText);
return newValue.copyWith(
text: newText,
selection: new TextSelection.collapsed(offset: newText.length));
}
}
I want to do
Intl actually provides you a way to do so.
import 'package:intl/intl.dart';
final moneyText = 1000;
NumberFormat.simpleCurrency().format(moneyText);
If you are already using translation, you should have intl already.
You can achieve this with flutter_masked_text package it can do exactly the same.
I solved. works great.
library currency_text_input_formatter;
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
/// The `symbol` argument is used to symbol of NumberFormat.
/// Put '\$' for symbol
///
/// The `locale` argument is used to locale of NumberFormat.
/// Put 'en' or 'es' for locale
///
/// The `decimalDigits` argument is used to decimalDigits of NumberFormat.
/// Defaults `decimalDigits` is 2.
class CurrencyTextInputFormatter extends TextInputFormatter {
#override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
if (newValue.text.isEmpty) {
return newValue.copyWith(text: '');
} else if (newValue.text == ".") {
return newValue.copyWith(
text: '0.00',
selection: TextSelection.collapsed(offset: 2),
);
} else {
NumberFormat f = NumberFormat("#,###,###.00", "en_US");
double newNumber = 0;
if ((!newValue.text.contains(".")) && oldValue.text.contains('.')) {
String tempString = newValue.text.replaceAll(f.symbols.GROUP_SEP, '');
tempString = tempString.substring(0, tempString.length - 2) +
"." +
tempString.substring(tempString.length - 2);
newNumber = double.parse(tempString);
} else {
newNumber = double.parse(newValue.text
.replaceAll(f.symbols.GROUP_SEP, '')
.replaceAll("..", '.'));
}
String newString = f.format(newNumber);
int cursorPosition = 0;
if (oldValue.text.length > newString.length) {
cursorPosition = -1;
} else if (oldValue.text.length < newString.length) {
cursorPosition = 1;
} else {
if (oldValue.text.replaceAll(f.symbols.GROUP_SEP, '').length >
newValue.text.replaceAll(f.symbols.GROUP_SEP, '').length) {
cursorPosition = -1;
if (newString == "0.00" && oldValue.selection.baseOffset == 0) {
newString = "";
}
} else if (oldValue.text.replaceAll(f.symbols.GROUP_SEP, '').length <
newValue.text.replaceAll(f.symbols.GROUP_SEP, '').length) {
cursorPosition = 1;
} else if (oldValue.selection.extentOffset >
oldValue.selection.baseOffset) {
cursorPosition =
oldValue.selection.baseOffset - oldValue.selection.extentOffset;
newString =
newString.substring(0, oldValue.selection.baseOffset - 1) +
newString.substring(oldValue.selection.baseOffset + 1);
newNumber = double.parse(newString
.replaceAll(f.symbols.GROUP_SEP, '')
.replaceAll("..", '.'));
newString = f.format(newNumber);
if (newString == "0.00" && oldValue.selection.baseOffset == 0) {
newString = "";
}
}
}
return TextEditingValue(
text: newString,
selection: TextSelection.collapsed(
offset: oldValue.selection.extent.offset +
cursorPosition +
(f.symbols.GROUP_SEP.allMatches(newString).length -
f.symbols.GROUP_SEP.allMatches(oldValue.text).length)),
);
}
}
}

Haxe, OpenFL android debug giving error in for cpp

I'm developing an app in FlashDevelop, using Haxe and OpenFl
When I test my app in flash target, it works fine. But when I compile for android, it comes up with this error during the compilation:
./src/ReaderView2.cpp: In member function 'virtual Void ReaderView2_obj::setZoom()':
./src/ReaderView2.cpp:653: error: base operand of '->' has non-pointer type 'String'
Build halted with errors (haxelib.exe).
...Which is obviously something to do with cpp, which I'm not really an expert.
Does any body know what the error means?
Here's the setZooom function: (the whole file is quite large)
public function setZoom()
{
hideOptions();
while (numChildren > 0)
{
Main.remove(getChildAt(0));
}
if (image != null) if (image.parent != null) image.parent.removeChild(image);
images = new Array();
field = new TextField();
var fieldFont = Assets.getFont("fonts/Kreon-Regular.ttf");
var format:TextFormat = new TextFormat(fieldFont.fontName, currentZoom, 0x4F4F4F);
format.align = TextFormatAlign.LEFT;
field.defaultTextFormat = format;
field.embedFonts = true;
field.text = fullText;
field.selectable = false;
field.wordWrap = true;
field.border = false;
field.autoSize = TextFieldAutoSize.LEFT;
field.width = displayWidth;
//field.x = 0;
//split string into words
var allParas:Array<String> = fullText.split("\r\n");
var words:Array<String>;
var fields:Array<TextField> = new Array();
var tempField:TextField = null;
var contentHeight:Float = displayHeight;
var wordI:Int;
var paraI:Int = 0;
var tempArr2:Array<String>;
while (paraI < allParas.length)
{
if (false) //check img tag
{
}
else //if para is words
{
wordI = 0;
words = allParas[paraI].split(" ");
while (wordI < words.length)
{
if (tempField == null || tempField.textHeight > contentHeight)
{
if (tempField != null) {
wordI--;
tempArr2 = tempField.text.toString().split(" ");
for (i in 0... tempArr2.length)
{
tempArr2.remove("");
}
tempArr2.pop();
tempField.text = tempArr2.join(" ");
}
tempField = new TextField();
tempField.defaultTextFormat = field.getTextFormat();
tempField.embedFonts = true;
tempField.text = "";
tempField.border = false;
tempField.selectable = false;
tempField.wordWrap = true;
tempField.autoSize = TextFieldAutoSize.LEFT;
tempField.width = displayWidth-2;
tempField.x = 0;
fields.push(tempField);
}
else
{
tempField.appendText(words[wordI] + (wordI == words.length - 1? "\n": " "));
wordI++;
}
}
}
paraI++;
}
var bd:BitmapData;
for (i in 0... fields.length)
{
bd = new BitmapData(Std.int(fields[i].width), Std.int(fields[i].height));
bd.draw(fields[i]);
images.push(new Bitmap(bd, PixelSnapping.AUTO, true));
}
//addChild(fields[0]);
images[0].x = 10;
addChild(images[0]);
currentPageInstance = images[0];
currentPage = 0;
drawScrollBar();
if (optionsBtn!=null)addChild(optionsBtn);
}
So apparently using the toString() funcion gives problems for a cpp target.

Unable to receive values more than 255 on Android device from Arduino

I am developing an application to receive data on an Android device from an Arduino. It displays values only up to 255 when I convert it to integer, but I want those values which are sent by the Arduino board. I have tried converting them to strings but that didn't work either.
How can I solve this problem?
Here's the code running on the Android device:
package pkg.MultipleDataReceiveFromArduinoArray;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import pkg.MultipleDataReceiveFromArduino.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;
public class MultipleDataReceiveFromArduinoActivity extends
Activity implements Runnable {
private TextView txtReceivedBytes;
private TextView txtWaterLitres;
private TextView txtSensor1;
private TextView txtSensor2;
private TextView txtSensor3;
private EditText etCallibrationValue;
private Button btnSetCallibrationValue;
private static final String ACTION_USB_PERMISSION =
"com.google.android.DemoKit.action.USB_PERMISSION";
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
private boolean mPermissionRequestPending;
private UsbAccessory mAccessory;
private ParcelFileDescriptor mFileDescriptor;
private FileInputStream mInputStream;
private FileOutputStream mOutputStream;
int countWaterVol = 0;
private int intCallibrationValue = 270;
private static final int MESSAGE_TEMPERATURE = 1;
private static final int MESSAGE_HUMIDITY = 2;
private static final int MESSAGE_WATERLEVEL = 3;
private static final byte COMMAND_OPEN_DOOR = 0x01;
private static final byte COMMAND_CLOSE_DOOR = 0x02;
protected class TelemetryPacket {
private int value;
public TelemetryPacket(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
private int composeInt(byte hi, byte lo) {
int val = (int) hi & 0xff;
val *= 256;
val += (int) lo & 0xff;
return val;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtReceivedBytes=(TextView)findViewById(R.id.txtReceivedBytes);
txtWaterLitres =(TextView)findViewById(R.id.txtWaterLitres);
txtSensor1 = (TextView) findViewById(R.id.txtSensor1);
txtSensor2 =(TextView)findViewById(R.id.txtSensor2);
txtSensor3 =(TextView)findViewById(R.id.txtSensor3);
etCallibrationValue = (EditText)findViewById(R.id.etCallibrationValue);
btnSetCallibrationValue =
(Button)findViewById(R.id.btnSetCallibrationValue);
setupAccessory();
btnSetCallibrationValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intCallibrationValue =
Integer.parseInt(etCallibrationValue.getText().toString());
Toast.makeText(getApplicationContext(),
"Callibration Value:" + intCallibrationValue,
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public Object onRetainNonConfigurationInstance() {
if (mAccessory != null) {
return mAccessory;
} else {
return super.onRetainNonConfigurationInstance();
}
}
#Override
public void onResume() {
super.onResume();
if (mInputStream != null && mOutputStream != null) {
// streams were not null");
return;
}
// streams were null");
UsbAccessory[] accessories = mUsbManager.getAccessoryList();
UsbAccessory accessory = (accessories == null ? null : accessories[0]);
if (accessory != null) {
if (mUsbManager.hasPermission(accessory)) {
openAccessory(accessory);
} else {
synchronized (mUsbReceiver) {
if (!mPermissionRequestPending) {
mUsbManager.requestPermission(
accessory, mPermissionIntent);
mPermissionRequestPending = true;
}
}
}
} else {
// null accessory
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
//TelemetryPacket p = (TelemetryPacket) msg.obj;
ValueMsg t = (ValueMsg) msg.obj;
txtReceivedBytes.setText("Received Bytes: "+t.getRet());
if (t.getReading4()==1) {
countWaterVol = countWaterVol+1;
txtWaterLitres.setText("Water Produced in Litres:"+
(countWaterVol+"\n"+"Interrupt Signal"+t.getReading3());
} else {
}
txtSensor1.setText("S 1: "+t.getReading1()+","+
"Reading 2: "+t.getReading2());
txtSensor2.setText("S 3: "+t.getReading3()+","+
"Reading 4: "+t.getReading4());
txtSensor3.setText("S 5: "+t.getReading5()+","+
"Reading 6: "+t.getReading6());
Alets alerts = new Alets();
}
};
private void setupAccessory() {
mUsbManager = UsbManager.getInstance(this);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
registerReceiver(mUsbReceiver, filter);
if (getLastNonConfigurationInstance() != null) {
mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
openAccessory(mAccessory);
}
}
private void openAccessory(UsbAccessory accessory) {
mFileDescriptor = mUsbManager.openAccessory(accessory);
if (mFileDescriptor != null) {
mAccessory = accessory;
FileDescriptor fd = mFileDescriptor.getFileDescriptor();
mInputStream = new FileInputStream(fd);
mOutputStream = new FileOutputStream(fd);
Thread thread = new Thread(null, this, "OpenAccessoryTest");
thread.start();
// Accessory opened
} else {
// failed to open accessory
}
}
private void closeAccessory() {
try {
if (mFileDescriptor != null) {
mFileDescriptor.close();
}
} catch (IOException e) {
} finally {
mFileDescriptor = null;
mAccessory = null;
}
}
public void run() {
int ret = 0;
//byte[] buffer = new byte[16384];
byte[] buffer = new byte[65536];
int i;
while (true) { // read data
try {
ret = mInputStream.read(buffer);
//ret= ret/3;
} catch (IOException e) {
break;
}
i = 0;
while (i < ret) {
int len = ret - i;
// if (len >= 1) {
int value = (int) buffer[0];
Message m = Message.obtain(mHandler);
m.obj = new ValueMsg('f',value,ret,buffer[1],buffer[2],
buffer[3],buffer[4],buffer[5]);
mHandler.sendMessage(m);
i += 1;
}
}
}
public static final long unsignedIntToLong(byte[] b)
{
long l = 0;
l |= b[0] & 0xFF;
l <<= 8;
l |= b[1] & 0xFF;
l <<= 8;
l |= b[2] & 0xFF;
l <<= 8;
l |= b[3] & 0xFF;
return l;
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0x10;
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
openAccessory(accessory);
} else {
// USB permission denied
}
}
} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
UsbAccessory accessory = UsbManager.getAccessory(intent);
if (accessory != null && accessory.equals(mAccessory)) {
// accessory detached
closeAccessory();
}
}
}
};
}
And here's the Arduino code (sketch):
#include <Usb.h>
#include <adk.h>
uint8_t b;
USB Usb;
ADK adk(&Usb,
"Ashok Kateshiya", // Manufacturer Name
"analog TEST", // Model Name
"TDS test ", // Description (user-visible string)
"0.1", // Version
"http://www.ashokkateshiya.co.cc",
"123456789"); // Serial Number (optional)
#define tds_pin A15
#define flow_pin 22
#define LLS_pin 49
float avg[10];
float value = 0;
int count;
int pin_state = 0, pin_old_state = 0;
int pulse_counter = 0;
int LLS_state;
int LLS_flag = 0;
int sensor_flag = 0;
int timer_flag = 0;
uint8_t msg[7] = { 0x00 };
uint16_t len = sizeof(msg);
uint8_t rcode;
void setup()
{
Serial.begin(115200);
Serial.print("\r\nADK demo start");
if (Usb.Init() == -1)
{
Serial.print("\r\nOSCOKIRQ failed to assert");
while(1); // halt
}
pinMode(tds_pin, INPUT);
pinMode(flow_pin, INPUT);
pinMode(LLS_pin, INPUT);
digitalWrite(LLS_pin, HIGH);
digitalWrite(flow_pin, HIGH);
TIMSK1 = 0x01;
TCCR1A = 0x00;
TCNT1 = 0x85EF;
TCCR1B = 0x05;
}
void loop()
{
Usb.Task();
if (adk.isReady() == false)
{
return;
}
TDS();
flow();
LLS();
}
void TDS()
{
for (count = 0; count < 10; count++)
{
avg[count] = analogRead(tds_pin);
}
for (count = 0; count < 10; count ++)
{
if (count == 0)
{
value = avg[count];
}
else
{
value = value + avg[count];
}
}
if (len > 0)
{
msg[0] = 0x1;
msg[1] = value/10;
rcode = adk.SndData (6, msg );
Serial.print("TDS 0 : ");
Serial.println(msg[0]);
Serial.print("TDS 1 : ");
Serial.println(msg[1]);
delay(10);
}
if (rcode && rcode != hrNAK)
USBTRACE2("DATA rcv :", rcode);
}
void flow()
{
pin_state = digitalRead(flow_pin);
if (pin_state == LOW)
{
pin_old_state = pin_state;
}
if ((pin_state == HIGH) && (pin_old_state == LOW))
{
pin_old_state = pin_state;
pulse_counter = (pulse_counter + 1);
sensor_flag = 1;
}
if ((pulse_counter / 25 == 1) && (sensor_flag == 1))
{
pulse_counter = 0;
sensor_flag = 0;
msg[2] = 0x2;
msg[3] = 1;
rcode = adk.SndData (6, msg );
Serial.print("value :");
Serial.println(msg[3]);
if (rcode && rcode != hrNAK)
{
USBTRACE2 ("USB DATA : ", rcode);
}
}
else
{
msg[2] = 0x2;
msg[3] = 0;
rcode = adk.SndData (6, msg );
Serial.print("value :");
Serial.println(msg[3]);
if (rcode && rcode != hrNAK)
{
USBTRACE2 ("USB DATA : ", rcode);
}
}
delay(10);
}
void LLS()
{
LLS_state = digitalRead(LLS_pin);
if (LLS_state != 0)
{
if (len > 0)
{
msg[4] = 0x3;
msg[5] = 0x0;
rcode = adk.SndData (6, msg );
Serial.print("LLS 4 : ");
Serial.println(msg[4]);
Serial.print("LLS 5 : ");
Serial.println(msg[5]);
}
}
else
{
msg[4] = 0x3;
msg[5] = 0x1;
rcode = adk.SndData (6, msg );
Serial.print("LLS 0 : ");
Serial.println(msg[4]);
Serial.print("LLS 2 : ");
Serial.println(msg[5]);
}
if (rcode && rcode != hrNAK)
USBTRACE2("DATA rcv :", rcode);
delay(10);
}
/****** timer overflow *******/
ISR(TIMER1_OVF_vect)
{
TCNT1 = 0x85EF;
if (pin_state == pin_old_state )
{
timer_flag = 1;
}
}
It looks like the problem is in the Arduino sketch. The msg array contains (unsigned) bytes which have a maximum value of 255.
The line:
msg[1] = value/10
implicitly truncates value/10 (which is an integer between 0 and 1023 - see http://arduino.cc/en/Reference/analogRead) to a maximum of 255.
To send value/10 you'll need to split it over 2 bytes. For example:
msg[1] = (uint8_t) (i & 0xFF);
msg[2] = (uint8_t) ((i >> 8) & 0xFF);
And msg will have to be one byte longer to accomodate.
On the Android (Java) side you'll need to do something like:
int value = (int) buffer[0];
// ...
int tds = buffer[1] + (buffer[2] << 8);
m.obj = new ValueMsg('f', value, ret, tds,
buffer[3], buffer[4], buffer[5], buffer[6]);
which will require a change to the definition of ValueMsg to accomodate.
Also, there may be a problem with the calls to SndData (assuming the library being used here is the USB_Host_Shield_2.0) as they always send 6 bytes even though in the first time through loop all 6 bytes of msg won't have been initialized.

Categories

Resources