設備控制
下面以開關燈為例,通過二進制、json兩種格式簡要介紹與安卓設備通訊的例子。實際開發請只選擇以下其中一種消息格式。
注意:msgCode從[64,200)范圍代表控制查詢及響應,[200,255]范圍代表消息主動上報,其他范圍為AbleCloud內部使用,不允許重復定義。
1 使用二進制消息格式進行通訊
1.1 設備控制
以開關燈為例,協議如下:
//請求數據包
{ 68 :[
//關燈(二進制流,由廠商自己解析)
{ 0 , 0 , 0 , 0 },
//開燈(二進制流,由廠商自己解析)
{ 1 , 0 , 0 , 0 }
]}
//響應數據包
{ 102 :[
//失?。ǘM制流,由廠商自己解析)
{ 0 , 0 , 0 , 0 },
//成功(二進制流,由廠商自己解析)
{ 1 , 0 , 0 , 0 }
]}
-------------------------------------
private static final int CODE_SWITCH_REQ = 68;
private static final int CODE_SWITCH_RESP = 102;
private static final int OFF = 0;
private static final int ON = 1;
AC.handleMsg(new ACMsgHandler() {
@Override
public void handleMsg(ACDeviceMsg req, ACDeviceMsg resp) {
switch (reqMsg.getMsgCode()) {
case CODE_SWITCH_REQ:
//請求消息體
byte[] payload = reqMsg.getPayload();
if (payload[0] == ON) {
if (Light.turnLightOn()) {
respMsg.setPayload(new byte[]{1, 0, 0, 0}); //開燈成功
} else
respMsg.setPayload(new byte[]{0, 0, 0, 0}); //開燈失敗
} else {
if (Light.turnLightOff()) {
respMsg.setPayload(new byte[]{1, 0, 0, 0}); //關燈成功
} else
respMsg.setPayload(new byte[]{0, 0, 0, 0}); //關燈失敗
}
respMsg.setMsgCode(CODE_SWITCH_RESP);
break;
}
}
});
2 使用JSON消息格式進行通訊
2.1 設備控制
以開關燈為例,協議如下:
//請求數據包
{ 70 :[
//關燈
{"switch", 0}
//開燈
{"switch", 1}
]}
//響應數據包--JSON格式的resp不需要設置msgCode
{
//失敗
{"result", false},
//成功
{"result", true}
]}
-----------------------------
private static final int CODE_JSON = 70;
private static final int OFF = 0;
private static final int ON = 1;
AC.handleMsg(new ACMsgHandler() {
@Override
public void handleMsg(ACDeviceMsg req, ACDeviceMsg resp) {
//JSON格式的resp不需要設置msgCode
switch (reqMsg.getMsgCode()) {
case CODE_JSON:
//請求消息體
JSONObject req = new JSONObject(reqMsg.getJsonPayload());
//請求操作類型,關燈或開燈
int value = req.getInt("switch");
//響應消息體
JSONObject resp = new JSONObject();
if (value == ON) {
if (Light.turnLightOn()) {
resp.put("result", true);
respMsg.setJsonPayload(resp.toString()); //開燈成功
} else {
resp.put("result", false);
respMsg.setJsonPayload(resp.toString()); //開燈失敗
}
} else if (value == OFF) {
if (Light.turnLightOff()) {
resp.put("result", true);
respMsg.setJsonPayload(resp.toString()); //關燈成功
} else {
resp.put("result", false);
respMsg.setJsonPayload(resp.toString()); //關燈失敗
}
}
break;
}
}
});
(審核編輯: 林靜)
分享