コード例 #1
0
        /// <summary>
        /// 这里解析的到的数据是会把头和尾部都给去掉的 包括0x7E
        /// </summary>
        /// <param name="readBuffer"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        protected override HLProtocolRequestInfo ProcessMatchedRequest(byte[] readBuffer, int offset, int length)
        {
            //var aJT808_PackageData = new JT808_PackageData();
            string all = "";

            for (int i = 0; i < length; i++)
            {
                all = all + readBuffer[offset + i].ToString("X2") + " ";
            }

            //转义还原
            byte[] message = ExplainUtils.DoEscape4Receive(readBuffer, offset, offset + length);
            string all2    = "";

            for (int i = 0; i < message.Length; i++)
            {
                all2 = all2 + message[i].ToString("X2") + " ";
            }

            //解析消息头
            JT808_PackageData aJT808_PackageData = decoder.Bytes2PackageData(message);

            aJT808_PackageData.all  = all;
            aJT808_PackageData.all2 = all2;

            if (aJT808_PackageData.errorlog == null)
            {
                //解析消息体
                ProcessPackageData(ref aJT808_PackageData);
            }


            return(new HLProtocolRequestInfo(aJT808_PackageData));
        }
コード例 #2
0
        /// <summary>
        /// 二进制数据 转成 内容包数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public JT808_PackageData Bytes2PackageData(byte[] data)
        {
            JT808_PackageData ret = new JT808_PackageData();

            // 1. 16byte 或 12byte 消息头
            JT808_PackageData.MsgHeader msgHeader = this.ParseMsgHeaderFromBytes(data);
            ret.msgHeader = msgHeader;

            int msgBodyByteStartIndex = 12 + 1;

            // 2. 消息体
            // 有子包信息,消息体起始字节后移四个字节:消息包总数(word(16))+包序号(word(16))
            if (msgHeader.hasSubPackage)
            {
                msgBodyByteStartIndex = 16 + 1;
            }

            byte[] tmp = new byte[msgHeader.msgBodyLength];
            Buffer.BlockCopy(data, msgBodyByteStartIndex, tmp, 0, tmp.Length);
            ret.setMsgBodyBytes(tmp);

            // 3. 去掉分隔符之后,最后一位就是校验码
            int checkSumInPkg      = data[data.Length - 1 - 1];
            int calculatedCheckSum = ExplainUtils.getCheckSum4JT808(data, 0 + 1, data.Length - 1 - 1);

            ret.checkSum = (checkSumInPkg);
            if (checkSumInPkg != calculatedCheckSum)
            {
                ret.errorlog = ret.errorlog + "检验码不一致;";// string.Format("检验码不一致,msgid:{},pkg:{},calculated:{}", msgHeader.getMsgId(), checkSumInPkg, calculatedCheckSum);
            }
            return(ret);
        }
コード例 #3
0
        //[TestMethod]
        public void TestByteParse()
        {
            string str = "07";
            byte   b   = byte.Parse(str);

            byte[] a = ExplainUtils.string2Bcd(str);
            Assert.AreEqual(a[0], 07);
        }
コード例 #4
0
        //[TestMethod]
        public void TestExplainUtils()
        {
            //byte[] byteArr = new byte[] { 0x68, 0xDC ,0x12 ,0x12 ,0x00 ,0x08 ,0x01, 0x93, 0x33, 0x00, 0x33, 0x33, 0x00 };
            byte[] byteArr = new byte[] { 0x18, 0x33 };
            byte   result  = ExplainUtils.makeCheckSum(byteArr);

            Assert.AreEqual(result, 0x4B);
        }
コード例 #5
0
        //[TestMethod]
        public void TestParseIntFromBytes()
        {
            byte[] arr = new byte[] { 0x42, 0x9A, 0x38, 0x5F };
            int    bcd = ExplainUtils.ParseIntFromBytes(arr, 0, arr.Length);

            Console.WriteLine(bcd);
            Assert.AreEqual(4, arr.Length);
        }
コード例 #6
0
        //[TestMethod]
        public void TestStrToHexStr()
        {
            string str = "D4A7";

            byte[] arr = ExplainUtils.strToToHexByte(str);
            Assert.AreEqual(arr[0], 0xD4);
            Assert.AreEqual(arr[1], 0xA7);
        }
