Example #1
0
        private async Task saveState(int slot)
        {
            if (!this.ROMLoaded)
            {
                return;
            }

            ByteWrapper bytes = this.emulator.GetSaveStateData();

            if (bytes != null)
            {
                SaveStateData stateData = new SaveStateData()
                {
                    Data = bytes.AsArray(),
                    Slot = slot
                };
                await this.storage.SaveStateDataAsync(stateData);
            }
#if DEBUG
            else
            {
                System.Diagnostics.Debug.WriteLine("Unable to get save state data.");
            }
#endif
        }
        }//WriteDatafileSummary

        private async void WriteBytesToDatabaseAsync(ByteWrapper image)
        {
            await Task.Run(() => {
                var db = new ImageAnalysisDAL.CaptureDb(ConfigurationManager.ConnectionStrings["LOCALDB"].ConnectionString);
                db.SaveDetectionImage(captureId, detectionId, image.bytes, image.sequenceNumber);
            });
        }
Example #3
0
 public Tile(byte x, byte y, byte[,] worldMapTiles, ByteWrapper wrapper)
 {
     _wrapper           = wrapper;
     this.X             = x;
     this.Y             = y;
     this.WorldMapTiles = worldMapTiles;
 }
Example #4
0
        public void Motion2aMultipleCompare()
        {
            try
            {
                //images in memory when sent to the
                ByteWrapper image1 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_0.jpg");
                ByteWrapper image2 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_1.jpg");

                PixelMatrix dummy = new PixelMatrix();
                dummy.LinkCompare = true;
                dummy.Populate(new BitmapWrapper(ImageConvert.ReturnBitmap(image1.bytes)), new BitmapWrapper(ImageConvert.ReturnBitmap(image2.bytes)));

                MotionSensor_2a motion = new MotionSensor_2a();
                motion.ThresholdSet         = true;
                motion.settings.linkCompare = true;
                motion.Comparison           = dummy.Comparision;

                motion.ImageCreated(image1, EventArgs.Empty);
                motion.ImageCreated(image2, EventArgs.Empty);

                motion.ImageCreated(image1, EventArgs.Empty);
                motion.ImageCreated(image2, EventArgs.Empty);


                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
Example #5
0
        /// <summary>
        /// Gets the next two images on the queue and sends for analysis, used when
        /// the system is running on an async basis
        /// </summary>
        private void SendForCompareAsync()
        {
            //as there are multiple threads working the queue may have images removed by other threads
            //move this to lock functionality, rather than losing
            ByteWrapper image1 = null;
            ByteWrapper image2 = null;

            lock (objLock)
            {
                if (WorkQueue.Count > 1)
                {
                    image1 = WorkQueue.Dequeue();
                    image2 = WorkQueue.Dequeue();
                }
            }

            //send for comparision
            if (image1 != null && image2 != null)
            {
                Compare(image1, image2);
                logging.imagesChecked = logging.imagesChecked + 2;
                lock (backlog.backlogLock)
                {
                    backlog.backlog.Add(backlog.lastImageReceived - image1.sequenceNumber);
                }

                MonitorWork();
            }
        }//SendForCompareAsync
Example #6
0
 /// <summary>
 /// Subscribes to a Image Validated event, then calls various other tied in methods
 /// </summary>
 /// <param name="img"></param>
 /// <param name="e"></param>
 static void ValidImageEventHandler(ByteWrapper img, EventArgs e)
 {
     if (imageSaver != null)
     {
         Task saveImage = imageSaver.ImageCreatedAsync(img);
     }
 }
Example #7
0
 public void ImageCreated(ByteWrapper img, EventArgs e)
 {
     backlog.lastImageReceived = img.sequenceNumber;
     logging.imagesReceived++;
     AddToWorkQueue(img);
     SendForCompare();
 }
        }//FileCreated

        protected virtual void OnImageValidated(ByteWrapper img)
        {
            if (imageValidated != null)
            {
                imageValidated(img, EventArgs.Empty);
            }
        }//OnImageValidated
Example #9
0
        public void MotionSensor_2b_threshold()
        {
            MotionSensor_2b motion = new MotionSensor_2b();

            motion.settings = new MotionSensorSettings();
            motion.settings.LoadDefaults();

            motion.ControlImageNumber = 10;

            foreach (var file in Directory.EnumerateFiles(@"d:\bsc\project\TestImages"))
            {
                ByteWrapper wrapper = ImageConvert.ReturnByteWrapper(file);
                motion.ImageCreatedAsync(wrapper, EventArgs.Empty);
                Thread.Sleep(250);
            }
            Assert.IsNotNull(motion.ThresholdImage);

            for (int i = 0; i < motion.ThresholdImage.Columns.Count; i++)
            {
                for (int n = 0; n < motion.ThresholdImage.Columns[i].grids.Count; n++)
                {
                    Assert.IsTrue(motion.ThresholdImage.Columns[i].grids[n].threshold != 0);
                }
            }
        }//MotionSensor_2b_threshold
 /// <summary>
 /// Event listener for when an image is created
 /// Fires the appropriate methods to classify and save the
 /// Image
 /// </summary>
 /// <param name="img"></param>
 /// <returns></returns>
 public async Task ImageCreatedAsync(ByteWrapper img)
 {
     await Task.Run(() => {
         WriteBytesToFile(img);
         SetSection();
     });
 }
Example #11
0
 public Tile(int x, int y, byte[,] worldMapTiles, ByteWrapper wrapper)
 {
     _wrapper           = wrapper;
     this.X             = _wrapper(x);
     this.Y             = _wrapper(y);
     this.WorldMapTiles = worldMapTiles;
 }
Example #12
0
        public void TestValidator()
        {
            ByteWrapper    image1    = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_0.jpg");
            ImageValidator validator = new ImageValidator();

            try
            {
                List <int> dimensions = ReturnDimensions();
                Stopwatch  sw         = new Stopwatch();
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"f:\temp\runtime\validator_analysis.txt", true))
                {
                    for (int i = 0; i < 10; i++)
                    {
                        sw.Restart();
                        validator.FileCreated(image1, EventArgs.Empty);
                        sw.Stop();
                        file.WriteLine(sw.Elapsed.TotalMilliseconds);
                    }
                }
                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
Example #13
0
        }                                                  //the thresholds, per grid

        public override void Compare(ByteWrapper image1, ByteWrapper image2)
        {
            var bm1 = new BitmapWrapper(ImageConvert.ReturnBitmap(image1.bytes));
            var bm2 = new BitmapWrapper(ImageConvert.ReturnBitmap(image2.bytes));

            PixelMatrix matrix = new PixelMatrix();

            if (settings.searchHeight > 0)
            {
                matrix.SearchHeight = settings.searchHeight;
            }
            if (settings.searchWidth > 0)
            {
                matrix.SearchWidth = settings.searchWidth;
            }
            if (settings.linkCompare)
            {
                matrix.LinkCompare = true;
            }
            matrix.GridSystemOn = true;
            matrix.Populate(bm1, bm2);

            double sumChangedPixels = matrix.SumChangedPixels;

            //keep adding for threshold calculation, set the threshold, or monitor
            if (ThresholdSet)
            {
                //do the motion detection
                for (int i = 0; i < ThresholdImage.Columns.Count; i++)
                {
                    for (int n = 0; n < ThresholdImage.Columns[i].grids.Count; n++)
                    {
                        if (matrix.imageGrid.Columns[i].grids[n].change > ThresholdImage.Columns[i].grids[n].threshold)
                        {
                            OnMotion(image1, image2, ThresholdImage.GridNumber(i, n));
                            return;
                        }
                    }
                }
            }
            else if (!ThresholdSet && gridImages.Count < ControlImageNumber)
            {
                gridImages.Add(matrix.imageGrid); //keep adding for the later threshold calculation
            }
            else
            {
                SetThreshold(); //enough images received to set the threshold and start monitoring
            }

            Comparison = matrix.Comparator;

            //clean up the memory
            matrix.Dispose();
            bm1.bitmap.Dispose();
            bm2.bitmap.Dispose();
            bm1 = null;
            bm2 = null;
        }//Compare
 public Task PutComplexPrimitiveByte() => TestStatus(async(host, pipeline) =>
 {
     var content = new byte[] { 0xFF, 0xFE, 0xFD, 0xFC, 0x00, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6 };
     var value   = new ByteWrapper
     {
         Field = content
     };
     return(await new PrimitiveClient(ClientDiagnostics, pipeline, host).PutByteAsync(value));
 });
 public static async void WriteBytesToFileAsync(ByteWrapper image, string filepath)
 {
     await Task.Run(() => {
         using (FileStream fs = new FileStream(filepath, FileMode.Create))
         {
             fs.Write(image.bytes, 0, image.bytes.Length);
         }
     });
 }
