Example #1
0
        /// <summary>
        /// Receive sent messages
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VirtualPortEventRaiser_VirtualPortEvent(object sender, NamedPortEventArgs e)
        {
            try
            {
                Debug.WriteLine("Tf Socket Server DataReceived:" + e.Text);
                Debug.Assert(true);
                if (e.PortEvent == NamedPortEventArgs.PortEventType.TextReceived)
                {
                    int portIndex = e.Port.LocalSocketName.IndexOf(":");
                    if (portIndex == -1)
                    {
                        return;
                    }

                    bool ok = int.TryParse(e.Port.LocalSocketName.Substring(portIndex + 1), out int port);
                    if (receivedMsgCount.ContainsKey(port))
                    {
                        receivedMsgCount[port] = receivedMsgCount[port] + 1;
                        Debug.WriteLine("HandleReceivedPlainText from port:" + port + ":" + receivedMsgCount[port] + "  " + e.Text);
                    }
                    else
                    {
                        SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Key for receivedMsgCount not found: " + port);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex, "VirtualPortEventRaiser_VirtualPortEvent");
            }
        }
Example #2
0
        } // Connect

        public bool Disconnect()
        {
            bool result = false;

            try
            {
                ConnectionState = NamedPortState.Disconnecting;
                if (tcpClient == null)
                {
                    return(true);
                }

                GetStream()?.Dispose();
                tcpClient.Client?.Dispose();
                tcpClient.Dispose();
                result = true;
            }
            catch (Exception ex)
            {
                var s = string.Format(CultureInfo.InvariantCulture, "Disconnect and stop listening. - Exception: {0}", ex.Message);
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, s);
                Debug.Assert(true, "OK." + ex.Message);
            }
            finally
            {
                Debug.Assert(!IsOpen(), "IsOpen in finally");
                ConnectionState = NamedPortState.Disconnected;
            }
            return(result);
        }
Example #3
0
        private static bool WriteSummaryToFile(string targetPath, string strContent)
        {
            var  fileWriter    = new SimpleFileWriter();
            bool writtenToFile = fileWriter.SaveSummary(targetPath, strContent);

            return(writtenToFile);
        }
Example #4
0
        private void LogInputData(string text, INamedPort virtualPort)
        {
            if (virtualPort.RemoteSocketName == null)
            {
                return;
            }

            if (WriteAllInputIntoLog)
            {
                if (WriteAllInputPortIntoLog)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Input,
                                                          string.Concat(virtualPort.RemoteSocketName
                                                                        , "_"
                                                                        , virtualPort.LocalSocketName
                                                                        ,
                                                                        text.Replace("\r", "<CR>").Replace("\n", "<NL>")));
                }
                else
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Input,
                                                          text.Replace("\r", "<CR>").Replace("\n", "<NL>"));
                }
            }
        }
        public void PrepareOutputForSavingOkTwoStrings()
        {
            var inputTable = new DataTable();

            inputTable.Columns.Add("advertiser");
            inputTable.Columns.Add("ad_spend", typeof(double));

            DataRow row = inputTable.NewRow();

            row["advertiser"] = "test1";
            row["ad_spend"]   = 4.6;

            DataRow row2 = inputTable.NewRow();

            row2["advertiser"] = "test2";
            row2["ad_spend"]   = 1;
            var writer = new SimpleFileWriter(new DataGroupingByAdv(), null);

            writer.PrepareOutputForSaving(new List <DataRow> {
                row, row2
            });
            Assert.IsTrue(writer.OutputRows.Count == 2, "Expected 2 grouped rows in the end");
            Assert.IsTrue((double)writer.OutputRows.First()["ad_spend"] == 4.6, "Wrong sum, expected 4.6, gor {0}");
            Assert.IsTrue((double)((List <DataRow>)writer.OutputRows)[1]["ad_spend"] == 1, "Wrong sum, expected 1, gor {0}");
        }
        public void WriteOutputFileOkGroupLine()
        {
            var inputTable = new DataTable();

            inputTable.Columns.Add("advertiser");
            inputTable.Columns.Add("ad_spend", typeof(double));

            DataRow row = inputTable.NewRow();

            row["advertiser"] = "test1";
            row["ad_spend"]   = 4.6;

            DataRow row2 = inputTable.NewRow();

            row2["advertiser"] = "test1";
            row2["ad_spend"]   = 1;
            var writer = new SimpleFileWriter(new DataGroupingByAdv(), "resultTest.csv");

            writer.PrepareOutputForSaving(new List <DataRow> {
                row, row2
            });
            writer.WriteOutputFile();
            if (!File.Exists("resultTest.csv"))
            {
                Assert.Fail("Result file was not created");
            }
            var resultlines = File.ReadLines("resultTest.csv").ToArray();

            Assert.IsTrue(resultlines.Length == 2, "Wrong number of line in result file. Expected:3, result:{0}", resultlines.Length);
            Assert.IsTrue(resultlines[0] == "advertiser,ad_spend", "header is wrong, expected: 'advertiser,ad_spend', got: {0}", resultlines[0]);
            Assert.IsTrue(resultlines[1] == "\"test1\",\"5.6\"", "line 1 is wrong, expected: \"test1\",\"4.6\", got: {0}", resultlines[1]);
            File.Delete("resultTest.csv");
        }
