/// <summary> Refills the input buffer.
        ///
        /// </summary>
        /// <returns>      <code>false</code>, iff there was new input.
        ///
        /// </returns>
        /// <exception cref="java.io.IOException"> if any I/O-Error occurs
        /// </exception>
        private bool zzRefill()
        {
            /* first: make room (if you can) */
            if (zzStartRead > 0)
            {
                Array.Copy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead - zzStartRead);

                /* translate stored positions */
                zzEndRead     -= zzStartRead;
                zzCurrentPos  -= zzStartRead;
                zzMarkedPos   -= zzStartRead;
                zzPushbackPos -= zzStartRead;
                zzStartRead    = 0;
            }

            /* is the buffer big enough? */
            if (zzCurrentPos >= zzBuffer.Length)
            {
                /* if not: blow it up */
                char[] newBuffer = new char[zzCurrentPos * 2];
                Array.Copy(zzBuffer, 0, newBuffer, 0, zzBuffer.Length);
                zzBuffer = newBuffer;
            }

            /* finally: fill the buffer with new input */
            int lengthToRead = zzBuffer.Length - zzEndRead;
            int numRead      = zzReader.Read(zzBuffer, zzEndRead, lengthToRead);

            if (numRead == 0)
            {
                return(true);
            }
            else
            {
                // dBera: set EOF is fewer chars were read
                zzAtEOF = (numRead < lengthToRead);

                zzEndRead += numRead;
                return(false);
            }
        }
示例#2
0
        private bool  Refill()
        {
            int newPosition = bufferLength - tokenStart;

            if (tokenStart == 0)
            {
                // token won't fit in buffer
                if (buffer == null)
                {
                    // first time: alloc buffer
                    buffer = new char[2048];
                }
                else if (bufferLength == buffer.Length)
                {
                    // grow buffer
                    char[] newBuffer = new char[buffer.Length * 2];
                    Array.Copy(buffer, 0, newBuffer, 0, bufferLength);
                    buffer = newBuffer;
                }
            }
            else
            {
                // shift token to front
                Array.Copy(buffer, tokenStart, buffer, 0, newPosition);
            }

            bufferLength   = newPosition;           // update state
            bufferPosition = newPosition;
            bufferStart   += tokenStart;
            tokenStart     = 0;

            int charsRead = input.Read(buffer, newPosition, buffer.Length - newPosition);

            if (charsRead <= 0)
            {
                return(false);
            }

            bufferLength += charsRead;
            return(true);
        }
示例#3
0
        /// <summary>Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.</summary>
        /// <param name="sourceTextReader">The source TextReader to read from</param>
        /// <param name="target">Contains the array of characteres read from the source TextReader.</param>
        /// <param name="start">The starting index of the target array.</param>
        /// <param name="count">The maximum number of characters to read from the source TextReader.</param>
        /// <returns>The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached.</returns>
        public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count)
        {
            // Returns 0 bytes if not enough space in target
            if (target.Length == 0)
            {
                return(0);
            }
            char[] charArray = new char[target.Length];
            int    bytesRead = sourceTextReader.Read(charArray, start, count);

            // Returns -1 if EOF
            if (bytesRead == 0)
            {
                return(-1);
            }
            for (int index = start; index < start + bytesRead; index++)
            {
                target[index] = (byte)charArray[index];
            }
            return(bytesRead);
        }
示例#4
0
        private static string ReadFunction(System.IO.TextReader reader)
        {
            System.Text.StringBuilder tokenBuilder = new System.Text.StringBuilder();

            int n;

            while ((n = reader.Peek()) != -1)
            {
                char ch = (char)reader.Read();
                if (ch == ')')
                {
                    return(tokenBuilder.ToString());
                }
                else
                {
                    tokenBuilder.Append(ch);
                }
            }

            throw new System.Exception("Invalid function: " + tokenBuilder.ToString());
        }
示例#5
0
 private static string GetSegment(System.IO.TextReader reader)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     while (reader.Peek() != -1)
     {
         char ch = (char)reader.Peek();
         if (ch == '[')
         {
             break;
         }
         else if (ch == '.')
         {
             break;
         }
         else
         {
             stringBuilder.Append(ch);
             reader.Read();
         }
     }
     return(stringBuilder.ToString());
 }
示例#6
0
        public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, short[] target, int start, int count)
        {
            if (target.Length == 0)
            {
                return(0);
            }

            char[] charArray = new char[target.Length];
            int    bytesRead = sourceTextReader.Read(charArray, start, count);

            if (bytesRead == 0)
            {
                return(-1);
            }

            for (int index = start; index < start + bytesRead; index++)
            {
                target[index] = (short)charArray[index];
            }

            return(bytesRead);
        }
示例#7
0
 public virtual int Read()
 {
     return(backingReader.Read());
 }
示例#8
0
        private static System.Collections.IList ParseRow(System.IO.TextReader reader)
        {
            System.Collections.IList row = new System.Collections.ArrayList();

            int n = -1;

            while ((n = reader.Peek()) != -1)
            {
                char ch = (char)n;

                switch (ch)
                {
                case '\"':
                {
                    reader.Read();
                    row.Add(ParseAtom(ParseQuotedString(reader)));
                    break;
                }

                case ',':
                {
                    reader.Read();
                    row.Add(null);
                    break;
                }

                case '\n':
                {
                    reader.Read();

                    if (row.Count == 0)
                    {
                        //Try again.
                        return(ParseRow(reader));
                    }
                    else
                    {
                        return(row);
                    }
                }

                case '\r':
                {
                    reader.Read();
                    if (reader.Peek() == (int)'\n')
                    {
                        reader.Read();
                    }

                    if (row.Count == 0)
                    {
                        //Try again.
                        return(ParseRow(reader));
                    }
                    else
                    {
                        return(row);
                    }
                }

                default:
                {
                    row.Add(ParseAtom(ParseUnquotedString(reader)));
                    break;
                }
                }
            }

            if (row.Count == 0)
            {
                return(null);
            }
            else
            {
                return(row);
            }
        }
示例#9
0
	  internal static int ReadFully(Reader reader, char[] dest, int offset, int len)
	  {
		int read = 0;
		while (read < len)
		{
		  int r = reader.Read(dest, offset + read, len - read);
		  if (r == -1)
		  {
			break;
		  }
		  read += r;
		}
		return read;
	  }
示例#10
0
        // parses a row from a csv file and yields the result back as a list of strings - one for each column.
        static IEnumerable <IList <string> > FromReader(System.IO.TextReader csv)
        {
            IList <string> result = new List <string>();

            StringBuilder curValue = new StringBuilder();
            var           c        = (char)csv.Read();

            while (csv.Peek() != -1)
            {
                // when we are here we are at the start of a new column and c contains the first character
                switch (c)
                {
                case ',':     //empty field
                    result.Add("");
                    c = (char)csv.Read();
                    break;

                case '"':     //qualified text
                case '\'':
                    char q = c;
                    c = (char)csv.Read();
                    bool inQuotes = true;
                    while (inQuotes && csv.Peek() != -1)
                    {
                        if (c == q)
                        {
                            c = (char)csv.Read();
                            if (c != q)
                            {
                                inQuotes = false;
                            }
                        }

                        if (inQuotes)
                        {
                            curValue.Append(c);
                            c = (char)csv.Read();
                        }
                    }
                    result.Add(curValue.ToString());
                    curValue = new StringBuilder();
                    if (c == ',')
                    {
                        c = (char)csv.Read();               // either ',', newline, or endofstream
                    }
                    break;

                case '\n':     //end of the record
                case '\r':
                    //potential bug here depending on what your line breaks look like
                    if (result.Count > 0)     // don't return empty records
                    {
                        yield return(result);

                        result = new List <string>();
                    }
                    c = (char)csv.Read();
                    break;

                default:     //normal unqualified text
                    while (c != ',' && c != '\r' && c != '\n' && csv.Peek() != -1)
                    {
                        curValue.Append(c);
                        c = (char)csv.Read();
                    }
                    // if end of file then make sure that we add the last read character
                    if (csv.Peek() == -1 && c != '\r' && c != '\n')
                    {
                        curValue.Append(c);
                    }

                    result.Add(curValue.ToString());
                    curValue = new StringBuilder();
                    if (c == ',')
                    {
                        c = (char)csv.Read();               //either ',', newline, or endofstream
                    }
                    break;
                }
            }
            if (curValue.Length > 0) //potential bug: I don't want to skip on a empty column in the last record if a caller really expects it to be there
            {
                result.Add(curValue.ToString());
            }
            if (result.Count > 0)
            {
                yield return(result);
            }
        }
