コード例 #1
0
ファイル: AsyncTcpServer.cs プロジェクト: tumoxuese/XSTORE_V3
        /// <summary>
        /// 发送报文至所有客户端
        /// </summary>
        /// <param name="datagram">报文</param>
        public void SendAll(byte[] datagram)
        {
            if (!IsRunning)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + "This TCP server has not been started.");
                return;
            }
            //throw new InvalidProgramException("This TCP server has not been started.");


            for (int i = 0; i < this.clients.Count; i++)
            {
                try
                {
                    if (this.clients[i].TcpClient != null && this.clients[i].TcpClient.Connected)
                    {
                        Send(this.clients[i].TcpClient, datagram);
                        Thread.Sleep(150);
                    }
                }
                catch (Exception e)
                {
                    //LogHelper.WriteLog("异常的客户端异常数据:" + e.Message);
                    LogHelper.WriteLog("异常的客户端:" + Converts.GetTPandMac(datagram) + ":" + e.Message);
                    continue;
                }
            }
        }
コード例 #2
0
ファイル: AsyncTcpServer.cs プロジェクト: tumoxuese/XSTORE_V3
        /// <summary>
        /// 发送报文至指定的客户端
        /// </summary>
        /// <param name="tcpClient">客户端</param>
        /// <param name="datagram">报文</param>
        public bool Send(TcpClient tcpClient, byte[] datagram)
        {
            bool result = false;

            if (!IsRunning)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + tcpClient.Client.RemoteEndPoint.ToString() + "This TCP server has not been started.");
                //throw new InvalidProgramException("This TCP server has not been started.");
                return(false);
            }


            if (tcpClient == null)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + tcpClient.Client.RemoteEndPoint.ToString() + "参数tcpClient空值异常");
                //throw new ArgumentNullException("tcpClient");
                return(false);
            }


            if (datagram == null)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH-mm-ss:") + tcpClient.Client.RemoteEndPoint.ToString() + "参数datagram空值异常");
                //throw new ArgumentNullException("datagram");
                return(false);
            }

            try
            {
                NetworkStream TCPStream;// = tcpClient.GetStream();
                //boxes.Common.LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "发送报文失败;" + ee.Message + "位置:" + ee.StackTrace);
                if (tcpClient != null && tcpClient.Connected)
                {
                    TCPStream = tcpClient.GetStream();
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";TCPStream:" + TCPStream.ToString());
                    if (TCPStream.CanWrite)
                    {
                        TCPStream.BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient);
                        result = true;
                    }
                }
                else
                {
                    result = false;
                }
                //tcpClient.GetStream().BeginWrite(datagram, 0, datagram.Length, HandleDatagramWritten, tcpClient);原代码
                result = true;
            }
            catch (Exception ee)
            {
                LogHelper.WriteLog("异常的客户端:" + Converts.GetTPandMac(datagram));
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "发送报文失败;" + ee.Message + "位置:" + ee.StackTrace);
                //if (tcpClient != null && tcpClient.Client != null && tcpClient.Client.RemoteEndPoint != null)
                //{
                //    boxes.Common.LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "发送报文至" + tcpClient.Client.RemoteEndPoint.ToString() + "失败:" + ee.Message + "位置:" + ee.StackTrace);
                //}
            }
            return(result);
        }