Example #7
0
        public void WriteToSocketServer()
        {
            const int   tcpPort      = 10097;
            TcpListener socketServer = null;

            try
            {
                socketServer = SocketServerHelper.Start(tcpPort);
                var ipAddress = "127.0.0.1";

                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Testing.");
                for (var testRun = 0; testRun < 2; testRun++)
                {
                    using (var tcpIpClient = new VaiTcpIpClient())
                    {
                        Assert.True(tcpIpClient.ConnectAsync(IPAddress.Parse(ipAddress), tcpPort).Result);
                        for (var i = 0; i < numSentMessages; i++)
                        {
                            var message = "Sample data " + i;
                            Assert.True(tcpIpClient.Write(message));
                            Task.Delay(TimeSpan.FromMilliseconds(100)).Wait();
                        }
                        Assert.True(tcpIpClient.Disconnect());
                    }
                }
            }
            finally
            {
                SocketServerHelper.Stop(null, socketServer);
            }
        }
Example #8
0
        private MeasMsg ParseStatioName(string lineValue, bool useStationId, MeasMsg measMsg)
        {
            string sName = lineValue;

            SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "ParseStatioName:" + useStationId + "|" + sName);

            if (useStationId)
            {
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "ParseStatioName 2:" + this.stationMessageNames.ContainsKey(sName));

                if (this.stationMessageNames.ContainsKey(sName))
                {
                    sName = stationMessageNames[sName];
                }
                else
                {
                    var sb = new StringBuilder();
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YV Station list 2:");
                    foreach (var key in stationMessageNames.Keys)
                    {
                        sb.AppendLine(key + ":" + stationMessageNames[key]);
                    }
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, sb.ToString());
                }
            }
            if (sName != null)
            {
                measMsg.Station = sName;
            }

            return(measMsg);
        }
Example #9
0
 internal void WriteToLog(string text)
 {
     if (!WriteDetailedLog)
     {
         return;
     }
     SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, text);
 }
Example #10
0
 private void InformCapacityLimitReached()
 {
     if (capacityInfoTimeMeasurer.IsTime())
     {
         string msg = "Output queue capacity (" + capacity + ") limit reached.";
         if (!string.IsNullOrEmpty(capacityInfoTimeMeasurer.Source))
         {
             msg = msg + capacityInfoTimeMeasurer.Source;
         }
         SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, msg);
     }
 }
Example #11
0
        private void PrintChannelDataCount()
        {
            StringBuilder sb = new StringBuilder("Cdc_:");

            foreach (var key in channelDataCount.Keys)
            {
                sb.Append(key + ":" + channelDataCount[key] + ";");
            }
            SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, sb.ToString());
            lastChannelDataCountReset = DateTime.Now;
            channelDataCount.Clear();
        }
Example #12
0
        protected void HandleParsingError(string error, string messageBeingParsed = "")
        {
            var e = new ParserEventArgs(error, this.virtualPort);

            ParserAssistant.portListenerEventHandler.ProcessParsingError(e);

            if (!WriteParserErrorsIntoLog)
            {
                return;
            }

            SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, error);
        }
