/// <inheritdoc />
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         ManagedStream.Dispose();
     }
 }
Ejemplo n.º 2
0
        public byte[] ReadBytes(int count)
        {
            byte[] bytes = new byte[count];

            ManagedStream.Read(bytes, 0, count);

            return(bytes);
        }
Ejemplo n.º 3
0
        public WriteCompare()
        {
            int size = sizeof(int) * AMOUNT;

            m_byteBuf       = new byte[size];
            m_ptrBuf        = Marshal.AllocHGlobal(size);
            managedStream   = new ManagedStream();
            unmanagedStream = new UnmanagedStream();
        }
Ejemplo n.º 4
0
        public void ResetWriteDefault()
        {
            ManagedStream bs = new ManagedStream();

            bs.ResetWrite();

            Assert.AreEqual(SerializationMode.Writing, bs.Mode);
            Assert.IsTrue(bs.IsWriting);

            Assert.AreEqual(ManagedStream.DefaultBufferSize, bs.Length);
        }
Ejemplo n.º 5
0
        public void ExpandStreamTest()
        {
            ManagedStream ms = new ManagedStream();

            ms.ResetWrite(2);

            ms.Write(123);

            // Resizes to the next power of two.
            // Which is 2 -> 4
            Assert.AreEqual(4, ms.Length);
        }
Ejemplo n.º 6
0
        public void InvalidateStreamer()
        {
            ManagedStream bs = new ManagedStream();

            bs.ResetWrite(new byte[4], true);

            bs.Write <int>(123);

            Assert.Catch <InvalidOperationException>(() =>
            {
                bs.Write <int>(321);
            });
        }
Ejemplo n.º 7
0
        public void InvalidateStream()
        {
            ManagedStream bs = new ManagedStream();

            bs.ResetWrite(new byte[2], true);

            Assert.Catch <InvalidOperationException>(() =>
            {
                bs.Write <int>(321);
            });

            Assert.AreEqual(2, bs.Length);
        }
Ejemplo n.º 8
0
        public byte ReadByte()
        {
            //would be -1 if it's invalid
            int b = ManagedStream.ReadByte();

            //TODO: Contract interface doesn't mention throwing in this case. Should we throw?
            if (b == -1)
            {
                throw new InvalidOperationException("Failed to read a desired byte from the stream.");
            }

            return((byte)b);
        }
Ejemplo n.º 9
0
            public byte[] ReadBytes(int count)
            {
                if (Count < ManagedStream.Position + count)
                {
                    throw new InvalidOperationException($"Failed to read a desired bytes from the stream. Count: {Count} Position: {ManagedStream.Position} Requested: {count}");
                }

                byte[] bytes = new byte[count];

                ManagedStream.Read(bytes, 0, count);

                return(bytes);
            }
Ejemplo n.º 10
0
        /// <inheritdoc />
        public async Task <byte[]> ReadBytesAsync(int count)
        {
            byte[] bytes = new byte[count];

            int readCount = await ManagedStream.ReadAsync(bytes, 0, count)
                            .ConfigureAwait(false);

            if (readCount != count)
            {
                throw new InvalidOperationException($"Failed to read {count} bytes from the stream.");
            }

            return(bytes);
        }
Ejemplo n.º 11
0
        /// <inheritdoc />
        public async Task <byte> ReadByteAsync()
        {
            byte[] singleByteBuffer = new byte[1];

            //would be -1 if it's invalid
            int readResult = await ManagedStream.ReadAsync(singleByteBuffer, 0, 1)
                             .ConfigureAwait(false);

            if (readResult == 0)
            {
                throw new InvalidOperationException($"Failed to read byte in {nameof(ReadByteAsync)}.");
            }

            return(singleByteBuffer[0]);
        }
Ejemplo n.º 12
0
        public ReadCompare()
        {
            managedStream   = new ManagedStream();
            unmanagedStream = new UnmanagedStream();
            int size = sizeof(int) * AMOUNT;

            m_byteBuf = new byte[size];
            m_ptrBuf  = Marshal.AllocHGlobal(size);

            for (int i = 0; i < size; i += 4)
            {
                int num = i / 4;
                BinaryHelper.Write(m_byteBuf, i, num);
                BinaryHelper.Write(m_ptrBuf, i, num);
            }
        }
