com.shouxun.server.netty.tcp.EchoServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for com.shouxun.server.netty.tcp.EchoServerHandler.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.shouxun.server.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.internal.StringUtil;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import com.shouxun.server.content.Constant;
import com.shouxun.server.domain.Binding;
import com.shouxun.server.domain.Bracelet;
import com.shouxun.server.domain.Fence;
import com.shouxun.server.domain.Pulse;
import com.shouxun.server.domain.PushMessage;
import com.shouxun.server.domain.Step;
import com.shouxun.server.domain.TrackRoute;
import com.shouxun.server.domain.User;
import com.shouxun.server.netty.TrackDataServerHandler;
import com.shouxun.server.service.BraceletService;
import com.shouxun.server.service.FenceService;
import com.shouxun.server.service.PulseService;
import com.shouxun.server.service.PushMessageService;
import com.shouxun.server.service.StepService;
import com.shouxun.server.service.TrackRouteService;
import com.shouxun.server.util.BaiduPushUtil;
import com.shouxun.server.util.MapUtil;
import com.shouxun.server.util.ModifyOffset;
import com.shouxun.server.util.PointDouble;

/**
 * Handler implementation for the echo server.
 */
@SuppressWarnings("deprecation")
@Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = Logger.getLogger(TrackDataServerHandler.class);

    StringBuffer sb = new StringBuffer();
    public static HashMap<String, ChannelHandlerContext> hashMapClient = new HashMap<String, ChannelHandlerContext>();
    public static HashMap<String, Integer> hashMapPulse = new HashMap<String, Integer>();

    private PulseService pulseService;
    private StepService stepService;
    private TrackRouteService trackRouteService;
    private BraceletService braceletService;
    private PushMessageService pushMessageService;
    private FenceService fenceService;

    public EchoServerHandler(PulseService pulseService, StepService stepService,
            TrackRouteService trackRouteService, BraceletService braceletService,
            PushMessageService pushMessageService, FenceService fenceService) {
        this.pulseService = pulseService;
        this.stepService = stepService;
        this.trackRouteService = trackRouteService;
        this.braceletService = braceletService;
        this.pushMessageService = pushMessageService;
        this.fenceService = fenceService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server channelActive...");
        sb.delete(0, sb.length());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        ByteBuf buffer = (ByteBuf) msg;

        for (int i = 0; i < buffer.capacity(); i++) {
            byte b = buffer.getByte(i);
            sb.append((char) b);
        }
        buffer.release();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        System.out.println("server channelReadComplete..." + sb.toString());
        execuseDate(sb.toString(), ctx);
        ctx.flush();
        sb.delete(0, sb.length());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        System.out.println("server exceptionCaught...");
        cause.printStackTrace();
        ctx.close();
        sb.delete(0, sb.length());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server channelInactive...");
        //removeFromHashMapClient(ctx);
        super.channelInactive(ctx);
        sb.delete(0, sb.length());

    }

    public void execuseDate(String data, ChannelHandlerContext ctx) {
        if (data == null || data.equals("") || data.length() < 8) {
            return;
        }
        String[] datas = StringUtil.split(data.replaceAll("\\[", "").replaceAll("\\]", "").trim(), ',');

        String requestCode = datas[8].trim();
        String imei = datas[6].trim();
        System.out.println("server channelRead...questCode=" + requestCode + " imei=" + imei + " localAddress="
                + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

        StringBuffer sb = new StringBuffer();

        if (!data.contains("]")) {
            if (datas.length > 9 && datas[9].length() > 14) {
                //??
                sb.delete(0, sb.length());
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S911").append(",").append("0").append("]");
                if (hashMapClient.get(datas[9].trim()) != null) {
                    sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
                }
            }
            return;
        }

        //ip?????
        /*if(null != hashMapClient && hashMapClient.get(imei) != null){
           hashMapClient.put(imei, ctx);
        }*/

        switch (requestCode) {
        case "T1":// T1/S1
            hashMapClient.put(imei, ctx);
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(datas[9])
                    .append(",").append("S1").append(",").append("1").append(",").append(getGMT(datas[7].trim()))
                    .append(",").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S1=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            break;
        case "T2"://T2/S2
            hashMapClient.put(imei, ctx);
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S2").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S2=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            break;
        case "T5"://??,S5/T5
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T5,imei?]
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2014-11-28 13:40:20,1-1,460021581801906,8,T5,355372020827303
            //???
            System.out.println("server channelRead...T5" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S112").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }

            break;
        case "T7"://???
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T7,imei]
            System.out.println("server channelRead...T7" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S113").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T10":
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-1,355372020827303,8,T10,imei?]
            //???
            System.out.println("server channelRead...T10" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S114").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T11"://?
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T11,imei]
            System.out.println("server channelRead...T11" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S115").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T13":
            //???
            System.out.println("server channelRead...T13" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S116").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T15"://GPS?
            System.out.println("server channelRead...T15" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T15,imei]
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S117").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T18":
            System.out.println("server channelRead...T18" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S118").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T19":
            System.out.println("server channelRead...T19" + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S119").append(",").append("1").append("]");
            if (datas.length > 9 && hashMapClient.get(datas[9].trim()) != null) {
                sendMsg(sb.toString(), hashMapClient.get(datas[9].trim()));
            }
            break;
        case "T28"://???(T28/S28)
            //[V1.0.0,a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T28, imei?,mt_pulse,118, 1267511609]
            //????
            hashMapClient.put(imei, ctx);
            Pulse pulse = new Pulse();
            try {
                pulse.setImei(imei);
                pulse.setDataType(datas[10]);
                pulse.setPulseCount(Integer.valueOf(datas[11]));
                pulseService.save(pulse);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //S28
            //[v1.0.0, a1d83kdeio3fg33k,1,d961,2013-08-07 00:12:52,123456789012345,S28]
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S28").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S28=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            //??
            if (!(datas[9] == null || datas[9].equals(""))) {
                sb.delete(0, sb.length());
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S112").append(",").append("2").append(",")
                        .append(datas[10]).append(",").append(datas[11]).append(",").append(datas[12]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(datas[9]));
            }
            break;
        case "T29":
            hashMapClient.put(imei, ctx);
            //S29
            //[v1.0.0, a1d83kdeio3fg33k,1,d961,2013-08-07 00:12:52,123456789012345,S28]
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S29").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S29=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            //????
            //[V1.0.0,a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00, 1-2,355372020827303,8,T29, imei?,GPS_AT, 114.356170, 34.824230, count$1$0|28725|18784,20,30,40,1267511609]
            double x = 0;
            double y = 0;
            PointDouble newpt = null;
            String url = "";
            String type = "";
            //GPS?LBS?????
            if ((datas[11] != null && !datas[11].equals("")) && (datas[12] != null && !datas[12].equals(""))) {
                //GPS?
                x = Double.valueOf(datas[11]);//?
                y = Double.valueOf(datas[12]);//
                type = "GPS";
                TrackRoute trackRoute = new TrackRoute();
                trackRoute.setImei(datas[6]);
                ModifyOffset mo;
                try {
                    mo = ModifyOffset
                            .getInstance(TrackDataServerHandler.class.getResourceAsStream("/axisoffset.dat"));
                    PointDouble pt = new PointDouble(x, y);
                    newpt = mo.s2c(pt);
                    trackRoute.setLongitude(newpt.x);
                    trackRoute.setLatitude(newpt.y);
                    trackRoute.setLocationType("GPS");

                    trackRouteService.save(trackRoute);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                //LBS?
                //[V1.0.0,31,1,abcd,2015-01-26 14:45:38,1-4,866161010000076,0,T29,,GPS_SOS,121.3927350,31.1634062,mcount$5$460$0$0#1806|1231|0|36#1806|3292|0|27#1806|1241|0|25#1806|1232|0|25#1806|2183|0|26,0,0,0,1422254738]
                //http://minigps.net/as?x=460-0-1806-1231-92-1806-2183-8d-1806-1241-87-1806-3292-8b-1806-21b2-8d-1806-2123-8f &p=1&mt&ta&needaddress
                //http://minigps.net/as?x=1cc-0-18be-9f22-95-18be-9121-7b-18be-91e2-76-18be-9122-76-18c2-f2b1-74-18cc-f412-79 &ta=0&p=1&mt=0&needaddress=0
                type = "LBS";
                url = "http://minigps.net/as?x=";
                String[] params = datas[13].trim().split("\\$");
                url += Integer.toHexString(Integer.valueOf(params[2])) + "-"
                        + Integer.toHexString(Integer.valueOf(params[3]));
                String[] lbs = params[4].split("#");
                String[] lbsParam;
                for (int i = 1; i < lbs.length; i++) {
                    lbsParam = lbs[i].split("\\|");
                    url += "-" + lbsParam[0];
                    url += "-" + lbsParam[1];
                    url += "-" + Integer.toHexString(Integer.valueOf(Integer.valueOf(lbsParam[3]) + 110));
                }
                url += "&ta=0&p=1&mt=0&needaddress=0";
                System.out.println("get LBS url=" + url);

                // (1) HttpGet
                HttpGet get = new HttpGet(url);

                // (2) HttpClient??getHttpResponse
                HttpClient http = new DefaultHttpClient();
                HttpResponse response;
                InputStream in = null;
                try {
                    response = http.execute(get);
                    // (3) ?
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();

                        in = entity.getContent();

                        String result = readString(in);
                        System.out.println("get LBS url result=" + result);
                        if (result != null && result.startsWith("{")) {
                            JSONObject jsonObject = JSONObject.fromObject(result);
                            if (jsonObject.getInt("status") == 0) {
                                x = jsonObject.getDouble("lon");
                                y = jsonObject.getDouble("lat");
                                TrackRoute trackRoute = new TrackRoute();
                                trackRoute.setImei(datas[6]);
                                ModifyOffset mo;
                                try {
                                    mo = ModifyOffset.getInstance(
                                            TrackDataServerHandler.class.getResourceAsStream("/axisoffset.dat"));
                                    PointDouble pt = new PointDouble(x, y);
                                    newpt = mo.s2c(pt);
                                    trackRoute.setLongitude(newpt.x);
                                    trackRoute.setLatitude(newpt.y);
                                    trackRoute.setLocationType("LBS");

                                    trackRouteService.save(trackRoute);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }

            }

            //??,????????
            if (!(datas[9] == null || datas[9].equals(""))) {
                sb.delete(0, sb.length());
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S116").append(",").append("2").append(",")
                        .append(null != newpt ? newpt.x : -1).append(",").append(null != newpt ? newpt.y : -1)
                        .append(",").append(type).append("]");
                sendMsg(sb.toString(), hashMapClient.get(datas[9]));
            }

            Bracelet bracelet = braceletService.get(imei);
            if (bracelet != null) {
                Set<Fence> fences = bracelet.getFences();
                for (Fence fence : fences) {
                    double distance = 0;
                    distance = MapUtil.getDistance(y, x, fence.getLatitude(), fence.getLongitude())
                            - fence.getRadius();
                    DecimalFormat df = new DecimalFormat(".##");
                    if (distance > 0) {

                        if (fence.getIsOutside() == 0) {
                            fence.setIsOutside(1);
                            fenceService.update(fence);
                            for (Binding binding : bracelet.getBingdings()) {
                                User user = binding.getUser();
                                JSONObject jsonObject = new JSONObject();
                                if (user.getDeivceType().equals("android") && user.getChannelID() != null
                                        && !user.getChannelID().equals("")) {
                                    String desc = "??[" + bracelet.getName() + "]"
                                            + df.format(distance) + "";
                                    jsonObject.put("title", "????");
                                    jsonObject.put("description", desc);
                                    jsonObject.put("open_type", 2);
                                    jsonObject.put("pkg_content", "");
                                    BaiduPushUtil.androidPushNotification(user.getChannelID(), user.getUserID(),
                                            jsonObject.toString());

                                    PushMessage pushMessage = new PushMessage();
                                    pushMessage.setChannelID(user.getChannelID());
                                    pushMessage.setDeivceType(user.getDeivceType());
                                    pushMessage.setPhoneCode(user.getPhoneCode());
                                    pushMessage.setTitle("????");
                                    pushMessage.setMessage(desc);
                                    pushMessage.setType(0);
                                    pushMessageService.save(pushMessage);
                                    logger.info("?android?" + desc);

                                } else if (user.getDeivceType().equals("iOS") && user.getChannelID() != null
                                        && !user.getChannelID().equals("")) {
                                    JSONObject js = new JSONObject();
                                    String alert = "??[" + bracelet.getName()
                                            + "]" + df.format(distance) + "";
                                    js.put("alert", alert);
                                    jsonObject.put("aps", js);
                                    BaiduPushUtil.iosPushNotification(user.getChannelID(), user.getUserID(),
                                            jsonObject.toString());
                                    PushMessage pushMessage = new PushMessage();
                                    pushMessage.setChannelID(user.getChannelID());
                                    pushMessage.setDeivceType(user.getDeivceType());
                                    pushMessage.setPhoneCode(user.getPhoneCode());
                                    pushMessage.setTitle("????");
                                    pushMessage.setMessage(alert);
                                    pushMessage.setType(0);
                                    pushMessageService.save(pushMessage);
                                    logger.info("?iOS?" + alert);
                                }
                            }
                        }
                        break;
                    } else {
                        if (fence.getIsOutside() == 1) {
                            fence.setIsOutside(0);
                            fenceService.update(fence);
                        }
                    }
                }
            }

            break;
        case "T30"://?(T30/S30)
            hashMapClient.put(imei, ctx);
            //[V1.0.0,460026734416459,1,6042,2014-04-10 08:00:47,1-1,356511170016386,8,T30,imei?,step,1,76,386,0,1,1397001635]
            //S30
            //[v1.0.0, a1d83kdeio3fg33k,1,d961,2013-08-07 00:12:52,123456789012345,S30]
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S30").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S30=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            //????
            Step step = new Step();
            step.setImei(imei);
            step.setDataType(datas[10]);
            step.setNumber(Integer.valueOf(datas[11]));
            step.setTotalSteps(Integer.valueOf(datas[12]));
            step.setTotalDis(datas[13]);
            step.setCalories(datas[14]);
            step.setFlag(Integer.valueOf(datas[15]));
            stepService.save(step);

            //sleep
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.set(Calendar.HOUR_OF_DAY, 8);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            Date endTime = c.getTime();

            Calendar c1 = Calendar.getInstance();
            c1.setTime(new Date());
            c1.add(c1.DATE, -1);
            c1.set(Calendar.HOUR_OF_DAY, 22);
            c1.set(Calendar.MINUTE, 00);
            c1.set(Calendar.SECOND, 00);
            Date startTime = c1.getTime();

            List<Step> list = stepService.getStepByDate(imei, startTime, endTime);
            //???
            int time_period = 10;//10
            int over_deep_value = Constant.OVER_DEEP_VALUE;
            int over_shallow_value = Constant.OVER_SHALLOW_VALUE;

            Step step1 = null;
            int totalsteps2 = 0;
            int deep_sleep_hour = 0;//10?,<=5
            int shallow_sleep_hour = 0;//10?<=10
            int zeor_count = 0;//0000 -8:00?
            for (int i = 0; i < list.size(); i++) {
                step1 = list.get(i);
                int totalsteps1 = step1.getTotalSteps();
                int count = totalsteps1 - totalsteps2;
                if (count <= over_deep_value) {
                    deep_sleep_hour += time_period;
                } else if (over_deep_value < count && count <= over_shallow_value) {
                    shallow_sleep_hour += time_period;
                }
                totalsteps2 = totalsteps1;

                if (i >= 12 && totalsteps1 == 0) {
                    zeor_count++;
                }
            }

            int wear = 0;
            int total_sleep = 0;
            int deep_sleep = 0;
            int shallow_sleep = 0;

            if (zeor_count > 40) {
                wear = 0;
                total_sleep = 0;
                deep_sleep = 0;
                shallow_sleep = 0;
            } else {
                wear = 1;
                total_sleep = deep_sleep_hour + shallow_sleep_hour;
                deep_sleep = deep_sleep_hour;
                shallow_sleep = shallow_sleep_hour;
            }

            //??
            if (!(datas[9] == null || datas[9].equals(""))) {
                sb.delete(0, sb.length());
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S114").append(",").append("2").append(",")
                        .append(datas[10]).append(",").append(datas[11]).append(",").append(datas[12]).append(",")
                        .append(total_sleep).append(",").append(deep_sleep).append(",").append(shallow_sleep)
                        .append(",").append(wear).append("]");
                sendMsg(sb.toString(), hashMapClient.get(datas[9]));
            }
            break;
        case "T34":
            //[V1.0.0,a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00, 1-2,355372020827303,8,T34, ,voltage,1,1267511609]
            Bracelet baterry_bracelet = braceletService.get(imei);
            baterry_bracelet.setBattery(datas[11]);
            braceletService.update(baterry_bracelet);
            hashMapClient.put(imei, ctx);
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S34").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S34=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());

            break;
        case "T47":
            //[V1.0.0,a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00, 1-2,355372020827303,8,T47,,wear,1,1267511609]
            Bracelet wear_bracelet = braceletService.get(imei);
            wear_bracelet.setWear(datas[11]);
            braceletService.update(wear_bracelet);
            hashMapClient.put(imei, ctx);
            sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2]).append(",")
                    .append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",").append(imei)
                    .append(",").append("S47").append("]");
            sendMsg(sb.toString(), ctx);
            System.out.println("server channelWrite...S47=" + sb.toString() + " imei=" + imei + " localAddress="
                    + ctx.channel().localAddress() + " remoteAddress=" + ctx.channel().remoteAddress());
            //??
            for (Binding binding : wear_bracelet.getBingdings()) {
                User user = binding.getUser();
                JSONObject jsonObject = new JSONObject();
                if (user.getDeivceType().equals("android") && user.getChannelID() != null
                        && !user.getChannelID().equals("")) {
                    String desc = "??[" + wear_bracelet.getName() + "]"
                            + (Integer.valueOf(datas[11]) == 0 ? "" : "?");
                    jsonObject.put("title", "??");
                    jsonObject.put("description", desc);
                    //jsonObject.put("open_type", 2);
                    //jsonObject.put("pkg_content", "");
                    BaiduPushUtil.androidPushNotification(user.getChannelID(), user.getUserID(),
                            jsonObject.toString());

                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setChannelID(user.getChannelID());
                    pushMessage.setDeivceType(user.getDeivceType());
                    pushMessage.setPhoneCode(user.getPhoneCode());
                    pushMessage.setTitle("??");
                    pushMessage.setMessage(desc);
                    pushMessage.setType(1);
                    pushMessageService.save(pushMessage);
                    logger.info("?android?" + desc);

                } else if (user.getDeivceType().equals("iOS") && user.getChannelID() != null
                        && !user.getChannelID().equals("")) {
                    JSONObject js = new JSONObject();
                    String alert = "??[" + wear_bracelet.getName() + "]"
                            + (Integer.valueOf(datas[11]) == 0 ? "" : "?");
                    js.put("alert", alert);
                    jsonObject.put("aps", js);
                    BaiduPushUtil.iosPushNotification(user.getChannelID(), user.getUserID(), jsonObject.toString());
                    PushMessage pushMessage = new PushMessage();
                    pushMessage.setChannelID(user.getChannelID());
                    pushMessage.setDeivceType(user.getDeivceType());
                    pushMessage.setPhoneCode(user.getPhoneCode());
                    pushMessage.setTitle("??");
                    pushMessage.setMessage(alert);
                    pushMessage.setType(1);
                    pushMessageService.save(pushMessage);
                    logger.info("?iOS?" + alert);
                }
            }
            break;
        case "T112"://??,imei?
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T112,?imei]
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,460021581801906,8,T112,355372020827303]

            if (hashMapClient.get(imei) == null) {
                //??
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S112").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S5").append(",").append(datas[9]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S5=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

            }
            break;
        case "T113"://??,imei???180
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T113,imei?,300]
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,460021581801906,8,T113,355372020827303]
            if (hashMapClient.get(imei) == null) {
                //???
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S113").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?
                //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,355372020827303,S7,imei?,300]
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S7").append(",").append(datas[9]).append(",")
                        .append(datas[10]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S7=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

                Bracelet b = braceletService.get(imei);
                b.setUploadPulseRate(datas[10]);
                braceletService.update(b);
            }
            break;
        case "T114"://
            if (hashMapClient.get(imei) == null) {
                //??
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S114").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S10").append(",").append(datas[9]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S10=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

            }
            break;
        case "T115"://,imei???180
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T115,imei?,300]
            if (hashMapClient.get(imei) == null) {
                //???
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S115").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?   (S11/T11)
                //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,355372020827303,S7,imei?,300]
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S11").append(",").append(datas[9]).append(",")
                        .append(datas[10]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S11=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

                Bracelet b = braceletService.get(imei);
                b.setUploadStepRate(datas[10]);
                braceletService.update(b);
            }
            break;
        case "T116"://GPS
            if (hashMapClient.get(imei) == null) {
                //??
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S116").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S13").append(",").append(datas[9]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S13=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

            }
            break;
        case "T117"://GPS,imei???180
            //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,1-2,355372020827303,8,T115,imei?,300]
            if (hashMapClient.get(imei) == null) {
                //???
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S117").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?   (S11/T11)
                //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,355372020827303,S7,imei?,300]
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S15").append(",").append(datas[9]).append(",")
                        .append(datas[10]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S15=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

                Bracelet b = braceletService.get(imei);
                b.setUploadGpsRate(datas[10]);
                braceletService.update(b);
            }
            break;
        case "T118"://SOS,imei?
            if (hashMapClient.get(imei) == null) {
                //???
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S118").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?   (S11/T11)
                //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,355372020827303,S7,imei?,sos??]
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S18").append(",").append(datas[9]).append(",")
                        .append(datas[10]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S18=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

                Bracelet b = braceletService.get(imei);
                if (b != null) {
                    b.setSosPhoneCode(datas[10]);
                    braceletService.update(b);
                }

            }
            break;
        case "T119"://?,imei?
            if (hashMapClient.get(imei) == null) {
                //???
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S119").append(",").append("0").append("]");
                sendMsg(sb.toString(), ctx);
            } else {
                //?   (S11/T11)
                //[V1.0.0, a1d83kdeio3fg33k,1,abcd,2011-12-15 10:00:00,355372020827303,S7,imei?,??]
                hashMapClient.put(datas[9].trim(), ctx);
                sb.append("[").append(datas[0]).append(",").append(datas[1]).append(",").append(datas[2])
                        .append(",").append(datas[3]).append(",").append(getGMT(datas[7].trim())).append(",")
                        .append(imei).append(",").append("S19").append(",").append(datas[9]).append(",")
                        .append(datas[10]).append("]");
                sendMsg(sb.toString(), hashMapClient.get(imei));
                System.out.println("server channelWrite...S19=" + sb.toString() + " imei=" + imei + " localAddress="
                        + hashMapClient.get(imei).channel().localAddress() + " remoteAddress="
                        + hashMapClient.get(imei).channel().remoteAddress());

                Bracelet b = braceletService.get(imei);
                if (b != null) {
                    b.setFamilyPhoneCode(datas[10]);
                    braceletService.update(b);
                }
            }
            break;
        default:
            break;
        }
    }

    public String getGMT(String timezone) {
        if (timezone == null || timezone.equals("")) {
            timezone = "8";
        }
        TimeZone zone1 = TimeZone.getTimeZone("GMT" + timezone);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(zone1);
        return sdf.format(new Date());
    }

    public void removeFromHashMapClient(ChannelHandlerContext ctxClient) {
        ChannelHandlerContext ctx;
        for (String imei : hashMapClient.keySet()) {
            ctx = hashMapClient.get(imei);
            if (ctx.name().equals(ctxClient.name())) {
                hashMapClient.remove(imei);
                break;
            }
        }
    }

    public void sendMsg(String msg, ChannelHandlerContext ctx) {
        //ByteBuf byteBuf = Unpooled.copiedBuffer(length+msg,CharsetUtil.UTF_8);
        if (null != msg && null != ctx) {
            ByteBuf byteBuf = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
            ctx.writeAndFlush(byteBuf);
        }

    }

    public String readString(InputStream in) throws IOException {

        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();

    }
}