Ejemplo n.º 1
0
        //  数据下行设置
        public String BuildSet(string sid, IList <EDownParam> cmds, CDownConf down, EChannelType ctype)
        {
            String result       = String.Empty;
            String dataProtocol = Manager.XmlStationData.Instance.GetProtocolBySId(sid);

            //RG30
            if (dataProtocol == "RG30")
            {
                Down = new Data.RG30.DownParser();
            }
            //时差法
            if (dataProtocol == "TDXY")
            {
                Down = new Data.TDXY.DownParser();
            }
            //中游局协议
            if (dataProtocol == "ZYJBX")
            {
                Down = new Data.ZYJBX.DownParser();
            }
            if (dataProtocol == "SM100H")
            {
                Down = new Data.SM100H.DownParser();
            }
            result = Down.BuildSet(sid, cmds, down, ctype);
            return(result);
        }
Ejemplo n.º 2
0
 private void ReadForData_EventHandler_3(object sender, DownEventArgs e)
 {
     try
     {
         CDownConf info = e.Value;
         //$60031G12000828
         //$60121G020845
         string rawData = e.RawData;
         if (info == null)
         {
             return;
         }
         string stationid = rawData.Substring(1, 4);
         string type      = rawData.Substring(5, 4);
         string data      = rawData.Substring(9, 4);
         if (type == "1G02")
         {
             if (info.Rain.HasValue)
             {
                 if (readDataDic.ContainsKey(stationid))
                 {
                     readDataDic[stationid] = data;
                 }
                 readDataDic.Add(stationid, data);
             }
         }
     }
     catch (Exception exp) { Debug.WriteLine(exp.Message); }
 }
 private void DownForUI_EventHandler_3(object sender, DownEventArgs e)
 {
     try
     {
         CDownConf info = e.Value;
         //$60031G12000828
         //$60121G020845
         string rawData = e.RawData.Replace(" ", "");
         if (info == null)
         {
             return;
         }
         string stationid = rawData.Substring(1, 4);
         string type      = rawData.Substring(5, 4);
         string data      = rawData.Substring(9, 4);
         //  if (this.IsHandleCreated && type=="1G02")
         if (type == "1G02")
         {
             #region 更新UI
             if (info.Rain.HasValue)
             {
                 try
                 {
                     UpdateRainStorage(stationid, data);
                 }
                 catch (Exception exp) { Debug.WriteLine(exp.Message); }
             }
             #endregion
         }
     }
     catch (Exception exp) { Debug.WriteLine(exp.Message); }
 }
Ejemplo n.º 4
0
 private void DownForUI_EventHandler_4(object sender, DownEventArgs e)
 {
     try
     {
         CDownConf info = e.Value;
         //$60031G12000828
         string rawData = e.RawData;
         if (info == null)
         {
             return;
         }
         if (rawData.Length >= 15)
         {
             string stationid = rawData.Substring(1, 4);
             string type      = rawData.Substring(5, 4);
             string data      = rawData.Substring(9, 6);
             if (this.IsHandleCreated)
             {
                 #region 更新UI
                 if (info.StorageWater.HasValue)
                 {
                     try
                     {
                         UpdateStorage(stationid, data);
                     }
                     catch (Exception exp) { Debug.WriteLine(exp.Message); }
                 }
                 #endregion
             }
         }
     }
     catch (Exception exp) { Debug.WriteLine(exp.Message); }
 }
        //public void RefreshGPRSInfo(List<CEntityStation> stations)
        //{
        //    if (null == stations || stations.Count == 0)
        //    {
        //        return;
        //    }
        //    // 判断是否在列中存在,如果不存在,则新建列
        //    // 先找到ID所在的行
        //    m_mutexDataTable.WaitOne();
        //    foreach (var station in stations)
        //    {
        //        CEntitySubCenter subcenter = CDBDataMgr.Instance.GetSubCenterById(station.SubCenterID.Value);
        //        string subCenterName = "";
        //        if (subcenter != null)
        //        {
        //            subCenterName = subcenter.SubCenterName;
        //        }

        //        if (!string.IsNullOrEmpty(station.GPRS))
        //        {
        //            // this.m_totalGprsCount += 1;
        //            base.AddRow(new string[] { "False", station.StationID, station.StationName, station.GPRS, subCenterName, "--", "" }, EDataState.ENormal);
        //        }
        //    }
        //    m_mutexDataTable.ReleaseMutex();
        //}

        //public void RefreshGPRSInfo(ushort port, string stationName, ModemInfoStruct dtu)
        //{
        //    string uid = ((uint)dtu.m_modemId).ToString("X").PadLeft(8, '0');
        //    string phoneno = CGprsUtil.Byte11ToPhoneNO(dtu.m_phoneno, 0);
        //    string dynIP = CGprsUtil.Byte4ToIP(dtu.m_dynip, 0);
        //    DateTime connetime = CGprsUtil.ULongToDatetime(dtu.m_conn_time);
        //    DateTime refreshTime = CGprsUtil.ULongToDatetime(dtu.m_refresh_time);
        //    //如果计算机当前时间与刷新时间间隔超过一小时,标记为红色
        //    //现在改为10分钟,不在线,红色标记
        //    EDataState state = EDataState.ENormal;

        //    //  if ((DateTime.Now - refreshTime).TotalMinutes > 60)
        //    //超过10分钟,表示不在线
        //    if ((DateTime.Now - refreshTime).TotalMinutes > 10)
        //    {
        //        this.cS_GprsOnlineOrOff = "离线";
        //        //      state = EDataState.EError;
        //    }
        //    else
        //    {
        //        this.cS_GprsOnlineOrOff = "在线";
        //        //      this.m_onlineGprsCount += 1;
        //    }
        //    // 判断是否在列中存在,如果不存在,则新建列
        //    // 先找到ID所在的行
        //    m_mutexDataTable.WaitOne();
        //    for (int i = 0; i < base.m_dataTable.Rows.Count; ++i)
        //    {
        //        if (m_dataTable.Rows[i][CS_StationGprs].ToString() == uid)
        //        {
        //            m_mutexDataTable.ReleaseMutex();
        //            CEntityStation entity = CDBDataMgr.Instance.GetStationByGprs(uid);
        //            // 找到匹配,更新行的内容
        //            base.UpdateRowData(i, new string[] { "False", entity.StationID, stationName, uid, m_listSubCenter[int.Parse(entity.SubCenterID.ToString()) - 1].SubCenterName.ToString(), cS_GprsOnlineOrOff.ToString(),"" }, state);
        //            CBatchManagement.ListOnlineStation1.Add(CDBDataMgr.Instance.GetStationByGprs(uid));
        //            return;
        //        }
        //    }
        //    // 没有找到匹配,添加新的行记录
        //    m_mutexDataTable.ReleaseMutex();
        //    //CEntityStation entity1 = CDBDataMgr.Instance.GetStationByGprs(uid);
        //    //base.AddRow(new string[] { "False", entity1.StationID, stationName, uid, m_listSubCenter[int.Parse(entity1.SubCenterID.ToString()) - 1].SubCenterName.ToString(), cS_GprsOnlineOrOff.ToString(), "" }, state);
        //    //CBatchManagement.ListOnlineStation1.Add(entity1);
        //    // this.m_totalGprsCount += 1;
        //}

        private void DownForUI_EventHandler_1(object sender, DownEventArgs e)
        {
            try
            {
                CDownConf info = e.Value;
                //$60031G12000828
                string rawData = e.RawData.Replace(" ", "");
                if (info == null)
                {
                    return;
                }
                if (rawData.Length >= 15)
                {
                    string stationid = rawData.Substring(1, 4);
                    string type      = rawData.Substring(5, 4);
                    string data      = rawData.Substring(9, 6);
                    if (this.IsHandleCreated)
                    {
                        #region 更新UI
                        if (info.storeWater.HasValue && type.Equals("1G12"))
                        {
                            try
                            {
                                UpdateStorage(stationid, data);
                                //this..Invoke((Action)delegate
                                //{
                                ////    this.vClock.Value = info.Clock.Value;
                                ////    HighlightControl(this.vClock);
                                //    this.
                                //});
                            }
                            catch (Exception exp) { Debug.WriteLine(exp.Message); }
                        }
                        #endregion
                    }
                }
            }
            catch (Exception exp) { Debug.WriteLine(exp.Message); }
        }
Ejemplo n.º 6
0
        //private void StationNotOL_EventHandler(object sender, DownEventArgs e)
        //{
        //    if(!notOL) notOL = true;
        //}

        /// <summary>
        /// 上行数据处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DownData_EventHandler(object sender, DownEventArgs e)
        {
            try
            {
                CDownConf info     = e.Value;
                DownConf  downConf = new DownConf();
                if (info == null)
                {
                    return;
                }
                if (info.Clock.HasValue)
                {
                    downConf.Clock = info.Clock.ToString();
                }
                if (info.NormalState.HasValue)
                {
                    if (info.NormalState == ENormalState.GPRS)
                    {
                        downConf.NormalState = DownConf.Types.NormalState.GprsState;
                    }
                    if (info.NormalState == ENormalState.GSM)
                    {
                        downConf.NormalState = DownConf.Types.NormalState.GsmState;
                    }
                }
                if (info.Voltage.HasValue)
                {
                    downConf.Voltage = (double)info.Voltage;
                }
                if (!String.IsNullOrEmpty(info.StationCmdID))
                {
                    downConf.StationCmdID = info.StationCmdID;
                }
                if (info.TimeChoice.HasValue)
                {
                    if (info.TimeChoice == ETimeChoice.AdjustTime)
                    {
                        downConf.TimeChoice = DownConf.Types.TimeChoice.AdjustTime;
                    }
                    if (info.TimeChoice == ETimeChoice.Two)
                    {
                        downConf.TimeChoice = DownConf.Types.TimeChoice.NoAdjustTime;
                    }
                }
                if (info.TimePeriod.HasValue)
                {
                    if (info.TimePeriod == ETimePeriod.One)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.One;
                    }
                    if (info.TimePeriod == ETimePeriod.Two)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.Two;
                    }
                    if (info.TimePeriod == ETimePeriod.Four)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.Four;
                    }
                    if (info.TimePeriod == ETimePeriod.Six)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.Six;
                    }
                    if (info.TimePeriod == ETimePeriod.Eight)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.Eight;
                    }
                    if (info.TimePeriod == ETimePeriod.Twelve)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.Twelve;
                    }
                    if (info.TimePeriod == ETimePeriod.TwentyFour)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.TwentyFour;
                    }
                    if (info.TimePeriod == ETimePeriod.FourtyEight)
                    {
                        downConf.TimePeriod = DownConf.Types.TimePeriod.FourtyEight;
                    }
                }
                if (info.WorkStatus.HasValue)
                {
                    if (info.WorkStatus == EWorkStatus.Debug)
                    {
                        downConf.WorkStatus = DownConf.Types.WorkStatus.Debug;
                    }
                    if (info.WorkStatus == EWorkStatus.DoubleAddress)
                    {
                        downConf.WorkStatus = DownConf.Types.WorkStatus.DoubleAddress;
                    }
                    if (info.WorkStatus == EWorkStatus.Normal)
                    {
                        downConf.WorkStatus = DownConf.Types.WorkStatus.Normal;
                    }
                }
                if (!String.IsNullOrEmpty(info.VersionNum))
                {
                    downConf.VersionNum = info.VersionNum;
                }
                if (info.MainChannel.HasValue && info.ViceChannel.HasValue)
                {
                    try
                    {
                        if (info.MainChannel == EChannelType.BeiDou)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.BeiDou;
                        }
                        if (info.MainChannel == EChannelType.Beidou500)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.Beidou500;
                        }
                        if (info.MainChannel == EChannelType.BeidouNormal)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.BeidouNormal;
                        }
                        if (info.MainChannel == EChannelType.GPRS)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.Gprs;
                        }
                        if (info.MainChannel == EChannelType.GSM)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.Gsm;
                        }
                        if (info.MainChannel == EChannelType.None)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.None;
                        }
                        if (info.MainChannel == EChannelType.PSTN)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.Pstn;
                        }
                        if (info.MainChannel == EChannelType.VHF)
                        {
                            downConf.MainChannel = DownConf.Types.ChannelType.Vhf;
                        }
                    }
                    catch (Exception exp) { Debug.WriteLine(exp.Message); }
                    try
                    {
                        if (info.ViceChannel == EChannelType.BeiDou)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.BeiDou;
                        }
                        if (info.ViceChannel == EChannelType.Beidou500)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.Beidou500;
                        }
                        if (info.ViceChannel == EChannelType.BeidouNormal)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.BeidouNormal;
                        }
                        if (info.ViceChannel == EChannelType.GPRS)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.Gprs;
                        }
                        if (info.ViceChannel == EChannelType.GSM)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.Gsm;
                        }
                        if (info.ViceChannel == EChannelType.None)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.None;
                        }
                        if (info.ViceChannel == EChannelType.PSTN)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.Pstn;
                        }
                        if (info.ViceChannel == EChannelType.VHF)
                        {
                            downConf.ViceChannel = DownConf.Types.ChannelType.Vhf;
                        }
                    }
                    catch (Exception exp) { Debug.WriteLine(exp.Message); }
                }
                if (!String.IsNullOrEmpty(info.TeleNum))
                {
                    downConf.TeleNum = info.TeleNum;
                }
                if (info.RingsNum.HasValue)
                {
                    downConf.RingsNum = (double)info.RingsNum;
                }
                if (!String.IsNullOrEmpty(info.DestPhoneNum))
                {
                    downConf.DestPhoneNum = info.DestPhoneNum;
                }
                if (!String.IsNullOrEmpty(info.TerminalNum))
                {
                    downConf.TerminalNum = info.TerminalNum;
                }
                if (!String.IsNullOrEmpty(info.RespBeam))
                {
                    downConf.RespBeam = info.RespBeam;
                }
                if (info.AvegTime.HasValue)
                {
                    downConf.AvegTime = (double)info.AvegTime;
                }
                if (info.RainPlusReportedValue.HasValue)
                {
                    downConf.RainPlusReportedValue = (double)info.RainPlusReportedValue;
                }
                if (!String.IsNullOrEmpty(info.KC))
                {
                    downConf.KC = info.KC;
                    // KC值长度为20时,前十位为k,后十位为C
                }
                if (info.Rain.HasValue)
                {
                    downConf.Rain = (double)info.Rain;
                }
                if (info.Water.HasValue)
                {
                    downConf.Water = (double)info.Water;
                }
                if (info.WaterPlusReportedValue.HasValue)
                {
                    downConf.WaterPlusReportedValue = (double)info.WaterPlusReportedValue;
                }
                if (info.SelectCollectionParagraphs.HasValue)
                {
                    if (info.SelectCollectionParagraphs == ESelectCollectionParagraphs.FiveOrSix)
                    {
                        downConf.Select = DownConf.Types.SelectCollectionParagraphs.FiveOrSix;
                    }
                    if (info.SelectCollectionParagraphs == ESelectCollectionParagraphs.TenOrTwelve)
                    {
                        downConf.Select = DownConf.Types.SelectCollectionParagraphs.TenOrTwelve;
                    }
                }
                if (!String.IsNullOrEmpty(info.UserName))
                {
                    downConf.UserName = info.UserName;
                }
                if (!String.IsNullOrEmpty(info.StationName))
                {
                    downConf.StationName = info.StationName;
                }

                if (downConf != null)
                {
                    this.downConfList.Add(downConf);
                }
            }
            catch (Exception exp)
            {
                Debug.WriteLine("" + exp.Message);
            }
        }