Ejemplo n.º 13
0
        public void ResetStreamer()
        {
            ManagedStream bs = new ManagedStream();

            bs.ResetWrite(new byte[8], true);

            bs.Write <int>(333);

            Assert.AreEqual(4, bs.Offset);
            Assert.IsTrue(bs.IsWriting);

            bs.ResetRead();

            Assert.AreEqual(0, bs.Offset);
            Assert.IsTrue(bs.IsReading);
        }
Ejemplo n.º 14
0
        public void LargeStringWrite()
        {
            ManagedStream ms = new ManagedStream();

            ms.ResetWrite(2);

            StringBuilder sb = new StringBuilder(50);

            for (int i = 0; i < 50; i++)
            {
                sb.Append(i);
            }

            var str = sb.ToString();

            ms.WriteString(str, Encoding.Default);

            Assert.IsTrue(ms.Length >= 64);

            ms.ResetRead();

            Assert.AreEqual(str, ms.ReadString(Encoding.Default));
        }
Ejemplo n.º 15
0
        private async Task SetOverrides()
        {
            //set door control outputs command 'A'
            int i = 0;

            for (; i < 3; i++)
            {
                try
                {
                    (await ManagedStream.GetStream()).WriteByte((byte)'?'); //enter the management interface
                    (await ManagedStream.GetStream()).WriteByte((byte)'A');

                    if ((byte)(await ManagedStream.GetStream()).ReadByte() != (byte)'?') //read ?
                    {
                        throw new Exception();
                    }

                    (await ManagedStream.GetStream()).WriteByte(Convert.ToByte((lock_override_flags[0] ? 1 : 0) | ((lock_override_flags[1] ? 1 : 0) << 1)));

                    if ((byte)(await ManagedStream.GetStream()).ReadByte() != (byte)'!') //read !
                    {
                        throw new Exception();
                    }

                    break;
                }
                catch (Exception ex)
                {
                }
            }

            if (i == 3)
            {
                throw new Exception();
            }
        }