コード例 #3
0
        private void SaveHeart(BoxModel model)
        {
            var errorPosition = string.Empty;

            for (int i = 0; i < model.State.Length; i++)
            {
                byte state = model.State[i];
                if (state == 0x05)
                {
                    errorPosition += i + 1 + ",";
                }
            }
            errorPosition = errorPosition.TrimEnd(',');
            var setErrorSql = string.Empty;

            if (!string.IsNullOrEmpty(errorPosition))
            {
                setErrorSql = string.Format(@"  update WP_箱子表 set BoxStatus = 1 where 库位id in(
  select top 1 id from WP_库位表 where 箱子MAC = '{0}') and 位置 in({1})", model.FormatMac, errorPosition);
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "异常开箱MAC:" + model.FormatMac + ";异常位置:" + errorPosition);
            }

            LogHelper.SaveHeart(model.FormatMac, model.Command);
            var sql = string.Format(@"
declare @cou int
select @cou =count(id)  from WP_设备心跳记录表 where  mac='{0}'
if @cou =0
begin
insert into WP_设备心跳记录表(mac,command) values('{0}','{1}')
end
else
begin
update WP_设备心跳记录表 set  command = '{1}',createtime = getdate() where mac = '{0}'
UPDATE [WP_库位表] SET [状态] = 1,修改时间 = getdate(),离线时长 = 0,版本号='{3}' WHERE 箱子MAC = '{0}'
update WP_BarCode set Version = '{3}' where BarCode ='{0}'
end 
{2}
", model.FormatMac, model.Command, setErrorSql, Converts.GetTPandMac(model.Placeholder));

            try
            {
                var b = DbHelperSQL.ExecuteSql(sql);
            }
            catch (Exception ex2)
            {
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ex2.Message);
            }
        }