Ejemplo n.º 7
0
        private void Parser_3(object str)
        {
            try
            {
                string data = str as string;
                /* 删除 '\r\n' 字符串 */
                while (data.StartsWith("\r\n"))
                {
                    data = data.Substring(2);
                }

                /*
                 * 解析数据,获取CGSMStruct
                 */
                var gsm = new CGSMStruct();
                if (!GsmHelper.Parse_3(data, out gsm))
                {
                    return;
                }
                /*  如果解析成功,触发GSM数据接收完成事件  */
                //string rawdata = "";
                //string rawdata1 = gsm.Message;
                //if (!rawdata1.Contains('$'))
                //{
                //    rawdata = "$" + rawdata1;
                //}

                if (data.EndsWith("+"))
                {
                    data = data.Substring(0, data.Length - 1);
                }
                InvokeMessage(data, "接收");

                string msg = string.Empty;
                if (!ProtocolHelpers.DeleteSpecialChar(gsm.Message, out msg))
                {
                    return;
                }
                msg = gsm.Message;
                string rawdata = msg;
                if (msg.Contains('$'))
                {
                    msg = msg.Substring(1);
                }
                //if (msg.Contains('9'))
                //{
                //    msg = msg.Substring(1);
                //}


                if (!msg.ToUpper().Contains("TRU"))
                {
                    string sid  = msg.Substring(0, 4);
                    string type = msg.Substring(4, 2);

                    /*
                     *  上行指令信息,
                     *  或者读取参数返回的信息
                     */
                    #region 1G
                    if (type == "1G")
                    {
                        string reportType = msg.Substring(6, 2);
                        /*  定时报,加报 */
                        if (reportType == "21" || reportType == "22")
                        {
                            //  YAC设备的墒情协议:
                            string stationType = msg.Substring(8, 2);
                            switch (stationType)
                            {
                            //  站类为04时墒情站 05墒情雨量站 06,16墒情水位站 07,17墒情水文站
                            case "04":
                            case "05":
                            case "06":
                            case "07":
                                //case "17":
                                //    {
                                //        CEntitySoilData soil = new CEntitySoilData();
                                //        CReportStruct soilReport = new CReportStruct();
                                //        Soil = new Protocol.Data.Lib.SoilParser();
                                //        if (Soil.Parse(rawdata, out soil, out soilReport))
                                //        {
                                //            soil.ChannelType = EChannelType.GSM;

                                //            if (null != this.SoilDataReceived)
                                //                this.SoilDataReceived(null, new CEventSingleArgs<CEntitySoilData>(soil));
                                //            //1111gm
                                //            string temp = soilReport.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                //            //InvokeMessage(String.Format("{0,-10}   ", temp) + rawdata, "接收");

                                //            if (null != soilReport && null != this.UpDataReceived)
                                //           // if (null != soilReport)
                                //             {
                                //                soilReport.ChannelType = EChannelType.GSM;
                                //                soilReport.ListenPort = "COM" + this.ListenPort.PortName;
                                //                this.UpDataReceived(null, new UpEventArgs() { RawData = rawdata, Value = soilReport });
                                //            }
                                //        }
                                //        else
                                //        {
                                //            //string temp = soilReport.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                //            InvokeMessage(" " + rawdata, "接收");
                                //        }
                                //    }
                                break;

                            //  站类为01,02,03,12,13时,不是墒情站
                            case "01":
                            case "02":
                            case "03":
                            case "12":
                            case "13":
                            {
                                CReportStruct report = new CReportStruct();
                                if (Up.Parse(msg, out report))         /* 解析成功 */
                                {
                                    report.ChannelType = EChannelType.GSM;
                                    report.ListenPort  = "COM" + this.ListenPort.PortName;
                                    report.flagId      = gsm.PhoneNumber;
                                    if (this.UpDataReceived != null)
                                    {
                                        this.UpDataReceived.Invoke(null, new UpEventArgs()
                                            {
                                                Value = report, RawData = data
                                            });
                                    }
                                }
                            }
                            break;

                            default:
                                break;
                            }
                        }
                        else if (reportType == "11")    //  人工水位
                        {
                        }
                        else if (reportType == "23")    //  人工流量
                        {
                        }
                        else if (reportType == "25")
                        {
                        }
                        else /* 下行指令 */
                        {
                            CDownConf downconf = new CDownConf();
                            if (Down.Parse(msg, out downconf)) /* 解析成功 */
                            {
                                if (this.DownDataReceived != null)
                                {
                                    this.DownDataReceived.Invoke(null, new DownEventArgs()
                                    {
                                        Value = downconf, RawData = data
                                    });
                                }
                            }
                        }
                    }

                    #endregion

                    #region 1K
                    if (type == "1K") /* 批量传输 */
                    {
                        var station = FindStationBySID(sid);
                        if (station == null)
                        {
                            throw new Exception("批量传输,站点传输类型匹配错误");
                        }
                        //  EStationBatchType batchType = station.BatchTranType;

                        //if (batchType == EStationBatchType.EFlash)          /* Flash传输 */
                        //{
                        CBatchStruct batch = new CBatchStruct();
                        if (FlashBatch.Parse(gsm.Message, out batch)) /* 解析成功 */
                        {
                            if (this.BatchDataReceived != null)
                            {
                                this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                {
                                    Value = batch, RawData = data
                                });
                            }
                        }
                        //}
                        //else if (batchType == EStationBatchType.EUPan)  /* U盘传输 */
                        //{
                        //    CBatchStruct batch = new CBatchStruct();
                        //    if (UBatch.Parse(gsm.Message, out batch))   /* 解析成功 */
                        //    {
                        //        if (this.BatchDataReceived != null)
                        //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = data });
                        //    }
                        //}
                        else
                        {
                            throw new Exception("批量传输,站点传输类型匹配错误");
                        }
                    }
                    #endregion

                    #region 1S
                    if (type == "1S") /* 远地下行指令,设置参数 */
                    {
                        CDownConf downconf = new CDownConf();
                        if (Down.Parse(gsm.Message, out downconf))/* 解析成功 */
                        {
                            if (this.DownDataReceived != null)
                            {
                                this.DownDataReceived.Invoke(null, new DownEventArgs()
                                {
                                    Value = downconf, RawData = data
                                });
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    if (this.ErrorReceived != null)
                    {
                        this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                        {
                            Msg = data
                        });
                    }
                }
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp.Message);
            }
        }