Example #13
0
 internal override void LineTimeoutReceived(object sender, NamedPortEventArgs e)
 {
     foreach (VaiTcpIpClient client in clients)
     {
         if (string.Compare(client.RemoteSocketName, e.PortLongName, false) == 0)
         {
             lock (clientsToBeRemovedLock)
             {
                 SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Client in timeout:" + e.PortLongName);
                 MarkClientToBeRemoved(client);
                 break;
             }
         }
     }
 }
        public void PrepareOutputForSavingOk()
        {
            var inputTable = new DataTable();

            inputTable.Columns.Add("advertiser");
            inputTable.Columns.Add("ad_spend", typeof(double));

            DataRow row = inputTable.NewRow();

            row["advertiser"] = "test1";
            row["ad_spend"]   = 4.6;
            var writer = new SimpleFileWriter(new DataGroupingByAdv(), null);

            writer.PrepareOutputForSaving(new List <DataRow> {
                row, row
            });
            Assert.IsTrue(writer.OutputRows.Count == 1, "There has to be 1 gruped row in the end");
            Assert.IsTrue((double)writer.OutputRows.First()["ad_spend"] == 9.2, "Wrong sum, expected 9.2, gor {0}");
        }
Example #15
0
        public bool Stop()
        {
            try
            {
                StartStopping();

                SocketServerHelper.Stop(cancellation, socketServer);

                Debug.WriteLine("Closing socket server ... " + IpAndPort);
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, "Stopping socket server at " + IpAndPort);

                DisposeTasks();
                return(true);
            }
            catch (Exception ex)
            {
                HandleError(StringManager.GetString("Error while stopping socket server: ") + ex.Message);
                return(false);
            }
        }
Example #16
0
        private static bool CheckLines(string[] lines)
        {
            if (lines == null)
            {
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: message does not contain newline.");
                return(false);
            }

            if (lines.GetLength(0) < 1)
            {
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: message contains only header line: " + lines[0]);
                return(false);
            }

            if (lines[0].Length < 4)
            {
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: unable to parse ceilo id from header line:" + lines[0]);
                return(false);
            }
            return(true);
        }
Example #17
0
        /// <summary>
        /// Executes the generation.
        /// </summary>
        /// <param name="model">The model of the crypto task.</param>
        public async void Execute(ICryptoCodeGenerationTaskModel model)
        {
            BeforeRunningHandler(model);

            var project = ProjectHelpers.GetProjectOfSelectedItem();

            if (project == null)
            {
                return;
            }

            var folder = ProjectHelpers.GetFolderOfSelectedItem();
            var file   = new FileInfo(Path.Combine(folder, model.FileName));

            if (file.Exists)
            {
                OnFileAlreadyExists(file);
            }
            else
            {
                using (var template = GetBaseTemplate(model))
                {
                    if (template == null)
                    {
                        return;
                    }
                    var te = new SimpleTemplateEngine(template);
                    ApplyTemplate(te, model, project, file);
                    using (var codeGenerator = new SimpleFileWriter(file))
                    {
                        await codeGenerator.WriteFileAsync(te.GetResult());
                    }
                }

                BeforeOpeningFile();

                ProjectHelpers.AddFileToSelectedItem(project, file);
                ProjectHelpers.OpenFile(file);
            }
        }
Example #18
0
        private MeasMsg ParseCellVelocityData(NMEAProprietarySentence nmeaSentence, MeasMsg measMsg)
        {
            const int cellIdIndex = 2;
            const int speedIndex  = 6;
            const int dirIndex    = 7;
            int       cell;
            string    cellId = nmeaSentence.parameters[cellIdIndex].ToString();

            if (!int.TryParse(cellId, out cell))
            {
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, StringManager.GetString("Unable to parse Nortec AWAC NMEA message cell id. Received cellId was:") + cellId);
                return(measMsg);
            }

            int index = cell - 1;

            // Ignore any message from cells which do not have variables defined
            if (-1 < index && index < CellSpeedVariables.Count)
            {
                var dataValue = nmeaSentence.parameters[speedIndex].ToString();
                measMsg.AddMeas(CellSpeedVariables[index], dataValue);
            }

            if (-1 < index && index < CellDirectionVariables.Count)
            {
                var dataValue = nmeaSentence.parameters[dirIndex].ToString();
                measMsg.AddMeas(CellDirectionVariables[index], dataValue);
            }

            if (measMsg.Count == 0)
            {
                return(null);
            }


            return(measMsg);
        }
