/// <summary>
        /// Reads words input registers
        /// </summary>
        /// <param name="offset">The register offset</param>
        /// <param name="count">Number of words to read</param>
        /// <returns>The words read</returns>
        public async Task <byte[]> ReadInputsAsync(int offset, int count, byte unit = 0x01)
        {
            if (tcpClient == null)
            {
                throw new Exception("Object not intialized");
            }

            var request = new ModbusRequest02(offset, count, unit);
            var buffer  = request.ToNetworkBuffer();

            using (var cancellationTokenSource = new CancellationTokenSource(socketTimeout))
            {
                using (cancellationTokenSource.Token.Register(() => transportStream.Close()))
                {
                    await transportStream.WriteAsync(buffer, 0, buffer.Length, cancellationTokenSource.Token);
                }
            }
            var response = await ReadResponseAsync <ModbusReply02>();

            return(response.RawData);
        }
Beispiel #2
0
        /// <summary>
        /// Reads digital input status (Function Code 02)
        /// </summary>
        /// <param name="offset">The register offset</param>
        /// <param name="count">Number of words to read</param>
        /// <returns>Digital inputs on/off status as array of bools</returns>
        public async Task <bool[]> ReadInputStatusAsync(int offset, int count, byte unitIdentifier)
        {
            if (tcpClient == null)
            {
                throw new Exception("Object not intialized");
            }


            var request = new ModbusRequest02(offset, count, unitIdentifier);
            var buffer  = request.ToNetworkBuffer();

            using (var cancellationTokenSource = new CancellationTokenSource(socketTimeout))
            {
                using (cancellationTokenSource.Token.Register(() => transportStream.Close()))
                {
                    await transportStream.WriteAsync(buffer, 0, buffer.Length, cancellationTokenSource.Token);
                }
            }

            var response = await ReadResponseAsync <ModbusReply02>();

            Console.BackgroundColor = ConsoleColor.DarkGray;

            Console.Write($"\n[DEBUG] Digital Input Status request bytes:  ");
            foreach (byte b in buffer)
            {
                Console.Write($"{b.ToString("X2")}  ");
            }

            Console.Write($"\n[DEBUG] Digital Input Status response (value) bytes:  ");
            foreach (byte b in response.Data)
            {
                Console.Write($"{b.ToString("X2")}  ");
            }

            Console.ResetColor();

            return(ReadAsBool(response.Data));
        }