Ejemplo n.º 8
0
        private void DealData()
        {
            while (true)
            {
                m_semaphoreData.WaitOne(); //阻塞当前线程,知道被其它线程唤醒
                // 获取对data内存缓存的访问权
                m_mutexListDatas.WaitOne();
                List <HDModemDataStruct> dataListTmp = m_listDatas;
                m_listDatas = new List <HDModemDataStruct>(); //开辟一快新的缓存区
                m_mutexListDatas.ReleaseMutex();
                for (int i = 0; i < dataListTmp.Count; ++i)
                {
                    try
                    {
                        HDModemDataStruct dat = dataListTmp[i];
                        //1获取gprs号码,并根据gprs号码获取站点id
                        //StringBuilder gprsId = new StringBuilder();
                        //foreach (byte b in dat.m_data_buf)
                        //{
                        //    gprsId.AppendFormat("{0:x2}", b);
                        //}
                        string gprs = System.Text.Encoding.Default.GetString(dat.m_modemId);
                        gprs = gprs.Replace("\0", "");
                        string sid = Manager.XmlStationData.Instance.GetStationByGprsID(gprs);

                        //1.2 获取ascii原始数据,获取报文头
                        string data = System.Text.Encoding.Default.GetString(dat.m_data_buf).TrimEnd('\0');
                        InvokeMessage(data, "原始数据");
                        data = data.Trim();


                        if (data.Contains("TRU"))
                        {
                            Debug.WriteLine("接收数据TRU完成,停止计时器");
                            //m_timer.Stop();
                            InvokeMessage("TRU " + System.Text.Encoding.Default.GetString(dat.m_modemId), "接收");
                            if (this.ErrorReceived != null)
                            {
                                this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                                {
                                    //   Msg = "TRU " + dat.m_modemId
                                    Msg = "TRU " + System.Text.Encoding.Default.GetString(dat.m_modemId)
                                });
                            }
                        }
                        if (data.Contains("ATE0"))
                        {
                            Debug.WriteLine("接收数据ATE0完成,停止计时器");
                            //m_timer.Stop();
                            // InvokeMessage("ATE0", "接收");
                            if (this.ErrorReceived != null)
                            {
                                this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                                {
                                    Msg = "ATE0"
                                });
                            }
                        }
                        string result = null;
                        if (data.Contains("$"))
                        {
                            result = data.Substring(data.IndexOf("$"), data.IndexOf("\0"));

                            if (!(result.StartsWith("$") && result.EndsWith("\r\n")))
                            {
                                InvokeMessage(result + "报文开始符结束符不合法", "接收");
                            }
                            String dataProtocol = Manager.XmlStationData.Instance.GetProtocolBySId(sid);

                            CReportStruct report     = new CReportStruct();
                            CDownConf     downReport = new CDownConf();
                            if (dataProtocol == "ZYJBX")
                            {
                                Up   = new Data.ZYJBX.UpParser();
                                Down = new Data.ZYJBX.DownParser();
                            }
                            if (dataProtocol == "RG30")
                            {
                                //回复TRU,确认接收数据
                                InvokeMessage("TRU " + gprs, "发送");
                                byte[] bts = new byte[] { 84, 82, 85, 13, 10 };
                                this.sendHex(gprs.Trim(), bts, (uint)bts.Length, null);


                                Up   = new Data.RG30.UpParser();
                                Down = new Data.RG30.DownParser();
                                //2.1 如果是RG30,则需获取16进制字符串
                                StringBuilder adcpMsg = new StringBuilder();
                                foreach (byte b in dat.m_data_buf)
                                {
                                    adcpMsg.AppendFormat("{0:x2}", b);
                                }
                                string temp = adcpMsg.ToString().Trim();
                                if (temp.Length < 200)
                                {
                                    return;
                                }
                                InvokeMessage(temp, "原始数据");
                                //2.2 获取封装的头部信息
                                string head   = data.Substring(0, 57);
                                int    length = int.Parse(data.Substring(53, 4));

                                //2.3 根据头部信息获取数据类型  HADCP OR VADCP
                                string type = "";
                                if (head.Contains("HADCP"))
                                {
                                    type = "H";
                                }
                                else if (head.Contains("VADCP"))
                                {
                                    type = "V";
                                }
                                string hdt0 = "";
                                string vdt0 = "";
                                //2.4 根据头部信息截图DT0数据
                                if (type == "H")
                                {
                                    hdt0 = temp.Substring(57, length * 2);
                                    //hdt0 = temp.Substring(57);
                                    //写入DT0文件
                                    Write2File writeClass = new Write2File("hdt0");
                                    Thread     t          = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile));
                                    t.Start(hdt0 + "\r\n");

                                    //调用dll解析计算
                                    //TODO需要调试
                                    //ReadPD0FileTest();
                                }
                                else if (type == "V")
                                {
                                    vdt0 = temp.Substring(57, length * 2);
                                    Write2File writeClass = new Write2File("vdt0");
                                    Thread     t          = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile));
                                    t.Start(vdt0 + "\r\n");
                                }
                                return;
                            }
                            //批量传输解析
                            if (data.Contains("1K"))
                            {
                                var station = FindStationBySID(sid);
                                if (station == null)
                                {
                                    throw new Exception("批量传输,站点匹配错误");
                                }
                                CBatchStruct batch = new CBatchStruct();
                                InvokeMessage(String.Format("{0,-10}   ", "批量传输") + data, "接收");

                                if (Down.Parse_Flash(result, EChannelType.GPRS, out batch))
                                {
                                    if (this.BatchDataReceived != null)
                                    {
                                        this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                        {
                                            Value = batch, RawData = data
                                        });
                                    }
                                }
                                else if (Down.Parse_Batch(result, out batch))
                                {
                                    if (this.BatchDataReceived != null)
                                    {
                                        this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                        {
                                            Value = batch, RawData = data
                                        });
                                    }
                                }
                            }
                            //+ 代表的是蒸发报文,需要特殊处理
                            //数据报文解析
                            if (result.Contains("1G21") || result.Contains("1G22") || result.Contains("1G23") ||
                                result.Contains("1G25") || result.Contains("1G29") || result.Contains("+"))
                            {
                                //回复TRU,确认接收数据
                                InvokeMessage("TRU " + gprs, "发送");
                                byte[] bts = new byte[] { 84, 82, 85, 13, 10 };
                                this.sendHex(gprs.Trim(), bts, (uint)bts.Length, null);

                                //根据$将字符串进行分割
                                var lists = result.Split('$');
                                foreach (var msg in lists)
                                {
                                    if (msg.Length < 10)
                                    {
                                        continue;
                                    }
                                    string plusMsg = "$" + msg.TrimEnd();
                                    bool   ret     = Up.Parse(plusMsg, out report);
                                    if (ret && report != null)
                                    {
                                        report.ChannelType = EChannelType.GPRS;
                                        report.ListenPort  = this.GetListenPort().ToString();
                                        report.flagId      = gprs;
                                        string rtype = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                        InvokeMessage("gprs号码:  " + gprs + "   " + String.Format("{0,-10}   ", rtype) + plusMsg, "接收");
                                        //TODO 重新定义事件
                                        if (this.UpDataReceived != null)
                                        {
                                            this.UpDataReceived.Invoke(null, new UpEventArgs()
                                            {
                                                Value = report, RawData = plusMsg
                                            });
                                        }
                                    }
                                }
                            }
                            //其他报文
                            else
                            {
                                Down.Parse(result, out downReport);
                                if (downReport != null)
                                {
                                    InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + result, "接收");
                                    if (this.DownDataReceived != null)
                                    {
                                        this.DownDataReceived.Invoke(null, new DownEventArgs()
                                        {
                                            Value = downReport, RawData = result
                                        });
                                    }
                                }
                            }
                        }
                        #region 报文解析部分
                        //报文解析 直接调用
                        //if (temp.StartsWith("24") && (temp.Contains("7F7F") || temp.Contains("7f7f")) && (temp.Contains("2A2A") || temp.Contains("2a2a")))
                        ////if ((temp.Contains("7F7F") || temp.Contains("7f7f")) && (temp.Contains("2A2A") || temp.Contains("2a2a")))
                        //{
                        //    //1.获取头部信息
                        //    string headInfo = temp.Substring(0, 114);
                        //    //2.集合头信息
                        //    //2.1 计算集合头信息总长度
                        //    string setHeadInfoID = temp.Substring(114, 4);
                        //    string setHeadInfoMsgLength = temp.Substring(118, 4);
                        //    string setHeadInfoStay = temp.Substring(122, 2);
                        //    string setHeadInfoNum = temp.Substring(123, 2);
                        //    int setHeadInfoLength = 4 + 4 + 2 + 2 + 2 * (Convert.ToInt32(setHeadInfoNum,16));
                        //    string setHeadInof = temp.Substring(114, setHeadInfoLength);

                        //    //3.固定头信息
                        //    string fixHeadInfo = temp.Substring(114 + setHeadInfoLength, 118);
                        //    //3.1 获取层数信息
                        //    string speedLayersStr = fixHeadInfo.Substring(18, 2);
                        //    int speedLayers = Convert.ToInt32(speedLayersStr, 16);
                        //    //3.2 获取层厚
                        //    decimal thickness = Convert.ToInt32(fixHeadInfo.Substring(26, 2) + fixHeadInfo.Substring(24, 2), 16);
                        //    //3.3 获取盲区
                        //    decimal blindzone = Convert.ToInt32(fixHeadInfo.Substring(30, 2) + fixHeadInfo.Substring(28, 2), 16);



                        //    //4.可变头信息
                        //    string variableHeadInfo = temp.Substring(114 + 118 + setHeadInfoLength, 112);
                        //    //4.1获取数据时间
                        //    string year = "20" + Convert.ToInt32(variableHeadInfo.Substring(8, 2), 16).ToString();
                        //    string month = Convert.ToInt32(variableHeadInfo.Substring(10, 2), 16).ToString();
                        //    string day = Convert.ToInt32(variableHeadInfo.Substring(12, 2), 16).ToString();
                        //    string hour = Convert.ToInt32(variableHeadInfo.Substring(14, 2), 16).ToString();
                        //    string minute = Convert.ToInt32(variableHeadInfo.Substring(16, 2), 16).ToString();
                        //    string second = Convert.ToInt32(variableHeadInfo.Substring(18, 2), 16).ToString();
                        //    DateTime datatime = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day), int.Parse(hour), int.Parse(minute),int.Parse(second));

                        //    //5.流速数据
                        //    string speedInfo = temp.Substring(114 + 118 + 112 + setHeadInfoLength, speedLayers * 16 + 4);



                        //    //6.相关系数
                        //    string coefficientInfo = temp.Substring(114 + 118 + 112 + setHeadInfoLength + speedLayers * 16 + 4, speedLayers * 8 + 4);

                        //    //7.回波强度
                        //    string echoIntensityInfo = temp.Substring(114 + 118 + 112 + setHeadInfoLength + speedLayers * 16 + 4 + speedLayers * 8 + 4, speedLayers * 8 + 4);

                        //    //5.1 6.1 7.1 解析获得每层的数据
                        //    List<CentityLayerSpeed> layerInfoList = new List<CentityLayerSpeed>();
                        //    int speedFlag = 4;
                        //    int cfctFlag = 4;
                        //    int echoFlag = 4;
                        //    for(int layer=0;i< speedLayers; layer++)
                        //    {
                        //        speedFlag = layer * 16 + 4;
                        //        cfctFlag = layer * 8 + 4;
                        //        cfctFlag = layer * 8 + 4;
                        //        CentityLayerSpeed layerInfo = new CentityLayerSpeed();
                        //        try
                        //        {
                        //            layerInfo.layers = layer + 1;
                        //            layerInfo.StationID = "6000";
                        //            layerInfo.datatime = datatime;
                        //            layerInfo.speed1 = Convert.ToInt32(speedInfo.Substring(speedFlag + 2, 2) + speedInfo.Substring(speedFlag, 2), 16);
                        //            layerInfo.speed2 = Convert.ToInt32(speedInfo.Substring(speedFlag + 6, 2) + speedInfo.Substring(speedFlag+4, 2), 16);
                        //            layerInfo.speed3 = Convert.ToInt32(speedInfo.Substring(speedFlag + 10, 2) + speedInfo.Substring(speedFlag+8, 2), 16);
                        //            layerInfo.speed4 = Convert.ToInt32(speedInfo.Substring(speedFlag + 14, 2) + speedInfo.Substring(speedFlag+12, 2), 16);
                        //            layerInfo.cfct1 = Convert.ToInt32(coefficientInfo.Substring(cfctFlag, 2), 16);
                        //            layerInfo.cfct2 = Convert.ToInt32(coefficientInfo.Substring(cfctFlag+2, 2), 16);
                        //            layerInfo.cfct3 = Convert.ToInt32(coefficientInfo.Substring(cfctFlag+4, 2), 16);
                        //            layerInfo.cfct4 = Convert.ToInt32(coefficientInfo.Substring(cfctFlag+6, 2), 16);
                        //            layerInfo.echo1 = Convert.ToInt32(echoIntensityInfo.Substring(echoFlag, 2), 16);
                        //            layerInfo.echo2 = Convert.ToInt32(echoIntensityInfo.Substring(echoFlag+2, 2), 16);
                        //            layerInfo.echo3 = Convert.ToInt32(echoIntensityInfo.Substring(echoFlag+4, 2), 16);
                        //            layerInfo.echo4 = Convert.ToInt32(echoIntensityInfo.Substring(echoFlag+6, 2), 16);
                        //            layerInfoList.Add(layerInfo);
                        //        }
                        //        catch(Exception e)
                        //        {

                        //        }
                        //    }

                        //    //8.比例因子
                        //    string scaleFactorInfo = temp.Substring(114 + 118 + 112 + setHeadInfoLength + speedLayers * 16 + 4 + speedLayers * 8 + 4 + speedLayers * 8 + 4, 22);
                        //    //8.1 相关参数
                        //    List<CEntityAdcpParam> adcpParamList = new List<CEntityAdcpParam>();
                        //    CEntityAdcpParam adcpParam = new CEntityAdcpParam();
                        //    adcpParam.StationID = "6000";
                        //    adcpParam.datatime = datatime;
                        //    adcpParam.layers = speedLayers;
                        //    adcpParam.thickness = thickness;
                        //    adcpParam.blindzone = blindzone;
                        //    try
                        //    {
                        //        adcpParam.cfct = Convert.ToInt32(scaleFactorInfo.Substring(4, 2), 16);
                        //        adcpParam.voltage = Convert.ToInt32(scaleFactorInfo.Substring(6, 2), 16);
                        //        adcpParam.height1 = Convert.ToInt32(scaleFactorInfo.Substring(8, 2), 16);
                        //        adcpParam.height2 = Convert.ToInt32(scaleFactorInfo.Substring(10, 2), 16);
                        //        adcpParam.height3 = Convert.ToInt32(scaleFactorInfo.Substring(12, 2), 16);
                        //        adcpParam.height4 = Convert.ToInt32(scaleFactorInfo.Substring(14, 2), 16);
                        //        adcpParam.v1 = Convert.ToInt32(scaleFactorInfo.Substring(16, 2), 16);
                        //        adcpParam.v2 = Convert.ToInt32(scaleFactorInfo.Substring(18, 2), 16);
                        //        adcpParam.echo = Convert.ToInt32(scaleFactorInfo.Substring(20, 2), 16);
                        //        adcpParamList.Add(adcpParam);
                        //    }catch(Exception e)
                        //    {

                        //    }
                        #endregion



                        //调用计算dll
                        //TODO


                        //11.将数据写入返回数据结构
                        //CReportStruct report = new CReportStruct();
                        //report.Stationid = "6000";
                        //report.Type = "01";
                        //report.ReportType = EMessageType.EAdditional;
                        //report.StationType = EStationType.EHydrology;
                        //report.ChannelType = EChannelType.GPRS;
                        //report.ListenPort = this.GetListenPort().ToString();
                        //report.flagId = gprs;
                        //string rtype = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                        //List<CReportData> datas = new List<CReportData>();
                        //foreach(CentityLayerSpeed layerInfo in layerInfoList)
                        //{
                        //    CReportData data = new CReportData();
                        //    data.Time = layerInfo.datatime;
                        //    data.layer = layerInfo.layers;
                        //    data.speed1 = layerInfo.speed1;
                        //    data.speed2 = layerInfo.speed2;
                        //    data.speed3 = layerInfo.speed3;
                        //    data.speed4 = layerInfo.speed4;
                        //    data.cfct1 = layerInfo.cfct1;
                        //    data.cfct2 = layerInfo.cfct2;
                        //    data.cfct3 = layerInfo.cfct3;
                        //    data.cfct4 = layerInfo.cfct4;
                        //    data.echo1 = layerInfo.echo1;
                        //    data.echo2 = layerInfo.echo2;
                        //    data.echo3 = layerInfo.echo3;
                        //    data.echo4 = layerInfo.echo4;
                        //    datas.Add(data);
                        //}

                        //foreach(CEntityAdcpParam param in adcpParamList)
                        //{
                        //    CReportData data = new CReportData();
                        //    data.Time = param.datatime;
                        //    data.layers = param.layers;
                        //    data.thickness = param.thickness;
                        //    data.blindzone = param.blindzone;
                        //    data.cfct   = param.cfct;
                        //    data.voltage = param.voltage;
                        //    data.height1 = param.height1;
                        //    data.height2 = param.height2;
                        //    data.height3 = param.height3;
                        //    data.height4 = param.height4;
                        //    data.v1 = param.v1;
                        //    data.v2 = param.v2;
                        //    data.echo = param.echo;
                        //    datas.Add(data);
                        //}

                        //if (this.UpDataReceived != null)
                        //{
                        //    this.UpDataReceived.Invoke(null, new UpEventArgs() { Value = report, RawData = temp });
                        //}
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("" + e.Message);
                    }
                }
            }
        }