Example #19
0
        //public TimerDaily(TimeSpan firstTime, TimeSpan period)
        //{
        //    this.PeriodMs = (int)Math.Round(period.TotalMilliseconds, 0);
        //    this.firstTime = firstTime;
        //    double milliSecondsToNextStep = GetMillisecondsToNextFiring;
        //    DueTimeMs = (int)Math.Round(milliSecondsToNextStep, 0);
        // //   timerCallback = null;

        //    timer = new System.Threading.Timer(OnTimerEvent, this, DueTimeMs, Timeout.Infinite);
        //}

        public TimerDaily(TimeSpan firstTime, TimeSpan period, TimerCallback timerDelegate, string keyData = "")
        {
            this.KeyData   = keyData;
            this.PeriodMs  = (int)Math.Round(period.TotalMilliseconds, 0);
            this.firstTime = firstTime;
            double milliSecondsToNextStep = GetMillisecondsToNextFiring;

            if (milliSecondsToNextStep < double.MaxValue)
            {
                DueTimeMs = (int)Math.Round(milliSecondsToNextStep, 0);
            }
            else
            {
                DueTimeMs = System.Threading.Timeout.Infinite;
            }

            if (DueTimeMs < 0)
            {
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Tried to set timer with negative due time:" + DueTimeMs + " keydata:" + keyData);
                return;
            }
            timer = new System.Threading.Timer(timerDelegate, this, DueTimeMs, Timeout.Infinite);
            //  UpdateTimerDueDate();
        }
Example #20
0
 private void MarkClientToBeRemoved(INamedPort client)
 {
     clientsToBeRemoved.Add(client.RemoteSocketName);
     SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "clientsToBeRemoved.Count:" + clientsToBeRemoved.Count + "\tMarkClientToBeRemoved:" + client.RemoteSocketName);
 }