コード例 #4
0
        //private string ipAddress = "139.199.160.173";
        public void OpenRemoteBox(string serialNumber, string orderNo, string warehouseIndexs, byte type = 0x01)
        {
            try
            {
                if (string.IsNullOrEmpty(serialNumber))
                {
                    throw new Exception("序列号无效");
                }
                if (string.IsNullOrEmpty(warehouseIndexs))
                {
                    throw new Exception("货箱序号无效");
                }
                if (string.IsNullOrEmpty(orderNo))
                {
                    orderNo = "999999999999999";
                }
                var    list      = warehouseIndexs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(o => int.Parse(o)).ToList();
                byte[] byte_open = new byte[12] {
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                };
                for (int i = 0; i < list.Count; i++)
                {
                    byte_open[list[i]] = 0x01;
                }

                byte[] order_no       = Encoding.UTF8.GetBytes(orderNo);
                byte[] ping           = Encoding.UTF8.GetBytes(serialNumber);
                byte[] commandByteArr = TcpClientHelper.GetSendMulty(ping, byte_open, order_no, type);
                var    commandStr     = Converts.GetTPandMac(commandByteArr);
                LogHelper.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";发送的开箱命令:" + commandStr);
                //SocketException exception;
                //定义一个套接字监听
                socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //获取文本框中的IP地址
                IPAddress address = IPAddress.Parse(ipAddress);
                //将获取的IP地址和端口号绑定在网络节点上
                IPEndPoint point = new IPEndPoint(address, port);
                socketclient.Connect(point);
                socketclient.Send(commandByteArr);
                var resultStr = string.Empty;
                socketclient.Close();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #5
0
        public Dictionary <string, string> OpenRemoteBox(string serialNumber, string orderNo, string warehouseIndexs, byte type = 0x01)
        {
            if (string.IsNullOrEmpty(serialNumber))
            {
                throw new Exception("序列号无效");
            }
            if (string.IsNullOrEmpty(warehouseIndexs))
            {
                throw new Exception("货箱序号无效");
            }
            var list = warehouseIndexs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(o => int.Parse(o)).ToList();

            byte[] byte_open = new byte[12] {
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            for (int i = 0; i < list.Count; i++)
            {
                byte_open[list[i]] = 0x01;
            }
            var dic = new Dictionary <string, string>();

            byte[] order_no = Encoding.UTF8.GetBytes(orderNo);
            byte[] ping     = Encoding.UTF8.GetBytes(serialNumber);
            //byte[] commandByteArr = TcpClientHelper.GetSendMulty(ping, byte_open, 0x02);
            byte[] commandByteArr = TcpClientHelper.GetSendMulty(ping, byte_open, order_no, type);
            var    commandStr     = Converts.GetTPandMac(commandByteArr);

            //SocketException exception;
            //定义一个套接字监听
            socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取文本框中的IP地址
            IPAddress address = IPAddress.Parse(ipAddress);
            //将获取的IP地址和端口号绑定在网络节点上
            IPEndPoint point = new IPEndPoint(address, port);

            socketclient.Connect(point);
            socketclient.Send(commandByteArr);
            var resultStr = string.Empty;

            socketclient.Close();
            dic["success"] = "成功";
            return(dic);
        }
コード例 #6
0
 public override string ToString()
 {
     return(string.Format("{9}-帧头码:{0},数据帧字节数:{1},时间戳:{2},功能码:{3},箱柜地址码:{4},柜门的状态:{5},信号强度:{6},版本号:{7},合校验:{8}",
                          Head, Lenght, Time, Type, FormatMac, Converts.GetTPandMac(State), Converts.GetTPandMac(Signal), Converts.GetTPandMac(Placeholder), Converts.GetTPandMac(Check), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
 }
コード例 #7
0
ファイル: Form1.cs プロジェクト: tumoxuese/XSTORE_V3
        void ExecuReceive(object data)
        {
            lock (CurrentClient)
            {
                AutoResetEvent exitEvent;
                exitEvent = new AutoResetEvent(false);
                //List<byte[]> mac_list = new List<byte[]>();
                //bool open = true;
                TcpDatagramReceivedEventArgs <byte[]> e = (TcpDatagramReceivedEventArgs <byte[]>)data;
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "服务器接收的基础数据:" + data);
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";服务器收到来自设备的数据:" + Converts.GetTPandMac(e.Datagram) + ";");
                int    lengths     = e.Datagram.Length;//接受客户端握手信息
                string str_mac     = "";
                string str_boxdate = "";
                //byte[] boxdate = new byte[6];
                //byte[] mac = new byte[12];
                byte[] boxdate = new byte[12];
                byte[] mac     = new byte[15];
                //byte[] macnew = new byte[13];
                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "服务器命令头:" + e.Datagram[0]);
                switch (e.Datagram[0])
                {
                //第一个字节是EF
                case 239:    //主机返回的数据
                {
                    #region 发送数据到客户端
                    //Array.Copy(e.Datagram, 10, mac, 0, 12);
                    //Array.Copy(e.Datagram, 22, boxdate, 0, 6);
                    try
                    {
                        Array.Copy(e.Datagram, 10, mac, 0, 15);
                        Array.Copy(e.Datagram, 25, boxdate, 0, 12);
                        str_mac     = Converts.GetTPandMac(mac);
                        str_boxdate = Converts.GetTPandMac(boxdate);
                        DeviceClient dev = new DeviceClient();
                        dev.BoxState = str_boxdate;
                        dev.myclient = e.TcpClient;        //请求端
                        dev.OnLine   = false;
                        dev.StrMac   = str_mac;
                        dev.typeid   = 2;
                        //byte[] LastRes = HexStringToByte(GetLastStrToEnd("EF02", Converts.GetTPandMac(e.Datagram)));
                        byte[] LastRes = HexStringToByte(GetLastStrToEnd("EF03", Converts.GetTPandMac(e.Datagram)));
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";服务器收到来自设备" + str_mac + "的数据:" + Converts.GetTPandMac(e.Datagram) + ";");
                        //showLog(DateTime.Now.ToString("HH:mm:ss") + ";服务器收到来自设备" + str_mac + "的数据:" + Converts.GetTPandMac(e.Datagram) + ";");
                        if (!CheckDataGram(LastRes))
                        {
                            //byte[] box_number = new byte[] { 0, 0, 0, 0, 0, 0 };
                            byte[] box_number  = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                            byte[] byteCommand = GetSendMulty(mac, box_number, 0x06);
                            string sss         = ByteToHexString(byteCommand);
                            //暂时注释掉,回复指令
                            //int j = 0;
                            //while (j < 3)
                            //{
                            //    try
                            //    {
                            //        Thread.Sleep(750);
                            //        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "向目标:" + dev.GetStrRemoteEndPoint + ";向MAC为" + str_mac + "发送重发要求" + sss);
                            //        dev.SendMsg(byteCommand);
                            //        break;
                            //    }
                            //    catch { j++; }
                            //}
                        }
                        else
                        {
                            if (e.Datagram[9] == 0x03)        //开箱指令响应
                            {
                                string       strLastCommanResponse = ByteToHexString(LastRes);
                                WeiXinClient wxclient = CurrentClient[str_mac, 1] as WeiXinClient;
                                if (wxclient != null)
                                {
                                    wxclient.receivenum += GetStrAppearTimes("EF03", Converts.GetTPandMac(e.Datagram));
                                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "接收到来自MAC为" + str_mac + "的响应,响应的内容为:" + Converts.GetTPandMac(e.Datagram));
                                    //LogHelper.showLog(txtLog, (DateTime.Now.ToString("HH:mm:ss") + "接收到来自MAC为" + str_mac + "的响应,响应的内容为:" + Converts.GetTPandMac(e.Datagram)));
                                    try
                                    {
                                        if (wxclient.SendMsg(LastRes))        //收到的报文回送
                                        {
                                            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "向微信端回送成功:" + wxclient.GetStrRemoteEndPoint + strLastCommanResponse);
                                            //LogHelper.showLog(txtLog, (DateTime.Now.ToString("HH:mm:ss") + "向微信端回送成功:" + wxclient.GetStrRemoteEndPoint + strLastCommanResponse));
                                            CurrentClient.RemoveClient(wxclient.myclient);
                                        }
                                        else
                                        {
                                            LogHelper.showLog(txtLog, (DateTime.Now.ToString("HH:mm:ss") + "向微信端" + wxclient.GetStrRemoteEndPoint + "回送失败:" + strLastCommanResponse));
                                            //LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "向微信端" + wxclient.GetStrRemoteEndPoint + "回送失败:" + strLastCommanResponse);
                                            CurrentClient.RemoveClient(wxclient.myclient);
                                        }
                                    }
                                    catch
                                    {
                                        CurrentClient.RemoveClient(wxclient.myclient);
                                        //LogHelper.showLog(txtLog, (DateTime.Now.ToString("HH:mm:ss") + "向微信端" + wxclient.GetStrRemoteEndPoint + "回送失败:" + strLastCommanResponse));
                                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "向微信端" + wxclient.GetStrRemoteEndPoint + "回送失败:" + strLastCommanResponse);
                                    }
                                }
                                dev.LastCommanResponse = strLastCommanResponse;
                                bool isAdded = CurrentClient.AddClient(dev);
                                CurrentClient.MultiSendOffLine();
                            }
                            else if (e.Datagram[9] == 0x01)        //心跳
                            {
                                #region 将心跳信息存入数据库
                                byte[] byte_list     = HexStringToByte(str_mac);
                                byte[] new_byte_list = new byte[byte_list.Length];
                                var    new_mac       = string.Empty;
                                for (int i = 0; i < byte_list.Length; i++)
                                {
                                    byte new_byte = (byte)(byte_list[i] - 0x30);
                                    new_mac += new_byte.ToString();
                                }
                                var commend = Converts.GetTPandMac(e.Datagram);
                                LogHelper.SaveHeart(new_mac, commend);
                                var sql = string.Format(@"
declare @cou int
select @cou =count(id)  from WP_设备心跳记录表 where  mac='{0}'
if @cou =0
begin
insert into WP_设备心跳记录表(mac,command) values('{0}','{1}')
end
else
begin
update WP_设备心跳记录表 set  command = '{1}',createtime = getdate() where mac = '{0}'
end", new_mac, commend);
                                try
                                {
                                    var b = DbHelperSQL.ExecuteSql(sql);
                                }
                                catch (Exception ex2)
                                {
                                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ex2.Message);
                                }
                                #endregion

                                /*
                                 * dev.LastBeat = ByteToHexString(e.Datagram);   //服务器回应心跳包
                                 * //LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "来自设备:" + dev.GetStrRemoteEndPoint + ";收到心跳" + dev.LastBeat);
                                 * byte[] responsebeats;
                                 * string strres;
                                 * responsebeats = GetRightBeatsResponse(mac, true);
                                 * strres = ByteToHexString(responsebeats);
                                 * //LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "会送命令:" + responsebeats.ToString() + ";收到心跳" + dev.LastBeat);
                                 * if (CheckDataGram(LastRes))
                                 * {
                                 * //LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "验证通过情况:" + responsebeats.ToString() + ";收到心跳" + dev.LastBeat);
                                 * //dev.SendMsg(responsebeats);
                                 * //LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "向" + str_mac + "发送响应心跳:" + strres);
                                 * }
                                 */
                                bool isAdded = CurrentClient.AddClientWithOutCmd(dev);
                                CurrentClient.MultiSendOffLine();
                            }
                            //bool isAdded = CurrentClient.AddClient(dev);
                            //CurrentClient.MultiSendOffLine();
                        }
                    }
                    catch (Exception e2)
                    {
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";" + e2.Message);
                    }
                    #endregion
                }
                break;

                //微信过来的,发命令
                case 02:
                {
                    //mac_list.Add(e.Datagram);
                    //if (open)
                    //{

                    //}
                    try
                    {
                        #region 客户端发送的控制数据
                        //open = false;
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "客户端:" + e.TcpClient.Client.RemoteEndPoint.ToString() + "的原始命令:" + ByteToHexString(e.Datagram));
                        LogHelper.showLog(txtLog, (DateTime.Now.ToString("HH:mm:ss") + "客户端:" + e.TcpClient.Client.RemoteEndPoint.ToString() + "的原始命令:" + ByteToHexString(e.Datagram)));
                        Array.Copy(e.Datagram, 1, mac, 0, 15);

                        //mac_list.RemoveAt(0);
                        str_mac = Converts.GetTPandMac(mac);
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "MAC:" + str_mac);
                        WeiXinClient wxclt = new WeiXinClient();
                        wxclt.sendnum    = 0;
                        wxclt.receivenum = 0;
                        wxclt.myclient   = e.TcpClient;
                        wxclt.StrMac     = str_mac;
                        wxclt.command    = ByteToHexString(e.Datagram);
                        wxclt.typeid     = 1;
                        CurrentClient.AddClient(wxclt);
                        DeviceClient dev = CurrentClient[str_mac, 2] as DeviceClient;
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + " MAC:" + str_mac);
                        if (dev != null)
                        {        //拆命令发送
                            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + " dev不为空:" + str_mac);
                            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + " 命令长度:" + e.Datagram.Length);

                            byte[] box_number = new byte[e.Datagram.Length - 16];

                            Array.Copy(e.Datagram, 16, box_number, 0, e.Datagram.Length - 16);
                            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + " boxnumber:" + Converts.GetTPandMac(box_number));
                            int sendnum = 0;
                            #region 一次性
                            byte[] byteCommand = GetSendMulty(mac, box_number);
                            string sss         = ByteToHexString(byteCommand);
                            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + " sss:" + sss);
                            try
                            {
                                Thread.Sleep(750);
                                LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + " byteCommand:" + byteCommand);
                                dev.SendMsg(byteCommand);

                                sendnum++;
                                break;
                            }
                            catch (Exception err)
                            {
                                LogHelper.WriteLog("发送指令异常:" + err.Message + "错误发生位置为" + err.StackTrace);
                                LogHelper.showLog(txtLog, ("发送指令异常:" + err.Message + "错误发生位置为" + err.StackTrace));
                            }
                            #endregion
                            wxclt.sendnum = sendnum;
                            CurrentClient.AddClient(wxclt);
                        }
                        #endregion
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog("发送指令异常:" + ex.Message + "错误发生位置为" + ex.StackTrace);
                    }
                }

                break;

                default:
                    break;
                }
                Control.CheckForIllegalCrossThreadCalls = false;
                label1.Text = CurrentClient.GetDevCount().ToString();
                label3.Text = CurrentClient.GetWeiXinNumber().ToString();
                //try
                //{

                //}
                //catch (Exception ex)
                //{
                //    string messages = string.Empty;
                //    messages = "捕获异常" + ex.Message + "错误发生位置为" + ex.StackTrace;
                //    //LogHelper.WriteLog(messages);
                //    //LogHelper.showLog(txtLog, messages);
                //}
                //finally
                //{

                //}
            }
        }