Ejemplo n.º 9
0
        private bool ParseData(string msg, string gprs)
        {
            //           InvokeMessage("协议。。。 ", "进入函数7");
            try
            {
                string rawData = msg;

                if (msg.Contains("$"))
                {
                    string data = string.Empty;
                    if (!ProtocolHelpers.DeleteSpecialChar(msg, out data))
                    {
                        return(false);
                    }
                    msg = data;

                    string sid  = msg.Substring(0, 4);
                    string type = msg.Substring(4, 2);

                    #region 1G
                    if (type == "1G")
                    {
                        string reportType = msg.Substring(6, 2);
                        if (reportType == "21" || reportType == "22")   //   定时报,加报
                        {
                            //  YAC设备的墒情协议:
                            string stationType = msg.Substring(8, 2);
                            switch (stationType)
                            {
                            //  站类为04时墒情站 05墒情雨量站 06,16墒情水位站 07,17墒情水文站
                            case "04":
                            case "05":
                            case "06":
                            case "07":
                            case "17":
                            {
                                //CEntitySoilData soilStruct = new CEntitySoilData();
                                //if (Soil.Parse(msg, out soilStruct))
                                //{
                                //    soilStruct.ChannelType = EChannelType.GPRS;
                                //    //soilStruct.ListenPort = this.GetListenPort().ToString();

                                //    //string temp = soilStruct.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                //    //InvokeMessage(String.Format("{0,-10}   ", temp) + rawData, "接收");

                                //    //  抛出YAC设备墒情事件
                                //    if (null != this.SoilDataReceived)
                                //        this.SoilDataReceived.Invoke(null, new YACSoilEventArg()
                                //        {
                                //            RawData = rawData,
                                //            Value = soilStruct
                                //        });
                                //}

                                CEntitySoilData soil       = new CEntitySoilData();
                                CReportStruct   soilReport = new CReportStruct();
                                if (Soil.Parse(rawData, out soil, out soilReport))
                                {
                                    soil.ChannelType = EChannelType.GPRS;

                                    if (null != this.SoilDataReceived)
                                    {
                                        this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                                    }
                                    //1111gm
                                    string temp = soilReport.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage("  gprs号码:  " + gprs + String.Format("  {0,-10}   ", temp) + rawData, "接收");

                                    if (null != soilReport && null != this.UpDataReceived)
                                    {
                                        soilReport.ChannelType = EChannelType.GPRS;
                                        soilReport.ListenPort  = this.GetListenPort().ToString();
                                        soilReport.flagId      = gprs;
                                        this.UpDataReceived(null, new UpEventArgs()
                                            {
                                                RawData = rawData, Value = soilReport
                                            });
                                    }
                                }
                                else
                                {
                                    //string temp = soilReport.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage("  gprs号码:  " + gprs + "  " + rawData, "接收");
                                }
                            }
                            break;

                            //  站类为01,02,03,12,13时,不是墒情站
                            case "01":
                            case "02":
                            case "03":
                            case "12":
                            case "13":
                            {
                                CReportStruct report = new CReportStruct();
                                if (Up.Parse(msg, out report))
                                {
                                    report.ChannelType = EChannelType.GPRS;
                                    report.ListenPort  = this.GetListenPort().ToString();
                                    report.flagId      = gprs;

                                    string temp = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage("  gprs号码:  " + gprs + String.Format("  {0,-10}   ", temp) + rawData, "接收");

                                    if (this.UpDataReceived != null)
                                    {
                                        this.UpDataReceived.Invoke(null, new UpEventArgs()
                                            {
                                                Value = report, RawData = rawData
                                            });
                                    }
                                    //   InvokeMessage("12333", "接收");
                                }
                                else
                                {
                                    //string temp = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage("  gprs号码:  " + gprs + "  可疑数据 " + rawData, "接收");
                                }
                            }
                            break;

                            case "11":
                            {
                                CReportStruct report = new CReportStruct();
                                //CReportArtificalWater report = new CReportArtificalWater();
                                if (Up.Parse_1(msg, out report))
                                {
                                    report.ChannelType = EChannelType.GPRS;
                                    report.ListenPort  = this.GetListenPort().ToString();
                                    report.ReportType  = EMessageType.Batch;
                                    string temptype = "人工水位";
                                    InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                                    //if (this.UpDataReceived != null)
                                    this.UpDataReceived.Invoke(null, new UpEventArgs()
                                        {
                                            Value = report, RawData = rawData
                                        });
                                }
                            }
                            break;

                            default:
                                break;
                            }
                        }
                        else if (reportType == "23")    //  人工流量
                        {
                            CReportStruct report = new CReportStruct();
                            if (Up.Parse_2(msg, out report))
                            {
                                report.ChannelType = EChannelType.GPRS;
                                report.ListenPort  = this.GetListenPort().ToString();
                                report.ReportType  = EMessageType.Batch;
                                string temptype = "人工流量";
                                InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                                this.UpDataReceived.Invoke(null, new UpEventArgs()
                                {
                                    Value = report, RawData = rawData
                                });
                            }
                        }
                        else if (reportType == "32")    //  人工报送水位
                        {
                            CReportStruct report = new CReportStruct();
                            report.ChannelType = EChannelType.GPRS;
                            report.ListenPort  = this.GetListenPort().ToString();
                            string temptype = "人工报送水位";
                            InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                            WriteToFileClass writeClass = new WriteToFileClass("RGwater");
                            //Thread t = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile));
                            //t.Start("GPRS: " + "长度:" + data.Length + " " + rawData + "\r\n");
                            string a1 = rawData.Substring(9, 1);
                            string a2 = rawData.Substring(10, 1);
                            if (a1 == "P" || a1 == "H" || a1 == "K" || a1 == "Z" || a1 == "D" || a1 == "T" || a1 == "M" || a1 == "G" || a1 == "Y" || a1 == "F" || a1 == "R")
                            {
                                if (a2 == "A")
                                {
                                    if (rawData.Contains("ST"))
                                    {
                                        WriteToFileClass writeClass1 = new WriteToFileClass("sharewater");
                                        Thread           t1          = new Thread(new ParameterizedThreadStart(writeClass1.WriteInfoToFile));
                                        t1.Start("GPRS: " + "长度:" + data.Length + " " + rawData + "\r\n");
                                    }
                                }
                            }
                        }
                        else if (reportType == "53")    // 人工报送时段雨量 日雨量 旬雨量 水库水位 蓄水量 入库流量 出库流量
                        {
                            CReportStruct report = new CReportStruct();
                            report.ChannelType = EChannelType.GPRS;
                            report.ListenPort  = this.GetListenPort().ToString();
                            string temptype = "人工报送雨量";
                            InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                            WriteToFileClass writeClass = new WriteToFileClass("RGRain");
                            Thread           t          = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile));
                            t.Start("GPRS: " + "长度:" + data.Length + " " + rawData + "\r\n");
                        }
                        else if (reportType == "25")
                        {
                            //CEntitySoilData readSoilStruct = new CEntitySoilData();
                            //if (Soil.Parse(msg, out readSoilStruct))
                            //{
                            //    readSoilStruct.ChannelType = EChannelType.GPRS;
                            //    //readSoilStruct.ListenPort = this.GetListenPort().ToString();

                            //    //string temp = readSoilStruct.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                            //    //InvokeMessage(String.Format("{0,-10}   ", temp) + rawData, "接收");
                            //    //  抛出读墒情事件
                            //    if (null != this.SoilDataReceived)
                            //        this.SoilDataReceived.Invoke(null, new YACSoilEventArg()
                            //        {
                            //            RawData = rawData,
                            //            Value = readSoilStruct
                            //        });
                            //}

                            CEntitySoilData soil       = new CEntitySoilData();
                            CReportStruct   soilReport = new CReportStruct();
                            if (Soil.Parse(rawData, out soil, out soilReport))
                            {
                                soil.ChannelType = EChannelType.GPRS;

                                if (null != this.SoilDataReceived)
                                {
                                    this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                                }

                                if (null != soilReport && null != this.UpDataReceived)
                                {
                                    soilReport.ChannelType = EChannelType.GPRS;
                                    soilReport.ListenPort  = this.GetListenPort().ToString();
                                    soilReport.flagId      = gprs;
                                    this.UpDataReceived(null, new UpEventArgs()
                                    {
                                        RawData = rawData, Value = soilReport
                                    });
                                }
                            }
                        }
                        else //  下行指令
                        {
                            CDownConf downconf = new CDownConf();
                            if (Down.Parse(msg, out downconf))
                            {
                                InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + rawData, "接收");
                                if (this.DownDataReceived != null)
                                {
                                    this.DownDataReceived.Invoke(null, new DownEventArgs()
                                    {
                                        Value = downconf, RawData = rawData
                                    });
                                }
                            }
                        }
                    }
                    #endregion

                    #region 1K
                    if (type == "1K")
                    {
                        var station = FindStationBySID(sid);
                        if (station == null)
                        {
                            throw new Exception("批量传输,站点匹配错误");
                        }
                        //EStationBatchType batchType = station.BatchTranType;

                        //if (batchType == EStationBatchType.EFlash)
                        //{
                        //    CBatchStruct batch = new CBatchStruct();
                        //    if (FlashBatch.Parse(msg, out batch))
                        //    {
                        //        InvokeMessage(String.Format("{0,-10}   ", "Flash批量传输") + rawData, "接收");

                        //        if (this.BatchDataReceived != null)
                        //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = rawData });
                        //    }
                        //}
                        //else if (batchType == EStationBatchType.EUPan)
                        //{
                        //    CBatchStruct batch = new CBatchStruct();
                        //    if (UBatch.Parse(msg, out batch))
                        //    {
                        //        InvokeMessage(String.Format("{0,-10}   ", "U盘批量传输") + rawData, "接收");

                        //        if (this.BatchDataReceived != null)
                        //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = rawData });
                        //    }
                        //}

                        CBatchStruct batch = new CBatchStruct();
                        if (FlashBatch.Parse(msg, out batch))
                        {
                            InvokeMessage(String.Format("{0,-10}   ", "批量传输") + rawData, "接收");

                            if (this.BatchDataReceived != null)
                            {
                                this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                {
                                    Value = batch, RawData = rawData
                                });
                            }
                        }
                    }
                    #endregion

                    #region 1S
                    if (type == "1S")
                    {
                        CDownConf downconf = new CDownConf();
                        if (Down.Parse(msg, out downconf))
                        {
                            InvokeMessage(String.Format("{0,-10}   ", "下行指令设置参数") + rawData, "接收");

                            if (this.DownDataReceived != null)
                            {
                                this.DownDataReceived.Invoke(null, new DownEventArgs()
                                {
                                    Value = downconf, RawData = rawData
                                });
                            }
                        }
                    }
                    #endregion
                }
                else if (msg.Contains("#"))
                {
                    CEntitySoilData soil       = new CEntitySoilData();
                    CReportStruct   soilReport = new CReportStruct();
                    if (Soil.Parse(rawData, out soil, out soilReport))
                    {
                        soil.ChannelType = EChannelType.GPRS;

                        if (null != this.SoilDataReceived)
                        {
                            this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                        }

                        if (null != soilReport && null != this.UpDataReceived)
                        {
                            soilReport.ChannelType = EChannelType.GPRS;
                            soilReport.ListenPort  = this.GetListenPort().ToString();
                            soilReport.flagId      = gprs;
                            this.UpDataReceived(null, new UpEventArgs()
                            {
                                RawData = rawData, Value = soilReport
                            });
                        }
                    }
                }
                else
                {
                    return(false);
                }
                return(true);
            }
            catch (Exception exp)
            {
                //System.Diagnostics.Debug.WriteLine("GPRS 数据解析出错 !" + msg + "\r\n" + exp.Message);
            }
            return(false);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 设置指令设置
        /// </summary>
        /// <param name="sid"></param>
        /// <param name="cmds"></param>
        /// <param name="down"></param>
        /// <param name="ctype"></param>
        /// <returns>
        /// GMS:
        ///     如果返回结果的长度>140字符,发送命令为String.Empty,即不发送命令
        ///     否则发送设置指令
        /// GPRS:
        ///     发送指令长度字节数的限制
        /// Beidou:
        ///      判断最终查询后的长度是否大于79*2Byte
        ///          如果大于79*2Byte,返回String.Empty
        /// </returns>
        public String BuildSet(string sid, IList <EDownParam> cmds, CDownConf down, EChannelType ctype)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(ProtocolMaps.ChannelProtocolStartCharMap.FindValue(ctype));
            sb.Append(String.Format("{0:D4}", Int32.Parse(sid.Trim())));
            sb.Append("0S");

            int length = 6;

            foreach (var cmd in cmds)
            {
                length = length + 3 + Int32.Parse(ProtocolMaps.DownParamLengthMap[cmd]);

                sb.Append(CSpecialChars.BALNK_CHAR);
                sb.Append(ProtocolMaps.DownParamMap.FindValue(cmd));
                switch (cmd)
                {
                case EDownParam.Clock: sb.Append(down.Clock.Value.ToString("yyMMddHHmmss")); break;

                case EDownParam.NormalState: sb.Append(ProtocolMaps.NormalState4ProtoMap.FindValue(down.NormalState.Value)); break;

                case EDownParam.Voltage: sb.Append(String.Format("{0:D4}", (int)down.Voltage.Value)); break;

                case EDownParam.StationCmdID: sb.Append(down.StationCmdID); break;

                case EDownParam.TimeChoice: sb.Append(ProtocolMaps.TimeChoice4ProtoMap.FindValue(down.TimeChoice.Value)); break;

                case EDownParam.TimePeriod: sb.Append(ProtocolMaps.TimePeriodMap.FindValue(down.TimePeriod.Value)); break;

                case EDownParam.WorkStatus: sb.Append(ProtocolMaps.WorkStatus4ProtoMap.FindValue(down.WorkStatus.Value)); break;

                case EDownParam.VersionNum: sb.Append(down.VersionNum); break;

                case EDownParam.StandbyChannel:
                    sb.Append(ProtocolMaps.ChannelType4ProtoMap.FindValue(down.MainChannel.Value));
                    sb.Append(ProtocolMaps.ChannelType4ProtoMap.FindValue(down.ViceChannel.Value));
                    break;

                case EDownParam.TeleNum: sb.Append(down.TeleNum); break;

                case EDownParam.RingsNum: sb.Append(String.Format("{0:D2}", (int)down.RingsNum.Value)); break;

                case EDownParam.DestPhoneNum: sb.Append(down.DestPhoneNum); break;

                case EDownParam.TerminalNum: sb.Append(down.TerminalNum); break;

                case EDownParam.RespBeam: sb.Append(down.RespBeam); break;

                case EDownParam.AvegTime: sb.Append(String.Format("{0:D2}", (int)down.AvegTime.Value)); break;

                case EDownParam.KC: sb.Append(down.KC); break;

                case EDownParam.RainPlusReportedValue: sb.Append(String.Format("{0:D2}", (int)down.RainPlusReportedValue.Value)); break;

                case EDownParam.Rain: sb.Append(String.Format("{0:D4}", (int)down.Rain.Value)); break;

                case EDownParam.Water: sb.Append(String.Format("{0:D6}", (int)down.StorageWater.Value)); break;

                case EDownParam.WaterPlusReportedValue: sb.Append(String.Format("{0:D2}", (int)down.WaterPlusReportedValue.Value)); break;

                case EDownParam.SelectCollectionParagraphs: sb.Append(ProtocolMaps.SelectCollectionParagraphs4ProtoMap.FindValue(down.SelectCollectionParagraphs.Value)); break;

                case EDownParam.StationType: sb.Append(ProtocolHelpers.StationType2ProtoStr_set(down.StationType.Value)); break;

                case EDownParam.UserName: sb.Append(down.UserName); break;

                case EDownParam.StationName: sb.Append(down.StationName); break;

                default:
                    throw new Exception("设置下行指令参数错误");
                }
            }
            sb.Append(CSpecialChars.ENTER_CHAR);
            if (ctype == EChannelType.GSM)
            {
                //  GSM类型
                //  判断最终查询后的长度是否大于140Byte
                //      如果大于140Byte,返回String.Empty
                return(length > 140 ? string.Empty : sb.ToString());
            }
            else if (ctype == EChannelType.GPRS)
            {
                return(sb.ToString());
            }
            else if (ctype == EChannelType.BeiDou)
            {
                //  Beidou类型
                //  判断最终查询后的长度是否大于79*2Byte
                //      如果大于79*2Byte,返回String.Empty
                return((length > 79 * 2) ? string.Empty : sb.ToString());
            }
            throw new Exception("信道协议未编写!");
        }