示例#11
0
 private static char EscapeQuotedString(System.IO.TextReader reader)
 {
     return((char)reader.Read());
 }
示例#12
0
文件: Lexer.cs 项目: zan00789/reko
        private Token ReadToken()
        {
            for (; ;)
            {
                int  ch = rdr.Peek();
                char c  = (char)ch;
                switch (st)
                {
                case State.StartOfLine:
                    if (ch == -1)
                    {
                        return(LightToken(TokenType.EOFile, State.StartOfLine));
                    }
                    switch (ch)
                    {
                    case ' ':
                    case '\t':
                        st = State.InitialWs;
                        rdr.Read();
                        break;

                    case '\r':
                        st = State.Cr;
                        rdr.Read();
                        break;

                    case '\n':
                        rdr.Read();
                        return(LightToken(TokenType.NL, State.StartOfLine));

                    default:
                        st = State.BetweenWs;
                        break;
                    }
                    break;

                case State.Cr:
                    st = State.StartOfLine;
                    if (c == '\n')
                    {
                        rdr.Read();
                    }
                    return(LightToken(TokenType.NL, State.StartOfLine));

                case State.InitialWs:
                    if (ch == -1)
                    {
                        return(LightToken(TokenType.EOFile, State.InitialWs));
                    }
                    switch (ch)
                    {
                    case ' ':
                    case '\t':
                        rdr.Read();
                        break;

                    default:
                        return(LightToken(TokenType.WS, State.BetweenWs));
                    }
                    break;

                case State.BetweenWs:
                    if (ch == -1)
                    {
                        return(new Token(TokenType.EOFile));
                    }
                    switch (ch)
                    {
                    case ' ':
                    case '\t':
                        rdr.Read();
                        break;

                    case '\r':
                        st = State.Cr;
                        rdr.Read();
                        break;

                    case '\n':
                        rdr.Read();
                        return(LightToken(TokenType.NL, State.StartOfLine));

                    case '"':
                        rdr.Read();
                        st = State.String;
                        break;

                    case ',':
                        rdr.Read();
                        return(LightToken(TokenType.COMMA, State.BetweenWs));

                    case '.':
                        rdr.Read();
                        return(LightToken(TokenType.DOT, State.BetweenWs));

                    case '#':
                        rdr.Read();
                        return(LightToken(TokenType.HASH, State.BetweenWs));

                    case '+':
                        rdr.Read();
                        return(LightToken(TokenType.PLUS, State.BetweenWs));

                    case '-':
                        rdr.Read();
                        return(LightToken(TokenType.MINUS, State.BetweenWs));

                    case '(':
                        rdr.Read();
                        return(LightToken(TokenType.LPAREN, State.BetweenWs));

                    case ')':
                        rdr.Read();
                        return(LightToken(TokenType.RPAREN, State.BetweenWs));

                    case ';':
                        rdr.Read();
                        st = State.Comment;
                        break;

                    case '$':
                        rdr.Read();
                        st = State.HexNumber;
                        break;

                    default:
                        if (Char.IsLetter(c) || c == '_')
                        {
                            sb.Append(c);
                            rdr.Read();
                            st = State.Id;
                            break;
                        }
                        if (Char.IsDigit(c))
                        {
                            sb.Append(c);
                            rdr.Read();
                            st = State.Integer;
                            break;
                        }
                        throw Unexpected(ch, c);
                    }
                    break;

                case State.Id:
                    if (ch == -1 || !Char.IsLetterOrDigit(c) && c != '_')
                    {
                        st = State.BetweenWs;
                        return(ClassifyTokenText());
                    }
                    rdr.Read();
                    sb.Append(c);
                    break;

                case State.String:
                    if (ch == -1)
                    {
                        throw new FormatException("Unterminated string constant.");
                    }
                    if (ch == '"')
                    {
                        rdr.Read();
                        return(BuildToken(TokenType.STRING, State.BetweenWs));
                    }
                    else
                    {
                        sb.Append(c);
                        rdr.Read();
                    }
                    break;

                case State.Integer:
                    if (ch == -1 || !Char.IsDigit(c))
                    {
                        st = State.BetweenWs;
                        return(BuildToken(TokenType.INTEGER, State.BetweenWs));
                    }
                    sb.Append(c);
                    rdr.Read();
                    break;

                case State.Comment:
                    if (ch == -1)
                    {
                        return(LightToken(TokenType.EOFile, State.BetweenWs));
                    }
                    rdr.Read();
                    if (c == '\r')
                    {
                        st = State.Cr;
                    }
                    else if (c == '\n')
                    {
                        return(LightToken(TokenType.NL, State.StartOfLine));
                    }
                    break;

                case State.HexNumber:
                    if (ch == -1)
                    {
                        return(HexToken(State.StartOfLine));
                    }
                    if ('0' <= c && c <= '9' ||
                        'a' <= c && c <= 'f' ||
                        'A' <= c && c <= 'F')
                    {
                        rdr.Read();
                        sb.Append(c);
                        break;
                    }
                    return(HexToken(State.StartOfLine));
                }
            }
            throw new NotImplementedException();
        }