コード例 #8
0
        private void BoxProtocolServer_NewRequestReceived(BoxSession session, BoxRequestInfo requestInfo)
        {
            //LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "所有的mac:" + JsonConvert.SerializeObject(boxServer.GetAllSessions().Select(o => new { o.CustomId, o.CustomType, o.SessionID }).ToList()));
            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "当前session的ID:" + session.SessionID);
            //如果头命令不是EF03则关闭当前的session
            if (requestInfo.Body.Head.Contains("EF"))
            {
                session.CustomId = requestInfo.Body.Mac;
                session.Mac      = requestInfo.Body.FormatMac;
                switch ((类型)requestInfo.Body.Type)
                {
                case 类型.微信:
                    session.CustomType = 2;
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "微信传过来的命令:" + requestInfo.Body.Command);
                    var command = BoxModel.ToCommand(requestInfo.Body);
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "微信端口命令:" + Converts.GetTPandMac(command));
                    if (!OpenBoxByMac(session.CustomId, command, requestInfo.Body.OrderNo, 1))
                    {
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "已经开箱失败:");
                        //需要发送byte数组的命令,返回微信处理
                        //session.Send(JsonConvert.SerializeObject(new ResponseResult() { Status = false, ErrorCode = 01, Message ="箱子未连接"}));
                    }
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "已经开箱成功:");
                    break;

                case 类型.心跳:
                    session.CustomType = 1;
                    var macDt = DbHelperSQL.GetDataTableBySQL(string.Format("select top 1 * from WP_库位表 where 箱子MAC ='{0}'", session.Mac));
                    //如果没有查到信息,那么说明箱子在三代上
                    if (macDt.Rows.Count == 0)
                    {
                        var cache = (List <OnlineBox>)CacheHelper.GetCache("Boxes");
                        if (cache != null)
                        {
                            var mac = cache.FirstOrDefault(o => o.mac.Equals(session.Mac));
                            LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";mac:" + mac);

                            if (mac != null)
                            {
                                //如果之前是离线的,需要通知管理后台
                                if (!mac.online)
                                {
                                    var requestUrl = string.Format("{0}test/online?mac={1}", Constant.YunApi, mac.mac);
                                    var response   = JsonConvert.DeserializeObject <BuyResponse>(Utils.HttpGet(requestUrl));
                                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";heartResponse:" + response);
                                    if (!response.operationStatus.Equals("SUCCESS"))
                                    {
                                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + ";在线通知接口请求失败");
                                    }
                                }
                                mac.online   = true;
                                mac.lineTime = DateTime.Now;
                                CacheHelper.SetCache("Boxes", cache);
                            }
                        }
                    }
                    else
                    {
                        //处理并存储心跳信息
                        SaveHeart(requestInfo.Body);
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "心跳命令:" + requestInfo.Body.Command);
                        //判断是否有异常开箱的情况,记录并反馈
                        ShowLog(txtLog, requestInfo.Body.ToString());
                    }
                    break;

                case 类型.开箱:
                    session.CustomType = 1;
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "开箱回复命令:" + requestInfo.Body.Command);
                    //发送微信反馈
                    SetOrderNo(session, requestInfo.Body.State);
                    ShowLog(txtLog, requestInfo.Body.ToString());
                    break;

                default:
                    session.CustomType = 1;
                    break;
                }
            }
            //三代微信过来的信息
            else if (requestInfo.Body.Head.Contains("FF"))
            {
                session.CustomId = requestInfo.Body.Mac;

                switch ((类型)requestInfo.Body.Type)
                {
                case 类型.微信:
                    session.CustomType = 2;
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "微信传过来的命令:" + requestInfo.Body.Command);
                    var command = BoxModel.ToCommand(requestInfo.Body);
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "微信端口命令:" + Converts.GetTPandMac(command));
                    if (!OpenBoxByMac(session.CustomId, command, requestInfo.Body.OrderNo, 1))
                    {
                        LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "已经开箱失败:");
                        //需要发送byte数组的命令,返回微信处理
                        //session.Send(JsonConvert.SerializeObject(new ResponseResult() { Status = false, ErrorCode = 01, Message ="箱子未连接"}));
                    }
                    LogHelper.WriteLog(DateTime.Now.ToString("HH:mm:ss") + "开箱命令发送成功:");
                    break;

                default:
                    session.CustomType = 1;
                    break;
                }
            }
            else
            {
                session.Close();
                return;
            }
        }