Ejemplo n.º 11
0
        private void DealData()
        {
            while (true)
            {
                m_semaphoreData.WaitOne(); //阻塞当前线程,知道被其它线程唤醒
                // 获取对data内存缓存的访问权
                m_mutexListDatas.WaitOne();
                List <HDModemDataStruct> dataListTmp = m_listDatas;
                m_listDatas = new List <HDModemDataStruct>(); //开辟一快新的缓存区
                m_mutexListDatas.ReleaseMutex();
                for (int i = 0; i < dataListTmp.Count; ++i)
                {
                    try
                    {
                        HDModemDataStruct dat  = dataListTmp[i];
                        string            data = System.Text.Encoding.Default.GetString(dat.m_data_buf);
                        string            temp = data.Trim();

                        string result = null;
                        if (temp.Contains("TRU"))
                        {
                            Debug.WriteLine("接收数据TRU完成,停止计时器");
                            //m_timer.Stop();
                            InvokeMessage("TRU " + System.Text.Encoding.Default.GetString(dat.m_modemId), "接收");
                            if (this.ErrorReceived != null)
                            {
                                this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                                {
                                    //   Msg = "TRU " + dat.m_modemId
                                    Msg = "TRU " + System.Text.Encoding.Default.GetString(dat.m_modemId)
                                });
                            }
                        }
                        if (temp.Contains("ATE0"))
                        {
                            Debug.WriteLine("接收数据ATE0完成,停止计时器");
                            //m_timer.Stop();
                            // InvokeMessage("ATE0", "接收");
                            if (this.ErrorReceived != null)
                            {
                                this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                                {
                                    Msg = "ATE0"
                                });
                            }
                        }
                        if (temp.Contains("$"))
                        {
                            result = temp.Substring(temp.IndexOf("$"), temp.IndexOf("\0"));
                            string sid  = result.Substring(1, 4);
                            string type = result.Substring(5, 2);

                            //if (sid == "\0\0\0\0")
                            //{
                            //    continue;
                            //}

                            ////批量传输解析
                            //if (type == "1K")
                            //{
                            //    var station = FindStationBySID(sid);
                            //    if (station == null)
                            //        throw new Exception("批量传输,站点匹配错误");
                            //    CBatchStruct batch = new CBatchStruct();
                            //    if (Down.Parse_Flash(result, out batch))
                            //    {
                            //        InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                            //        if (this.BatchDataReceived != null)
                            //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = temp });
                            //    }
                            //    if (Down.Parse_Batch(result, out batch))
                            //    {
                            //        InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                            //        if (this.BatchDataReceived != null)
                            //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = temp });
                            //    }
                            //}

                            String dataProtocol = null;
                            if (HdProtocolMap.ContainsKey("HD-GPRS"))
                            {
                                dataProtocol = HdProtocolMap["HD-GPRS"];
                            }

                            switch (dataProtocol)
                            {
                            //case "LN":
                            //    break;
                            //case "SXDZ":
                            //    {
                            //        CReportStruct report = new CReportStruct();
                            //        CDownConf downReport = new CDownConf();
                            //        Data.SXDZ.UpParser Up1 = new Data.SXDZ.UpParser();
                            //        Data.SXDZ.DownParser down1 = new Data.SXDZ.DownParser();

                            //        //批量传输解析
                            //        if (type == "1K")
                            //        {
                            //            var station = FindStationBySID(sid);
                            //            if (station == null)
                            //                throw new Exception("批量传输,站点匹配错误");
                            //            CBatchStruct batch = new CBatchStruct();
                            //            if (down1.Parse_Flash(result, out batch))
                            //            {
                            //                InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                            //                if (this.BatchDataReceived != null)
                            //                    this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = temp });
                            //            }
                            //            //if (down1.Parse_Batch(result, out batch))
                            //            //{
                            //            //    InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                            //            //    if (this.BatchDataReceived != null)
                            //            //        this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = temp });
                            //            //}
                            //        }

                            //        Up1.Parse(result, out report);
                            //        down1.Parse(result, out downReport);
                            //        if (report != null)
                            //        {
                            //            report.ChannelType = EChannelType.GPRS;
                            //            report.ListenPort = this.GetListenPort().ToString();
                            //            InvokeMessage(String.Format("{0,-10}   ", "") + result, "接收");
                            //            //TODO 重新定义事件
                            //            if (this.UpDataReceived != null)
                            //            {
                            //                this.UpDataReceived.Invoke(null, new UpEventArgs() { Value = report, RawData = result });
                            //            }
                            //        }
                            //        if (downReport != null)
                            //        {
                            //            InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + result, "接收");
                            //            if (this.DownDataReceived != null)
                            //                this.DownDataReceived.Invoke(null, new DownEventArgs() { Value = downReport, RawData = result });
                            //        }
                            //        break;
                            //    }
                            //case "HJJBX":
                            //    //需要处理新老协议

                            //    //TODO 判断新老协议
                            //    bool isNew = false;

                            //    if (isNew)
                            //    {
                            //        List<CUpReport> reports = new List<CUpReport>();
                            //        Up = new Protocol.Data.HJJBX.UpParser();
                            //        Up.Parse_New(result, out reports);
                            //        foreach(var report2 in reports)
                            //        {
                            //            report2.ChannelType = EChannelType.GPRS;
                            //            report2.ListenPort = this.GetListenPort().ToString();
                            //        }
                            //        InvokeMessage(String.Format("{0,-10}   ","") + result, "接收");
                            //        //TODO 重新定义事件
                            //        if (this.UpDataReceived_new != null)
                            //        {
                            //            this.UpDataReceived_new.Invoke(null, new UpEventArgs_new() { Value = reports, RawData = result });
                            //        }

                            //    }
                            //    else
                            //    {
                            //        List<CUpReport> reports = new List<CUpReport>();
                            //        Up = new Protocol.Data.HJJBX.UpParser();
                            //        Up.Parse_Old(result, out reports);
                            //        foreach (var report1 in reports)
                            //        {
                            //            report1.ChannelType = EChannelType.GPRS;
                            //            report1.ListenPort = this.GetListenPort().ToString();
                            //        }
                            //        InvokeMessage(String.Format("{0,-10}   ", "") + result, "接收");
                            //        //测试代码
                            //        Dictionary<string, HDModemInfoStruct> data11 = new Dictionary<string, HDModemInfoStruct>();
                            //        this.getDTUList(out data11);

                            //        //TODO 重新定义事件
                            //        if (this.UpDataReceived_new != null)
                            //        {
                            //            this.UpDataReceived_new.Invoke(null, new UpEventArgs_new() { Value = reports, RawData = result });
                            //        }
                            //    }
                            //    break;
                            case "ZYJBX":
                            {
                                CReportStruct         report     = new CReportStruct();
                                CDownConf             downReport = new CDownConf();
                                Data.ZYJBX.UpParser   Up1        = new Data.ZYJBX.UpParser();
                                Data.ZYJBX.DownParser down1      = new Data.ZYJBX.DownParser();

                                //批量传输解析
                                if (type == "1K")
                                {
                                    var station = FindStationBySID(sid);
                                    if (station == null)
                                    {
                                        throw new Exception("批量传输,站点匹配错误");
                                    }
                                    CBatchStruct batch = new CBatchStruct();
                                    InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                                    if (down1.Parse_Flash(result, EChannelType.GPRS, out batch))
                                    {
                                        if (this.BatchDataReceived != null)
                                        {
                                            this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                                {
                                                    Value = batch, RawData = temp
                                                });
                                        }
                                    }
                                    else if (down1.Parse_Batch(result, out batch))
                                    {
                                        if (this.BatchDataReceived != null)
                                        {
                                            this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                                {
                                                    Value = batch, RawData = temp
                                                });
                                        }
                                    }
                                }

                                if (result.Contains("1G21") || result.Contains("1G22") || result.Contains("1G25"))
                                {
                                    var lists = result.Split('$');
                                    foreach (var msg in lists)
                                    {
                                        if (msg.Length < 5)
                                        {
                                            continue;
                                        }
                                        string plusMsg = "$" + msg;
                                        Up1.Parse(plusMsg, out report);
                                        if (report != null)
                                        {
                                            string gprs = System.Text.Encoding.Default.GetString(dat.m_modemId);
                                            gprs = gprs.Contains("\0")? gprs.Replace("\0", "") : gprs;
                                            report.ChannelType = EChannelType.GPRS;
                                            report.ListenPort  = this.GetListenPort().ToString();
                                            report.flagId      = gprs;
                                            string rtype = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                            InvokeMessage("gprs号码:  " + gprs + "   " + String.Format("{0,-10}   ", rtype) + plusMsg, "接收");
                                            //TODO 重新定义事件
                                            if (this.UpDataReceived != null)
                                            {
                                                this.UpDataReceived.Invoke(null, new UpEventArgs()
                                                    {
                                                        Value = report, RawData = plusMsg
                                                    });
                                            }
                                            InvokeMessage("TRU " + gprs, "发送");
                                            byte[] bts = new byte[] { 84, 82, 85, 13, 10 };
                                            this.sendHex(gprs.Trim(), bts, (uint)bts.Length, null);
                                        }
                                    }
                                }
                                else
                                {
                                    down1.Parse(result, out downReport);
                                    if (downReport != null)
                                    {
                                        InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + result, "接收");
                                        if (this.DownDataReceived != null)
                                        {
                                            this.DownDataReceived.Invoke(null, new DownEventArgs()
                                                {
                                                    Value = downReport, RawData = result
                                                });
                                        }
                                    }
                                }

                                break;
                            }
                            //case "XYJBX":
                            //    {
                            //        CReportStruct report = new CReportStruct();
                            //        CDownConf downReport = new CDownConf();
                            //        Data.XYJBX.UpParser Up1 = new Data.XYJBX.UpParser();
                            //        Data.XYJBX.DownParser down1 = new Data.XYJBX.DownParser();

                            //        //批量传输解析
                            //        if (type == "1K")
                            //        {
                            //            var station = FindStationBySID(sid);
                            //            if (station == null)
                            //                throw new Exception("批量传输,站点匹配错误");
                            //            CBatchStruct batch = new CBatchStruct();
                            //            //if (down1.Parse_Flash(result, out batch))
                            //            //{
                            //            //    InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                            //            //    if (this.BatchDataReceived != null)
                            //            //        this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = temp });
                            //            //}
                            //            //if (down1.Parse_Batch(result, out batch))
                            //            //{
                            //            //    InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                            //            //    if (this.BatchDataReceived != null)
                            //            //        this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = temp });
                            //            //}
                            //        }

                            //        Up1.Parse(result, out report);
                            //        down1.Parse(result, out downReport);
                            //        if (report != null)
                            //        {
                            //            report.ChannelType = EChannelType.GPRS;
                            //            report.ListenPort = this.GetListenPort().ToString();
                            //            InvokeMessage(String.Format("{0,-10}   ", "") + result, "接收");
                            //            //TODO 重新定义事件
                            //            if (this.UpDataReceived != null)
                            //            {
                            //                this.UpDataReceived.Invoke(null, new UpEventArgs() { Value = report, RawData = result });
                            //            }
                            //        }
                            //        if (downReport != null)
                            //        {
                            //            InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + result, "接收");
                            //            if (this.DownDataReceived != null)
                            //                this.DownDataReceived.Invoke(null, new DownEventArgs() { Value = downReport, RawData = result });
                            //        }
                            //        break;
                            //    }
                            default:
                                break;
                            }
                        }
                        //List<CUpReport> reports = new List<CUpReport>();
                        //Up = new UpParser();
                        //Up.Parse_New(result, out reports);


                        //获取DTU列表的函数,DTU在线列表测试
                        //uint amount = this.getDTUAmount();
                        //HDModemInfoStruct data1= new HDModemInfoStruct();
                        //this.getDTUByPosition(0, out data1);
                        //Dictionary<string, HDModemInfoStruct> datas = new Dictionary<string, HDModemInfoStruct>();
                        //this.getDTUList(out datas);
                        if (temp.Contains("BEG"))
                        {
                            Data.ZYJBX.DownParser down1 = new Data.ZYJBX.DownParser();
                            CSDStruct             sd    = new CSDStruct();
                            string gprs = System.Text.Encoding.Default.GetString(dat.m_modemId);
                            gprs = gprs.Replace("\0", "");
                            //string gprs = dat.m_modemId.ToString();
                            string id = Manager.XmlStationDataSerializer.Instance.GetStationByGprsID(gprs);
                            if (down1.Parse_SD(temp, id, out sd))
                            {
                                InvokeMessage(String.Format("{0,-10}   ", "批量SD传输") + temp, "接收");

                                if (this.BatchSDDataReceived != null)
                                {
                                    this.BatchSDDataReceived.Invoke(null, new BatchSDEventArgs()
                                    {
                                        Value = sd, RawData = temp
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("" + e.Message);
                    }
                }
            }
        }
Ejemplo n.º 12
0
        private bool ParseData(string msg)
        {
            //           InvokeMessage("协议。。。 ", "进入函数7");
            try
            {
                string rawData = msg;

                if (msg.Contains("$"))
                {
                    string data = string.Empty;
                    if (!ProtocolHelpers.DeleteSpecialChar(msg, out data))
                    {
                        return(false);
                    }
                    msg = data;

                    string sid  = msg.Substring(0, 4);
                    string type = msg.Substring(4, 2);

                    #region 1G
                    if (type == "1G")
                    {
                        //   InvokeMessage("1: " + DateTime.Now, "函数");
                        string reportType = msg.Substring(6, 2);
                        if (reportType == "21" || reportType == "22")   //   定时报,加报
                        {
                            //  YAC设备的墒情协议:
                            string stationType = msg.Substring(8, 2);
                            switch (stationType)
                            {
                            //  站类为04时墒情站 05墒情雨量站 06,16墒情水位站 07,17墒情水文站
                            case "04":
                            case "05":
                            case "06":
                            case "07":
                            case "17":
                            {
                                //CEntitySoilData soilStruct = new CEntitySoilData();
                                //if (Soil.Parse(msg, out soilStruct))
                                //{
                                //    soilStruct.ChannelType = EChannelType.GPRS;
                                //    //soilStruct.ListenPort = this.GetListenPort().ToString();

                                //    //string temp = soilStruct.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                //    //InvokeMessage(String.Format("{0,-10}   ", temp) + rawData, "接收");

                                //    //  抛出YAC设备墒情事件
                                //    if (null != this.SoilDataReceived)
                                //        this.SoilDataReceived.Invoke(null, new YACSoilEventArg()
                                //        {
                                //            RawData = rawData,
                                //            Value = soilStruct
                                //        });
                                //}

                                CEntitySoilData soil       = new CEntitySoilData();
                                CReportStruct   soilReport = new CReportStruct();
                                if (Soil.Parse(rawData, out soil, out soilReport))
                                {
                                    soil.ChannelType = EChannelType.GPRS;

                                    if (null != this.SoilDataReceived)
                                    {
                                        this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                                    }
                                    //1111gm
                                    string temp = soilReport.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage(String.Format("{0,-10}   ", temp) + rawData, "接收");

                                    if (null != soilReport && null != this.UpDataReceived)
                                    {
                                        soilReport.ChannelType = EChannelType.GPRS;
                                        soilReport.ListenPort  = this.GetListenPort().ToString();
                                        this.UpDataReceived(null, new UpEventArgs()
                                            {
                                                RawData = rawData, Value = soilReport
                                            });
                                    }
                                }
                                else
                                {
                                    //string temp = soilReport.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage(" " + rawData, "接收");
                                }
                            }
                            break;

                            //  站类为01,02,03,12,13时,不是墒情站
                            case "01":
                            case "02":
                            case "03":
                            case "12":
                            case "13":
                            {
                                CReportStruct report = new CReportStruct();
                                if (Up.Parse(msg, out report))
                                {
                                    report.ChannelType = EChannelType.GPRS;
                                    report.ListenPort  = this.GetListenPort().ToString();

                                    string temp = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage(String.Format("{0,-10}   ", temp) + rawData, "接收");
                                    //by LH 10.05
                                    //读取数据
                                    //ModemDataStruct dat = new ModemDataStruct();
                                    //while (this.GetNextData(out dat))
                                    //{
                                    //uint dtuID = 0;

                                    //var gprs = FindGprsByUserid(userID);
                                    //if (gprs.FindByID(userID, out dtuID))
                                    //{
                                    //    //query = gprs.Down.BuildQuery(stationID, cmds, EChannelType.GPRS);
                                    //    gprs.SendHex(dtuID, bts);
                                    //}

                                    //InvokeMessage("TRU,modemId: " + dat.m_modemId, "发送");
                                    //    InvokeMessage("bts: " + bts, "发送");
                                    //    //InvokeMessage("bts.length: " + (ushort)bts.Length, "发送");
                                    //    // 发送回执

                                    //InvokeMessage("3: " + DateTime.Now, "函数");
                                    // }
                                    //DTUdll.Instance.SendHex(m, bts, (ushort)bts.Length);

                                    //byte[] bts = new byte[] { 84, 82, 85, 13, 10 };
                                    //uint m = 1610637336;
                                    //InvokeMessage("2: " + DateTime.Now, "函数");
                                    //DTUdll.Instance.SendHex(m, bts, (ushort)bts.Length);
                                    //   report.Datas[0].Voltge = Decimal.Parse("111111") * (Decimal)0.01;
                                    //  InvokeMessage(report.Datas[0].Voltge.ToString(), "接收");
                                    if (this.UpDataReceived != null)
                                    {
                                        this.UpDataReceived.Invoke(null, new UpEventArgs()
                                            {
                                                Value = report, RawData = rawData
                                            });
                                    }
                                    //   InvokeMessage("12333", "接收");
                                }
                                else
                                {
                                    //string temp = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                    InvokeMessage(" " + rawData, "接收");
                                }
                            }
                            break;

                            case "11":
                            {
                                CReportStruct report = new CReportStruct();
                                //CReportArtificalWater report = new CReportArtificalWater();
                                if (Up.Parse_1(msg, out report))
                                {
                                    report.ChannelType = EChannelType.GPRS;
                                    report.ListenPort  = this.GetListenPort().ToString();
                                    report.ReportType  = EMessageType.Batch;
                                    string temptype = "人工水位";
                                    InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                                    //if (this.UpDataReceived != null)
                                    this.UpDataReceived.Invoke(null, new UpEventArgs()
                                        {
                                            Value = report, RawData = rawData
                                        });
                                }
                            }
                            break;

                            default:
                                break;
                            }
                        }
                        else if (reportType == "23")    //  人工流量
                        {
                            CReportStruct report = new CReportStruct();
                            if (Up.Parse_2(msg, out report))
                            {
                                report.ChannelType = EChannelType.GPRS;
                                report.ListenPort  = this.GetListenPort().ToString();
                                report.ReportType  = EMessageType.Batch;
                                string temptype = "人工流量";
                                InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                                this.UpDataReceived.Invoke(null, new UpEventArgs()
                                {
                                    Value = report, RawData = rawData
                                });
                            }
                        }
                        else if (reportType == "32")    //  人工报送水位
                        {
                            CReportStruct report = new CReportStruct();
                            report.ChannelType = EChannelType.GPRS;
                            report.ListenPort  = this.GetListenPort().ToString();
                            string temptype = "人工报送水位";
                            InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                            WriteToFileClass writeClass = new WriteToFileClass("RGwater");
                            Thread           t          = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile));
                            t.Start("GPRS: " + "长度:" + data.Length + " " + rawData + "\r\n");
                            string a1 = rawData.Substring(9, 1);
                            string a2 = rawData.Substring(10, 1);
                            if (a1 == "P" || a1 == "H" || a1 == "K" || a1 == "Z" || a1 == "D" || a1 == "T" || a1 == "M" || a1 == "G" || a1 == "Y" || a1 == "F" || a1 == "R")
                            {
                                if (a2 == "A")
                                {
                                    if (rawData.Contains("ST"))
                                    {
                                        WriteToFileClass writeClass1 = new WriteToFileClass("sharewater");
                                        Thread           t1          = new Thread(new ParameterizedThreadStart(writeClass1.WriteInfoToFile));
                                        t1.Start("GPRS: " + "长度:" + data.Length + " " + rawData + "\r\n");
                                    }
                                }
                            }
                        }
                        else if (reportType == "53")    // 人工报送时段雨量 日雨量 旬雨量 水库水位 蓄水量 入库流量 出库流量
                        {
                            CReportStruct report = new CReportStruct();
                            report.ChannelType = EChannelType.GPRS;
                            report.ListenPort  = this.GetListenPort().ToString();
                            string temptype = "人工报送雨量";
                            InvokeMessage(String.Format("{0,-10}   ", temptype) + rawData, "接收");
                            WriteToFileClass writeClass = new WriteToFileClass("RGRain");
                            Thread           t          = new Thread(new ParameterizedThreadStart(writeClass.WriteInfoToFile));
                            t.Start("GPRS: " + "长度:" + data.Length + " " + rawData + "\r\n");
                        }
                        else if (reportType == "25")
                        {
                            //CEntitySoilData readSoilStruct = new CEntitySoilData();
                            //if (Soil.Parse(msg, out readSoilStruct))
                            //{
                            //    readSoilStruct.ChannelType = EChannelType.GPRS;
                            //    //readSoilStruct.ListenPort = this.GetListenPort().ToString();

                            //    //string temp = readSoilStruct.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                            //    //InvokeMessage(String.Format("{0,-10}   ", temp) + rawData, "接收");
                            //    //  抛出读墒情事件
                            //    if (null != this.SoilDataReceived)
                            //        this.SoilDataReceived.Invoke(null, new YACSoilEventArg()
                            //        {
                            //            RawData = rawData,
                            //            Value = readSoilStruct
                            //        });
                            //}

                            CEntitySoilData soil       = new CEntitySoilData();
                            CReportStruct   soilReport = new CReportStruct();
                            if (Soil.Parse(rawData, out soil, out soilReport))
                            {
                                soil.ChannelType = EChannelType.GPRS;

                                if (null != this.SoilDataReceived)
                                {
                                    this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                                }

                                if (null != soilReport && null != this.UpDataReceived)
                                {
                                    soilReport.ChannelType = EChannelType.GPRS;
                                    soilReport.ListenPort  = this.GetListenPort().ToString();
                                    this.UpDataReceived(null, new UpEventArgs()
                                    {
                                        RawData = rawData, Value = soilReport
                                    });
                                }
                            }
                        }
                        else //  下行指令
                        {
                            CDownConf downconf = new CDownConf();
                            if (Down.Parse(msg, out downconf))
                            {
                                InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + rawData, "接收");
                                if (this.DownDataReceived != null)
                                {
                                    this.DownDataReceived.Invoke(null, new DownEventArgs()
                                    {
                                        Value = downconf, RawData = rawData
                                    });
                                }
                            }
                        }
                    }
                    #endregion

                    #region 1K
                    if (type == "1K")
                    {
                        var station = FindStationBySID(sid);
                        if (station == null)
                        {
                            throw new Exception("批量传输,站点匹配错误");
                        }
                        //EStationBatchType batchType = station.BatchTranType;

                        //if (batchType == EStationBatchType.EFlash)
                        //{
                        //    CBatchStruct batch = new CBatchStruct();
                        //    if (FlashBatch.Parse(msg, out batch))
                        //    {
                        //        InvokeMessage(String.Format("{0,-10}   ", "Flash批量传输") + rawData, "接收");

                        //        if (this.BatchDataReceived != null)
                        //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = rawData });
                        //    }
                        //}
                        //else if (batchType == EStationBatchType.EUPan)
                        //{
                        //    CBatchStruct batch = new CBatchStruct();
                        //    if (UBatch.Parse(msg, out batch))
                        //    {
                        //        InvokeMessage(String.Format("{0,-10}   ", "U盘批量传输") + rawData, "接收");

                        //        if (this.BatchDataReceived != null)
                        //            this.BatchDataReceived.Invoke(null, new BatchEventArgs() { Value = batch, RawData = rawData });
                        //    }
                        //}

                        CBatchStruct batch = new CBatchStruct();
                        if (FlashBatch.Parse(msg, out batch))
                        {
                            InvokeMessage(String.Format("{0,-10}   ", "批量传输") + rawData, "接收");

                            if (this.BatchDataReceived != null)
                            {
                                this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                {
                                    Value = batch, RawData = rawData
                                });
                            }
                        }
                    }
                    #endregion

                    #region 1S
                    if (type == "1S")
                    {
                        CDownConf downconf = new CDownConf();
                        if (Down.Parse(msg, out downconf))
                        {
                            InvokeMessage(String.Format("{0,-10}   ", "下行指令设置参数") + rawData, "接收");

                            if (this.DownDataReceived != null)
                            {
                                this.DownDataReceived.Invoke(null, new DownEventArgs()
                                {
                                    Value = downconf, RawData = rawData
                                });
                            }
                        }
                    }
                    #endregion
                }
                else if (msg.Contains("#"))
                {
                    CEntitySoilData soil       = new CEntitySoilData();
                    CReportStruct   soilReport = new CReportStruct();
                    if (Soil.Parse(rawData, out soil, out soilReport))
                    {
                        soil.ChannelType = EChannelType.GPRS;

                        if (null != this.SoilDataReceived)
                        {
                            this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                        }

                        if (null != soilReport && null != this.UpDataReceived)
                        {
                            soilReport.ChannelType = EChannelType.GPRS;
                            soilReport.ListenPort  = this.GetListenPort().ToString();
                            this.UpDataReceived(null, new UpEventArgs()
                            {
                                RawData = rawData, Value = soilReport
                            });
                        }
                    }
                }
                else
                {
                    return(false);
                }
                return(true);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine("GPRS 数据解析出错 !" + msg + "\r\n" + exp.Message);
            }
            return(false);
        }