示例#13
0
        /// <summary>
        /// Lexes and parses a JSON object as a hash table in the specified text reader.
        /// </summary>
        /// <typeparam name="TValue">The type of the values to deserialize.</typeparam>
        /// <param name="reader">The text reader to lex and parse an object from.</param>
        /// <param name="context">The parser context.</param>
        /// <param name="parseValue">The parser to use for values.</param>
        /// <returns>A hash table, if found; otherwise, a ParseException is thrown.</returns>
        /// <remarks>
        /// This method does not consume whitespace; the character at the specified start index in the string is expected to be the start of a valid JSON object.
        /// </remarks>
        internal static Dictionary <string, TValue> ParseAnyObject <TValue>(System.IO.TextReader reader, ParserContext context, ParseReaderFunc <TValue> parseValue)
        {
            Debug.Assert(reader.Peek() == '{');

            //
            // CONSIDER: Add support for different representations of objects, e.g. ExpandoObject from the DLR. For
            //           now, we'll go with the most obvious choice and users can wrap the resulting value in case
            //           they want to support dynamic behavior.
            //

            var res = new Dictionary <string, TValue>();

            reader.Read();

            SkipWhiteSpace(reader); // NB: We *have* to skip trailing whitespace after the { token.

            var c = reader.Peek();

            if (c < 0)
            {
                throw new ParseException("Unexpected end of stream when parsing object expecting an object body or '}' terminator.", -1, ParseError.PrematureEndOfInput);
            }

            if (c == '}')
            {
                reader.Read();
                SkipWhiteSpace(reader); // NB: We *have* to skip trailing whitespace after the } token.
                return(res);
            }

            while (c >= 0)
            {
                var key = ParseStringNonNull(reader);

                SkipWhiteSpace(reader); // NB: This skips leading whitespace before the : token; we can't rely on the trie to do it.

                c = reader.Peek();

                if (c < 0)
                {
                    throw new ParseException("Unexpected end of stream when parsing object expecting a ':' separator between a key name and a value.", -1, ParseError.PrematureEndOfInput);
                }

                if (c != ':')
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Unexpected character '{0}' encountered when parsing object expecting a ':' token to separate key name and a value.", (char)c), -1, ParseError.UnexpectedToken);
                }

                reader.Read();

                SkipWhiteSpace(reader); // NB: We *have* to skip trailing whitespace after the : token.

                //
                // NB: We're not using Add here in order to allow for duplicate keys. The last one in lexical order wins, which is
                //     consistent with behavior of other popular JSON frameworks and the behavior of our strongly typed object
                //     deserializer.
                //

                res[key] = parseValue(reader, context);

                //
                // CONSIDER: Parsers for primitives don't trim trailing whitespace. We could change this and eliminate the need to
                //           skip whitespace here ourselves. This trimming is duplicate work if we're dealing with objects or
                //           arrays which already guarantee trimming trailing whitespace.
                //

                SkipWhiteSpace(reader);

                c = reader.Peek();

                if (c < 0)
                {
                    throw new ParseException("Unexpected end of stream when parsing object.", -1, ParseError.PrematureEndOfInput);
                }

                switch (c)
                {
                case ',':
                    reader.Read();
                    SkipWhiteSpace(reader);     // NB: We *have* to skip trailing whitespace after the , token.
                    break;

                case '}':
                    reader.Read();
                    SkipWhiteSpace(reader);     // NB: We *have* to skip trailing whitespace after the } token.
                    return(res);

                default:
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Unexpected character '{0}' encountered when parsing object expecting either ',' or '}}'.", (char)c), -1, ParseError.UnexpectedToken);
                }

                c = reader.Peek();
            }

            throw new ParseException("Unexpected end of stream when parsing object and expecting a key.", -1, ParseError.PrematureEndOfInput);
        }
示例#14
0
        public static List <List <string> > ParseSimple(System.IO.TextReader reader, char delimiter, char qualifier)
        {
            List <List <string> > ls = new List <List <string> >();

            bool          inQuote = false;
            List <string> record  = new List <string>();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            while (reader.Peek() != -1)
            {
                var readChar = (char)reader.Read();

                if (readChar == '\n' || (readChar == '\r' && (char)reader.Peek() == '\n'))
                {
                    // If it's a \r\n combo consume the \n part and throw it away.
                    if (readChar == '\r')
                    {
                        reader.Read();
                    }

                    if (inQuote)
                    {
                        if (readChar == '\r')
                        {
                            sb.Append('\r');
                        }
                        sb.Append('\n');
                    }
                    else
                    {
                        if (record.Count > 0 || sb.Length > 0)
                        {
                            record.Add(sb.ToString());
                            sb.Clear();
                        }

                        if (record.Count > 0)
                        {
                            // yield return record;
                            ls.Add(record);
                        }


                        record = new List <string>(record.Count);
                    }
                }
                else if (sb.Length == 0 && !inQuote)
                {
                    if (readChar == qualifier)
                    {
                        inQuote = true;
                    }
                    else if (readChar == delimiter)
                    {
                        record.Add(sb.ToString());
                        sb.Clear();
                    }
                    else if (char.IsWhiteSpace(readChar))
                    {
                        // Ignore leading whitespace
                    }
                    else
                    {
                        sb.Append(readChar);
                    }
                }
                else if (readChar == delimiter)
                {
                    if (inQuote)
                    {
                        sb.Append(delimiter);
                    }
                    else
                    {
                        record.Add(sb.ToString());
                        sb.Clear();
                    }
                }
                else if (readChar == qualifier)
                {
                    if (inQuote)
                    {
                        if ((char)reader.Peek() == qualifier)
                        {
                            reader.Read();
                            sb.Append(qualifier);
                        }
                        else
                        {
                            inQuote = false;
                        }
                    }
                    else
                    {
                        sb.Append(readChar);
                    }
                }
                else
                {
                    sb.Append(readChar);
                }
            }

            if (record.Count > 0 || sb.Length > 0)
            {
                record.Add(sb.ToString());
            }

            if (record.Count > 0)
            {
                // yield return record;
                ls.Add(record);
            }

            return(ls);
        }
示例#15
0
        protected void FillBuff()
        {
            if (maxNextCharInd == available)
            {
                if (available == bufsize)
                {
                    if (tokenBegin > 2048)
                    {
                        bufpos    = maxNextCharInd = 0;
                        available = tokenBegin;
                    }
                    else if (tokenBegin < 0)
                    {
                        bufpos = maxNextCharInd = 0;
                    }
                    else
                    {
                        ExpandBuff(false);
                    }
                }
                else if (available > tokenBegin)
                {
                    available = bufsize;
                }
                else if ((tokenBegin - available) < 2048)
                {
                    ExpandBuff(true);
                }
                else
                {
                    available = tokenBegin;
                }
            }

            int i;

            try
            {
                if ((i = inputStream.Read(buffer, maxNextCharInd,
                                          available - maxNextCharInd)) == -1)
                {
                    inputStream.Close();
                    throw new System.IO.IOException();
                }
                else
                {
                    maxNextCharInd += i;
                }
                return;
            }
            catch (System.IO.IOException)
            {
                --bufpos;
                Backup(0);
                if (tokenBegin == -1)
                {
                    tokenBegin = bufpos;
                }
                throw;
            }
        }
示例#16
0
        public static bool Match(System.IO.TextReader tr)
        {
            int ch;

            goto state0;
state0:
            {
                ch = tr.Read();
                if (ch == 'a')
                {
                    goto state1;
                }
                return(false);
            }
state1:
            {
                ch = tr.Read();
                if (ch == 's')
                {
                    goto state2;
                }
                return(false);
            }
state2:
            {
                ch = tr.Read();
                if (ch == 'd')
                {
                    goto state3;
                }
                return(false);
            }
state3:
            {
                ch = tr.Read();
                if (ch == 'f')
                {
                    goto state4;
                }
                return(false);
            }
state4:
            {
                ch = tr.Read();
                if (ch == '2')
                {
                    goto state5;
                }
                if (ch == '3')
                {
                    goto state6;
                }
                if (ch == '4')
                {
                    goto state7;
                }
                return(ch == -1);
            }
state5:
            {
                ch = tr.Read();
                if (ch == '2')
                {
                    goto state5;
                }
                if (ch == '3')
                {
                    goto state6;
                }
                if (ch == '4')
                {
                    goto state7;
                }
                return(ch == -1);
            }
state6:
            {
                ch = tr.Read();
                if (ch == '2')
                {
                    goto state5;
                }
                if (ch == '3')
                {
                    goto state6;
                }
                if (ch == '4')
                {
                    goto state7;
                }
                return(ch == -1);
            }
state7:
            {
                ch = tr.Read();
                if (ch == '2')
                {
                    goto state5;
                }
                if (ch == '3')
                {
                    goto state6;
                }
                if (ch == '4')
                {
                    goto state7;
                }
                return(ch == -1);
            }
        }
