0. Demo介绍
服务器IP Receiver控制整个安防系统,要求添加移动客户端App,手机用户控制IP Receiver获取安防设备的布撤防信息对其实时监控。
移动端设计:用户登陆->九宫格加密->实时监控
1. 设计通信协议
手机通过Http应用层协议的post方式与服务端IP Receiver通信。设计协议须注意添加command命令,通常情况下,客户端需要服务端有一个command的反馈确认,以便解析response.
try { JSONObject jo= new JSONObject(info); r_res = jo.getString("response"); // registration if (r_res.equals("login")) { r_code = jo.getString("code"); if (r_code.equals("100")) { r_data = jo.getString("data");
2 实现Http接口函数
程序基于C/S架构,Http通信的实现考虑一个统一的接口函数,把它作为一个独立类的方法。调用时,先new一个该类的对象,再调用方法。
由于通信过程有时间延迟,须更新UI,故sendMessage发送消息给主线程处理UI事件,这里要注意几点,
ws = new WampServer(DeviceActivity.this); Thread connectThread = new Thread(new Runnable() { public void run() { ws.connect(registerUrl, pairs1); } });3. 用户登陆
public SwitchView(Context context, String device) { super(context); this.context = context; dev = device; initView(); }每隔5秒发送心跳包从服务端更新设备信息,若有状态变化,则发送消息更新UI,由于涉及多个设备,须逐个检查更新,解决bundle.getString()空指针问题。
case MSG_UPDATE_DEV: { for (int i = 0; i < total_count; i++) { try { if (!bundle.getString("host_status" + i).isEmpty()) { sv[i].changeView(bundle.getString("host_status" + i)); System.out.println("update:"+i+" status:"+bundle.getString("host_status"+i)); } } catch (NullPointerException e) { e.printStackTrace(); continue; } } break;3) 开关控制逻辑设计
case MotionEvent.ACTION_MOVE: //1s delay to ensure safety if ((System.currentTimeMillis() - downTime) < 1000) { if (delayFlag == 0) { Toast.makeText(getContext(), "press more than 1s", Toast.LENGTH_SHORT).show(); delayFlag = 1; } //prevent the cursor from large movement int dx = (int) event.getRawX() - lastX; if (dx > bg_left + margin) { dx = bg_left + margin; } if (dx < -(bg_left + margin)) { dx = -(bg_left + margin); } //control the cursor movement cursor_left = v.getLeft() + dx; cursor_right = v.getRight() + dx; if(cursor_left <= bg_left + margin) { cursor_left = bg_left + margin; cursor_right = cursor_left + v.getWidth(); } if(cursor_right >= bg_right - margin) { cursor_right = bg_right - margin; cursor_left = cursor_right - v.getWidth(); } //maintain the cursor in the scope v.layout(cursor_left, cursor_top, cursor_right, cursor_bottom); lastX = (int) event.getRawX(); break; } //control the cursor movement
// do arm/disarm if ((isArm ^ isChecked()) && isSet == true) {
int result = ws.connect(commandUrl, pairs); // turn back to the last position if (result == 0) { if (isArm) sendMessageToUI(MSG_LAYOUT_CHANGE, "disarm"); else sendMessageToUI(MSG_LAYOUT_CHANGE, "arm"); }
JSONArray ja_host = jo_data.getJSONArray("host"); JSONObject jo_host; //add device if (account.isEmpty()) { for (int i = 0; i < ja_host.length(); i++) { jo_host = (JSONObject) ja_host.get(i); account.add(i, jo_host.getString("account")); host_status.add(i, jo_host.getString("host_status")); group_id.add(i, jo_host.getString("group_id")); }