Ejemplo n.º 13
0
        //  数据下行解析
        public bool Parse(string msg, out CDownConf downConf)
        {
            downConf = new CDownConf();
            int mgb = 0;

            try
            {
                string data = string.Empty;
                if (!ProtocolHelpers.DeleteSpecialChar(msg, out data))
                {
                    return(false);
                }



                //  解析站点ID
                String stationID = data.Substring(0, 4);
                //  解析通信类别
                String type = data.Substring(4, 2);
                data = data.Substring(6);
                var segs = data.Split(CSpecialChars.BALNK_CHAR);
                foreach (var item in segs)
                {
                    try
                    {
                        //  数据分为两部分
                        //  2 Byte 指令  +  剩下的为数据,数据的长度>= 2
                        //  解析指令类型param
                        EDownParam param = ProtocolMaps.DownParamMap.FindKey(item.Substring(0, 2) == "13" ? "12" : item.Substring(0, 2));
                        //  如果接收到的数据段长度大于2,表示对应的字段有值
                        //  默认为String.Empty
                        string info = string.Empty;
                        if (item.Length > 2)
                        {
                            int length = Int32.Parse(ProtocolMaps.DownParamLengthMap.FindValue(param));
                            //  如果接收到的数据段的长度不等于规定长度,或者规定长度为-1(即长度不定)
                            //        截取剩下的所有字符串
                            //  否则,截取规定长度的字符串
                            info = (item.Length - 2 != length || length == -1) ? item.Substring(2) : item.Substring(2, length);
                        }
                        if (String.IsNullOrEmpty(info))
                        {
                            continue;
                        }

                        switch (param)
                        {
                        case EDownParam.Clock:
                            int year   = Int32.Parse("20" + info.Substring(0, 2));
                            int month  = Int32.Parse(info.Substring(2, 2));
                            int day    = Int32.Parse(info.Substring(4, 2));
                            int hour   = Int32.Parse(info.Substring(6, 2));
                            int minute = Int32.Parse(info.Substring(8, 2));
                            int second = Int32.Parse(info.Substring(10, 2));
                            downConf.Clock = new DateTime(year, month, day, hour, minute, second);
                            break;

                        case EDownParam.NormalState: downConf.NormalState = ProtocolMaps.NormalState4ProtoMap.FindKey(info); break;

                        case EDownParam.Voltage: downConf.Voltage = (Decimal.Parse(info) * (Decimal)0.01); break;

                        case EDownParam.StationCmdID: downConf.StationCmdID = info; break;

                        case EDownParam.TimeChoice: downConf.TimeChoice = ProtocolMaps.TimeChoice4ProtoMap.FindKey(info == "01" ? info : "02"); break;

                        case EDownParam.TimePeriod: downConf.TimePeriod = ProtocolMaps.TimePeriodMap.FindKey(info); break;

                        case EDownParam.WorkStatus: downConf.WorkStatus = ProtocolMaps.WorkStatus4ProtoMap.FindKey(info); break;

                        case EDownParam.VersionNum: downConf.VersionNum = info; break;

                        case EDownParam.StandbyChannel:
                            downConf.MainChannel = ProtocolMaps.ChannelType4ProtoMap.FindKey(info.Substring(0, 2));
                            System.Diagnostics.Debug.Assert(downConf.MainChannel != EChannelType.None, "主用信道不能为NONE");
                            downConf.ViceChannel = ProtocolMaps.ChannelType4ProtoMap.FindKey(info.Substring(2, 2));
                            break;

                        case EDownParam.TeleNum: downConf.TeleNum = info; break;

                        case EDownParam.RingsNum: downConf.RingsNum = Decimal.Parse(info); break;

                        case EDownParam.DestPhoneNum: downConf.DestPhoneNum = info; break;

                        case EDownParam.TerminalNum: downConf.TerminalNum = info; break;

                        case EDownParam.GSMElec: downConf.GSMElec = ProtocolMaps.GSMElec4ProtoMap.FindKey(info); break;

                        case EDownParam.RespBeam: downConf.RespBeam = info; break;

                        case EDownParam.AvegTime: downConf.AvegTime = Decimal.Parse(info); break;

                        case EDownParam.RainPlusReportedValue: downConf.RainPlusReportedValue = Decimal.Parse(info); break;

                        case EDownParam.KC: downConf.KC = info; break;

                        case EDownParam.Rain: downConf.Rain = Decimal.Parse(info); break;

                        //  单位为米    case EDownParam.Water: downConf.Water = (Decimal.Parse(info) * (Decimal)0.01); break;
                        //  默认单位为厘米
                        case EDownParam.storeWater: downConf.storeWater = Decimal.Parse(info); break;

                        case EDownParam.realWater: downConf.realWater = Decimal.Parse(info); break;

                        case EDownParam.WaterBase: downConf.WaterBase = Decimal.Parse(info); break;

                        case EDownParam.WaterPlusReportedValue: downConf.WaterPlusReportedValue = Decimal.Parse(info); break;

                        case EDownParam.SelectCollectionParagraphs: downConf.SelectCollectionParagraphs = ProtocolMaps.SelectCollectionParagraphs4ProtoMap.FindKey(info); break;

                        case EDownParam.StationType:
                            var stype = ProtocolMaps.StationType4ProtoMap.FindKey(info);
                            downConf.StationType = stype; break;

                        case EDownParam.UserName:
                            downConf.UserName = info;
                            break;

                        case EDownParam.StationName:
                            downConf.StationName = info;
                            break;

                        case EDownParam.SensorType:
                            downConf.SensorType = ProtocolMaps.SensorType4ProtoMap.FindKey(info);
                            break;

                        case EDownParam.FlashClear:
                            downConf.FlashClear = info;
                            break;

                        default:
                            mgb--;
                            break;
                        }
                        mgb++;
                    }
                    catch (Exception e)
                    {
                        System.Diagnostics.Debug.WriteLine("数据:" + msg);
                        System.Diagnostics.Debug.WriteLine("下行指令解析数据不完整!" + e.Message);
                    }
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.Message);
            }
            if (mgb == 0)
            {
                downConf = null;
                return(false);
            }
            return(true);
        }
