Commit 8e9921cf6cf316b9bc7c8f90d94817db954b0e50

Authored by wugian
1 parent dbea6dcc

添加踢除机制

  1 +package com.gimi.common.cinema.utils;
  2 +
  3 +import android.os.Environment;
  4 +import android.support.annotation.IntDef;
  5 +import android.util.Log;
  6 +import org.json.JSONArray;
  7 +import org.json.JSONException;
  8 +import org.json.JSONObject;
  9 +
  10 +import javax.xml.transform.OutputKeys;
  11 +import javax.xml.transform.Source;
  12 +import javax.xml.transform.Transformer;
  13 +import javax.xml.transform.TransformerFactory;
  14 +import javax.xml.transform.stream.StreamResult;
  15 +import javax.xml.transform.stream.StreamSource;
  16 +import java.io.BufferedWriter;
  17 +import java.io.File;
  18 +import java.io.FileWriter;
  19 +import java.io.IOException;
  20 +import java.io.StringReader;
  21 +import java.io.StringWriter;
  22 +import java.lang.annotation.Retention;
  23 +import java.lang.annotation.RetentionPolicy;
  24 +import java.text.SimpleDateFormat;
  25 +import java.util.Date;
  26 +import java.util.Formatter;
  27 +import java.util.Locale;
  28 +
  29 +/**
  30 + * <pre>
  31 + * author: Blankj
  32 + * blog : http://blankj.com
  33 + * time : 2016/9/21
  34 + * desc : 日志相关工具类
  35 + * </pre>
  36 + */
  37 +public final class LogUtils {
  38 +
  39 + private LogUtils() {
  40 + throw new UnsupportedOperationException("u can't instantiate me...");
  41 + }
  42 +
  43 + public static final int V = 0x01;
  44 + public static final int D = 0x02;
  45 + public static final int I = 0x04;
  46 + public static final int W = 0x08;
  47 + public static final int E = 0x10;
  48 + public static final int A = 0x20;
  49 +
  50 + @IntDef({V, D, I, W, E, A})
  51 + @Retention(RetentionPolicy.SOURCE)
  52 + public @interface TYPE {
  53 + }
  54 +
  55 + private static final int FILE = 0xF1;
  56 + private static final int JSON = 0xF2;
  57 + private static final int XML = 0xF4;
  58 +
  59 + private static String dir; // log存储目录
  60 + private static boolean sLogSwitch = true; // log总开关
  61 + private static String sGlobalTag = null; // log标签
  62 + private static boolean sTagIsSpace = true; // log标签是否为空白
  63 + private static boolean sLog2FileSwitch = false;// log写入文件开关
  64 + private static boolean sLogBorderSwitch = true; // log边框开关
  65 + private static int sLogFilter = V; // log过滤器
  66 +
  67 + private static final String TOP_BORDER = "╔═══════════════════════════════════════════════════════════════════════════════════════════════════";
  68 + private static final String LEFT_BORDER = "║ ";
  69 + private static final String BOTTOM_BORDER = "╚═══════════════════════════════════════════════════════════════════════════════════════════════════";
  70 + private static final String LINE_SEPARATOR = System.getProperty("line.separator");
  71 +
  72 + private static final int MAX_LEN = 4000;
  73 + private static final String NULL_TIPS = "Log with null object.";
  74 + private static final String NULL = "null";
  75 + private static final String ARGS = "args";
  76 +
  77 + public static class Builder {
  78 +
  79 + public Builder() {
  80 + if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
  81 +// dir = Utils.getContext().getExternalCacheDir() + File.separator + "log" + File.separator;
  82 + } else {
  83 +// dir = Utils.getContext().getCacheDir() + File.separator + "log" + File.separator;
  84 + }
  85 + }
  86 +
  87 + public Builder setGlobalTag(String tag) {
  88 + if (!isSpace(tag)) {
  89 + LogUtils.sGlobalTag = tag;
  90 + sTagIsSpace = false;
  91 + } else {
  92 + LogUtils.sGlobalTag = "";
  93 + sTagIsSpace = true;
  94 + }
  95 + return this;
  96 + }
  97 +
  98 + public Builder setLogSwitch(boolean logSwitch) {
  99 + LogUtils.sLogSwitch = logSwitch;
  100 + return this;
  101 + }
  102 +
  103 + public Builder setLog2FileSwitch(boolean log2FileSwitch) {
  104 + LogUtils.sLog2FileSwitch = log2FileSwitch;
  105 + return this;
  106 + }
  107 +
  108 + public Builder setBorderSwitch(boolean borderSwitch) {
  109 + LogUtils.sLogBorderSwitch = borderSwitch;
  110 + return this;
  111 + }
  112 +
  113 + public Builder setLogFilter(@TYPE int logFilter) {
  114 + LogUtils.sLogFilter = logFilter;
  115 + return this;
  116 + }
  117 + }
  118 +
  119 + public static void v(Object contents) {
  120 + log(V, sGlobalTag, contents);
  121 + }
  122 +
  123 + public static void v(String tag, Object... contents) {
  124 + log(V, tag, contents);
  125 + }
  126 +
  127 + public static void d(Object contents) {
  128 + log(D, sGlobalTag, contents);
  129 + }
  130 +
  131 + public static void d(String tag, Object... contents) {
  132 + log(D, tag, contents);
  133 + }
  134 +
  135 + public static void i(Object contents) {
  136 + log(I, sGlobalTag, contents);
  137 + }
  138 +
  139 + public static void i(String tag, Object... contents) {
  140 + log(I, tag, contents);
  141 + }
  142 +
  143 + public static void w(Object contents) {
  144 + log(W, sGlobalTag, contents);
  145 + }
  146 +
  147 + public static void w(String tag, Object... contents) {
  148 + log(W, tag, contents);
  149 + }
  150 +
  151 + public static void e(Object contents) {
  152 + log(E, sGlobalTag, contents);
  153 + }
  154 +
  155 + public static void e(String tag, Object... contents) {
  156 + log(E, tag, contents);
  157 + }
  158 +
  159 + public static void a(Object contents) {
  160 + log(A, sGlobalTag, contents);
  161 + }
  162 +
  163 + public static void a(String tag, Object... contents) {
  164 + log(A, tag, contents);
  165 + }
  166 +
  167 + public static void file(Object contents) {
  168 + log(FILE, sGlobalTag, contents);
  169 + }
  170 +
  171 + public static void file(String tag, Object contents) {
  172 + log(FILE, tag, contents);
  173 + }
  174 +
  175 + public static void json(String contents) {
  176 + log(JSON, sGlobalTag, contents);
  177 + }
  178 +
  179 + public static void json(String tag, String contents) {
  180 + log(JSON, tag, contents);
  181 + }
  182 +
  183 + public static void xml(String contents) {
  184 + log(XML, sGlobalTag, contents);
  185 + }
  186 +
  187 + public static void xml(String tag, String contents) {
  188 + log(XML, tag, contents);
  189 + }
  190 +
  191 + private static void log(int type, String tag, Object... contents) {
  192 + if (!sLogSwitch) return;
  193 + final String[] processContents = processContents(type, tag, contents);
  194 + tag = processContents[0];
  195 + String msg = processContents[1];
  196 + switch (type) {
  197 + case V:
  198 + case D:
  199 + case I:
  200 + case W:
  201 + case E:
  202 + case A:
  203 + if (V == sLogFilter || type >= sLogFilter) {
  204 + printLog(type, tag, msg);
  205 + }
  206 + if (sLog2FileSwitch) {
  207 + print2File(tag, msg);
  208 + }
  209 + break;
  210 + case FILE:
  211 + print2File(tag, msg);
  212 + break;
  213 + case JSON:
  214 + printLog(D, tag, msg);
  215 + break;
  216 + case XML:
  217 + printLog(D, tag, msg);
  218 + break;
  219 + }
  220 +
  221 + }
  222 +
  223 + private static String[] processContents(int type, String tag, Object... contents) {
  224 + StackTraceElement targetElement = Thread.currentThread().getStackTrace()[5];
  225 + String className = targetElement.getClassName();
  226 + String[] classNameInfo = className.split("\\.");
  227 + if (classNameInfo.length > 0) {
  228 + className = classNameInfo[classNameInfo.length - 1];
  229 + }
  230 + if (className.contains("$")) {
  231 + className = className.split("\\$")[0];
  232 + }
  233 + if (!sTagIsSpace) {// 如果全局tag不为空,那就用全局tag
  234 + tag = sGlobalTag;
  235 + } else {// 全局tag为空时,如果传入的tag为空那就显示类名,否则显示tag
  236 + tag = isSpace(tag) ? className : tag;
  237 + }
  238 +
  239 + String head = new Formatter()
  240 + .format("Thread: %s, %s(%s.java:%d)" + LINE_SEPARATOR,
  241 + Thread.currentThread().getName(),
  242 + targetElement.getMethodName(),
  243 + className,
  244 + targetElement.getLineNumber())
  245 + .toString();
  246 + String msg = NULL_TIPS;
  247 + if (contents != null) {
  248 + if (contents.length == 1) {
  249 + Object object = contents[0];
  250 + msg = object == null ? NULL : object.toString();
  251 + if (type == JSON) {
  252 + msg = formatJson(msg);
  253 + } else if (type == XML) {
  254 + msg = formatXml(msg);
  255 + }
  256 + } else {
  257 + StringBuilder sb = new StringBuilder();
  258 + for (int i = 0, len = contents.length; i < len; ++i) {
  259 + Object content = contents[i];
  260 + sb.append(ARGS)
  261 + .append("[")
  262 + .append(i)
  263 + .append("]")
  264 + .append(" = ")
  265 + .append(content == null ? NULL : content.toString())
  266 + .append(LINE_SEPARATOR);
  267 + }
  268 + msg = sb.toString();
  269 + }
  270 + }
  271 + if (sLogBorderSwitch) {
  272 + StringBuilder sb = new StringBuilder();
  273 + String[] lines = msg.split(LINE_SEPARATOR);
  274 + for (String line : lines) {
  275 + sb.append(LEFT_BORDER).append(line).append(LINE_SEPARATOR);
  276 + }
  277 + msg = sb.toString();
  278 + }
  279 + return new String[]{tag, head + msg};
  280 + }
  281 +
  282 + private static String formatJson(String json) {
  283 + try {
  284 + if (json.startsWith("{")) {
  285 + json = new JSONObject(json).toString(4);
  286 + } else if (json.startsWith("[")) {
  287 + json = new JSONArray(json).toString(4);
  288 + }
  289 + } catch (JSONException e) {
  290 + e.printStackTrace();
  291 + }
  292 + return json;
  293 + }
  294 +
  295 + private static String formatXml(String xml) {
  296 + try {
  297 + Source xmlInput = new StreamSource(new StringReader(xml));
  298 + StreamResult xmlOutput = new StreamResult(new StringWriter());
  299 + Transformer transformer = TransformerFactory.newInstance().newTransformer();
  300 + transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  301 + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  302 + transformer.transform(xmlInput, xmlOutput);
  303 + xml = xmlOutput.getWriter().toString().replaceFirst(">", ">" + LINE_SEPARATOR);
  304 + } catch (Exception e) {
  305 + e.printStackTrace();
  306 + }
  307 + return xml;
  308 + }
  309 +
  310 + private static void printLog(int type, String tag, String msg) {
  311 + if (sLogBorderSwitch) printBorder(type, tag, true);
  312 + int len = msg.length();
  313 + int countOfSub = len / MAX_LEN;
  314 + if (countOfSub > 0) {
  315 + int index = 0;
  316 + String sub;
  317 + for (int i = 0; i < countOfSub; i++) {
  318 + sub = msg.substring(index, index + MAX_LEN);
  319 + printSubLog(type, tag, sub);
  320 + index += MAX_LEN;
  321 + }
  322 + printSubLog(type, tag, msg.substring(index, len));
  323 + } else {
  324 + printSubLog(type, tag, msg);
  325 + }
  326 + if (sLogBorderSwitch) printBorder(type, tag, false);
  327 + }
  328 +
  329 + private static void printSubLog(final int type, final String tag, String msg) {
  330 + if (sLogBorderSwitch) msg = LEFT_BORDER + msg;
  331 + switch (type) {
  332 + case V:
  333 + Log.v(tag, msg);
  334 + break;
  335 + case D:
  336 + Log.d(tag, msg);
  337 + break;
  338 + case I:
  339 + Log.i(tag, msg);
  340 + break;
  341 + case W:
  342 + Log.w(tag, msg);
  343 + break;
  344 + case E:
  345 + Log.e(tag, msg);
  346 + break;
  347 + case A:
  348 + Log.wtf(tag, msg);
  349 + break;
  350 + }
  351 + }
  352 +
  353 + private static void printBorder(int type, String tag, boolean isTop) {
  354 + String border = isTop ? TOP_BORDER : BOTTOM_BORDER;
  355 + switch (type) {
  356 + case V:
  357 + Log.v(tag, border);
  358 + break;
  359 + case D:
  360 + Log.d(tag, border);
  361 + break;
  362 + case I:
  363 + Log.i(tag, border);
  364 + break;
  365 + case W:
  366 + Log.w(tag, border);
  367 + break;
  368 + case E:
  369 + Log.e(tag, border);
  370 + break;
  371 + case A:
  372 + Log.wtf(tag, border);
  373 + break;
  374 + }
  375 + }
  376 +
  377 + private synchronized static void print2File(final String tag, final String msg) {
  378 + Date now = new Date();
  379 + String date = new SimpleDateFormat("MM-dd", Locale.getDefault()).format(now);
  380 + final String fullPath = dir + date + ".txt";
  381 + if (!createOrExistsFile(fullPath)) {
  382 + Log.e(tag, "log to " + fullPath + " failed!");
  383 + return;
  384 + }
  385 + String time = new SimpleDateFormat("MM-dd HH:mm:ss.SSS ", Locale.getDefault()).format(now);
  386 + StringBuilder sb = new StringBuilder();
  387 + if (sLogBorderSwitch) sb.append(TOP_BORDER).append(LINE_SEPARATOR);
  388 + sb.append(time)
  389 + .append(tag)
  390 + .append(": ")
  391 + .append(msg)
  392 + .append(LINE_SEPARATOR);
  393 + if (sLogBorderSwitch) sb.append(BOTTOM_BORDER).append(LINE_SEPARATOR);
  394 + final String dateLogContent = sb.toString();
  395 + new Thread(new Runnable() {
  396 + @Override
  397 + public void run() {
  398 + BufferedWriter bw = null;
  399 + try {
  400 + bw = new BufferedWriter(new FileWriter(fullPath, true));
  401 + bw.write(dateLogContent);
  402 + Log.d(tag, "log to " + fullPath + " success!");
  403 + } catch (IOException e) {
  404 + e.printStackTrace();
  405 + Log.e(tag, "log to " + fullPath + " failed!");
  406 + } finally {
  407 + try {
  408 + if (bw != null) {
  409 + bw.close();
  410 + }
  411 + } catch (IOException e) {
  412 + e.printStackTrace();
  413 + }
  414 + }
  415 + }
  416 + }).start();
  417 + }
  418 +
  419 + private static boolean createOrExistsFile(String filePath) {
  420 + return createOrExistsFile(isSpace(filePath) ? null : new File(filePath));
  421 + }
  422 +
  423 + private static boolean createOrExistsFile(File file) {
  424 + if (file == null) return false;
  425 + if (file.exists()) return file.isFile();
  426 + if (!createOrExistsDir(file.getParentFile())) return false;
  427 + try {
  428 + return file.createNewFile();
  429 + } catch (IOException e) {
  430 + e.printStackTrace();
  431 + return false;
  432 + }
  433 + }
  434 +
  435 + private static boolean createOrExistsDir(File file) {
  436 + return file != null && (file.exists() ? file.isDirectory() : file.mkdirs());
  437 + }
  438 +
  439 + private static boolean isSpace(String s) {
  440 + if (s == null) return true;
  441 + for (int i = 0, len = s.length(); i < len; ++i) {
  442 + if (!Character.isWhitespace(s.charAt(i))) {
  443 + return false;
  444 + }
  445 + }
  446 + return true;
  447 + }
  448 +}