Example #21
0
        internal bool Parse(string data, out MeasMsg measMsg)
        {
            //    Debug.WriteLine(DateTimeEx.NowToStringWithMs + "\tYourview Parser starts" + data.Substring(0, Math.Min(data.Length, 30)));


            measMsg = new MeasMsg();
            try
            {
                if (variableNames.Count == 0)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, "YourView parser has not been initialised. Variable names have not been set.");
                    return(false);
                }

                CheckControlParameters();

                if (string.IsNullOrEmpty(data))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: null or empty input data.");
                    return(false);
                }

                string messageName = GetMessageName(data);

                if (string.IsNullOrEmpty(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: unable to solve message name.");
                    return(false);
                }

                if (!fieldSeparators.ContainsKey(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: field separator has not been defined for message " + messageName);
                    return(false);
                }


                string   fieldSeparator = ConvertFieldSeparator(fieldSeparators[messageName]);
                string[] separator      = { fieldSeparator };


                if (!messageStarts.ContainsKey(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: field start character(s) have not been defined for message " + messageName);
                    return(false);
                }

                string convertedStart = ConvertMsgStart(messageStarts[messageName]).Trim();

                string msgStart = convertedStart;
                if (messageStarts.Count > 1)
                {
                    msgStart = messageName + convertedStart;
                }

                string tmp = sSTX + " ";
                while (data.Contains(tmp))
                {
                    data = data.Replace(tmp, sSTX);
                }
                string tmp2 = " " + sSTX;
                while (data.Contains(tmp2))
                {
                    data = data.Replace(tmp2, sSTX);
                }


                int startOfDataValues = data.IndexOf(msgStart);
                if (startOfDataValues == -1)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: cannot find start of message:" + messageName + ". Looking for:" + msgStart + ".Data to be parsed is:" + data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: cannot find start of message:" + messageName + ". msgStart len" + msgStart.Length + ".Data len:" + data.Length);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Index of STX:" + data.IndexOf(STX).ToIcString() + " ");
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Index of first 0:" + data.IndexOf("0").ToIcString() + " ");
                    foreach (var c in msgStart)
                    {
                        SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "Index of first " + c + ":" + data.IndexOf(c).ToIcString() + " ");
                    }
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: cannot find start of message:" + messageName + ". Looking for:" + msgStart.ReplaceSohStxEtx() + ".Data to be parsed is:" + data.ReplaceSohStxEtx());
                    return(false);
                }

                int    msgStartLen     = msgStart.Length;
                string dataValueString = data.Substring(startOfDataValues + msgStartLen);
                if (fieldSeparators[messageName] == YV_SPACE)
                {
                    while (dataValueString.Contains("  "))
                    {
                        dataValueString = dataValueString.Replace("  ", " ");
                    }
                }

                Debug.Assert(data.Contains(msgStart), "data.Contains(msgStart)");

                /*
                 * Debug.WriteLine("message  in data:" + data.Contains(msgStart));
                 * Debug.WriteLine("data:" + data.ReplaceLfCr() + "\t\t" + "datavalue:" + dataValueString);
                 * Debug.WriteLine("messageStarts[messageName]:" + messageStarts[messageName] +"\t" +"startOfDataValues:" + startOfDataValues);
                 */

                if (!doNotUseSeparatorAtBeginningOfMessage[messageName])
                {
                    if (dataValueString.StartsWith(fieldSeparator))
                    {
                        dataValueString = dataValueString.Substring(fieldSeparator.Length);
                    }
                }

                if (subParsers.ContainsKey(messageName))
                {
                    if (subParsers[messageName] == "CTK25KAM61")
                    {
                        int ceiloStart = data.IndexOf("CT");
                        if (ceiloStart == -1)
                        {
                            return(false);
                        }
                        return(this.ceiloParser.Parse(data.Substring(ceiloStart), out measMsg));
                    }
                }

                string[] lines = dataValueString.Split(separator, StringSplitOptions.None);

                /*
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:dataValueString :" + dataValueString.ReplaceSohStxEtx());
                 * for(int i = 0; i< lines.GetLength(0);i++)
                 *  SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:line " + i + ":" + lines[i].ReplaceSohStxEtx());
                 */
                if (UseStationName)
                {
                    measMsg.Station = StationName;
                }
                measMsg.Time = DateTimeEx.Now;


                // char[] charsToTrim = { '\n', 'r', SOH, STX, ETX };
                // string messageName = lines[0].Trim(charsToTrim);



                if (!variableNames.ContainsKey(messageName))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser: unknown message received. Message name =" + messageName);
                    return(false);
                }

                var varList   = variableNames[messageName];
                int lineLen   = lines.GetLength(0);
                int lineIndex = 0;
                var max       = varList.Count;
                for (var varCount = 0; varCount < max; varCount++)
                {
                    lineIndex = varCount;
                    if (lineIndex < lineLen)
                    {
                        string varname = varList[varCount];
                        if (string.IsNullOrEmpty(varname))
                        {
                            continue;
                        }

                        string lineValue = lines[lineIndex];
                        if (SpecialFields.Contains(varname) || varname.StartsWith("<DATE ") || varname.StartsWith("<TIME "))
                        {
                            measMsg = HandleSpecialField(varname, lineValue, measMsg);
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(lineValue))
                            {
                                continue;
                            }
                            measMsg.AddMeas(new Meas(varname, measMsg.Time, lineValue, MeasStatus.c*K, measMsg.Station));
                        }
                    }
                }

                /*
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:message successfully parsed.Station name" + measMsg.Station);
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:message date:" + measMsg.Time);
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:message contents:" + measMsg.ToString());
                 * SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "YourView parser:UseStation:" + UseStationName);
                 */

                //                Debug.WriteLine(DateTimeEx.NowToStringWithMs + "\tYourview Parser ends" + data.Substring(0, Math.Min(data.Length, 30)));
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Error in parsing yourview message." + " data:" + data, ex);
                return(false);
            }
        }