Ejemplo n.º 14
0
 public string BuildSet(string sid, IList <EDownParam> cmds, CDownConf down, EChannelType ctype)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 15
0
 public String BuildSet(string sid, string type, IList <CDownParam> cmds, CDownConf down)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 16
0
        public CDownConf Parse(string resp)
        {
            //  判断是否是合法输入
            Debug.Assert(resp.StartsWith(CSpecialChars.StartCh.ToString()), "数据以非'$'字符开始");
            Debug.Assert(resp.EndsWith(CSpecialChars.EndCh.ToString()), "数据以非'\r'字符结束");

            var result = new CDownConf();

            int startIndex = resp.IndexOf(CSpecialChars.StartCh);
            int endIndex   = resp.IndexOf(CSpecialChars.EndCh);

            string data = resp.Substring(startIndex + 1, endIndex - 1);

            var segs = data.Split(CSpecialChars.BlankCh);

            for (int i = 0; i < segs.Count(); i++)
            {
                string value = segs[i].ToString();

                if (i == 0) //  解析站点信息
                {
                    result.StationID = value.Substring(0, 4);
                    result.Type      = value.Substring(4, 2);
                }
                else        //  解析数据
                {
                    //  数据分为两部分
                    //  2 Byte 指令
                    //  剩下的为数据
                    int    cmd  = Int32.Parse(value.Substring(0, 2));
                    string info = value.Substring(2, value.Length - 2);
                    switch (cmd)
                    {
                    case (int)CDownParam.Clock: result.Clock = info; break;

                    case (int)CDownParam.NormalState: result.NormalState = info; break;

                    case (int)CDownParam.Voltage: result.Voltage = info; break;

                    case (int)CDownParam.StationCmdID: result.StationCmdID = info; break;

                    case (int)CDownParam.TimeChoice: result.TimeChoice = info; break;

                    case (int)CDownParam.TimePeriod: result.TimePeriod = info; break;

                    case (int)CDownParam.WorkStatus: result.WorkStatus = info; break;

                    case (int)CDownParam.VersionNum: result.VersionNum = info; break;

                    case (int)CDownParam.StandbyChannel: result.StandbyChannel = info; break;

                    case (int)CDownParam.TeleNum: result.TeleNum = info; break;

                    case (int)CDownParam.RingsNum: result.RingsNum = info; break;

                    case (int)CDownParam.DestPhoneNum: result.DestPhoneNum = info; break;

                    case (int)CDownParam.TerminalNum: result.TerminalNum = info; break;

                    case (int)CDownParam.RespBeam: result.RespBeam = info; break;

                    case (int)CDownParam.AvegTime: result.AvegTime = info; break;

                    case (int)CDownParam.RainPlusReportedValue: result.RainPlusReportedValue = info; break;

                    case (int)CDownParam.KC: result.KC = info; break;

                    case (int)CDownParam.Rain: result.Rain = info; break;

                    case (int)CDownParam.Water: result.Water = info; break;

                    case (int)CDownParam.WaterPlusReportedValue: result.WaterPlusReportedValue = info; break;

                    case (int)CDownParam.SelectCollectionParagraphs: result.SelectCollectionParagraphs = info; break;

                    case (int)CDownParam.StationType: result.StationType = info; break;

                    default: break;
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 17
0
 //  数据下行解析
 public bool Parse(string msg, out CDownConf downConf)
 {
     downConf = null;
     return(true);
 }
Ejemplo n.º 18
0
 public bool Parse(string resp, out CDownConf downConf)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 19
0
        private bool ParseData(string msg, string gprs, uint modemId)
        {
            //           InvokeMessage("协议。。。 ", "进入函数7");
            try
            {
                string rawData = msg;
                string sid;
                try
                {
                    sid = Manager.XmlStationData.Instance.GetStationByGprsID(gprs);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("查找站点id失败,赋值为9999" + e.ToString());
                    sid = "9999";
                }
                if (msg.Contains("$"))
                {
                    string data = string.Empty;
                    if (!ProtocolHelpers.DeleteSpecialChar(msg, out data))
                    {
                        return(false);
                    }
                    msg = data;

                    CReportStruct report     = new CReportStruct();
                    CDownConf     downReport = new CDownConf();
                    string        protocol   = Manager.XmlStationData.Instance.GetProtocolBySId(sid);

                    if (protocol == "YNXY")
                    {
                        Up   = new Data.YNXY.UpParser();
                        Down = new Data.YNXY.DownParser();
                    }
                    else if (protocol == "ZYJBX")
                    {
                        Up   = new Data.ZYJBX.UpParser();
                        Down = new Data.ZYJBX.DownParser();
                    }


                    #region 1K
                    //批量传输解析
                    if (msg.Contains("1K"))
                    {
                        var station = FindStationBySID(sid);
                        if (station == null)
                        {
                            throw new Exception("批量传输,站点匹配错误");
                        }
                        CBatchStruct batch = new CBatchStruct();
                        InvokeMessage(String.Format("{0,-10}   ", "批量传输") + msg, "接收");

                        if (Down.Parse_Flash(msg, EChannelType.GPRS, out batch))
                        {
                            if (this.BatchDataReceived != null)
                            {
                                this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                {
                                    Value = batch, RawData = msg
                                });
                            }
                        }
                    }
                    #endregion

                    #region 1G
                    if (msg.Contains("1G"))
                    {
                        //if (msg.Contains("RG"))
                        //{
                        //    var lists = msg.Split('$');
                        //    foreach (var segMsg in lists)
                        //    {
                        //        if (segMsg.Length < 5)
                        //        {
                        //            continue;
                        //        }
                        //        string plusMsg = "$" + segMsg;
                        //        string rtype = "人工报";
                        //        InvokeMessage("gprs号码:  " + gprs + "   " + String.Format("{0,-10}   ", rtype) + plusMsg, "接收");
                        //        string package = Up.Parse_1(plusMsg, out report);
                        //        if (package != "")
                        //        {
                        //            report.ChannelType = EChannelType.GPRS;
                        //            report.ListenPort = this.GetListenPort().ToString();
                        //            report.flagId = gprs;
                        //            SendTru(modemId, package);
                        //            //TODO 重新定义事件
                        //            if (this.UpDataReceived != null)
                        //            {
                        //                this.UpDataReceived.Invoke(null, new UpEventArgs() { Value = report, RawData = plusMsg });
                        //            }
                        //        }
                        //        else
                        //        {
                        //            InvokeMessage(" " + rawData, "接收");
                        //        }
                        //    }
                        //}
                        //else
                        if (msg.Contains("1G21") || msg.Contains("1G22") || msg.Contains("1G25"))   //   定时报,加报
                        {
                            if (msg.Contains("1G29"))
                            {
                                var station = FindStationBySID(sid);
                                if (station == null)
                                {
                                    throw new Exception("批量传输,站点匹配错误");
                                }
                                CBatchStruct batch = new CBatchStruct();
                                InvokeMessage(String.Format("{0,-10}   ", "批量传输") + msg, "接收");
                                if (Down.Parse_Batch(msg, out batch))
                                {
                                    if (this.BatchDataReceived != null)
                                    {
                                        this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                        {
                                            Value = batch, RawData = msg
                                        });
                                    }
                                }
                            }
                            else
                            {
                                var lists = msg.Split('$');
                                foreach (var segMsg in lists)
                                {
                                    if (segMsg.Length < 5)
                                    {
                                        continue;
                                    }
                                    string plusMsg = "$" + segMsg;
                                    if (Up.Parse(plusMsg, out report))
                                    {
                                        report.ChannelType = EChannelType.GPRS;
                                        report.ListenPort  = this.GetListenPort().ToString();
                                        report.flagId      = gprs;
                                        string rtype = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                        InvokeMessage("gprs号码:  " + gprs + "   " + String.Format("{0,-10}   ", rtype) + plusMsg, "接收");
                                        //TODO 重新定义事件
                                        if (this.UpDataReceived != null)
                                        {
                                            this.UpDataReceived.Invoke(null, new UpEventArgs()
                                            {
                                                Value = report, RawData = plusMsg
                                            });
                                        }
                                    }
                                    else
                                    {
                                        InvokeMessage(" " + rawData, "接收");
                                    }
                                }
                            }
                        }
                        else
                        {
                            Down.Parse(rawData, out downReport);
                            if (downReport != null)
                            {
                                InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + rawData, "接收");
                                if (this.DownDataReceived != null)
                                {
                                    this.DownDataReceived.Invoke(null, new DownEventArgs()
                                    {
                                        Value = downReport, RawData = rawData
                                    });
                                }
                            }
                        }
                        #endregion
                    }
                }
                else if (msg.Contains("BEG"))
                {
                    CSDStruct sd = new CSDStruct();
                    if (Down.Parse_SD(msg, sid, out sd))
                    {
                        InvokeMessage(String.Format("{0,-10}   ", "批量SD传输") + msg, "接收");

                        if (this.BatchSDDataReceived != null)
                        {
                            this.BatchSDDataReceived.Invoke(null, new BatchSDEventArgs()
                            {
                                Value = sd, RawData = msg
                            });
                        }
                    }
                }
                else if (msg.Contains("#"))
                {
                    CEntitySoilData soil       = new CEntitySoilData();
                    CReportStruct   soilReport = new CReportStruct();
                    if (Soil.Parse(rawData, out soil, out soilReport))
                    {
                        soil.ChannelType = EChannelType.GPRS;

                        if (null != this.SoilDataReceived)
                        {
                            this.SoilDataReceived(null, new CEventSingleArgs <CEntitySoilData>(soil));
                        }

                        if (null != soilReport && null != this.UpDataReceived)
                        {
                            soilReport.ChannelType = EChannelType.GPRS;
                            soilReport.ListenPort  = this.GetListenPort().ToString();
                            this.UpDataReceived(null, new UpEventArgs()
                            {
                                RawData = rawData, Value = soilReport
                            });
                        }
                    }
                }
                else
                {
                    return(false);
                }
                return(true);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine("GPRS 数据解析出错 !" + msg + "\r\n" + exp.Message);
            }
            return(false);
        }
Ejemplo n.º 20
0
        //  数据下行设置
        public String BuildSet(string sid, IList <EDownParam> cmds, CDownConf down, EChannelType ctype)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(ProtocolMaps.ChannelProtocolStartCharMap.FindValue(ctype)); //添加首字符
            sb.Append(String.Format("{0:D4}", Int32.Parse(sid.Trim())));          //添加四位站点ID号
            sb.Append("0S");                                                      //添加指令类型

            int length = 6;                                                       //  查询后指令的长度

            foreach (var cmd in cmds)
            {
                length = length + 3 + Int32.Parse(ProtocolMaps.DownParamLengthMap[cmd]);

                sb.Append(CSpecialChars.BALNK_CHAR);
                sb.Append(ProtocolMaps.DownParamMap.FindValue(cmd));
                switch (cmd)
                {
                case EDownParam.Clock: sb.Append(down.Clock.Value.ToString("yyMMddHHmmss")); break;

                case EDownParam.NormalState: sb.Append(ProtocolMaps.NormalState4ProtoMap.FindValue(down.NormalState.Value)); break;

                case EDownParam.Voltage: sb.Append(String.Format("{0:D4}", (int)down.Voltage.Value)); break;

                case EDownParam.StationCmdID: sb.Append(down.StationCmdID); break;

                case EDownParam.TimeChoice: sb.Append(ProtocolMaps.TimeChoice4ProtoMap.FindValue(down.TimeChoice.Value)); break;

                case EDownParam.TimePeriod: sb.Append(ProtocolMaps.TimePeriodMap.FindValue(down.TimePeriod.Value)); break;

                case EDownParam.WorkStatus: sb.Append(ProtocolMaps.WorkStatus4ProtoMap.FindValue(down.WorkStatus.Value)); break;

                case EDownParam.VersionNum: sb.Append(down.VersionNum); break;

                case EDownParam.StandbyChannel:
                    sb.Append(ProtocolMaps.ChannelType4ProtoMap.FindValue(down.MainChannel.Value));
                    sb.Append(ProtocolMaps.ChannelType4ProtoMap.FindValue(down.ViceChannel.Value));
                    break;

                case EDownParam.TeleNum: sb.Append(down.TeleNum); break;

                case EDownParam.RingsNum: sb.Append(String.Format("{0:D2}", (int)down.RingsNum.Value)); break;

                case EDownParam.DestPhoneNum: sb.Append(down.DestPhoneNum); break;

                case EDownParam.TerminalNum: sb.Append(down.TerminalNum); break;

                case EDownParam.GSMElec: sb.Append(ProtocolMaps.GSMElec4ProtoMap.FindValue(down.GSMElec.Value)); break;

                case EDownParam.RespBeam: sb.Append(down.RespBeam); break;

                case EDownParam.AvegTime: sb.Append(String.Format("{0:D2}", (int)down.AvegTime.Value)); break;

                case EDownParam.KC: sb.Append(down.KC); break;

                case EDownParam.RainPlusReportedValue: sb.Append(String.Format("{0:D2}", (int)down.RainPlusReportedValue.Value)); break;

                case EDownParam.Rain: sb.Append(String.Format("{0:D4}", (int)down.Rain.Value)); break;

                case EDownParam.realWater: sb.Append(String.Format("{0:D6}", (int)down.realWater.Value)); break;

                case EDownParam.WaterBase: sb.Append(String.Format("{0:D6}", (int)down.WaterBase.Value)); break;

                case EDownParam.WaterPlusReportedValue: sb.Append(String.Format("{0:D2}", (int)down.WaterPlusReportedValue.Value)); break;

                case EDownParam.SelectCollectionParagraphs: sb.Append(ProtocolMaps.SelectCollectionParagraphs4ProtoMap.FindValue(down.SelectCollectionParagraphs.Value)); break;

                case EDownParam.StationType: sb.Append(ProtocolHelpers.StationType2ProtoStr_set_proto(down.StationType.Value)); break;

                case EDownParam.SensorType: sb.Append(ProtocolMaps.SensorType4ProtoMap.FindValue(down.SensorType.Value)); break;

                case EDownParam.UserName: sb.Append(down.UserName); break;

                case EDownParam.StationName: sb.Append(down.StationName); break;

                default:
                    throw new Exception("设置下行指令参数错误");
                }
            }
            sb.Append(CSpecialChars.ENTER_CHAR);    //添加结束符

            if (ctype == EChannelType.None)
            {
                //  短信一包最大字节数为160
                return(length > 160 ? string.Empty : sb.ToString());
            }
            else if (ctype == EChannelType.BeiDou)
            {
                //  北斗卫星最大字节数为98
                return(length > 98 ? string.Empty : sb.ToString());
            }
            else if (ctype == EChannelType.GPRS || ctype == EChannelType.GSM)
            {
                return(sb.ToString());
            }
            throw new Exception("信道协议未编写!");
        }