コード例 #7
0
        //[TestMethod]
        public void TestInt16Parse()
        {
            byte a = ExplainUtils.integerTo1Bytes(122)[0];
            byte d = ExplainUtils.string2Bcd(a.ToString("X2"))[0];

            Console.WriteLine(d);
            Assert.AreEqual(a, 0x7A);
        }
コード例 #8
0
        public void TestGetIndexFromByteArr()
        {
            string str = "68 18 18 66 5A 12 12 00 08 68 01 00 08 01 77 BE 7F BF A6 9B 04 3F 12 03 68 11 1A 27 97 16";

            byte[] arr   = ExplainUtils.HexSpaceStringToByteArray(str);
            int    index = ExplainUtils.GetSecondIndexFromByteArr(arr, 0x68);

            Assert.AreEqual(index, 9);
        }
コード例 #9
0
        //[TestMethod]
        public void TestIntToBytes()
        {
            byte[] arr = ExplainUtils.integerTo2Bytes(7000);
            string a   = arr[0].ToString("X2");
            string b   = arr[1].ToString("X2");

            Console.WriteLine(a + "," + b);
            Assert.AreEqual(a, "1B");
        }
コード例 #10
0
        private void ProcessPackageData(ref JT808_PackageData packageData)
        {
            //消息ID
            int msgId = packageData.msgHeader.msgId;
            //消息体属性
            int msgBodyProps = packageData.msgHeader.msgBodyPropsField;
            //终端手机号
            string terminalPhone = packageData.msgHeader.terminalPhone;
            //消息流水号
            int flowId = packageData.msgHeader.flowId;


            //1. 终端注册 ==> 终端注册应答
            if (msgId == ExplainUtils.msg_id_terminal_register)
            {
                //客户端消息应答
                byte[] sendMsg = ExplainUtils.rtnTerminalRespMsg(0014, terminalPhone, flowId);
                //设置回复信息
                packageData.setMsgRespBytes(sendMsg);
            }
            //2. 终端鉴权 ==> 平台通用应答
            else if (msgId == ExplainUtils.msg_id_terminal_authentication)
            {
                //客户端消息应答
                byte[] sendMsg = ExplainUtils.rtnServerCommonRespMsg(0005, terminalPhone, flowId, msgId);
                //设置回复信息
                packageData.setMsgRespBytes(sendMsg);
            }
            //3. 终端心跳-消息体为空 ==> 平台通用应答
            else if (msgId == ExplainUtils.msg_id_terminal_heart_beat)
            {
                //客户端消息应答
                byte[] sendMsg = ExplainUtils.rtnServerCommonRespMsg(0005, terminalPhone, flowId, msgId);
                //设置回复信息
                packageData.setMsgRespBytes(sendMsg);
            }
            //4. 位置信息汇报 ==> 平台通用应答
            else if (msgId == ExplainUtils.msg_id_terminal_location_info_upload)
            {
                packageData.locationInfo = (decoder.ToLocationInfoMsg(packageData.getMsgBodyBytes()));
                //客户端消息应答
                byte[] sendMsg = ExplainUtils.rtnServerCommonRespMsg(0005, terminalPhone, flowId, msgId);
                //设置回复信息
                packageData.setMsgRespBytes(sendMsg);
            }
            // 其他情况
            else
            {
                packageData.errorlog = ">>>>>[未知消息类型-0x{" + msgId + "}],phone=" + terminalPhone + ",flowid={" + flowId + "}";
            }
        }
コード例 #11
0
        protected override NewEnergyRequestInfo ProcessMatchedRequest(byte[] readBuffer, int offset, int length)
        {
            //转义还原
            byte[] message = ExplainUtils.DoEscape4Receive(readBuffer, offset, offset + length);
            string all     = "";

            for (int i = 0; i < message.Length; i++)
            {
                all = all + message[i].ToString("X2") + " ";
            }

            NewEnergyProtocol protocol = new NewEnergyProtocol();

            protocol.all = all;

            return(new NewEnergyRequestInfo(protocol));
        }
コード例 #12
0
 public string SendInclinometerMsg([FromBody] dynamic param)
 {
     try
     {
         var      code       = param.code.Value;
         var      config     = param.config.Value;//01000801
         string[] strArr     = ExplainUtils.str2StrArr(config);
         var      serialPort = strArr[0];
         var      address    = strArr[1] + strArr[2];
         var      producer   = strArr[3];
         string   type       = "52";
         MsgHandler.SendInclinometerMsg(code, type, serialPort, address, producer);
         return("操作成功!");
     }
     catch (Exception e)
     {
         logger.Error("<<Method-SendInclinometerMsg>>" + e.GetType() + ":" + e.Message);
         return("操作失败!");
     }
 }