Example #22
0
        new internal bool Parse(string data, out MeasMsg measMsg)
        {
            var progress = 0;

            measMsg = new MeasMsg();
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: null or empty input data.");
                    return(false);
                }
                progress++;


                char[] charsToTrim = { '\n', '\r', '\x01' };
                data = data.TrimStart(charsToTrim);
                char[] separator = { '\n' };
                var    lines     = data.Split(separator);
                if (!CheckLines(lines))
                {
                    return(false);
                }

                var lineCount = lines.GetLength(0);
                if (lineCount < 2)
                {
                    string error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: incomplete message. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }

                progress++;
                lines[0] = lines[0].Replace("\x01", string.Empty);
                var stationName = lines[0].Trim().Substring(0, 3).Replace("\r", "").Replace("\n", "");
                if (!Validation.IsValidDirectoryName(stationName))
                {
                    var error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: invalid station name. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }
                measMsg.Station = stationName;
                measMsg.Time    = DateTimeEx.Now;

                ResetVariables();
                progress++;


                string tmp = lines[1].Trim(charsToTrim);
                if (!ParseSecondLine(tmp))
                {
                    return(false);
                }
                progress++;

                measMsg.AddMeas(new Meas("CL_HDSTATUS", measMsg.Time, cloudHeightDetectionStatus, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CL_WARNING", measMsg.Time, alarmsAndWarningsInformation, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CB1", measMsg.Time, lowestCloudBase, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CB2", measMsg.Time, secondLowestCloudBase, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CB3", measMsg.Time, highestCloudBase, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("VV", measMsg.Time, verticalVisibility, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas("CL_STATUSCODE", measMsg.Time, alarmsAndWarnings, MeasStatus.c*K, measMsg.Station));

                progress++;
                if (lineCount > 2)
                {
                    progress++;
                    ParseThirdLine(lines[2].Trim(charsToTrim));
                    progress++;
                    measMsg.AddMeas(new Meas("CL_SCSTATUS", measMsg.Time, skyConditionDetectionStatus, MeasStatus.c*K, measMsg.Station));
                    if (cloudHeightsBySkycondition.Count > 0)
                    {
                        measMsg.AddMeas(new Meas("CL1", measMsg.Time, cloudHeightsBySkycondition[0], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 1)
                    {
                        measMsg.AddMeas(new Meas("CL2", measMsg.Time, cloudHeightsBySkycondition[1], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 2)
                    {
                        measMsg.AddMeas(new Meas("CL3", measMsg.Time, cloudHeightsBySkycondition[2], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 3)
                    {
                        measMsg.AddMeas(new Meas("CL4", measMsg.Time, cloudHeightsBySkycondition[3], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudHeightsBySkycondition.Count > 4)
                    {
                        measMsg.AddMeas(new Meas("CL5", measMsg.Time, cloudHeightsBySkycondition[4], MeasStatus.c*K, measMsg.Station));
                    }

                    if (cloudAmountBySkycondition.Count > 0)
                    {
                        measMsg.AddMeas(new Meas("SC1", measMsg.Time, cloudAmountBySkycondition[0], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 1)
                    {
                        measMsg.AddMeas(new Meas("SC2", measMsg.Time, cloudAmountBySkycondition[1], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 2)
                    {
                        measMsg.AddMeas(new Meas("SC3", measMsg.Time, cloudAmountBySkycondition[2], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 3)
                    {
                        measMsg.AddMeas(new Meas("SC4", measMsg.Time, cloudAmountBySkycondition[3], MeasStatus.c*K, measMsg.Station));
                    }
                    if (cloudAmountBySkycondition.Count > 4)
                    {
                        measMsg.AddMeas(new Meas("SC5", measMsg.Time, cloudAmountBySkycondition[4], MeasStatus.c*K, measMsg.Station));
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Error in parsing ceilo message. Progress:" + progress + " data:" + data, ex);
                return(false);
            }
        }
Example #23
0
        private bool ParseSecondLine(string secondLine)
        {
            try
            {
                if (secondLine.Length < 2)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "CeiloMsg61Parser: 2nd line is empty or contains only 1 character:" + secondLine);
                    return(false);
                }

                int iDetectionStatus;
                cloudHeightDetectionStatus = secondLine[0].ToString();
                var detectionStatusIsInteger = Validation.TryParseInt(cloudHeightDetectionStatus, out iDetectionStatus);

                alarmsAndWarningsInformation = secondLine[1].ToString();

                char[] spaceSeparator = { ' ' };
                var    groups         = secondLine.Substring(2).Split(spaceSeparator);

                var groupCount = groups.GetLength(0);
                if (detectionStatusIsInteger)
                {
                    if (iDetectionStatus == 0 || iDetectionStatus == 5)
                    {
                    }
                    else if (iDetectionStatus == 1 && groupCount > 1)
                    {
                        lowestCloudBase = groups[1];
                    }
                    else if (iDetectionStatus == 2 && groupCount > 2)
                    {
                        lowestCloudBase       = groups[1];
                        secondLowestCloudBase = groups[2];
                    }
                    else if (iDetectionStatus == 3 && groupCount > 3)
                    {
                        lowestCloudBase       = groups[1];
                        secondLowestCloudBase = groups[2];
                        highestCloudBase      = groups[3];
                    }
                    else if (iDetectionStatus == 4 && groupCount > 4)
                    {
                        verticalVisibility = groups[1];
                        highestSignal      = groups[2];
                    }
                }

                if (groupCount > 4)
                {
                    alarmsAndWarnings = groups[4];
                }

                return(true);
            }
            catch (Exception ex)
            {
                var msg = "Exception parsing second line";
                if (secondLine != null)
                {
                    //var sb = new StringBuilder();
                    //for (var  i = 0; i< secondLine.Length; i++)
                    //   msg.
                    msg = msg + secondLine;
                }

                ExceptionHandler.HandleException(ex, msg);
                return(false);
            }
        }
Example #24
0
        private bool ParseDataItems(string line)
        {
            try
            {
                if (line.Length < 2)
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: line is empty or contains only 1 character:" + line);
                    return(false);
                }

                //int iDetectionStatus;
                visibilityAlarm = line[0].ToString();
                //               bool detectionStatusIsInteger = Validation.TryParseInt(visibilityAlarm, out iDetectionStatus);

                alarmsAndWarningsInformation = line[1].ToString();

                var remainingLine = line.Substring(2);
                while (remainingLine.Contains("  "))
                {
                    remainingLine = remainingLine.Replace("  ", " ").Trim();
                }

                char[] spaceSeparator = { ' ' };
                var    dataItems      = remainingLine.Split(spaceSeparator, StringSplitOptions.RemoveEmptyEntries);

                var itemCount = dataItems.GetLength(0);
                if (itemCount > 0)
                {
                    visibility1MinAvg = dataItems[0];
                }
                if (itemCount > 1)
                {
                    visibility10MinAvg = dataItems[1];
                }
                if (itemCount > 2)
                {
                    instantPresentWeatherNwsCode = dataItems[2];
                }
                if (itemCount > 3)
                {
                    instantPresentWeather = dataItems[3];
                }
                if (itemCount > 4)
                {
                    presentWeather15m = dataItems[4];
                }
                if (itemCount > 5)
                {
                    presentWeather1h = dataItems[5];
                }
                if (itemCount > 6)
                {
                    precipitationIntensity = dataItems[6];
                }
                if (itemCount > 7)
                {
                    cumulativeWaterSum = dataItems[7];
                }
                if (itemCount > 8)
                {
                    cumulativeSnowSum = dataItems[8];
                }
                if (itemCount > 9)
                {
                    temperature = dataItems[9];
                }
                if (itemCount > 10)
                {
                    backgroundLuminance = dataItems[10];
                }


                return(true);
            }
            catch (Exception ex)
            {
                var msg = "Exception parsing data items on first line";
                if (line != null)
                {
                    //var sb = new StringBuilder();
                    //for (var  i = 0; i< secondLine.Length; i++)
                    //   msg.
                    msg = msg + line;
                }

                ExceptionHandler.HandleException(ex, msg);
                return(false);
            }
        }
Example #25
0
        new internal bool Parse(string data, out MeasMsg measMsg)
        {
            var progress = 0;

            measMsg = new MeasMsg();
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: null or empty input data.");
                    return(false);
                }
                progress++;


                int indexOfSOH = data.IndexOf('\x01');
                if (indexOfSOH > -1)
                {
                    data = data.Substring(indexOfSOH);
                }

                char[] charsToTrim = { '\n', '\r' };
                data = data.TrimStart(charsToTrim);
                char[] separator = { '\n' };
                var    lines     = data.Split(separator);
                if (!CheckLines(lines))
                {
                    return(false);
                }


                if (lines.GetLength(0) < 3)
                {
                    var error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: incomplete message. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }

                progress++;

                string pw1 = lines[0].Substring(0, 5).Trim(invalidChars).Replace("\r", "").Replace("\n", "").Replace('\x01', ' ').Replace('\x02', ' ').Replace(" ", string.Empty);
                if (!Validation.IsValidFileName(pw1) || !Validation.IsValidDirectoryName(pw1))
                {
                    var error = GetErrorData(data);
                    SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, "PwdMsg7Parser: invalid station name. Lines:" + lines.GetLength(0) + data + " " + error);
                    return(false);
                }
                measMsg.Station = pw1;
                measMsg.Time    = DateTimeEx.Now;

                ResetVariables();
                progress++;

                const char STX      = '\x02';
                var        stxIndex = lines[0].IndexOf(STX);
                if (stxIndex < 0)
                {
                    return(false);
                }
                var tmp = lines[0].Substring(stxIndex + 1).Trim(charsToTrim);
                if (!ParseDataItems(tmp))
                {
                    return(false);
                }
                progress++;

                measMsg.AddMeas(new Meas(GetVariableName("PWD_VISALARM"), measMsg.Time, visibilityAlarm, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PWD_WARNING"), measMsg.Time, alarmsAndWarningsInformation, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("VISAVG1M"), measMsg.Time, visibility1MinAvg, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("VISAVG10M"), measMsg.Time, visibility10MinAvg, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("NWSCODE"), measMsg.Time, instantPresentWeatherNwsCode, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PW"), measMsg.Time, instantPresentWeather, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PW15M"), measMsg.Time, presentWeather15m, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PW1H"), measMsg.Time, presentWeather1h, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PRFAVG1M"), measMsg.Time, precipitationIntensity, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PRSUM24H"), measMsg.Time, cumulativeWaterSum, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("SNOWSUM24H"), measMsg.Time, cumulativeSnowSum, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("PWD_TA"), measMsg.Time, temperature, MeasStatus.c*K, measMsg.Station));
                measMsg.AddMeas(new Meas(GetVariableName("LMAVG1M"), measMsg.Time, backgroundLuminance, MeasStatus.c*K, measMsg.Station));


                progress++;

                if (lines.GetLength(0) > 1)
                {
                    progress++;
                    string line = (lines[1].Trim(charsToTrim));
                    progress++;
                    measMsg.AddMeas(new Meas(GetVariableName("METARPWCODE"), measMsg.Time, line, MeasStatus.c*K, measMsg.Station));
                }
                if (lines.GetLength(0) > 2)
                {
                    progress++;
                    string line = (lines[2].Trim(charsToTrim));
                    progress++;
                    measMsg.AddMeas(new Meas(GetVariableName("METARRWCODE"), measMsg.Time, line, MeasStatus.c*K, measMsg.Station));
                }
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionRecorder.RecordException("Error in parsing pwd message. Progress:" + progress + " data:" + data, ex);
                return(false);
            }
        }
Example #26
0
        /// <summary>
        /// Open a connection to the given socket
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="tcpPort"></param>
        /// <returns></returns>
        public async Task <bool> ConnectAsync(IPAddress ipAddress, int tcpPort)
        {
            try
            {
                InitializeConnection(ipAddress, tcpPort);
                await tcpClient.Client.ConnectAsync(IpAddr, Port);

                return(true);
            }
            catch (SocketException ex)
            {
                var msg = string.Format(CultureInfo.InvariantCulture, "Please check connection port parameters: {0} ", ex.Message);
                if (null != IpAddr)
                {
                    msg += " Ip: " + IpAddr;
                }
#if DEBUG
                SimpleFileWriter.WriteLineToEventFile(DirectoryName.Diag, msg);
#endif
                Debug.Assert(true, msg);

                // keep this delay above 100 ms. If the connection is broken, the system will try again
                Thread.Sleep(250);
                ConnectionState = NamedPortState.Disconnected;

                //     Debug.WriteLine(DateTimeEx.NowToString + msg);
                return(false);
            }
            catch (ArgumentOutOfRangeException ex)
            {
                //     port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort.
                Debug.Assert(false, " port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort." + ex.Message);
                ExceptionRecorder.RecordException(" port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort." + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                Debug.WriteLine(DateTimeEx.NowToString + " port is not between System.Net.IPEndPoint.MinPort and System.Net.IPEndPoint.MaxPort.");
                return(false);
            }
            catch (ObjectDisposedException ex)
            {
                ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Connect. - ObjectDisposedException: {0}", ex.Message));
                Debug.Assert(false, " System.Net.Sockets.TcpClient is closed" + ex.Message);
                Debug.WriteLine(DateTimeEx.NowToString + " System.Net.Sockets.TcpClient is closed" + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                throw;
            }
            catch (ArgumentNullException ex)
            {
                ExceptionRecorder.RecordException("hostname is null " + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                throw;
            }
            catch (System.Security.SecurityException ex)
            {
                ExceptionRecorder.RecordException(string.Format(CultureInfo.InvariantCulture, "Connect. - SecurityException: {0}", ex.Message));
                Debug.WriteLine(DateTimeEx.NowToString + " Connect. - SecurityException:" + ex.Message);
                ConnectionState = NamedPortState.Disconnected;
                throw;
            }
            catch (Exception ex)
            {
                ExceptionHandler.HandleException(ex);
                return(false);
            }
        } // Connect
Example #27
0
 protected static void HandleError(string msg)
 {
     SimpleFileWriter.WriteLineToEventFile(DirectoryName.EventLog, msg);
 }