Ejemplo n.º 21
0
        private void DealData()
        {
            while (true)
            {
                m_semaphoreData.WaitOne(); //阻塞当前线程,知道被其它线程唤醒
                // 获取对data内存缓存的访问权
                m_mutexListDatas.WaitOne();
                List <HDModemDataStruct> dataListTmp = m_listDatas;
                m_listDatas = new List <HDModemDataStruct>(); //开辟一快新的缓存区
                m_mutexListDatas.ReleaseMutex();
                for (int i = 0; i < dataListTmp.Count; ++i)
                {
                    try
                    {
                        HDModemDataStruct dat      = dataListTmp[i];
                        string            data     = System.Text.Encoding.Default.GetString(dat.m_data_buf).TrimEnd('\0');
                        string            recvData = data.Trim();

                        InvokeMessage(data, "原始数据");

                        string temp = data.Trim();

                        string gprs = System.Text.Encoding.Default.GetString(dat.m_modemId);
                        gprs = gprs.Replace("\0", "");
                        string sid = Manager.XmlStationData.Instance.GetStationByGprsID(gprs);

                        string result = null;
                        if (temp.Contains("TRU"))
                        {
                            Debug.WriteLine("接收数据TRU完成,停止计时器");
                            //m_timer.Stop();
                            InvokeMessage("TRU " + System.Text.Encoding.Default.GetString(dat.m_modemId), "接收");
                            if (this.ErrorReceived != null)
                            {
                                this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                                {
                                    //   Msg = "TRU " + dat.m_modemId
                                    Msg = "TRU " + System.Text.Encoding.Default.GetString(dat.m_modemId)
                                });
                            }
                        }
                        if (temp.Contains("ATE0"))
                        {
                            Debug.WriteLine("接收数据ATE0完成,停止计时器");
                            //m_timer.Stop();
                            // InvokeMessage("ATE0", "接收");
                            if (this.ErrorReceived != null)
                            {
                                this.ErrorReceived.Invoke(null, new ReceiveErrorEventArgs()
                                {
                                    Msg = "ATE0"
                                });
                            }
                        }
                        if (temp.Contains("$"))
                        {
                            result = temp.Substring(temp.IndexOf("$"));
                            int length = int.Parse(result.Substring(11, 4));
                            //获取报文长度
                            if (length > MAX_BUFFER)
                            {
                                continue;
                            }

                            result = result.Substring(0, length);

                            if (!(result.StartsWith("$") && result.EndsWith("\r\n")))
                            {
                                InvokeMessage(result + "报文开始符结束符不合法", "接收");
                            }

                            String dataProtocol = Manager.XmlStationData.Instance.GetProtocolBySId(sid);

                            CReportStruct report     = new CReportStruct();
                            CDownConf     downReport = new CDownConf();
                            if (dataProtocol == "RG30")
                            {
                                Up   = new Data.RG30.UpParser();
                                Down = new Data.RG30.DownParser();
                            }

                            if (dataProtocol == "SM100H")
                            {
                                Up   = new Data.SM100H.UpParser();
                                Down = new Data.SM100H.DownParser();
                            }
                            //时差法
                            if (dataProtocol == "TDXY")
                            {
                                Up   = new Data.TDXY.UpParser();
                                Down = new Data.TDXY.DownParser();
                            }

                            //中游局协议
                            if (dataProtocol == "ZYJBX")
                            {
                                Up   = new Data.ZYJBX.UpParser();
                                Down = new Data.ZYJBX.DownParser();
                            }

                            //蒸发协议
                            if (dataProtocol == "ZFXY")
                            {
                                Up   = new Data.ZFXY.UpParse();
                                Down = new Data.ZFXY.DownParse();
                            }

                            if (dataProtocol == "EN2B")
                            {
                                Up   = new Data.EN2B.UpParser();
                                Down = new Data.EN2B.DownParser();
                            }
                            if (dataProtocol == "OBS")
                            {
                                Up   = new Protocol.Data.OBS.UpParser();
                                Down = new Protocol.Data.OBS.DownParser();
                            }
                            //云南协议
                            if (dataProtocol == "YNXY")
                            {
                                Up   = new Data.YNXY.UpParser();
                                Down = new Data.YNXY.DownParser();
                            }

                            //批量传输解析
                            if (temp.Contains("1K"))
                            {
                                var station = FindStationBySID(sid);
                                if (station == null)
                                {
                                    throw new Exception("批量传输,站点匹配错误");
                                }
                                CBatchStruct batch = new CBatchStruct();
                                InvokeMessage(String.Format("{0,-10}   ", "批量传输") + temp, "接收");

                                if (Down.Parse_Flash(result, EChannelType.GPRS, out batch))
                                {
                                    if (this.BatchDataReceived != null)
                                    {
                                        this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                        {
                                            Value = batch, RawData = temp
                                        });
                                    }
                                }
                                else if (Down.Parse_Batch(result, out batch))
                                {
                                    if (this.BatchDataReceived != null)
                                    {
                                        this.BatchDataReceived.Invoke(null, new BatchEventArgs()
                                        {
                                            Value = batch, RawData = temp
                                        });
                                    }
                                }
                            }
                            //+ 代表的是蒸发报文,需要特殊处理
                            //数据报文解析
                            if (result.Contains("1G21") || result.Contains("1G22") || result.Contains("1G23") ||
                                result.Contains("1G25") || result.Contains("1G29") || result.Contains("+"))
                            {
                                //回复TRU
                                InvokeMessage("TRU " + gprs, "发送");
                                byte[] bts = new byte[] { 84, 82, 85, 13, 10 };
                                this.sendHex(gprs.Trim(), bts, (uint)bts.Length, null);

                                //根据$将字符串进行分割

                                var lists = result.Split('$');
                                foreach (var msg in lists)
                                {
                                    if (msg.Length < 10)
                                    {
                                        continue;
                                    }
                                    string plusMsg = "$" + msg.TrimEnd();
                                    bool   ret     = Up.Parse(plusMsg, out report);
                                    if (ret && report != null)
                                    {
                                        report.ChannelType = EChannelType.GPRS;
                                        report.ListenPort  = this.GetListenPort().ToString();
                                        report.flagId      = gprs;
                                        string rtype = report.ReportType == EMessageType.EAdditional ? "加报" : "定时报";
                                        InvokeMessage("gprs号码:  " + gprs + "   " + String.Format("{0,-10}   ", rtype) + plusMsg, "接收");
                                        //TODO 重新定义事件
                                        if (this.UpDataReceived != null)
                                        {
                                            this.UpDataReceived.Invoke(null, new UpEventArgs()
                                            {
                                                Value = report, RawData = plusMsg
                                            });
                                        }
                                    }
                                }
                            }
                            //其他报文
                            else
                            {
                                Down.Parse(result, out downReport);
                                if (downReport != null)
                                {
                                    InvokeMessage(String.Format("{0,-10}   ", "下行指令读取参数") + result, "接收");
                                    if (this.DownDataReceived != null)
                                    {
                                        this.DownDataReceived.Invoke(null, new DownEventArgs()
                                        {
                                            Value = downReport, RawData = result
                                        });
                                    }
                                }
                            }
                        }

                        if (temp.Contains("BEG"))
                        {
                            Data.ZYJBX.DownParser down1 = new Data.ZYJBX.DownParser();
                            CSDStruct             sd    = new CSDStruct();
                            string id = Manager.XmlStationData.Instance.GetStationByGprsID(gprs);
                            if (down1.Parse_SD(temp, id, out sd))
                            {
                                InvokeMessage(String.Format("{0,-10}   ", "批量SD传输") + temp, "接收");

                                if (this.BatchSDDataReceived != null)
                                {
                                    this.BatchSDDataReceived.Invoke(null, new BatchSDEventArgs()
                                    {
                                        Value = sd, RawData = temp
                                    });
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("" + e.Message);
                    }
                }
            }
        }