@@ -25,17 +25,26 @@ import android.view.Window; @@ -25,17 +25,26 @@ import android.view.Window;
25 import android.widget.Button; 25 import android.widget.Button;
26 import android.widget.SeekBar; 26 import android.widget.SeekBar;
27 import android.widget.TextView; 27 import android.widget.TextView;
  28 +import android.widget.Toast;
28 import com.gimi.common.cinema.utils.Utils; 29 import com.gimi.common.cinema.utils.Utils;
29 import com.qnbar.smc.model.Light; 30 import com.qnbar.smc.model.Light;
30 import com.qnbar.smc.model.Lights; 31 import com.qnbar.smc.model.Lights;
31 import com.qnbar.smc.service.TelinkLightService; 32 import com.qnbar.smc.service.TelinkLightService;
  33 +import com.telink.bluetooth.event.DeviceEvent;
  34 +import com.telink.bluetooth.event.LeScanEvent;
  35 +import com.telink.bluetooth.light.LightAdapter;
  36 +import com.telink.util.Event;
  37 +import com.telink.util.EventListener;
32 import com.xgimi.gimicinema.R; 38 import com.xgimi.gimicinema.R;
  39 +import com.xgimi.gimicinema.application.FangTangApplication;
33 40
34 41
35 -public class DeviceSettingActivity extends Activity implements OnClickListener { 42 +public class DeviceSettingActivity extends Activity implements OnClickListener, EventListener<String> {
36 43
37 private Handler handler = new Handler(); 44 private Handler handler = new Handler();
38 45
  46 + private FangTangApplication mApplication;
  47 +
39 private SeekBar brightnessBar; 48 private SeekBar brightnessBar;
40 private SeekBar temperatureBar; 49 private SeekBar temperatureBar;
41 private TextView temperatureTv; 50 private TextView temperatureTv;
@@ -107,6 +116,7 @@ public class DeviceSettingActivity extends Activity implements OnClickListener { @@ -107,6 +116,7 @@ public class DeviceSettingActivity extends Activity implements OnClickListener {
107 this.requestWindowFeature(Window.FEATURE_NO_TITLE); 116 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
108 this.setContentView(R.layout.activity_device_setting); 117 this.setContentView(R.layout.activity_device_setting);
109 118
  119 + mApplication = (FangTangApplication) getApplication();
110 this.meshAddress = this.getIntent().getIntExtra("meshAddress", 0); 120 this.meshAddress = this.getIntent().getIntExtra("meshAddress", 0);
111 121
112 Light light = Lights.getInstance().getByMeshAddress(meshAddress); 122 Light light = Lights.getInstance().getByMeshAddress(meshAddress);
@@ -142,8 +152,22 @@ public class DeviceSettingActivity extends Activity implements OnClickListener { @@ -142,8 +152,22 @@ public class DeviceSettingActivity extends Activity implements OnClickListener {
142 } 152 }
143 153
144 @Override 154 @Override
145 - public void onClick(View v) { 155 + public void onResume() {
  156 + super.onResume();
  157 + // 监听各种事件
  158 + mApplication.addEventListener(LeScanEvent.LE_SCAN, this);
  159 + mApplication.addEventListener(DeviceEvent.STATUS_CHANGED, this);
  160 + }
146 161
  162 + @Override
  163 + public void onClick(View v) {
  164 + switch (v.getId()) {
  165 + case R.id.btn_remove:
  166 + byte opcode = (byte) 0xE3;
  167 + TelinkLightService.Instance().sendCommand(opcode, meshAddress, null);
  168 + show("请稍候,踢除成功,若需要控制请联out_of_mesh");
  169 + break;
  170 + }
147 } 171 }
148 172
149 int brightness; 173 int brightness;
@@ -188,13 +212,47 @@ public class DeviceSettingActivity extends Activity implements OnClickListener { @@ -188,13 +212,47 @@ public class DeviceSettingActivity extends Activity implements OnClickListener {
188 } 212 }
189 213
190 @Override 214 @Override
  215 + protected void onPause() {
  216 + super.onPause();
  217 + mApplication.removeEventListener(this);
  218 + }
  219 +
  220 + @Override
191 protected void onDestroy() { 221 protected void onDestroy() {
192 super.onDestroy(); 222 super.onDestroy();
193 - Utils.saveInt(this,"brightness",brightnessBar.getProgress());  
194 - Utils.saveInt(this,"temperature",temperatureBar.getProgress()); 223 + Utils.saveInt(this, "brightness", brightnessBar.getProgress());
  224 + Utils.saveInt(this, "temperature", temperatureBar.getProgress());
195 } 225 }
196 226
197 public void changeBrightness(View view) { 227 public void changeBrightness(View view) {
198 brightnessUp(); 228 brightnessUp();
199 } 229 }
  230 +
  231 +
  232 + @Override
  233 + public void performed(Event<String> event) {
  234 + if (event instanceof DeviceEvent) {
  235 + this.onDeviceEvent((DeviceEvent) event);
  236 + }
  237 + }
  238 +
  239 + private void onDeviceEvent(DeviceEvent event) {
  240 + String type = event.getType();
  241 + switch (type) {
  242 + case DeviceEvent.STATUS_CHANGED:
  243 + int status = event.getArgs().status;
  244 + if (status == LightAdapter.STATUS_CONNECTED) {
  245 + show("device setting activity connected");
  246 + } else if (status == LightAdapter.STATUS_DELETE_COMPLETED) {
  247 + show("delete success");
  248 + } else if (status == LightAdapter.STATUS_DELETE_FAILURE) {
  249 + show("delete fail");
  250 + }
  251 + break;
  252 + }
  253 + }
  254 +
  255 + private void show(String msg) {
  256 + Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
  257 + }
200 } 258 }
@@ -141,6 +141,7 @@ public class MainActivity extends Activity implements EventListener<String> { @@ -141,6 +141,7 @@ public class MainActivity extends Activity implements EventListener<String> {
141 141
142 } 142 }
143 143
  144 +
144 @Override 145 @Override
145 protected void onRestart() { 146 protected void onRestart() {
146 super.onRestart(); 147 super.onRestart();
@@ -6,6 +6,7 @@ package com.qnbar.smc.service; @@ -6,6 +6,7 @@ package com.qnbar.smc.service;
6 public class SocketSendMsg { 6 public class SocketSendMsg {
7 public static final String REGISTER = "register"; 7 public static final String REGISTER = "register";
8 public static final String RECONNECT = "reconnect"; 8 public static final String RECONNECT = "reconnect";
  9 + public static final String HEART_BEAT = "heartbeat";
9 /** 10 /**
10 * cmd : register 11 * cmd : register
11 * data : {"room_sn":"000002"} 12 * data : {"room_sn":"000002"}
@@ -64,4 +65,10 @@ public class SocketSendMsg { @@ -64,4 +65,10 @@ public class SocketSendMsg {
64 return this; 65 return this;
65 } 66 }
66 67
  68 + public SocketSendMsg contractHeartBeatMsg(String roomSn) {
  69 + this.cmd = HEART_BEAT;
  70 + getDataEntity(roomSn);
  71 + return this;
  72 + }
  73 +
67 } 74 }
@@ -3,7 +3,6 @@ package com.qnbar.smc.service; @@ -3,7 +3,6 @@ package com.qnbar.smc.service;
3 import android.app.Service; 3 import android.app.Service;
4 import android.content.Context; 4 import android.content.Context;
5 import android.content.Intent; 5 import android.content.Intent;
6 -import android.os.Handler;  
7 import android.os.IBinder; 6 import android.os.IBinder;
8 import android.util.Log; 7 import android.util.Log;
9 import com.gimi.common.cinema.model.MessageEvent; 8 import com.gimi.common.cinema.model.MessageEvent;
@@ -26,15 +25,17 @@ public class SocketService extends Service { @@ -26,15 +25,17 @@ public class SocketService extends Service {
26 25
27 public static final int OPEN_DOOR_CMD = 1701; 26 public static final int OPEN_DOOR_CMD = 1701;
28 27
  28 + private static final int SUCESS_MESSAGE = 0;
29 private static final int ROOM_HAS_REGISTERED = 1001; 29 private static final int ROOM_HAS_REGISTERED = 1001;
30 private static final int ROOM_NOT_EXIST_M = 1002; 30 private static final int ROOM_NOT_EXIST_M = 1002;
31 private static final int HEAT_BEAT_RTN = 1003; 31 private static final int HEAT_BEAT_RTN = 1003;
32 32
33 - public static final String HOST = "121.43.189.162";// "192.168.1.21";// 33 + public static final String HOST = "192.168.200.191";// "192.168.1.21";//
34 public static final int PORT = 9501; 34 public static final int PORT = 9501;
35 35
36 - public static final String HEART_BEAT_STRING = "\\r\\n\\r\\n";//心跳包内容 36 + public static final String END_SYMBOL = "\\r\\n\\r\\n";//心跳包内容
37 public String testRoomSn = "000003"; 37 public String testRoomSn = "000003";
  38 +
38 private ReadThread mReadThread; 39 private ReadThread mReadThread;
39 private HeatBeatThread mHeatBeatThread; 40 private HeatBeatThread mHeatBeatThread;
40 private Gson gson; 41 private Gson gson;
@@ -44,28 +45,28 @@ public class SocketService extends Service { @@ -44,28 +45,28 @@ public class SocketService extends Service {
44 private WeakReference<Socket> mSocket; 45 private WeakReference<Socket> mSocket;
45 46
46 // For heart Beat 47 // For heart Beat
47 - private Handler mHandler = new Handler();  
48 - private Runnable heartBeatRunnable = new Runnable() {  
49 -  
50 - @Override  
51 - public void run() {  
52 - if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {  
53 - Log.d(TAG, "heart beat");  
54 - boolean isSuccess = sendMsg(HEART_BEAT_STRING);//就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket  
55 - if (!isSuccess) {  
56 - Log.d(TAG, "heart beat error restart");  
57 - mHandler.removeCallbacks(heartBeatRunnable);  
58 - mReadThread.release();  
59 - mHeatBeatThread.release();  
60 - releaseLastSocket(mSocket);  
61 - new InitSocketThread().start();  
62 - }  
63 - } else {  
64 - Log.d(TAG, "heart beat less than beat rate");  
65 - }  
66 - mHandler.postDelayed(this, HEART_BEAT_RATE);  
67 - }  
68 - }; 48 +// private Handler mHandler = new Handler();
  49 +// private Runnable heartBeatRunnable = new Runnable() {
  50 +//
  51 +// @Override
  52 +// public void run() {
  53 +// if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
  54 +// Log.d(TAG, "heart beat");
  55 +// boolean isSuccess = sendMsg(new Gson().toJson(new SocketSendMsg().contractHeartBeatMsg(testRoomSn)) + END_SYMBOL);//就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket
  56 +// if (!isSuccess) {
  57 +// Log.d(TAG, "heart beat error restart");
  58 +// mHandler.removeCallbacks(heartBeatRunnable);
  59 +// mReadThread.release();
  60 +// mHeatBeatThread.release();
  61 +// releaseLastSocket(mSocket);
  62 +// new InitSocketThread().start();
  63 +// }
  64 +// } else {
  65 +// Log.d(TAG, "heart beat less than beat rate");
  66 +// }
  67 +// mHandler.postDelayed(this, HEART_BEAT_RATE);
  68 +// }
  69 +// };
69 70
70 private long sendTime = 0L; 71 private long sendTime = 0L;
71 private Context context; 72 private Context context;
@@ -92,7 +93,7 @@ public class SocketService extends Service { @@ -92,7 +93,7 @@ public class SocketService extends Service {
92 if (null == mSocket || null == mSocket.get()) { 93 if (null == mSocket || null == mSocket.get()) {
93 return false; 94 return false;
94 } 95 }
95 - Log.d(TAG, msg); 96 + Log.d(TAG, "send msg:" + msg);
96 Socket soc = mSocket.get(); 97 Socket soc = mSocket.get();
97 try { 98 try {
98 if (!soc.isClosed() && !soc.isOutputShutdown()) { 99 if (!soc.isClosed() && !soc.isOutputShutdown()) {
@@ -179,7 +180,7 @@ public class SocketService extends Service { @@ -179,7 +180,7 @@ public class SocketService extends Service {
179 if (!sendRegister) { 180 if (!sendRegister) {
180 Log.d(TAG, "send register mes"); 181 Log.d(TAG, "send register mes");
181 SocketSendMsg ssm = new SocketSendMsg().contractRegisterMsg(testRoomSn); 182 SocketSendMsg ssm = new SocketSendMsg().contractRegisterMsg(testRoomSn);
182 - String msg = gson.toJson(ssm) + HEART_BEAT_STRING; 183 + String msg = gson.toJson(ssm) + END_SYMBOL;
183 sendMsg(msg); 184 sendMsg(msg);
184 Log.d(TAG, "" + msg); 185 Log.d(TAG, "" + msg);
185 sendRegister = true; 186 sendRegister = true;
@@ -193,13 +194,17 @@ public class SocketService extends Service { @@ -193,13 +194,17 @@ public class SocketService extends Service {
193 if (length > 0) { 194 if (length > 0) {
194 String message = new String(Arrays.copyOf(buffer, 195 String message = new String(Arrays.copyOf(buffer,
195 length)).trim(); 196 length)).trim();
196 - Log.d(TAG, message); 197 + Log.d(TAG, "end:" + message.contains(END_SYMBOL) + "");
  198 + Log.d(TAG, "recv msg:" + message);
197 try { 199 try {
198 SocketResponse socketResponse = gson.fromJson(message.trim(), SocketResponse.class); 200 SocketResponse socketResponse = gson.fromJson(message.trim(), SocketResponse.class);
199 switch (socketResponse.getCode()) { 201 switch (socketResponse.getCode()) {
  202 + case SUCESS_MESSAGE:
  203 + Log.d(TAG, "success:" + socketResponse.getCmd());
  204 + break;
200 case ROOM_HAS_REGISTERED: 205 case ROOM_HAS_REGISTERED:
201 SocketSendMsg ssm = new SocketSendMsg().contractReconnectMsg(testRoomSn); 206 SocketSendMsg ssm = new SocketSendMsg().contractReconnectMsg(testRoomSn);
202 - String msg = gson.toJson(ssm) + HEART_BEAT_STRING; 207 + String msg = gson.toJson(ssm) + END_SYMBOL;
203 sendMsg(msg); 208 sendMsg(msg);
204 Log.d(TAG, "send reconnect mes: " + msg); 209 Log.d(TAG, "send reconnect mes: " + msg);
205 break; 210 break;
@@ -225,7 +230,7 @@ public class SocketService extends Service { @@ -225,7 +230,7 @@ public class SocketService extends Service {
225 e.printStackTrace(); 230 e.printStackTrace();
226 } 231 }
227 //收到服务器过来的消息,就通过Broadcast发送出去 232 //收到服务器过来的消息,就通过Broadcast发送出去
228 -// if (message.equals(HEART_BEAT_STRING)) {//处理心跳回复 233 +// if (message.equals(END_SYMBOL)) {//处理心跳回复
229 // Intent intent = new Intent(HEART_BEAT_ACTION); 234 // Intent intent = new Intent(HEART_BEAT_ACTION);
230 // mLocalBroadcastManager.sendBroadcast(intent); 235 // mLocalBroadcastManager.sendBroadcast(intent);
231 // } else { 236 // } else {
@@ -268,7 +273,7 @@ public class SocketService extends Service { @@ -268,7 +273,7 @@ public class SocketService extends Service {
268 while (isStart) { 273 while (isStart) {
269 if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) { 274 if (System.currentTimeMillis() - sendTime >= HEART_BEAT_RATE) {
270 Log.d(TAG, "heart beat:" + Thread.currentThread().getId()); 275 Log.d(TAG, "heart beat:" + Thread.currentThread().getId());
271 - boolean isSuccess = sendMsg(HEART_BEAT_STRING);//就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket 276 + boolean isSuccess = sendMsg(new Gson().toJson(new SocketSendMsg().contractHeartBeatMsg(testRoomSn)) + END_SYMBOL);//就发送一个HEART_BEAT_STRING过去 如果发送失败,就重新初始化一个socket
272 if (!isSuccess) { 277 if (!isSuccess) {
273 Log.d(TAG, "heart beat error restart:" + Thread.currentThread().getId()); 278 Log.d(TAG, "heart beat error restart:" + Thread.currentThread().getId());
274 // mHandler.removeCallbacks(heartBeatRunnable); 279 // mHandler.removeCallbacks(heartBeatRunnable);
@@ -90,6 +90,7 @@ @@ -90,6 +90,7 @@
90 </LinearLayout> 90 </LinearLayout>
91 <TextView android:layout_width="match_parent" 91 <TextView android:layout_width="match_parent"
92 android:padding="15dp" 92 android:padding="15dp"
  93 + android:textSize="16sp"
93 android:textColor="@android:color/holo_red_dark" 94 android:textColor="@android:color/holo_red_dark"
94 android:layout_marginTop="30dp" 95 android:layout_marginTop="30dp"
95 android:layout_height="wrap_content" 96 android:layout_height="wrap_content"
@@ -97,29 +98,6 @@ @@ -97,29 +98,6 @@
97 98
98 /> 99 />
99 100
100 - <View  
101 - android:layout_width="match_parent"  
102 - android:layout_height="1dp"  
103 - android:layout_marginBottom="10dp"  
104 - android:layout_marginTop="10dp"  
105 - android:background="@color/gray"/>  
106 -  
107 -  
108 - <View  
109 - android:layout_width="match_parent"  
110 - android:layout_height="1dp"  
111 - android:layout_marginBottom="10dp"  
112 - android:layout_marginTop="10dp"  
113 - android:background="@color/gray"/>  
114 -  
115 -  
116 - <View  
117 - android:layout_width="match_parent"  
118 - android:layout_height="1dp"  
119 - android:layout_marginBottom="10dp"  
120 - android:layout_marginTop="10dp"  
121 - android:background="@color/gray"/>  
122 -  
123 101
124 <!-- Remove DeviceSchema --> 102 <!-- Remove DeviceSchema -->
125 103
@@ -127,36 +105,20 @@ @@ -127,36 +105,20 @@
127 android:id="@+id/btn_remove" 105 android:id="@+id/btn_remove"
128 android:layout_width="match_parent" 106 android:layout_width="match_parent"
129 android:layout_height="46dp" 107 android:layout_height="46dp"
  108 + android:textSize="16sp"
130 android:layout_margin="10dp" 109 android:layout_margin="10dp"
131 - android:background="@color/theme_positive_color"  
132 - android:text="Remove Device(Kick out)"  
133 - android:textColor="@android:color/white"/> 110 + android:text="踢除(重置mesh_name为out_of_mesh,请不要同时踢除多个!!)"
  111 + android:textColor="@color/black"/>
134 112
135 <Button 113 <Button
136 android:id="@+id/btn_delete" 114 android:id="@+id/btn_delete"
137 android:layout_width="match_parent" 115 android:layout_width="match_parent"
138 android:layout_height="46dp" 116 android:layout_height="46dp"
139 android:layout_margin="10dp" 117 android:layout_margin="10dp"
  118 + android:visibility="gone"
140 android:background="@color/theme_positive_color" 119 android:background="@color/theme_positive_color"
141 android:text="Remove Device(Pair Delete)" 120 android:text="Remove Device(Pair Delete)"
142 android:textColor="@android:color/white"/> 121 android:textColor="@android:color/white"/>
143 -  
144 - <Button  
145 - android:layout_width="match_parent"  
146 - android:layout_height="46dp"  
147 - android:layout_margin="10dp"  
148 - android:background="@color/theme_positive_color"  
149 - android:text="change brightness"  
150 - android:onClick="changeBrightness"  
151 - android:textColor="@android:color/white"/>  
152 - <Button  
153 - android:layout_width="match_parent"  
154 - android:layout_height="46dp"  
155 - android:layout_margin="10dp"  
156 - android:background="@color/theme_positive_color"  
157 - android:text="change color temperature"  
158 - android:onClick="changeTemperature"  
159 - android:textColor="@android:color/white"/>  
160 </LinearLayout> 122 </LinearLayout>
161 123
162 </LinearLayout> 124 </LinearLayout>
Please register or login to post a comment