Example #16
0
 /// <summary>
 /// Called when the object detects motion, creates the event
 /// </summary>
 /// <param name="image"></param>
 protected async void OnMotionAsync(ByteWrapper image1, ByteWrapper image2)
 {
     await Task.Run(() =>
     {
         if (motionDetected != null)
         {
             motionDetected(image1, EventArgs.Empty);
         }
     });
 }
 private async void SaveMotionFile(ByteWrapper image)
 {
     await Task.Run(() =>
     {
         if (!Directory.Exists(saveDirectory))
         {
             CreateSaveDirectory();
         }
         ImageSaver.WriteBytesToFileAsync(image, saveDirectory + @"\movement_" + image.sequenceNumber + ".jpg");
     });
 }
 public void FileCreated(ByteWrapper img, EventArgs e)
 {
     if (img.bytes[0] == JPEG_start[0] && img.bytes[1] == JPEG_start[1] && img.bytes[img.bytes.Length - 2] == JPEG_end[0] && img.bytes[img.bytes.Length - 1] == JPEG_end[1])
     {
         OnImageValidated(img); //raise the event
     }
     else
     {
         //throw new Exception("JPEG image is not well formed");
         Console.WriteLine("Badly formed image");
     }
 }//FileCreated
Example #19
0
        public async void ImageCreatedAsync(ByteWrapper img, EventArgs e)
        {
            backlog.lastImageReceived = img.sequenceNumber;
            logging.imagesReceived++;

            AddToWorkQueue(img); //do this outside the anonymous method

            await Task.Run(() =>
            {
                SendForCompareAsync();
            });
        }
        private async void MotionDetected(ByteWrapper image, EventArgs e)
        {
            await Task.Run(() =>
            {
                //    Console.Beep(1000, 250);

                SaveMotionFile(image);
                if (movementFrames != null)
                {
                    movementFrames.Add(image.sequenceNumber);
                }
            });
        }
        public void JObjectFromObjectOnByteMaxValueSucceeds()
        {
            var instance = new ByteWrapper
            {
                Value = byte.MaxValue
            };

            var output = JObject.FromObject(instance);

            StringUtils.AssertAreEqualWithNormalizedLineEndings(@"{
  ""Value"": 255
}", output.ToString());
        }