示例#17
0
        private void SendeStreamAnPlotter(System.IO.TextReader datenquelle, long länge)
        {
            DateTime StartZeitpunkt   = DateTime.Now;
            TimeSpan SendeZeit        = TimeSpan.Zero;
            DateTime LetztesETAUpdate = DateTime.Now;

            PlotterCom.StaticLogger.Log("Sende Stream an Plotter!", 6);

            long   geschriebeneBytes = 0;
            int    geleseneBytes     = 0;
            double Fortschritt       = 0;

            char[] buffer     = null;
            int    blockGröße = 8;

            if (datenquelle == null)
            {
                PlotterCom.StaticLogger.Log("Kann keine Daten senden. Datenquelle ist null!", 4);
                return;
            }

            _SendenAbbrechen = false;

            button_Senden.Enabled          = false;
            button_SpeichernAls.Enabled    = false;
            button_UmschrRechteck.Enabled  = false;
            button_SendenAbbrechen.Enabled = true;
            button_DirektSenden.Enabled    = false;
            button_Abbruch.Enabled         = false;
            button_Optimieren.Enabled      = false;
            button_Analysieren.Enabled     = false;
            button_Öffnen.Enabled          = false;
            button_Schließen.Enabled       = false;
            button_Viewer.Enabled          = false;
            button_Skalieren.Enabled       = false;
            button_Speichern.Enabled       = false;
            button_Verschieben.Enabled     = false;
            button_UmschrRechteck.Enabled  = false;
            button_Verbinden.Enabled       = false;
            button_Dubletten.Enabled       = false;


            if (_Port == null || !_Port.IsOpen)
            {
                PlotterCom.StaticLogger.Log("Der Port exisitiert noch nicht. Erestelle neuen SerialPort!", 6);

                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(50);
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(50);
                System.Windows.Forms.Application.DoEvents();

                _Port           = new System.IO.Ports.SerialPort();
                _Port.PortName  = PlotterCom.ConfigManager.Config.ComPort;
                _Port.Parity    = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), PlotterCom.ConfigManager.Config.ComParity);
                _Port.BaudRate  = PlotterCom.ConfigManager.Config.ComBaudRate;
                _Port.DataBits  = PlotterCom.ConfigManager.Config.ComDataBits;
                _Port.Handshake = (System.IO.Ports.Handshake)(Enum.Parse(typeof(System.IO.Ports.Handshake), PlotterCom.ConfigManager.Config.ComHandshake));
                _Port.StopBits  = (System.IO.Ports.StopBits)(Enum.Parse(typeof(System.IO.Ports.StopBits), PlotterCom.ConfigManager.Config.ComStopBits));


                if (Array.IndexOf(System.IO.Ports.SerialPort.GetPortNames(), _Port.PortName) == -1)
                {
                    MessageBox.Show("Der in den Einstellungen hinterlegte Port \"" + _Port.PortName +
                                    "\" ist nicht verfügbar. Bitte die Port-Einstellungen anpassen!",
                                    "Fehler!", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    button_Senden.Enabled          = true;
                    button_SpeichernAls.Enabled    = true;
                    button_UmschrRechteck.Enabled  = true;
                    button_SendenAbbrechen.Enabled = true;
                    button_DirektSenden.Enabled    = true;
                    button_Abbruch.Enabled         = true;
                    button_Optimieren.Enabled      = true;
                    button_Analysieren.Enabled     = true;
                    button_Öffnen.Enabled          = true;
                    button_Schließen.Enabled       = true;
                    button_Viewer.Enabled          = true;

                    ButtonsAnAus();

                    label_Senden.Text        = "Bereit...";
                    progressBar_Senden.Value = 0;

                    button_SendenAbbrechen.Enabled = false;

                    return;
                }

                try {
                    PlotterCom.StaticLogger.Log("Versuche den Port zu öffnen!", 6);
                    _Port.Open();
                } catch (Exception ex) {
                    PlotterCom.StaticLogger.Log("Konnte den Port nicht öffnen!", 4);
                    PlotterCom.StaticLogger.Log("Fehlermeldung: " + ex.Message, 4);
                    return;
                }

                PlotterCom.StaticLogger.Log("Port wurde neu geöffnet. Warte 100ms auf Bereitschaft!", 7);
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(50);
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(50);
                System.Windows.Forms.Application.DoEvents();
            }
            else
            {
                _Port.DiscardOutBuffer();
            }

            buffer = new char[blockGröße];

            while (!_SendenAbbrechen)
            {
                System.Windows.Forms.Application.DoEvents();

                while (!_Port.CtsHolding)
                {
                    toolStripStatusLabel.Text = "Warte...";

                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();

                    if (_SendenAbbrechen)
                    {
                        break;
                    }

                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();

                    if (_SendenAbbrechen)
                    {
                        break;
                    }

                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                    System.Windows.Forms.Application.DoEvents();

                    if (_SendenAbbrechen)
                    {
                        break;
                    }
                } // Warten.

                toolStripStatusLabel.Text = "Sende...";

                // Lese einen Datenblock.
                geleseneBytes = datenquelle.Read(buffer, 0, blockGröße);

                if (geleseneBytes == 0)
                {
                    break;
                }

                // Sende einen Datenblock
                try {
                    _Port.Write(buffer, 0, blockGröße);
                } catch (Exception ex) {
                    PlotterCom.StaticLogger.Log("Konnte nicht senden!", 4);
                    PlotterCom.StaticLogger.Log("Fehlermeldung: " + ex.Message, 4);
                }

                geschriebeneBytes += blockGröße;

                if ((länge > 0) && (länge > geleseneBytes))
                {
                    if (geschriebeneBytes < länge)
                    {
                        Fortschritt = ((double)geschriebeneBytes / (double)(länge + 4D));
                    }
                    else
                    {
                        Fortschritt = 1;
                    }

                    SendeZeit = DateTime.Now - StartZeitpunkt;

                    progressBar_Senden.Value = (int)(Fortschritt * 100D);
                    label_Senden.Text        = "Fortschritt: " + (Fortschritt * 100D).ToString("00.0") + "%";

                    if ((DateTime.Now - LetztesETAUpdate) > TimeSpan.FromSeconds(1))
                    {
                        LetztesETAUpdate = DateTime.Now;

                        if (SendeZeit > TimeSpan.FromSeconds(4) && Fortschritt > 0.001D)
                        {
                            double   Sekunden = SendeZeit.TotalSeconds;
                            TimeSpan RestZeit;
                            Sekunden = Sekunden * (1D / Fortschritt);
                            RestZeit = TimeSpan.FromSeconds(Math.Abs(Sekunden - SendeZeit.TotalSeconds));
                            //label_ETA.Text = "ETA: " + RestZeit.ToString("hh\\:mm\\:ss") + " ";
                        }
                        else
                        {
                            label_ETA.Text = "ETA: berechne...  ";
                        }
                    }
                }

                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(12); // 10 reicht auch. 12 als Sicherheit...
                System.Windows.Forms.Application.DoEvents();
            } // while !EndOfStream

            button_Senden.Enabled          = true;
            button_SpeichernAls.Enabled    = true;
            button_UmschrRechteck.Enabled  = true;
            button_SendenAbbrechen.Enabled = true;
            button_DirektSenden.Enabled    = true;
            button_Abbruch.Enabled         = true;
            button_Optimieren.Enabled      = true;
            button_Analysieren.Enabled     = true;
            button_Öffnen.Enabled          = true;
            button_Schließen.Enabled       = true;
            button_Viewer.Enabled          = true;

            ButtonsAnAus();

            label_Senden.Text        = "Bereit...";
            progressBar_Senden.Value = 0;

            button_SendenAbbrechen.Enabled = false;
        }