コード例 #13
0
        /// <summary>
        /// 解析生成 消息头
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private JT808_PackageData.MsgHeader ParseMsgHeaderFromBytes(byte[] bytes)
        {
            JT808_PackageData.MsgHeader msgHeader = new JT808_PackageData.MsgHeader();

            // 1. 消息ID word(16)
            msgHeader.msgId = ExplainUtils.ParseIntFromBytes(bytes, 1, 2);
            // 2. 消息体属性 word(16)
            int msgBodyProps = ExplainUtils.ParseIntFromBytes(bytes, 2 + 1, 2);

            msgHeader.msgBodyPropsField = (msgBodyProps);
            // [ 0-9 ] 0000,0011,1111,1111(3FF)(消息体长度)
            msgHeader.msgBodyLength = (msgBodyProps & 0x3ff);
            // [10-12] 0001,1100,0000,0000(1C00)(加密类型)
            msgHeader.encryptionType = ((msgBodyProps & 0x1c00) >> 10);
            // [ 13_ ] 0010,0000,0000,0000(2000)(是否有子包)
            msgHeader.hasSubPackage = (((msgBodyProps & 0x2000) >> 13) == 1);
            // [14-15] 1100,0000,0000,0000(C000)(保留位)
            msgHeader.reservedBit = (((msgBodyProps & 0xc000) >> 14) + "");
            // 3. 终端手机号 bcd[6]
            msgHeader.terminalPhone = (ExplainUtils.ParseBcdStringFromBytes(bytes, 4 + 1, 6));
            // 4. 消息流水号 word(16) 按发送顺序从 0 开始循环累加
            msgHeader.flowId = ExplainUtils.ParseIntFromBytes(bytes, 10 + 1, 2);

            // 5. 消息包封装项
            // 有子包信息
            if (msgHeader.hasSubPackage)
            {
                // 消息包封装项字段
                msgHeader.packageInfoField = ExplainUtils.ParseIntFromBytes(bytes, 12 + 1, 4);

                msgHeader.totalSubPackage = ExplainUtils.ParseIntFromBytes(bytes, 12 + 1, 2);

                msgHeader.subPackageSeq = ExplainUtils.ParseIntFromBytes(bytes, 12 + 1, 2);
            }
            return(msgHeader);
        }