Example #22
0
 public async Task SaveScreenshotAsync()
 {
     if (this.emulator.ROMLoaded)
     {
         int         rowPitch = 0;
         ByteWrapper bytes    = this.emulator.GetSnapshot(out rowPitch);
         await this.storage.SaveScreenshotAsync(new SnapshotData()
         {
             Data  = bytes.AsArray(),
             Pitch = rowPitch
         });
     }
 }
        public IAsyncAction SaveSRAMAsync(ByteWrapper bytes)
        {
            byte[]      data   = bytes.AsArray();
            Func <Task> helper = async() =>
            {
                await this.manager.SaveSRAMDataAsync(new SRAMData()
                {
                    Data = data
                });
            };

            return(helper().AsAsyncAction());
        }
 public virtual Response PutByte(ByteWrapper complexBody, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("PrimitiveClient.PutByte");
     scope.Start();
     try
     {
         return(RestClient.PutByte(complexBody, cancellationToken));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
 /// <summary>
 /// Writes a single file to the location specified, called outide of this
 /// </summary>
 public async void WriteBytesToFileAsync(ByteWrapper image, EventArgs e)
 {
     await Task.Run(() => {
         string fileName = GenerateFileName();
         using (FileStream fs = new FileStream(GenerateFileName(image.sequenceNumber), FileMode.Create))
         {
             fs.Write(image.bytes, 0, image.bytes.Length);
         }
         if (imageCreated != null)
         {
             imageCreated(fileName, EventArgs.Empty);
         }
     });
 }
 public virtual async Task <Response> PutByteAsync(ByteWrapper complexBody, CancellationToken cancellationToken = default)
 {
     using var scope = _clientDiagnostics.CreateScope("PrimitiveClient.PutByte");
     scope.Start();
     try
     {
         return(await RestClient.PutByteAsync(complexBody, cancellationToken).ConfigureAwait(false));
     }
     catch (Exception e)
     {
         scope.Failed(e);
         throw;
     }
 }
Example #27
0
        public void Motion2aSubequent()
        {
            try
            {
                List <int> dimensions = ReturnDimensions();
                Stopwatch  sw         = new Stopwatch();
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"f:\temp\runtime\motion_analysis.txt", true))
                {
                    for (int i = 0; i < dimensions.Count; i++)
                    {
                        for (int n = 0; n < 200; n++)
                        {
                            //images in memory when sent to the
                            ByteWrapper image1 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_0.jpg");
                            image1.sequenceNumber = i;
                            ByteWrapper image2 = ImageConvert.ReturnByteWrapper(@"F:\temp\analysis\640x480\test_1.jpg");
                            image2.sequenceNumber = i;


                            PixelMatrix dummy = new PixelMatrix();
                            dummy.LinkCompare = true;
                            dummy.SearchWidth = dimensions[i];
                            dummy.Populate(new BitmapWrapper(ImageConvert.ReturnBitmap(image1.bytes)), new BitmapWrapper(ImageConvert.ReturnBitmap(image2.bytes)));


                            sw.Restart();
                            MotionSensor_2a motion = new MotionSensor_2a();
                            motion.ThresholdSet         = true;
                            motion.settings.linkCompare = true;
                            motion.settings.searchWidth = dimensions[i];
                            motion.Comparison           = dummy.Comparision;

                            motion.ImageCreated(image1, EventArgs.Empty);
                            motion.ImageCreated(image2, EventArgs.Empty);

                            motion.ImageCreated(image1, EventArgs.Empty);
                            motion.ImageCreated(image2, EventArgs.Empty);
                            sw.Stop();
                            file.WriteLine(i + " - " + n + " - " + " no grid - " + sw.Elapsed.TotalMilliseconds);
                        }
                    }
                }
                Assert.IsTrue(true);
            }
            catch
            {
                Assert.IsTrue(false);
            }
        }
 /// <summary>
 /// Event listener for when an image is created
 /// Fires the appropriate methods to classify and save the
 /// Image
 /// </summary>
 /// <param name="img"></param>
 /// <param name="e"></param>
 /// <returns></returns>
 public async void ImageCreatedAsync(ByteWrapper img, EventArgs e)
 {
     await Task.Run(() => {
         // WriteBytesToFile(img);
         if (saveToFileServer)
         {
             WriteBytesToFile(img);
         }
         if (saveToDatabase)
         {
             WriteBytesToDatabaseAsync(img);
         }
         SetSection();
     });
 }