コード例 #9
0
        protected override BoxRequestInfo ProcessMatchedRequest(byte[] buffer, int offset, int length, bool toBeCopied)
        {
            var boxModel = new BoxModel();
            var headByte = new byte[2];
            var command  = buffer.CloneRange(offset, 50);

            if (!CheckDataGram(command))
            {
                return(new BoxRequestInfo(new BoxModel()));
            }
            boxModel.Head   = ByteToHexString(buffer.CloneRange(offset, 2));//开始标识的解析,2个字节
            boxModel.Lenght = BitConverter.ToUInt16(buffer, offset + 2);

            if (boxModel.Head.Equals("EF02"))
            {
                boxModel.Type      = 2;
                boxModel.OpenType  = buffer[offset + 3];
                boxModel.Mac       = Converts.GetTPandMac(buffer.CloneRange(offset + 4, 15));
                boxModel.FormatMac = FormatMac(boxModel.Mac);
                boxModel.Command   = Converts.GetTPandMac(command);
                boxModel.State     = buffer.CloneRange(offset + 19, 12);
                var oderCount = int.Parse(Encoding.UTF8.GetString(buffer.CloneRange(offset + 46, 2)));
                var orderNo   = buffer.CloneRange(offset + 31, oderCount);
                LogHelper.WriteLog("命令过来的type类型:" + (int)boxModel.OpenType);
                switch ((Enum.OpenType)((int)boxModel.OpenType))
                {
                case Enum.OpenType.订单开箱:
                    boxModel.OrderNo = "S" + Encoding.UTF8.GetString(orderNo);
                    break;

                case Enum.OpenType.补货开箱:
                    boxModel.OrderNo = "B" + Encoding.UTF8.GetString(orderNo);
                    break;

                case Enum.OpenType.开箱检查:
                    boxModel.OrderNo = "J" + Encoding.UTF8.GetString(orderNo);
                    break;

                case Enum.OpenType.测试开箱:
                    boxModel.OrderNo = "C" + Encoding.UTF8.GetString(orderNo);
                    break;
                }
            }
            else if (boxModel.Head.Equals("EF03"))
            {
                boxModel.Type        = buffer[offset + 9];
                boxModel.Time        = Converts.GetTPandMac(buffer.CloneRange(offset + 3, 6));
                boxModel.Mac         = Converts.GetTPandMac(buffer.CloneRange(offset + 10, 15));
                boxModel.FormatMac   = FormatMac(Converts.GetTPandMac(buffer.CloneRange(offset + 10, 15)));
                boxModel.State       = buffer.CloneRange(offset + 25, 12);
                boxModel.Signal      = buffer.CloneRange(offset + 37, 1);
                boxModel.Placeholder = buffer.CloneRange(offset + 47, 1);
                boxModel.Check       = buffer.CloneRange(offset + 48, 2);
                boxModel.Command     = Converts.GetTPandMac(command);
            }
            //三代箱子
            else if (boxModel.Head.Equals("FF02"))
            {
                boxModel.Type      = 2;
                boxModel.OpenType  = buffer[offset + 3];
                boxModel.Mac       = Converts.GetTPandMac(buffer.CloneRange(offset + 4, 15));
                boxModel.FormatMac = FormatMac(boxModel.Mac);
                boxModel.Command   = Converts.GetTPandMac(command);
                boxModel.State     = buffer.CloneRange(offset + 19, 12);
                var oderCount = int.Parse(Encoding.UTF8.GetString(buffer.CloneRange(offset + 47, 1)));
                var orderNo   = buffer.CloneRange(offset + 31, oderCount);
                LogHelper.WriteLog("命令过来的type类型:" + (int)boxModel.OpenType);
                boxModel.OrderNo = Encoding.UTF8.GetString(orderNo);
            }
            return(new BoxRequestInfo(boxModel));
        }