コード例 #14
0
        /// <summary>
        /// 解析生成 位置信息 消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public JT808_PackageData.LocationInfo ToLocationInfoMsg(byte[] data)
        {
            JT808_PackageData.LocationInfo locationInfo = new JT808_PackageData.LocationInfo();

            //基本信息
            locationInfo.alc = data[0].ToString("X2") + data[1].ToString("X2") + data[2].ToString("X2") + data[3].ToString("X2"); //报警标志 4位
            locationInfo.bst = data[4].ToString("X2") + data[5].ToString("X2") + data[6].ToString("X2") + data[7].ToString("X2"); //状态 4位
            locationInfo.lat = (double)ExplainUtils.ParseIntFromBytes(data, 8, 4) / 1000000;                                      //纬度 4位 除以10的6次方 转为度
            locationInfo.lon = (double)ExplainUtils.ParseIntFromBytes(data, 12, 4) / 1000000;                                     //经度 4位 除以10的6次方 转为度
            locationInfo.hgt = ExplainUtils.ParseIntFromBytes(data, 16, 2);                                                       //高程 2位
            locationInfo.spd = (float)ExplainUtils.ParseIntFromBytes(data, 18, 2) / 10;                                           //速度 2位 转为十进制 除以10即62.2KM/H
            locationInfo.agl = ExplainUtils.ParseIntFromBytes(data, 20, 2);                                                       //方向 2位

            string gtm = string.Format("{0}-{1}-{2} {3}:{4}:{5}", ExplainUtils.ParseBcdStringFromBytes(data, 22, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 23, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 24, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 25, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 26, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 27, 1));

            locationInfo.gtm = DateTime.Parse(gtm);//时间

            //扩展信息
            locationInfo.mlg  = 0;  // 里程  0x01 4
            locationInfo.oil  = 0;  // 油量  0x02 2
            locationInfo.spd2 = 0;  // 记录仪速度 0x03 2
            locationInfo.est  = ""; //扩展车辆信号状态位 0x25  4
            locationInfo.io   = ""; // IO状态位 0x2A 2
            locationInfo.ad1  = ""; // 模拟量 0x2B 4
            locationInfo.yte  = 0;  // 无线通信网络信号强度 0x30 1
            locationInfo.gnss = 0;  // 定位卫星数 0x31 1
            locationInfo.ecu  = ""; // ECU透传数据 0xE0 n

            for (int i = 28; i < data.Length; i++)
            {
                if (data[i] == 0x01)// 里程  0x01 4
                {
                    locationInfo.mlg = (float)ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]) / 10;
                }
                else if (data[i] == 0x02)// 油量  0x02 2
                {
                    locationInfo.oil = (float)ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]) / 10;
                }
                else if (data[i] == 0x03)// 记录仪速度 0x03 2
                {
                    locationInfo.spd2 = ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]);
                }
                else if (data[i] == 0x25)//扩展车辆信号状态位 0x25  4
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.est = locationInfo.est + data[ii].ToString("X2");
                    }
                }
                else if (data[i] == 0x2a)// IO状态位 0x2A 2
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.io = locationInfo.io + data[ii].ToString("X2");
                    }
                }
                else if (data[i] == 0x2b)// 模拟量 0x2B 4
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.ad1 = locationInfo.ad1 + data[ii].ToString("X2");
                    }
                }
                else if (data[i] == 0x30)// 无线通信网络信号强度 0x30 1
                {
                    locationInfo.yte = ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]);
                }
                else if (data[i] == 0x31)// 定位卫星数 0x31 1
                {
                    locationInfo.gnss = ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]);
                }
                else if (data[i] == 0xE0)// ECU透传数据 0xE0 n
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.ecu = locationInfo.ecu + data[ii].ToString("X2");
                    }
                }
                else //其它字段,先过滤
                {
                }

                i = i + 1 + data[i + 1];
            }
            return(locationInfo);
        }
コード例 #15
0
        /// <summary>
        /// 解析生成 位置信息 消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public JT808_PackageData.LocationInfo ToLocationInfoMsg(byte[] data)
        {
            JT808_PackageData.LocationInfo locationInfo = new JT808_PackageData.LocationInfo();

            //基本信息
            locationInfo.alc = data[6].ToString("X2") + data[7].ToString("X2") + data[8].ToString("X2") + data[9].ToString("X2");     //报警标志 4位
            locationInfo.bst = data[10].ToString("X2") + data[11].ToString("X2") + data[12].ToString("X2") + data[13].ToString("X2"); //状态 4位
            locationInfo.lon = (double)ExplainUtils.ParseIntFromBytes(data, 14, 4) / 1000000;                                         //经度 4位 除以10的6次方 转为度
            locationInfo.lat = (double)ExplainUtils.ParseIntFromBytes(data, 18, 4) / 1000000;                                         //纬度 4位 除以10的6次方 转为度
            locationInfo.hgt = ExplainUtils.ParseIntFromBytes(data, 22, 2);                                                           //高程 2位
            locationInfo.spd = (float)ExplainUtils.ParseIntFromBytes(data, 24, 2) / 10;                                               //速度 2位 转为十进制 除以10即62.2KM/H
            locationInfo.agl = ExplainUtils.ParseIntFromBytes(data, 26, 2);                                                           //方向 2位

            string gtm = string.Format("{0}-{1}-{2} {3}:{4}:{5}", ExplainUtils.ParseBcdStringFromBytes(data, 28, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 29, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 30, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 31, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 32, 1),
                                       ExplainUtils.ParseBcdStringFromBytes(data, 33, 1));

            try
            {
                locationInfo.gtm = DateTime.Parse(gtm);
                //locationInfo.gtm = DateTime.Parse("09-01-2017 12:15:12");
            }
            catch (Exception e)
            {
                logger.log("error happens when parsing gtm! " + e.Message);
            }


            //扩展信息
            locationInfo.mlg  = 0;  // 里程  0x01 4
            locationInfo.oil  = 0;  // 油量  0x02 2
            locationInfo.spd2 = 0;  // 记录仪速度 0x03 2
            locationInfo.est  = ""; //扩展车辆信号状态位 0x25  4
            locationInfo.io   = ""; // IO状态位 0x2A 2
            locationInfo.ad1  = ""; // 模拟量 0x2B 4
            locationInfo.yte  = 0;  // 无线通信网络信号强度 0x30 1
            locationInfo.gnss = 0;  // 定位卫星数 0x31 1
            locationInfo.ecu  = ""; // ECU透传数据 0xE0 n

            for (int i = 34; i < data.Length; i++)
            {
                if (data[i] == 0x01)// 里程  0x01 4
                {
                    locationInfo.mlg = (float)ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]) / 10;
                }
                else if (data[i] == 0x02)// 油量  0x02 2
                {
                    locationInfo.oil = (float)ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]) / 10;
                }
                else if (data[i] == 0x03)// 记录仪速度 0x03 2
                {
                    locationInfo.spd2 = ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]);
                }
                else if (data[i] == 0x25)//扩展车辆信号状态位 0x25  4
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.est = locationInfo.est + data[ii].ToString("X2");
                    }
                }
                else if (data[i] == 0x2a)// IO状态位 0x2A 2
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.io = locationInfo.io + data[ii].ToString("X2");
                    }
                }
                else if (data[i] == 0x2b)// 模拟量 0x2B 4
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.ad1 = locationInfo.ad1 + data[ii].ToString("X2");
                    }
                }
                else if (data[i] == 0x30)// 无线通信网络信号强度 0x30 1
                {
                    locationInfo.yte = ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]);
                }
                else if (data[i] == 0x31)// 定位卫星数 0x31 1
                {
                    locationInfo.gnss = ExplainUtils.ParseIntFromBytes(data, i + 2, data[i + 1]);
                }
                else if (data[i] == 0xE0)// ECU透传数据 0xE0 n
                {
                    for (int ii = i + 2; ii < i + 2 + data[i + 1]; ii++)
                    {
                        locationInfo.ecu = locationInfo.ecu + data[ii].ToString("X2");
                    }
                }
                else //其它字段,先过滤
                {
                }

                i = i + 1 + data[i + 1];
            }
            return(locationInfo);
        }