Example #29
0
 /// <summary>
 /// Adds to the queue, unless frame should be skipped
 /// </summary>
 /// <param name="img"></param>
 private void AddToWorkQueue(ByteWrapper img)
 {
     if (this.settings.framesToSkip > 0)
     {
         if (numberSkipped == settings.framesToSkip)
         {
             WorkQueue.Enqueue(img);
             numberSkipped = 0;
         }
         else
         {
             numberSkipped++;
         }
     }
     else
     {
         WorkQueue.Enqueue(img);
     }
 }
 private void WriteBytesToFile(ByteWrapper img)
 {
     try
     {
         string fileName = GenerateFileName();
         using (FileStream fs = new FileStream(fileName, FileMode.Create))
         {
             fs.Write(img.bytes, 0, img.bytes.Length);
         }
         if (imageCreated != null)
         {
             imageCreated(fileName, EventArgs.Empty);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(DateTime.Now + " - " + ex.Message);
     }
 }
 /// <summary>
 /// Put complex types with byte properties
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='complexBody'>
 /// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6)
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task PutByteAsync( this IPrimitive operations, ByteWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
 {
     await operations.PutByteWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
 }
 private void MotionDetected(ByteWrapper image, EventArgs e)
 {
     Console.WriteLine(image.sequenceNumber);
 }
 /// <summary>
 /// Put complex types with byte properties
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='complexBody'>
 /// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6)
 /// </param>
 public static void PutByte(this IPrimitive operations, ByteWrapper complexBody)
 {
     Task.Factory.StartNew(s => ((IPrimitive)s).PutByteAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
 }