Ejemplo n.º 1
0
        //   /// <summary>
        //   /// Receive data
        //   /// </summary>
        //   /// <param name="sender"></param>
        //   /// <param name="e"></param>
        //   private void DataReceived(object sender, CipDataReceivedEventArgs e) {
        //       try {
        //           SipException exception = (SipException)null;
        //           bool r = MessageFormatter.IsResponse(e.BytesRead, out exception);
        //           if (r) {
        //               SipResponse response = CipSipParser.GetSipReponse(e.DataRead, e.BytesRead, e.TotalBytesRead);
        //               using (CipRequest invite = CipTransaction.Get(response)) {
        //                   if (invite != null) {
        //                       CipResponseEventArgs e1 = new CipResponseEventArgs(response, e.DestinationTuple);
        //                       invite.ResponseReceived(e1);
        //                   }
        //               }
        //           } else {
        //               SipRequest request = CipSipParser.GetSipRequest(e.DataRead, e.BytesRead, e.TotalBytesRead);
        //               if (request == null) { return; }
        //               string content = this.encoding.GetString(request.Body);//jira-icoc-228
        //bool isSCAIP = false;
        //               string tid = this.GetTid(content, out isSCAIP);//jira-icoc-228
        //               bool rsltACK = this.Send200OK(request, e.DestinationTuple, content /*jira-icoc-228*/);
        //               //string content = this.encoding.GetString(request.Body);//comment for jira-icoc-228
        //               //string tid = this.GetTid(content);//comment for jira-icoc-228
        //               if (string.IsNullOrEmpty(tid))
        //                   return;

        //               using (AlarmProduct p = AppServerProductCache.Instance.FindValidProductBySn(tid)) {
        //	if (p == null) {
        //		if (AppServerCache.Instance.IsMaster()) {
        //			ProductAwt _p = AppServerCache.Instance.FindProduct(tid);

        //			if (_p != null) {
        //				AlarmAppServer aas = AppServerCache.Instance.Find(_p.MessageServerID);
        //				if (aas == null) { return; }
        //				//Get Firmware from Sip UserAgent Header
        //				AlarmMessage m = new AlarmMessage(request.UserAgent);
        //				for (int i = 0; i < 60000; i += 10000) {
        //					if (!String.IsNullOrEmpty(_p.Firmware))
        //						break;
        //					else if (String.IsNullOrEmpty(_p.Firmware) && !String.IsNullOrEmpty(m.Firmware)) {
        //						AppServerCache.Instance.UpdateProduct(aas.MessageServerID, _p.SerialNumber, m.Firmware);
        //						break;
        //					}
        //					Thread.Sleep(10000);
        //				}
        //				//this.WriteProduct(aas, _p, e);//comment for jira-icoc-228
        //				//jira-icoc-228
        //				if (!isSCAIP)
        //					this.WriteProduct(aas, _p, e);
        //				//end jira-icoc-228
        //			}
        //		}
        //		if ((request.RequestLine.Method == SipMethod.Message) && (content.Contains(startupHeartbeat) || content.Contains(nStartupHeartbeat))) {
        //			using (AlarmMessage m = new AlarmMessage(MessageType.Request, SipMethod.Message, request.From.Uri.ToString(), content,
        //				e.DestinationTuple.RemoteEndPoint, e.DestinationTuple.LocalEndPoint, request.UserAgent, true)) {
        //				m.ExecutedBy = (int)ExecutedByConstant.CareIP;
        //				m.Priority = System.Messaging.MessagePriority.Lowest;
        //				AlarmMessageQueue.AddMessage(m);
        //			}
        //		}
        //		return;
        //	} else {
        //		if ((p.ProductState == (int)ProductStateConstant.Inactive)
        //			|| (p.ProductState == (int)ProductStateConstant.Paused)) {
        //			//end #3465 #067
        //			return;
        //		}
        //	}

        //                   if ((request.RequestLine.Method == SipMethod.Message) && (content.Contains(heartbeat) || content.Contains(nheartbeat) || Regex.Match(content, @"<mty>(?<mty>PI)</mty>", RegexOptions.IgnoreCase).Length > 0 /*jira-icoc-228*/)) {
        //                       using (AlarmMessage m = new AlarmMessage(MessageType.Request, SipMethod.Message, request.From.Uri.ToString(), content,
        //                           e.DestinationTuple.RemoteEndPoint, e.DestinationTuple.LocalEndPoint, request.UserAgent, true)) {
        //                           m.ExecutedBy = (int)ExecutedByConstant.CareIP;
        //                           m.Priority = System.Messaging.MessagePriority.Lowest;
        //                           AlarmMessageQueue.AddMessage(m);
        //                       }
        //                   }
        //                   e.BytesRead = null;
        //               }
        //           }
        //       } catch (Exception exception) {
        //           LogHelper.Error(Assembly.GetExecutingAssembly().GetName().Name, Dns.GetHostName(), (int)ServerType.WS
        //               , "[CipSipCore][DataReceived]_SIP: " + exception.Message + " | innerException: " + (exception.InnerException != null && !string.IsNullOrEmpty(exception.InnerException.Message) ? exception.InnerException.Message : "")
        //               , exception.StackTrace);
        //           throw exception;
        //       }
        //   }

        ///// <summary>
        ///// Auto write template (auto re-programming)
        ///// </summary>
        ///// <param name="aas"></param>
        ///// <param name="p"></param>
        ///// <param name="e"></param>
        //private void WriteProduct(AlarmAppServer aas, ProductAwt p, CipDataReceivedEventArgs e) {
        //    try {
        //        if (AwtJobCache.Instance.Found(p.ProductID))
        //            return;
        //        SipRequest request = CipSipParser.GetSipRequest(e.DataRead, e.BytesRead, e.TotalBytesRead);
        //        if (request == null) {
        //            AwtJobCache.Instance.Remove(p.ProductID);
        //            return;
        //        }
        //        if (!this.Send200OK(request, e.DestinationTuple)) {
        //            AwtJobCache.Instance.Remove(p.ProductID);
        //            return;
        //        }
        //        AwtJobCache.Instance.Add(p.ProductID);
        //        bool awt = false;
        //        using (iCareContainer container1 = new iCareContainer()) {
        //            List<int?> awtr = container1.AlarmJob_GetCipAwt(p.ProductID, (int)JobCommandConstant.AutoWriteTemplate, p.BusinessID,
        //                (int)JobStateConstant.Queued, (int)JobStateConstant.Running).ToList();
        //            if (awtr.Count > 0)
        //                awt = true;
        //        }
        //        if (awt) {
        //            AwtJobCache.Instance.Remove(p.ProductID);
        //            return;
        //        }
        //        AlarmJobCache.Instance.CleanUpJobs(p.ProductID);
        //        using (AlarmMessage m = new AlarmMessage(MessageType.Request, SipMethod.Message, request.From.Uri.ToString(), string.Empty, e.DestinationTuple.RemoteEndPoint, e.DestinationTuple.LocalEndPoint, null, false)) {
        //            AlarmEndPoint alarmEndPoint = new AlarmEndPoint(m, p.SerialNumber);
        //            string almEndPoint = SerializationClass.SerializeObject(alarmEndPoint, false, true, true);
        //            JobMessage job = new JobMessage(-1,
        //                p.ProductID,
        //                p.ProductTypeID,
        //                p.SerialNumber,
        //                almEndPoint,
        //                (int)JobCommandConstant.AutoWriteTemplate,
        //                p.Firmware,
        //                string.Empty,
        //                (int)ExecutedByConstant.CareIP,
        //                SystemAdminUser.Instance.BusinessUserID,
        //                AppServerCache.MessageServerId);
        //            string js = SerializationClass.SerializeObject(job, false, true, true);
        //            CipContentFile cipContentFile = new CipContentFile();
        //            cipContentFile.ContentType = (int)CipContentFileConstant.ConfOnly;
        //            cipContentFile.ConfFile = p.SerialNumber + MsConf.Instance.ConfFileExtension;
        //            cipContentFile.ConfVersion = Guid.NewGuid().ToString().Substring(0, 16).Replace('-', '0');
        //            string cipContentFileText = SerializationClass.SerializeObject(cipContentFile, false, true, true);
        //            string parameters = string.Format("{0}={1}\r\n{2}={3}\r\n{4}\r\n", MsConf.Instance.Config9300, p.SerialNumber, MsConf.Instance.MsContact, aas.ExternalIPAddress, MsConf.Instance.Reboot);
        //            //jira-icoc-30
        //            if (int.Parse(job.FirmwareVersion.Replace(".", "")) >= 1304) {
        //                List<string> lst = parameters.Split(new string[] { "\r", "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
        //                parameters = "";
        //                for (int i = 0; i < lst.Count; i++)
        //                    parameters += (lst[i].Length % 2 == 0 ? lst[i] : (lst[i] + " ")) + "\r\n";
        //                parameters += string.Format(":MD5={0}\r\n", StringFormat.CalculateMD5Hash(parameters));
        //            }
        //            //end jira-icoc-30
        //            using (iCareContainer container = new iCareContainer()) {
        //                string name = string.Format(JobTitleConstant.WriteTemplate, p.SerialNumber);
        //                var affectedRows = container.AlarmJob_InsertAwt(Guid.NewGuid(),
        //                                                                    name,
        //                                                                    (int)JobStateConstant.Queued,
        //                                                                    p.ProductID,
        //                                                                    (int)JobCommandConstant.AutoWriteTemplate,
        //                                                                    p.BusinessID,
        //                                                                    null,
        //                                                                    (int)ExecutedByConstant.CareIP,
        //                                                                    null,
        //                                                                    parameters,
        //                                                                    js,
        //                                                                    cipContentFileText,
        //                                                                    (int)JobStateConstant.Queued,
        //                                                                    (int)JobStateConstant.Running,
        //                                                                    SystemAdminUser.Instance.BusinessUserID,
        //                                                                    SystemAdminUser.Instance.BusinessUserID);
        //            }
        //            AwtJobCache.Instance.Remove(p.ProductID);
        //        }
        //    } catch (Exception exception) {
        //        StackTrace st = new StackTrace(exception, true);
        //        LogHelper.Error(Assembly.GetExecutingAssembly().GetName().Name, Dns.GetHostName(), (int)ServerType.MS,
        //            string.Format("care ip auto reroute adding exception,line : {0}, Full stack {1}, exception.Source: {2}, excepton message : {3}, data from unit: {4}", st.GetFrame(0).GetFileLineNumber(), st.ToString(), exception.Source, exception.Message, e.DataRead),
        //            exception.StackTrace);
        //        AwtJobCache.Instance.Remove(p.ProductID);
        //        LogService.Instance.Write(exception, LogType.Error);
        //    }
        //}

        /// <summary>
        /// Send message 200 OK
        /// </summary>
        /// <param name="request"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private bool Send200OK(SipRequest request, DestinationTuple dt, string requestContent = null /*jira-icoc-228*/)
        {
            try {
                if (request == null || dt == null)
                {
                    throw new ArgumentNullException();
                }
                SipResponse response = new SipResponse(SipStatusCode.Ok);

                //response.From = request.From;//comment for jira-icoc-228
                //response.To = request.To;//comment for jira-icoc-228
                response.From.Uri = new SipUriBuilder(request.To.Uri).SipUri;                //jira-icoc-228
                response.To.Uri   = new SipUriBuilder(request.From.Uri).SipUri;              //jira-icoc-228

                response.ViaHeaders.AddRange(request.ViaHeaders);
                response.CallId = request.CallId;
                response.CSeq   = request.CSeq;
                this.CipConnection.Send(response, dt);

                //jira-icoc-228
                if (requestContent != null && (requestContent.Contains("<mrq>") || requestContent.Contains("<MRQ>")))
                {
                    Match  tp  = patternSCAIP.Match(requestContent);
                    string cid = "";
                    if (tp.Length > 0)
                    {
                        cid = tp.Groups["cid"].Value.Trim();
                        Match  tp2 = patternSCAIP_Heartbeat.Match(requestContent);
                        string mty = "";
                        if (tp2.Length > 0)
                        {
                            mty = tp2.Groups["mty"].Value.Trim();
                            if ("pi".Equals(mty, StringComparison.OrdinalIgnoreCase) || "me".Equals(mty, StringComparison.OrdinalIgnoreCase))
                            {
                                Match  tp3    = patternSCAIP_Ref.Match(requestContent);
                                string strRef = "";
                                if (tp3.Length > 0)
                                {
                                    strRef = tp3.Groups["ref"].Value.Trim();
                                    string body    = string.Format("<mrs><ref>{0}</ref><snu>0</snu></mrs>", strRef);
                                    byte[] content = Encoding.UTF8.GetBytes(body);

                                    SipRequest serverRequest = MessageRequest.CreateRequest(SipMethod.Message, response.To.Uri, response.From.Uri);
                                    //ViaHeaderField via = new ViaHeaderField(new IPDomainPort(new IPEndPoint(IPAddress.Parse(request.To.Uri.Host), 5060)), TransportProtocol.Udp);
                                    serverRequest.ViaHeaders.Clear();
                                    //serverRequest.ViaHeaders.Add(via);
                                    serverRequest.ViaHeaders.AddRange(request.ViaHeaders);
                                    serverRequest.CSeq = request.CSeq;
                                    serverRequest.Body = content;
                                    //serverRequest.ContentType.MediaType = "application";
                                    //serverRequest.ContentType.MediaSubType = "scaip+xml";
                                    serverRequest.ContentType   = new ContentTypeHeaderField(MediaType.Application, "scaip+xml");
                                    serverRequest.ContentLength = content.Length;
                                    this.CipConnection.Send(serverRequest, dt);
                                }
                            }
                        }
                    }
                }
                //end jira-icoc-228

                return(true);
            } catch (Exception exception) {
                Console.WriteLine(exception.Message);
                return(false);
            }
        }