Ejemplo n.º 16
0
        private async Task SyncStates()
        {
            //get door control outputs command 'Z'
            if (comm_busy)
            {
                missed++;
                return;
            }
            else
            {
                missed    = 0;
                comm_busy = true;
            }

            try
            {
                if (pending_override_change)
                {
                    await SetOverrides();

                    pending_override_change = false;
                }

                Stopwatch polling_duration_stopwatch = Stopwatch.StartNew();

                (await ManagedStream.GetStream()).WriteByte((byte)'?'); //enter the management interface
                (await ManagedStream.GetStream()).WriteByte((byte)'Z');

                int response = (await ManagedStream.GetStream()).ReadByte();

                if (response == -1)
                {
                    throw new Exception("No Response");
                }
                else
                {
                    int ext0 = response & 1;

                    if (ext0 == 0 && ext0 != last_ext0_state)
                    {
                        //a new motion event has began
                        last_ext0_state = ext0;
                        ext0_active_motion_event_start = DateTime.Now;
                    }
                    else
                    if (ext0 == 1 && ext0 != last_ext0_state)
                    {
                        last_ext0_state = ext0;
                        ext0_motion_events.Add(ext0_active_motion_event_start, DateTime.Now - ext0_active_motion_event_start);
                    }

                    int ext1 = (response >> 1) & 1;

                    if (ext1 == 0 && ext1 != last_ext1_state)
                    {
                        //a new motion event has began
                        last_ext1_state = ext1;
                        ext1_active_motion_event_start = DateTime.Now;
                    }
                    else
                    if (ext1 == 1 && ext1 != last_ext1_state)
                    {
                        last_ext1_state = ext1;
                        ext1_motion_events.Add(ext1_active_motion_event_start, DateTime.Now - ext1_active_motion_event_start);
                    }

                    Func <Dictionary <DateTime, TimeSpan>, Task <string> > motion_stats_gen = new Func <Dictionary <DateTime, TimeSpan>, Task <string> >((dict) =>
                    {
                        return(Task.Run <string>(() =>
                        {
                            string motion_stats = "";

                            TimeSpan record_span = dict.Last().Key - dict.First().Key;

                            if (record_span >= TimeSpan.FromMinutes(1))
                            {
                                double seconds_of_motion_during_last_minute = dict.Where(x => x.Key >= DateTime.Now - TimeSpan.FromMinutes(1)).Select(x => x.Value.TotalMilliseconds).Sum();
                                if (seconds_of_motion_during_last_minute > 0)
                                {
                                    seconds_of_motion_during_last_minute /= 1000;
                                    motion_stats += "1m:" + Math.Round((seconds_of_motion_during_last_minute / (60)) * 100, 2) + "%,";
                                }
                            }

                            double seconds_of_motion_during_last_five_minutes = dict.Where(x => x.Key >= DateTime.Now - TimeSpan.FromMinutes(5)).Select(x => x.Value.TotalMilliseconds).Sum();
                            if (seconds_of_motion_during_last_five_minutes > 0)
                            {
                                seconds_of_motion_during_last_five_minutes /= 1000;
                                motion_stats += "5m:" + Math.Round((seconds_of_motion_during_last_five_minutes / (60 * 5)) * 100, 2) + "%,";
                            }

                            double seconds_of_motion_during_last_ten_minutes = dict.Where(x => x.Key >= DateTime.Now - TimeSpan.FromMinutes(10)).Select(x => x.Value.TotalMilliseconds).Sum();
                            if (seconds_of_motion_during_last_ten_minutes > 0)
                            {
                                seconds_of_motion_during_last_ten_minutes /= 1000;
                                motion_stats += "10m:" + Math.Round((seconds_of_motion_during_last_ten_minutes / (60 * 10)) * 100, 2) + "%,";
                            }

                            double seconds_of_motion_during_last_thirty_minutes = dict.Where(x => x.Key >= DateTime.Now - TimeSpan.FromMinutes(30)).Select(x => x.Value.TotalMilliseconds).Sum();
                            if (seconds_of_motion_during_last_thirty_minutes > 0)
                            {
                                seconds_of_motion_during_last_thirty_minutes /= 1000;
                                motion_stats += "30m:" + Math.Round((seconds_of_motion_during_last_thirty_minutes / (60 * 30)) * 100, 2) + "%,";
                            }

                            double seconds_of_motion_during_last_hour = dict.Where(x => x.Key >= DateTime.Now - TimeSpan.FromMinutes(60)).Select(x => x.Value.TotalMilliseconds).Sum();
                            if (seconds_of_motion_during_last_hour > 0)
                            {
                                seconds_of_motion_during_last_hour /= 1000;
                                motion_stats += "1h:" + Math.Round((seconds_of_motion_during_last_hour / (60 * 60)) * 100, 2) + "%,";
                            }

                            double seconds_of_motion_during_last_day = dict.Where(x => x.Key >= DateTime.Now - TimeSpan.FromHours(24)).Select(x => x.Value.TotalMilliseconds).Sum();
                            if (seconds_of_motion_during_last_day > 0)
                            {
                                seconds_of_motion_during_last_day /= 1000;
                                motion_stats += "1d:" + Math.Round((seconds_of_motion_during_last_day / (60 * 60 * 24)) * 100, 2) + "%";
                            }

                            if (motion_stats.Last() == ',')
                            {
                                motion_stats = motion_stats.Substring(0, motion_stats.Length - 1);
                            }

                            return motion_stats;
                        }));
                    });

                    Invoke((MethodInvoker)(async() =>
                    {
                        label4.Text = ext0_motion_events.Count() > 0 ? await motion_stats_gen(ext0_motion_events) : "No Motion Records";
                        label5.Text = ext1_motion_events.Count() > 0 ? await motion_stats_gen(ext1_motion_events): "No Motion Records";
                    }));



                    if (!pending_override_change)
                    {
                        lock_override_flags[0] = Convert.ToBoolean((response >> 2) & 1);
                        lock_override_flags[1] = Convert.ToBoolean((response >> 3) & 1);
                    }

                    Invoke((MethodInvoker)(() =>
                    {
                        if (ext0 == 1 && !lock_override_flags[0] && !TimeCheck())
                        {
                            button1.Text = "Locked";
                            button1.BackColor = Color.Red;
                        }
                        else
                        {
                            button1.Text = "Unlocked (";
                            if (ext0 == 0)
                            {
                                button1.Text += "Motion, ";
                            }
                            if (lock_override_flags[0])
                            {
                                button1.Text += "Override, ";
                            }
                            if (TimeCheck())
                            {
                                button1.Text += "Time, ";
                            }

                            if (button1.Text.Last() == ' ')
                            {
                                button1.Text = button1.Text.Substring(0, button1.Text.Length - 2) + ")";
                            }
                            else
                            if (button1.Text.Last() == '(')
                            {
                                button1.Text = button1.Text.Substring(0, button1.Text.Length - 2);
                            }

                            button1.BackColor = Color.Green;
                        }

                        if (ext1 == 1 && !lock_override_flags[1] && !TimeCheck())
                        {
                            button2.Text = "Locked";
                            button2.BackColor = Color.Red;
                        }
                        else
                        {
                            button2.Text = "Unlocked (";
                            if (ext1 == 0)
                            {
                                button2.Text += "Motion, ";
                            }
                            if (lock_override_flags[1])
                            {
                                button2.Text += "Override, ";
                            }
                            if (TimeCheck())
                            {
                                button2.Text += "Time, ";
                            }

                            if (button2.Text.Last() == ' ')
                            {
                                button2.Text = button2.Text.Substring(0, button2.Text.Length - 2) + ")";
                            }
                            else
                            if (button2.Text.Last() == '(')
                            {
                                button2.Text = button2.Text.Substring(0, button2.Text.Length - 2);
                            }

                            button2.BackColor = Color.Green;
                        }
                    }));
                }

                polling_duration_stopwatch.Stop();

                DateTime now = DateTime.Now;

                polling_op_durations.Add(now, (double)polling_duration_stopwatch.Elapsed.Ticks / 10000);

                polling_op_durations = polling_op_durations.Where(x => x.Key >= (now - TimeSpan.FromMinutes(1))).ToDictionary(x => x.Key, x => x.Value); //filter the records based on time

                double average_polling_op_duration = polling_op_durations.Select(x => x.Value).Average();
                double max_polling_op_duration     = polling_op_durations.Select(x => x.Value).Max();
                double min_polling_op_duration     = polling_op_durations.Select(x => x.Value).Min();

                Invoke((MethodInvoker)(() =>
                {
                    label6.Text = "Operation Execution Time (ms): {" + Math.Round(max_polling_op_duration, 4) + ", " + Math.Round(min_polling_op_duration, 4) + ", " + Math.Round(average_polling_op_duration, 4) + "}, "
                                  + "RPS: {" + Math.Round(1000 / max_polling_op_duration, 4) + ", " + Math.Round(1000 / min_polling_op_duration, 4) + ", " + Math.Round(1000 / average_polling_op_duration, 4) + "}, " + "Missed: " + missed;

                    if ((decimal)average_polling_op_duration > numericUpDown1.Value)
                    {
                        numericUpDown1.BackColor = Color.Red;
                    }
                    else
                    {
                        numericUpDown1.BackColor = Color.LightGreen;
                    }
                }));
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker)(() => { label6.Text += " *"; }));
            }

            comm_busy = false;
        }
 /// <inheritdoc />
 public Task <byte[]> GetBytesAsync()
 {
     //Do this syncronously
     return(Task.FromResult(ManagedStream.ToArray()));
 }