示例#18
0
        private static string ReadSymbol(System.IO.TextReader reader)
        {
            System.Text.StringBuilder tokenBuilder = new System.Text.StringBuilder();

            int n;

            while ((n = reader.Peek()) != -1)
            {
                char ch = (char)n;

                if (ch == '(')
                {
                    reader.Read();
                    return(tokenBuilder.ToString() + "(" + ReadFunction(reader) + ")");
                }
                else if (ch == ' ')
                {
                    reader.Read();

                    if (tokenBuilder.Length > 0)
                    {
                        return(tokenBuilder.ToString());
                    }
                }
                else if (ch == '.')
                {
                    if (tokenBuilder.Length > 0)
                    {
                        return(tokenBuilder.ToString());
                    }
                }
                else if (ch == '\r')
                {
                    reader.Read();

                    if (tokenBuilder.Length > 0)
                    {
                        return(tokenBuilder.ToString());
                    }
                }
                else if (ch == '\n')
                {
                    reader.Read();

                    if (tokenBuilder.Length > 0)
                    {
                        return(tokenBuilder.ToString());
                    }
                }
                else if (ch == ',')
                {
                    if (tokenBuilder.Length == 0)
                    {
                        reader.Read();
                        return(",");
                    }
                    else
                    {
                        //if (reader.Peek() != -1 && (char)reader.Peek() == ' ')
                        //{
                        //    reader.Read();
                        //}
                        return(tokenBuilder.ToString());
                    }
                }
                else
                {
                    reader.Read();
                    tokenBuilder.Append(ch);
                }
            }

            return(tokenBuilder.ToString());
        }
示例#19
0
        private string ScanGramarTokenString(System.IO.TextReader reader)
        {
            StringBuilder builder = new StringBuilder();
            char          c;
            Token         tk;

            while (reader.Peek() != -1)
            {
                c = (char)reader.Peek();
                if (char.IsWhiteSpace(c))
                {
                    break;
                }
                else
                {
                    string str = builder.ToString();
                    if (simpleTokens.TryGetValue(c, out tk))
                    {
                        break;
                    }
                    if (complexTokens.TryGetValue(str, out tk))
                    {
                        if (complexTokens.TryGetValue(str + c, out tk))
                        {
                            reader.Read();
                            builder.Append(c);
                        }
                        break;
                    }

                    if (gramar.Contains(c) && str != string.Empty)
                    {
                        if (complexTokens.TryGetValue(str + c, out tk))
                        {
                            reader.Read();
                            builder.Append(c);
                        }
                        break;
                    }
                    reader.Read();
                    builder.Append(c);
                }
            }
            string input = builder.ToString();
            Token  token;

            if (!complexTokens.TryGetValue(input, out token))
            {
                if (input.StartsWith("[") && input.EndsWith("]"))
                {
                    return(input);
                }
                else
                {
                    return("[" + input + "]");
                }
            }
            else
            {
                return(builder.ToString());
            }
        }
示例#20
0
        /// <summary>
        /// Lexes and parses a JSON array as a System.Object[] in the specified string starting from the specified index.
        /// </summary>
        /// <param name="reader">The text reader to lex and parse an array from.</param>
        /// <param name="context">The parser context.</param>
        /// <returns>An array, if found; otherwise, a ParseException is thrown.</returns>
        /// <remarks>
        /// This method does not consume whitespace; the character at the specified start index in the string is expected to be the start of a valid JSON array.
        /// </remarks>
        private static object[] ParseAnyArray(System.IO.TextReader reader, ParserContext context)
        {
            Debug.Assert(reader.Peek() == '[');

            reader.Read();

            SkipWhiteSpace(reader); // NB: We *have* to skip trailing whitespace after the [ token.

            var c = reader.Peek();

            if (c < 0)
            {
                throw new ParseException("Unexpected end of stream when parsing array.", -1, ParseError.PrematureEndOfInput);
            }

            if (c == ']')
            {
                reader.Read();
                SkipWhiteSpace(reader); // NB: We *have* to skip trailing whitespace after the ] token.
                return(ArrayBuilder <object> .Empty);
            }

            var builder = ArrayBuilder.Create <object>();

            while (c >= 0)
            {
                builder.Add(ParseAny(reader, context));

                //
                // CONSIDER: Parsers for primitives don't trim trailing whitespace. We could change this and eliminate the need to
                //           skip whitespace here ourselves. This trimming is duplicate work if we're dealing with objects or
                //           arrays which already guarantee trimming trailing whitespace.
                //

                SkipWhiteSpace(reader);

                c = reader.Peek();

                if (c < 0)
                {
                    throw new ParseException("Unexpected end of stream when parsing array.", -1, ParseError.PrematureEndOfInput);
                }

                switch (c)
                {
                case ',':
                    reader.Read();
                    SkipWhiteSpace(reader);     // NB: We *have* to skip trailing whitespace after the , token.
                    break;

                case ']':
                    reader.Read();
                    SkipWhiteSpace(reader);     // NB: We *have* to skip trailing whitespace after the ] token.
                    return(builder.ToArray());

                default:
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Unexpected character '{0}' encountered when parsing array expecting either ',' or ']'.", (char)c), -1, ParseError.UnexpectedToken);
                }

                c = reader.Peek();
            }

            throw new ParseException("Unexpected end of stream when parsing array.", -1, ParseError.PrematureEndOfInput);
        }
示例#21
0
        /// <summary>
        /// Lexes and parses a JSON String as a System.Char in the specified text reader.
        /// </summary>
        /// <param name="reader">The text reader to lex and parse a Char from.</param>
        /// <param name="_">The parser context.</param>
        /// <returns>A System.String value, if found; otherwise, a ParseException is thrown.</returns>
        /// <remarks>
        /// This method does not consume whitespace; the character at the specified start index in the string is expected to be the start of a valid JSON String.
        /// Valid inputs for Char values are considered to be single-character JSON Strings. Note that JSON does not support a ' token for the start of a character.
        /// </remarks>
        internal static char ParseChar(System.IO.TextReader reader, ParserContext _ = null)
        {
            var c = reader.Read();

            if (c != '"')
            {
                throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected Char. Unexpected character '{0}' found when '\"' was expected.", c), -1, ParseError.UnexpectedToken);
            }

            c = reader.Read();

            char res;

            switch (c)
            {
            case '\\':
                c = reader.Read();

                switch (c)
                {
                case '"':
                case '\\':
                case '/':
                    res = (char)c;
                    break;

                case 'b':
                    res = '\b';
                    break;

                case 'f':
                    res = '\f';
                    break;

                case 'n':
                    res = '\n';
                    break;

                case 'r':
                    res = '\r';
                    break;

                case 't':
                    res = '\t';
                    break;

                case 'u':
                    var u0 = reader.Read();
                    var u1 = reader.Read();
                    var u2 = reader.Read();
                    var u3 = reader.Read();

                    if (!ToHex(ref u0) || !ToHex(ref u1) || !ToHex(ref u2) || !ToHex(ref u3))
                    {
                        throw new ParseException("Expected Char. Expected hexadecimal character escape sequence after '\\u' escape character.", -1, ParseError.UnexpectedToken);
                    }

                    res = (char)((u0 << 12) + (u1 << 8) + (u2 << 4) + u3);
                    break;

                default:
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected Char. Unexpected character '{0}' found after '\\' escape character.", c), -1, ParseError.UnexpectedToken);
                }
                break;

            case '"':
                //
                // CONSIDER: Introduce a configuration option in the parser context to allow empty strings? Would it be null and/or some configurable character a la '\0'?
                //

                throw new ParseException("Expected Char. Unexpected empty string literal found.", -1, ParseError.UnexpectedToken);

            default:
                if (char.IsControl((char)c))
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected Char. Unexpected control character '{0}' found in string literal.", c), -1, ParseError.UnexpectedToken);
                }

                res = (char)c;
                break;
            }

            c = reader.Read();

            if (c == '\"')
            {
                return(res);
            }

            throw new ParseException("Expected Char. Unexpected string termination found.", -1, ParseError.PrematureEndOfInput);
        }
示例#22
0
            public override int yylex()
            {
                char ch;
                int  ord = reader.Read();

                //
                // Must check for EOF
                //
                if (ord == -1)
                {
                    return((int)Tokens.EOF);
                }
                else
                {
                    ch = (char)ord;
                }

                if (ch == '{' && reader.Peek() == '%')
                {
                    reader.Read();
                    inTag = true;

                    // Consume Whitespace
                    ch = (char)reader.Read();
                    while (char.IsWhiteSpace(ch))
                    {
                        ch = (char)reader.Read();
                    }

                    StringBuilder text = new StringBuilder();
                    text.Append(ch);

                    while (char.IsLetter((char)reader.Peek()))
                    {
                        text.Append((char)reader.Read());
                    }

                    switch (text.ToString())
                    {
                    case "block":
                        return((int)Tokens.TAG_START_BLOCK);

                    case "endblock":
                        return((int)Tokens.TAG_START_ENDBLOCK);

                    case "if":
                        return((int)Tokens.TAG_START_IF);

                    case "endif":
                        return((int)Tokens.TAG_START_ENDIF);

                    case "else":
                        return((int)Tokens.TAG_START_ELSE);

                    case "for":
                        return((int)Tokens.TAG_START_FOR);

                    case "endfor":
                        return((int)Tokens.TAG_START_ENDFOR);

                    case "using":
                        return((int)Tokens.TAG_START_USING);

                    case "context":
                        return((int)Tokens.TAG_START_CONTEXT);

                    case "extends":
                        return((int)Tokens.TAG_START_EXTENDS);

                    default:
                        return((int)Tokens.error);
                    }
                }
                else if (ch == '%' && reader.Peek() == '}')
                {
                    reader.Read();
                    inTag = false;
                    return((int)Tokens.TAG_END);
                }
                else if (ch == '{' && reader.Peek() == '{')
                {
                    reader.Read();
                    inTag = true;
                    return((int)Tokens.VALUE_START);
                }
                else if (ch == '}' && reader.Peek() == '}')
                {
                    reader.Read();
                    inTag = false;
                    return((int)Tokens.VALUE_END);
                }
                else if (!inTag)
                {
                    StringBuilder text = new StringBuilder();
                    text.Append(ch);

                    while (reader.Peek() >= 0 && reader.Peek() != '{')
                    {
                        ch = (char)reader.Read();
                        text.Append(ch);
                    }

                    yylval = text.ToString();
                    return((int)Tokens.TEXT);
                }
                else if (char.IsWhiteSpace(ch) && inTag)
                {
                    return(yylex());
                }
                else if (char.IsLetter(ch) && inTag)
                {
                    char          peek;
                    StringBuilder text = new StringBuilder();
                    text.Append(ch);

                    while (char.IsLetter(peek = (char)reader.Peek()))
                    {
                        text.Append((char)reader.Read());
                    }

                    switch (text.ToString())
                    {
                    case "in":
                        return((int)Tokens.KEY_IN);

                    default:
                        yylval = text.ToString();
                        return((int)Tokens.TEXT);
                    }
                }
                else
                {
                    yylval = ch.ToString();
                    return((int)Tokens.TEXT);
                }
            }
        private double EvalStatement()
        {
            double result = this.EvalNextValue();

            if (_current == ')')
            {
                int c = _reader.Read();
                if (c >= 0)
                {
                    _current = (char)c;
                }
                _parenCount--;
                return(result);
            }

            for (int i = _current; i >= 0; i = _reader.Read())
            {
                _current = (char)i;

                if (char.IsWhiteSpace(_current))
                {
                    continue;
                }

                switch (_current)
                {
                case '+':
                    result += this.EvalNextValue();
                    break;

                case '*':
                    result *= this.EvalNextValue();
                    break;

                case '-':
                    result -= this.EvalNextValue();
                    break;

                case '/':
                    result /= this.EvalNextValue();
                    break;

                case '^':
                    result = Math.Pow(result, this.EvalNextValue());
                    break;

                case '%':
                    result %= this.EvalNextValue();
                    break;

                case '=':
                {
                    if (_reader.Peek() == '=')
                    {
                        _reader.Read();
                        result = MathUtil.FuzzyEqual((float)result, (float)this.EvalNextValue()) ? 1d : 0d;
                    }
                    else
                    {
                        result = MathUtil.FuzzyEqual((float)result, (float)this.EvalNextValue()) ? 1d : 0d;
                    }
                }
                break;

                case '<':
                {
                    if (_reader.Peek() == '=')
                    {
                        _reader.Read();
                        result = (result <= this.EvalNextValue()) ? 1d : 0d;
                    }
                    else
                    {
                        result = (result < this.EvalNextValue()) ? 1d : 0d;
                    }
                }
                break;

                case '>':
                {
                    if (_reader.Peek() == '=')
                    {
                        _reader.Read();
                        result = (result >= this.EvalNextValue()) ? 1d : 0d;
                    }
                    else
                    {
                        result = (result > this.EvalNextValue()) ? 1d : 0d;
                    }
                }
                break;

                case '|':
                {
                    if (_reader.Peek() == '|')
                    {
                        _reader.Read();
                        result = (ConvertUtil.ToBool(result) || ConvertUtil.ToBool(this.EvalNextValue())) ? 1d : 0d;
                    }
                    else
                    {
                        result = (double)((int)result | (int)this.EvalNextValue());
                    }
                }
                break;

                case '&':
                {
                    if (_reader.Peek() == '&')
                    {
                        _reader.Read();
                        result = (ConvertUtil.ToBool(result) && ConvertUtil.ToBool(this.EvalNextValue())) ? 1d : 0d;
                    }
                    else
                    {
                        result = (double)((int)result & (int)this.EvalNextValue());
                    }
                }
                break;

                case ')':
                    //reached the end of the statement
                    i = _reader.Read();
                    if (i >= 0)
                    {
                        _current = (char)i;
                    }
                    return(result);
                }

                if (_current == ')')
                {
                    int c = _reader.Read();
                    if (c >= 0)
                    {
                        _current = (char)c;
                    }
                    _parenCount--;
                    return(result);
                }
            }

            //ran out of statement with no errors, must be the end
            return(result);
        }
        private double EvalStatement()
        {
            int i = _reader.Read();

            for (; i >= 0 && char.IsWhiteSpace((char)i); i = _reader.Read())
            {
            }
            if (i < 0)
            {
                return(0d);
            }

            _current = (char)i;
            if (!IsValidWordPrefix(_current))
            {
                throw new System.InvalidOperationException("Failed to parse the command.");
            }
            double result = this.EvalNextValue();

            if (_parenCount > 0 && _current == ')')
            {
                _parenCount--;
                return(result);
            }

            for (i = _current; i >= 0; i = _reader.Read())
            {
                _current = (char)i;

                if (char.IsWhiteSpace(_current))
                {
                    continue;
                }

                switch (_current)
                {
                case '+':
                    result += this.EvalStatement();
                    break;

                case '*':
                    result *= this.EvalStatement();
                    break;

                case '-':
                    result -= this.EvalStatement();
                    break;

                case '/':
                    result /= this.EvalStatement();
                    break;

                case '^':
                    result = Math.Pow(result, this.EvalStatement());
                    break;

                case '%':
                    result %= this.EvalStatement();
                    break;

                case '=':
                {
                    if (_reader.Peek() == '=')
                    {
                        _reader.Read();
                        result = MathUtil.FuzzyEqual((float)result, (float)this.EvalStatement()) ? 1d : 0d;
                    }
                    else
                    {
                        result = MathUtil.FuzzyEqual((float)result, (float)this.EvalStatement()) ? 1d : 0d;
                    }
                }
                break;

                case '<':
                {
                    if (_reader.Peek() == '=')
                    {
                        _reader.Read();
                        result = (result <= this.EvalStatement()) ? 1d : 0d;
                    }
                    else
                    {
                        result = (result < this.EvalStatement()) ? 1d : 0d;
                    }
                }
                break;

                case '>':
                {
                    if (_reader.Peek() == '=')
                    {
                        _reader.Read();
                        result = (result >= this.EvalStatement()) ? 1d : 0d;
                    }
                    else
                    {
                        result = (result > this.EvalStatement()) ? 1d : 0d;
                    }
                }
                break;

                case '|':
                {
                    if (_reader.Peek() == '|')
                    {
                        _reader.Read();
                        result = (ConvertUtil.ToBool(result) || ConvertUtil.ToBool(this.EvalStatement())) ? 1d : 0d;
                    }
                    else
                    {
                        result = (double)((int)result | (int)this.EvalStatement());
                    }
                }
                break;

                case '&':
                {
                    if (_reader.Peek() == '&')
                    {
                        _reader.Read();
                        result = (ConvertUtil.ToBool(result) && ConvertUtil.ToBool(this.EvalStatement())) ? 1d : 0d;
                    }
                    else
                    {
                        result = (double)((int)result & (int)this.EvalStatement());
                    }
                }
                break;

                case ')':
                    //reached the end of the statement
                    return(result);
                }
            }

            //ran out of statement with no errors, must be the end
            return(result);
        }
示例#25
0
        private void SendeStreamAnNetzwetrk(System.IO.TextReader datenquelle, long länge)
        {
            DateTime StartZeitpunkt   = DateTime.Now;
            TimeSpan SendeZeit        = TimeSpan.Zero;
            DateTime LetztesETAUpdate = DateTime.Now;

            PlotterCom.StaticLogger.Log("Sende Stream an Plotter!", 6);

            long   geschriebeneBytes = 0;
            int    geleseneBytes     = 0;
            double Fortschritt       = 0;

            char[] buffer     = null;
            int    blockGröße = 16;

            if (datenquelle == null)
            {
                PlotterCom.StaticLogger.Log("Kann keine Daten senden. Datenquelle ist null!", 4);
                return;
            }

            _SendenAbbrechen = false;

            button_Senden.Enabled          = false;
            button_SpeichernAls.Enabled    = false;
            button_UmschrRechteck.Enabled  = false;
            button_SendenAbbrechen.Enabled = true;
            button_DirektSenden.Enabled    = false;
            button_Abbruch.Enabled         = false;
            button_Optimieren.Enabled      = false;
            button_Analysieren.Enabled     = false;
            button_Öffnen.Enabled          = false;
            button_Schließen.Enabled       = false;
            button_Viewer.Enabled          = false;
            button_Skalieren.Enabled       = false;
            button_Speichern.Enabled       = false;
            button_Verschieben.Enabled     = false;
            button_UmschrRechteck.Enabled  = false;
            button_Verbinden.Enabled       = false;
            button_Dubletten.Enabled       = false;



            try {
                PlotterCom.StaticLogger.Log("Versuche den Port zu öffnen!", 6);
                // tcpopen
            } catch (Exception ex) {
                PlotterCom.StaticLogger.Log("Konnte den Port nicht öffnen!", 4);
                PlotterCom.StaticLogger.Log("Fehlermeldung: " + ex.Message, 4);
                return;
            }

            PlotterCom.StaticLogger.Log("Port wurde neu geöffnet. Warte 100ms auf Bereitschaft!", 7);
            System.Windows.Forms.Application.DoEvents();
            System.Threading.Thread.Sleep(50);
            System.Windows.Forms.Application.DoEvents();
            System.Threading.Thread.Sleep(50);
            System.Windows.Forms.Application.DoEvents();

            IPAddress  ipAddress  = IPAddress.Parse("10.0.1.134");
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8888);

            System.Net.Sockets.NetworkStream nwStream;


            System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
            tcpClient.NoDelay        = true;
            tcpClient.SendBufferSize = 12;

            tcpClient.Connect(ipEndPoint);

            nwStream = tcpClient.GetStream();

            buffer = new char[blockGröße];

            while (!_SendenAbbrechen)
            {
                System.Windows.Forms.Application.DoEvents();



                toolStripStatusLabel.Text = "Sende...";

                // Lese einen Datenblock.
                geleseneBytes = datenquelle.Read(buffer, 0, blockGröße);

                if (geleseneBytes == 0)
                {
                    break;
                }

                // Sende einen Datenblock
                try {
                    string str = new String(buffer);

                    nwStream.Write(Encoding.ASCII.GetBytes(buffer, 0, blockGröße), 0, blockGröße);
                    nwStream.Flush();
                } catch (Exception ex) {
                    PlotterCom.StaticLogger.Log("Konnte nicht senden!", 4);
                    PlotterCom.StaticLogger.Log("Fehlermeldung: " + ex.Message, 4);
                }

                geschriebeneBytes += blockGröße;

                if ((länge > 0) && (länge > geleseneBytes))
                {
                    if (geschriebeneBytes < länge)
                    {
                        Fortschritt = ((double)geschriebeneBytes / (double)(länge + 4D));
                    }
                    else
                    {
                        Fortschritt = 1;
                    }

                    SendeZeit = DateTime.Now - StartZeitpunkt;

                    progressBar_Senden.Value = (int)(Fortschritt * 100D);
                    label_Senden.Text        = "Fortschritt: " + (Fortschritt * 100D).ToString("00.0") + "%";

                    if ((DateTime.Now - LetztesETAUpdate) > TimeSpan.FromSeconds(1))
                    {
                        LetztesETAUpdate = DateTime.Now;

                        if (SendeZeit > TimeSpan.FromSeconds(4) && Fortschritt > 0.001D)
                        {
                            double   Sekunden = SendeZeit.TotalSeconds;
                            TimeSpan RestZeit;
                            Sekunden = Sekunden * (1D / Fortschritt);
                            RestZeit = TimeSpan.FromSeconds(Math.Abs(Sekunden - SendeZeit.TotalSeconds));
                            //label_ETA.Text = "ETA: " + RestZeit.ToString("hh\\:mm\\:ss") + " ";
                        }
                        else
                        {
                            label_ETA.Text = "ETA: berechne...  ";
                        }
                    }
                }

                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(12); // 10 reicht auch. 12 als Sicherheit...
                System.Windows.Forms.Application.DoEvents();
            } // while !EndOfStream

            button_Senden.Enabled          = true;
            button_SpeichernAls.Enabled    = true;
            button_UmschrRechteck.Enabled  = true;
            button_SendenAbbrechen.Enabled = true;
            button_DirektSenden.Enabled    = true;
            button_Abbruch.Enabled         = true;
            button_Optimieren.Enabled      = true;
            button_Analysieren.Enabled     = true;
            button_Öffnen.Enabled          = true;
            button_Schließen.Enabled       = true;
            button_Viewer.Enabled          = true;

            ButtonsAnAus();

            label_Senden.Text        = "Bereit...";
            progressBar_Senden.Value = 0;

            button_SendenAbbrechen.Enabled = false;
        }
示例#26
0
        /// <summary>
        /// Lexes and parses a JSON Number as a System.Int64 in the specified text reader.
        /// </summary>
        /// <param name="reader">The text reader to lex and parse a System.Int64 from.</param>
        /// <param name="context">The parser context.</param>
        /// <returns>A System.Int64 value, if found; otherwise, a ParseException is thrown.</returns>
        /// <remarks>
        /// This method does not consume whitespace; the character at the specified start index in the string is expected to be the start of a valid JSON Number.
        /// </remarks>
        internal static Int64 ParseInt64(System.IO.TextReader reader, ParserContext context)
        {
            var res = default(Int64);

            var c = reader.Read();

            if (c < 0)
            {
                throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected {0}. Unexpected string termination found.", typeof(Int64).Name), -1, ParseError.PrematureEndOfInput);
            }

            var neg = false;

            if (c == '-')
            {
                neg = true;
                c   = reader.Read();

                if (c < 0)
                {
                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected {0}. Unexpected string termination found after '-' sign.", typeof(Int64).Name), -1, ParseError.PrematureEndOfInput);
                }
            }

            if (c == '0')
            {
                return(res);
            }
            else if (c >= '1' && c <= '9')
            {
                res = (Int64)(c - '0');
            }
            else
            {
                throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected {0}. Unexpected character '{1}' found at start of number.", typeof(Int64).Name, c), -1, ParseError.UnexpectedToken);
            }

            while (((c = reader.Peek()) >= '0') && c <= '9')
            {
                reader.Read();

                var next = (Int64)(res * 10 + (Int64)(c - '0'));

                if (next < res)
                {
                    if (next == Int64.MinValue && neg)
                    {
                        res = next;
                        continue;
                    }

                    throw new ParseException(string.Format(CultureInfo.InvariantCulture, "Expected {0}. The JSON number does not fit in a value of type {0}.", typeof(Int64).Name), -1, ParseError.UnexpectedToken);
                }
                else
                {
                    res = next;
                }
            }

            return(neg ? (Int64)(-res) : res);
        }
