Stap 13: MCU gegevens via het protocol ontvangen
MCU gegevens ontvangen en verzenden van protocol maakt gebruik van JSON pakketten, en de indeling is {"T": uw-waarde, "V": uw waarde,...}. Natuurlijk kunt u andere waarden definiëren. Maak de MyArray.java in src directory, gericht aan het verbinden van twee matrices. De code werd getoond zoals hieronder:
public class MyArray { static public byte[] arrayCat(byte[] buf1,byte[] buf2){ byte[] bufret=null; int len1 = 0; int len2 = 0; if(buf1 != null) len1 = buf1.length; if(buf2 != null) len2 = buf2.length; if(len1+len2 > 0) bufret = new byte[len1+len2]; if(len1 > 0) System.arraycopy(buf1, 0, bufret, 0, len1); if(len2 > 0) System.arraycopy(buf2, 0, bufret, len1, len2); return bufret; } }
Kopiëren van de protocol.java in mijn code van de steekproef aan src directory toevoegen lid
private Protocol protocol
Uit onCreate, verwijderen:
bluetoothHandler.setOnRecievedDataListener();
Toevoegen:
protocol = new Protocol(this, new Transmitter(this, bluetoothHandler)); protocol.setOnReceivedDataListener(recListener);
Het toevoegen van lid in MainActivity:
private static final boolean INPUT = false; private static final boolean OUTPUT = true; private static final boolean LOW = false; private static final boolean HIGH = true; private boolean digitalVal[]; private int analogVal[];
Initialiseren in onCreate:
digitalVal = new boolean[14]; analogVal = new int[14]; private OnReceivedRightDataListener recListener = new OnReceivedRightDataListener() { public int onReceivedData(String str) { // TODO Auto-generated method stub try { JSONObject readJSONObject = new JSONObject(str); int type = readJSONObject.getInt("T"); int value = readJSONObject.getInt("V"); switch(type){ case Protocol.ANALOG:{ int pin = readJSONObject.getInt("P"); analogVal[pin] = value; }break; case Protocol.DIGITAL:{ int pin = readJSONObject.getInt("P"); digitalVal[pin] = (value>0)?HIGH:LOW; }break; case Protocol.TEMPERATURE:{ float temperature = ((float)value)/100; }break; case Protocol.HUMIDITY:{ float humidity = ((float)value)/100; }break; default:break; } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return 0; } };