Ejemplo n.º 2
0
        public void Go_Send(int currentPort)
        {
            try
            {
                SipUri from = new SipUri(this.AppServerSipUri);

                string AlarmEndPointSipUri = "sip:contact@" + this.LocalIpAddress + ":" + currentPort;
                SipUri to = new SipUri(AlarmEndPointSipUri);

                SipRequest request = MessageRequest.CreateRequest(SipMethod.Message, to, from);
                Random     random  = new Random();

                int cSeq = random.Next(0, 10000);
                request.CSeq.SequenceNumber = cSeq;
                request.CSeq.Method         = SipMethod.Message;

                //int FreePort = DoroCommon.GetAvailablePort(5060);
                //Console.WriteLine(FreePort);

                IPAddress localIP = NetworkInformation.IPv4Address;

                ViaHeaderField via = new ViaHeaderField(new IPDomainPort(new IPEndPoint(localIP, currentPort)), TransportProtocol.Udp);
                via.ResponsePort = currentPort;
                request.ViaHeaders.Clear();
                request.ViaHeaders.Add(via);

                AlarmReq ar = new AlarmReq();
                ar.Ref = random.Next(0, 16).ToString();
                ar.Aty = "PI";
                ar.Tty = "C9300";
                ar.Tid = "7942098";
                ar.Inf = "Heartbeat";

                Console.WriteLine(ar.ToString());

                string body = SerializationClass.SerializeObject(ar, false, true, true);

                byte[] content = Encoding.UTF8.GetBytes(body);

                Console.WriteLine(content.ToString());

                request.Body          = content;
                request.ContentType   = new ContentTypeHeaderField(MediaType.Text, "text");
                request.ContentLength = content.Length;

                //Console.WriteLine(request.Body.ToString());

                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(this.ServerIpAddress), this.ServerPort);
                IPEndPoint localEndpoint  = new IPEndPoint(localIP, currentPort);

                Protocol.DestinationTuple d = new Protocol.DestinationTuple(localEndpoint, remoteEndPoint);

                Console.WriteLine("Open Port: " + localIP + ":" + currentPort + " => Sent Message to " + this.ServerIpAddress + ":" + this.ServerPort);
                Set_TextBox("Open Port: " + localIP + ":" + currentPort + " => Sent Message to " + this.ServerIpAddress + ":" + this.ServerPort);

                //Protocol.DestinationTuple d = new Protocol.DestinationTuple(this.ServerIpAddress.ToString(), this.ServerPort);

                CipConnection cipConnection = new CipConnection(this);
                cipConnection.StartListening(currentPort);
                cipConnection.Send(request, d);

                Interlocked.Increment(ref CountConnection);
                Set_Status();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }