Exemple #1
0
        /// <summary>
        /// Sends a command to the serial port. The first byte is sent as is, but
        /// all other successive bytes are expanded to two "Kamstrup bytes".
        /// </summary>
        /// <returns>
        /// The command.
        /// </returns>
        /// <param name='data'>
        /// Data.
        /// </param>
        /// <param name='log'>
        /// Log.
        /// </param>
        public byte[] SendCommand(byte[] data)
        {
            byte[] payload = ToKamstrupBytes(data.Subset(MAGICBYTE_LENGTH));

            byte[] checksum = ToKamstrupPair(Checksum(data.Subset(MAGICBYTE_LENGTH)));

            return(device.SendCommand(data.Subset(0, MAGICBYTE_LENGTH).Merge(payload, checksum)));
        }
        private Dictionary <string, string> Fetch()
        {
            var results = new Dictionary <string, string>();

            byte[] reply = connection.SendCommand(Encoding.ASCII.GetBytes(DOWNLOAD_METERDATA));

            string stringReply = Encoding.ASCII.GetString(reply);

            results.Add("MAKE", stringReply.Substring(1, 3));
            results.Add("MODEL", stringReply.Substring(5));

            if (connection.ReadByte() != STX)
            {
                throw new MeterException("STX expected!");
            }

            int checksum = 0;

            String input;
            int    i = 2;

            do
            {
                input = connection.ReadLine();

                string[] parts = input.Split("(".ToCharArray());

                if (parts.Length == 2)
                {
                    results.Add(parts[0], parts[1].Substring(0, parts[1].IndexOf(")")));
                }
                else
                {
                    results.Add("#" + i, input);
                }

                foreach (char value in input)
                {
                    checksum += value;
                }
                checksum += CR;
                i++;
            }while(!input.Contains("!"));            // TODO: Replace by EndsWith(..)?

            int etx = connection.ReadByte();

            if (etx != ETX)
            {
                throw new MeterException("ETX expected!");
            }

            checksum += etx;
            checksum &= 0x7F;             // Remove anything but the 7 LSB's

            if (connection.ReadByte() != checksum)
            {
                throw new MeterException("Invalid checksum!");
            }

            return(results);
        }