示例#27
0
        public RTFTokenType PeekTokenType()
        {
            int c = myReader.Peek();

            while (c == '\r' ||
                   c == '\n' ||
                   c == '\t' ||
                   c == '\0')
            {
                c = myReader.Read();
                c = myReader.Peek();
            }
            if (c == EOF)
            {
                return(RTFTokenType.Eof);
            }
            else
            {
                switch (c)
                {
                case '{':
                    return(RTFTokenType.GroupStart);

                case '}':
                    return(RTFTokenType.GroupEnd);

                case '\\':
                    return(RTFTokenType.Control);

                default:
                    return(RTFTokenType.Text);
                }
            }
        }
示例#28
0
        public Token(System.IO.TextReader reader)
        {
            type = Type.EOF;

            try
            {
                bool done          = false;
                bool foundNonWhite = false;

                do
                {
                    int c = reader.Peek();

                    if (c == -1)
                    {
                        break;
                    }

                    if (!foundNonWhite && Char.IsWhiteSpace((char)c))
                    {
                        reader.Read();

                        if ((char)c == '\n')
                        {
                            type = Type.Newline;
                            return;
                        }
                    }
                    else
                    {
                        foundNonWhite = true;

                        if (c == '$')
                        {
                            reader.Read();                             // chomp $
                            readLiteral(reader);
                            type = Type.ID;
                            return;
                        }

                        if (c == '"')
                        {
                            readString(reader);
                            return;
                        }
                        else if (IsKeyChar(c))
                        {
                            if (readKeyWord(reader))
                            {
                                // a comment, keep on reading
                                foundNonWhite = false;
                                type          = Type.Newline;
                            }

                            return;
                        }
                        else
                        {
                            readLiteral(reader);
                            type = Type.Literal;
                            return;
                        }
                    }
                } while (!done);
            }
            catch (ObjectDisposedException)
            {
                type = Type.EOF;
            }
            catch (System.IO.IOException)
            {
                type = Type.EOF;
            }

            type = Type.EOF;
        }
示例#29
0
        protected void FillBuff()
        {
            if (maxNextCharInd == available)
            {
                if (available == bufsize)
                {
                    if (tokenBegin > 2048)
                    {
                        bufpos    = maxNextCharInd = 0;
                        available = tokenBegin;
                    }
                    else if (tokenBegin < 0)
                    {
                        bufpos = maxNextCharInd = 0;
                    }
                    else
                    {
                        ExpandBuff(false);
                    }
                }
                else if (available > tokenBegin)
                {
                    available = bufsize;
                }
                else if ((tokenBegin - available) < 2048)
                {
                    ExpandBuff(true);
                }
                else
                {
                    available = tokenBegin;
                }
            }

            int i;

            try {
                if (stream_closed || (i = inputStream.Read(buffer, maxNextCharInd, available - maxNextCharInd)) <= 0)
                {
                    stream_closed = true;
                        #if PCL || NETSTANDARD1_0 || NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4 || NETSTANDARD1_5 || NETSTANDARD1_6 || NETCOREAPP1_0 || NETCOREAPP1_1
                    inputStream.Dispose();
                        #else
                    inputStream.Close();
                        #endif
                    throw new System.IO.IOException();
                }
                else
                {
                    maxNextCharInd += i;
                }
                return;
            }
            catch (System.IO.IOException e) {
                --bufpos;
                backup(0);
                if (tokenBegin == -1)
                {
                    tokenBegin = bufpos;
                }
                throw e;
            }
        }
示例#30
0
            private void ReadNext()
            {
                var next = _reader.Read();

                _nextChar = next >= 0 ? (char)next : (char?)null;
            }
示例#31
0
        public static IList <string> ReadNextCSVRow(System.IO.TextReader reader, string separatorCharacters)
        {
            const int EndOfStreamValue = -1;

            if (reader.Peek() == EndOfStreamValue)
            {
                return(new List <string>());
            }

            var rowItems     = new List <string>();
            var currentItem  = new System.Text.StringBuilder();
            var insideQuotes = false;
            var isEndOfRow   = false;

            while (!isEndOfRow)
            {
                var isEndOfStream = reader.Peek() == EndOfStreamValue;
                isEndOfRow = isEndOfStream;
                var isEndOfItem = isEndOfRow;
                if (!isEndOfRow)
                {
                    var nextItem = (char)reader.Read();
                    if (!insideQuotes)
                    {
                        isEndOfRow = nextItem == '\r' || nextItem == '\n';
                        // Eat \r\n
                        if (nextItem == '\r' && (char)reader.Peek() == '\n')
                        {
                            reader.Read();
                        }

                        isEndOfItem = isEndOfRow || separatorCharacters.Contains(nextItem);
                        if (!isEndOfItem)
                        {
                            if (nextItem == '"')
                            {
                                insideQuotes = true;
                            }
                            else
                            {
                                currentItem.Append(nextItem);
                            }
                        }
                    }
                    else
                    {
                        if (nextItem == '"')
                        {
                            var peekedValue = reader.Peek();
                            if (peekedValue != EndOfStreamValue &&
                                (char)peekedValue == '"')
                            {
                                currentItem.Append('"');
                                reader.Read();
                            }
                            else
                            {
                                insideQuotes = false;
                            }
                        }
                        else
                        {
                            currentItem.Append(nextItem);
                        }
                    }
                }

                var isEmptyRow = isEndOfRow &&
                                 rowItems.Count == 0 &&
                                 currentItem.Length == 0;
                if (isEndOfItem && !isEmptyRow)
                {
                    rowItems.Add(currentItem.ToString());
                    currentItem.Length = 0;
                }
            }
            return(rowItems);
        }
示例#32
0
		/// <summary>
		/// Loads and buffers the contents of the specified reader to be 
		/// used as this ANTLRReaderStream's source
		/// </summary>
		public virtual void Load(TextReader reader, int size, int readChunkSize)
		{
			if (reader == null)
			{
				return;
			}
			if (size <= 0)
			{
				size = INITIAL_BUFFER_SIZE;
			}
			if (readChunkSize <= 0)
			{
				readChunkSize = READ_BUFFER_SIZE;
			}

			try
			{
				// alloc initial buffer size.
				data = new char[size];
				// read all the data in chunks of readChunkSize
				int numRead = 0;
				int p = 0;
				do
				{
					if (p + readChunkSize > data.Length)
					{ // overflow?
						char[] newdata = new char[data.Length * 2]; // resize
						Array.Copy(data, 0, newdata, 0, data.Length);
						data = newdata;
					}
					numRead = reader.Read(data, p, readChunkSize);
					p += numRead;
				} while (numRead != 0); // while not EOF
				// set the actual size of the data available;
				// EOF subtracted one above in p+=numRead; add one back
				//n = p + 1;
				n = p;
			}
			finally
			{
				reader.Close();
			}
		}