コード例 #16
0
        static void protocolServer_NewRequestReceived(NewEnergySession session, NewEnergyRequestInfo requestInfo)
        {
            bool checkTimeDone = false;

            byte[] sendMsg = ExplainUtils.HexSpaceStringToByteArray(requestInfo.Body.all);
            String content = BitConverter.ToString(sendMsg).Replace("-", " ");

            Console.WriteLine("<<{0}>>Received == {1}", session.RemoteEndPoint, content);
            logger.Info("<<" + session.RemoteEndPoint + ">>Received:" + content);
            //68 31 00 31 00 68 C9 12 12 08 00 00 02 70 00 00 01 00 68 16
            int    index          = ExplainUtils.GetSecondIndexFromByteArr(sendMsg, (byte)0x68); //第二个68的索引
            int    indexOfControl = index + 1;                                                   //控制字的索引
            int    typeIndex;                                                                    //帧类型索引
            string code;                                                                         //地址码
            int    codeIndex;                                                                    //地址码索引
            int    len;                                                                          //要校验的长度:有C9控制字则从C9开始,否则从第二个68开始到校验和前一位
            int    checkIndex;                                                                   //校验的起始位

            if (sendMsg[indexOfControl] == 0xC9)
            {
                typeIndex = indexOfControl + 5;
                codeIndex = indexOfControl + 1;
                //有C9控制字的地址码高低位互换
                code = sendMsg[codeIndex + 1].ToString("X2") + sendMsg[codeIndex].ToString("X2")
                       + sendMsg[codeIndex + 3].ToString("X2") + sendMsg[codeIndex + 2].ToString("X2");
                len        = sendMsg.Length - 2 - indexOfControl;
                checkIndex = indexOfControl;
            }
            else
            {
                typeIndex = index + 6;
                codeIndex = index + 2;
                code      = code = sendMsg[codeIndex].ToString("X2") + sendMsg[codeIndex + 1].ToString("X2")
                                   + sendMsg[codeIndex + 2].ToString("X2") + sendMsg[codeIndex + 3].ToString("X2");
                len        = sendMsg.Length - 2 - index;
                checkIndex = index;
            }

            var sessions = MsgHandler.sessions;

            if (!sessions.ContainsKey(code))
            {
                sessions.TryAdd(code, session);
            }
            else
            {
                sessions[code].Close();
                sessions[code] = session;
            }
            byte type = sendMsg[typeIndex]; //帧类型

            if (type == 0x00)               //登录、心跳、失电
            {
                string markCode = sendMsg[sendMsg.Length - 4].ToString("X2") + sendMsg[sendMsg.Length - 3].ToString("X2");
                string markName = "unknown frame";
                if ("0100".Equals(markCode))
                {
                    markName = "login";
                    if (!checkTimeDone)
                    {
                        MsgHandler.SendCheckTimerInfo(session, code);
                    }
                }
                else if ("0400".Equals(markCode))
                {
                    markName = "heartbeat";
                }
                else if ("0010".Equals(markCode))
                {
                    markName = "power-lossing";
                }
                sendMsg[indexOfControl]     = 0x00;
                sendMsg[indexOfControl + 6] = 0x00;
                byte[] newArr = new byte[len];
                Buffer.BlockCopy(sendMsg, checkIndex, newArr, 0, len);
                sendMsg[sendMsg.Length - 2] = ExplainUtils.makeCheckSum(newArr);//计算校验码

                String reply = BitConverter.ToString(sendMsg).Replace("-", " ");
                Console.WriteLine("{0} reply:{1}", markName, reply);
                logger.Info(markName + " reply: " + reply);
                session.Send(sendMsg, 0, sendMsg.Length); //回复客户端
            }
            else if (type == 0x09)                        //校时
            {
                byte controlCode = sendMsg[indexOfControl];
                if (controlCode == 0xDC)//校时成功
                {
                    checkTimeDone = true;
                    if (MsgHandler.timers.ContainsKey(code))
                    {
                        System.Timers.Timer timer = MsgHandler.timers[code];
                        timer.Enabled = false;
                        timer.Stop();
                        MsgHandler.timers.TryRemove(code, out timer);
                    }
                    Console.WriteLine("<<{0}>><<{1}>>check time done,sotpped the timer.", code, session.RemoteEndPoint);
                    logger.Info("<<" + code + ">><<" + session.RemoteEndPoint + ">>check time done,sotpped the timer.");
                }
                else//校时回复
                {
                    MsgHandler.SendCheckTimerInfo(sendMsg, session, typeIndex, checkIndex);
                }
            }
            else if (type == 0x01)  //采集频率回复
            {
                //MsgHandler.SendFrequencyForCollection();//测试
                Console.WriteLine("reply from client<<" + session.RemoteEndPoint + ">> : set collection frequency done.");
                logger.Info("reply from client<<" + session.RemoteEndPoint + ">> : set collection frequency done.");
            }
            else if (type == 0x03)  //初始化成功
            {
                Console.WriteLine("reply from client<<" + session.RemoteEndPoint + ">> : init done.");
                logger.Info("reply from client<<" + session.RemoteEndPoint + ">> : init done.");
            }
            else if (type == 0x04)  //重启成功
            {
                Console.WriteLine("reply from client<<" + session.RemoteEndPoint + ">> : restart done.");
                logger.Info("reply from client<<" + session.RemoteEndPoint + ">> : restart done.");
            }
            else if (type == 0x52) //下发倾角仪回复
            {
                Console.WriteLine("reply from client<<" + session.RemoteEndPoint + ">> : received inclinometer configuration.");
                logger.Info("reply from client<<" + session.RemoteEndPoint + ">> : received inclinometer configuration.");
            }
            else if (type == 0x53)  //取消倾角仪回复
            {
                //同下发,只是帧类型不同
                Console.WriteLine("reply from client<<" + session.RemoteEndPoint + ">> : cancelled inclinometer.");
                logger.Info("reply from client<<" + session.RemoteEndPoint + ">> : cancelled inclinometer.");
            }
            else if (type == 0x39)  //倾角仪数据上报
            {
                MsgHandler.ParseInclinometerMsg(sendMsg);
            }
            else if (type == 0x15)  //倾角数据采集无响应
            {
                //68 0A 0A 68 5B 12 12 00 08 15 02 01 01 D4 DC 16
                //68 0A 0A 68 DB 12 12 00 08 15 02 01 01 D4 5C 16
                byte   controlCode = sendMsg[4];
                byte[] arr         = new byte[] { controlCode, 0x80 };
                sendMsg[4] = ExplainUtils.makeCheckSum(arr);
                byte[] newArr = new byte[len];
                Buffer.BlockCopy(sendMsg, checkIndex, newArr, 0, len);
                sendMsg[14] = ExplainUtils.makeCheckSum(newArr);
                String reply = BitConverter.ToString(sendMsg).Replace("-", " ");
                Console.WriteLine("reply from client<<" + session.RemoteEndPoint + ">> : no response from inclinometer >> reply:" + reply);
                logger.Info("reply from client<<" + session.RemoteEndPoint + ">> : no response from inclinometer >> reply:" + reply);
                session.Send(sendMsg, 0, sendMsg.Length);//回复客户端
            }
        }