Ejemplo n.º 18
0
 /// <inheritdoc />
 public byte[] GetBytes()
 {
     return(ManagedStream.ToArray());
 }
Ejemplo n.º 19
0
 /// <inheritdoc />
 public void Write(byte data)
 {
     ManagedStream.WriteByte(data);
 }
Ejemplo n.º 20
0
 /// <inheritdoc />
 public void Write(byte[] data)
 {
     //Stream handles throwing. Don't need to validate or check.
     ManagedStream.Write(data, 0, data.Length);
 }
Ejemplo n.º 21
0
        public void ResetReadFault()
        {
            ManagedStream bs = new ManagedStream();

            Assert.Catch <InvalidOperationException>(() => { bs.ResetRead(); });
        }
Ejemplo n.º 22
0
 public void Init()
 {
     bs       = new ManagedStream();
     m_buffer = new byte[BUFSIZE];
 }
 /// <inheritdoc />
 public Task WriteAsync(byte[] data, int offset, int count)
 {
     return(ManagedStream.WriteAsync(data, offset, count));
 }
Ejemplo n.º 24
0
 /// <inheritdoc />
 public void Write(byte[] data, int offset, int count)
 {
     //Stream handles throwing. Don't need to validate or check.
     ManagedStream.Write(data, offset, count);
 }