コード例 #17
0
        static void Main(string[] args)
        {
            serverConfig.Ip   = ConfigurationManager.AppSettings["ip"];
            serverConfig.Port = int.Parse(ConfigurationManager.AppSettings["port"]);
            serverConfig.MaxConnectionNumber = 65535;
            appServer.Setup(serverConfig);
            //注册连接事件
            appServer.NewSessionConnected += protocolServer_NewSessionConnected;
            //注册请求事件
            appServer.NewRequestReceived += protocolServer_NewRequestReceived;
            //注册Session关闭事件
            appServer.SessionClosed += protocolServer_SessionClosed;
            //尝试启动应用服务
            if (!appServer.Start())
            {
                Console.WriteLine("=====Failed to start the server!====");
                return;
            }
            Console.WriteLine("SuperSocket Server listening at {0}:{1}", serverConfig.Ip, serverConfig.Port);
            StartWebApiService();
            string userCommand = "";

            while (userCommand != "exit")
            {
                userCommand = Console.ReadLine();
                if (userCommand.Equals("1"))
                {
                    Console.WriteLine("请输入需要重启的汇集器地址码:");
                    string input = Console.ReadLine();
                    if (!input.Equals(""))
                    {
                        MsgHandler.SendRestartCommand(input);
                    }
                    else
                    {
                        Console.WriteLine("参数不能为空,请重新输入!");
                    }
                }
                else if (userCommand.Equals("0"))
                {
                    Console.WriteLine("请输入需要初始化的汇集器地址码:");
                    string input = Console.ReadLine();
                    if (!input.Equals(""))
                    {
                        MsgHandler.SendInitialCommand(input);
                    }
                    else
                    {
                        Console.WriteLine("参数不能为空,请重新输入!");
                    }
                }
                else if (userCommand.Equals("2"))
                {
                    Console.WriteLine("请输入汇集器地址码:");
                    string code = Console.ReadLine();
                    Console.WriteLine("请输入ip地址:");
                    string ip = Console.ReadLine();
                    Console.WriteLine("请输入端口号:");
                    string port = Console.ReadLine();
                    Console.WriteLine("请输入备用端口号:");
                    string port2 = Console.ReadLine();
                    if (code != "" && ip != "" && port != "")
                    {
                        if (port2.Equals(""))
                        {
                            port2 = port;
                        }
                        MsgHandler.SendConfigurationInfo(code, ip, int.Parse(port), int.Parse(port2));
                    }
                    else
                    {
                        Console.WriteLine("参数不正确,请重新输入!");
                    }
                }
                else if (userCommand.Equals("3"))
                {
                    Console.WriteLine("请输入汇集器地址码:");
                    string code = Console.ReadLine();
                    Console.WriteLine("请输入采集频率(秒):");
                    string time = Console.ReadLine();
                    if (code != "" && time != "")
                    {
                        MsgHandler.SendFrequencyForCollection(code, time);
                    }
                    else
                    {
                        Console.WriteLine("参数不能为空,请重新输入!");
                    }
                }
                else if (userCommand.Equals("4"))
                {
                    try
                    {
                        Console.WriteLine("请输入倾角仪数据:");
                        string msg    = Console.ReadLine();
                        byte[] result = ExplainUtils.HexSpaceStringToByteArray(msg);
                        MsgHandler.ParseInclinometerMsg(result);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("出错啦!{0}", e.Message);
                    }
                }
                else if (userCommand.Equals("help"))
                {
                    Console.WriteLine("0:初始化汇集器\r\n" + "1:重启汇集器\r\n" + "2:下发汇集器配置信息\r\n" + "3:设置采集频率\r\n" + "4:解析倾角仪上报数据");
                }
                else
                {
                    Console.WriteLine("不能识别的指令,请重新输入!");
                }
            }
            Console.ReadKey();
        }