Exemple #1
0
 public IMAGEController(
     ILogger <IMAGEController> logger)
 {
     this.logger = logger;
     this.cam    = MMALCamera.Instance;
     MMALCameraConfig.StillResolution = new Resolution(640, 480);
 }
Exemple #2
0
        public static void TakeVideoManualMode()
        {
            MMALCamera cam = MMALCamera.Instance;

            AsyncContext.Run(async() =>
            {
                //using (var vidCaptureHandler = new VideoStreamCaptureHandler("/home/pi/videos/", "mjpeg"))
                using (var vidCaptureHandler = new VideoStreamCaptureHandler("/home/pi/videos/", "avi"))
                    using (var vidEncoder = new MMALVideoEncoder(vidCaptureHandler))
                        //using (var ffCaptureHandler = FFmpegCaptureHandler.RawVideoToAvi("/home/pi/videos/", "testing1234"))
                        //using (var vidEncoder = new MMALVideoEncoder(ffCaptureHandler))
                        using (var renderer = new MMALVideoRenderer())
                        {
                            cam.ConfigureCameraSettings();

                            // Create our component pipeline. Here we are using the H.264 standard with a YUV420 pixel format. The video will be taken at 25Mb/s.
                            vidEncoder.ConfigureOutputPort(0, MMALEncoding.MJPEG, MMALEncoding.I420, 90, 25000000);

                            cam.Camera.VideoPort.ConnectTo(vidEncoder);
                            cam.Camera.PreviewPort.ConnectTo(renderer);

                            // Camera warm up time
                            await Task.Delay(2000);

                            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

                            // Take video for 3 minutes.
                            await cam.ProcessAsync(cam.Camera.VideoPort, cts.Token);
                        }
            });

            cam.Cleanup();
        }
        public async Task TakePicturesAsync(string filename, TimeSpan duration, int msWaitBetweenPictures)
        {
            try
            {
                // Singleton initialized lazily. Reference once in your application.
                MMALCamera cam = this.MMALSharpCameraInstance;
                MMALCameraConfig.StillResolution = new Resolution(1080, 920);
                cam.ConfigureCameraSettings();

                using (var imgCaptureHandler = new IndexedImageStreamCaptureHandler(filename))
                {
                    Console.WriteLine($"Current filename in handler: {imgCaptureHandler.CurrentFilename}");

                    var cts       = new CancellationTokenSource(duration);
                    var timelapse = new Timelapse
                    {
                        Mode              = TimelapseMode.Millisecond,
                        Value             = msWaitBetweenPictures,
                        CancellationToken = cts.Token
                    };
                    await cam.TakePictureTimelapse(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420, timelapse);
                }

                // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
                // on the camera.
                Console.WriteLine($"Wrote picture to: {filename} with running index");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakePictureAsync)} Failed");
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakePictureAsync)} {ex.ToString()}");
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakePictureAsync)} Failed");
            }
        }
Exemple #4
0
        public static void TakePictureManualMode()
        {
            MMALCamera cam = MMALCamera.Instance;

            AsyncContext.Run(async() =>
            {
                using (var imgCaptureHandler = new ImageStreamCaptureHandler("/home/pi/images/", "jpg"))
                    using (var imgEncoder = new MMALImageEncoder(imgCaptureHandler))
                        using (var nullSink = new MMALNullSinkComponent())
                        {
                            cam.ConfigureCameraSettings();

                            // Create our component pipeline.
                            imgEncoder.ConfigureOutputPort(0, MMALEncoding.JPEG, MMALEncoding.I420, 90);

                            cam.Camera.StillPort.ConnectTo(imgEncoder);
                            cam.Camera.PreviewPort.ConnectTo(nullSink);

                            // Camera warm up time
                            await Task.Delay(2000);
                            await cam.ProcessAsync(cam.Camera.StillPort);
                        }
            });

            cam.Cleanup();
        }
 public PiCamVideoStream(int width = 1296, int height = 972, int mode = 4)
 {
     cam       = MMALCamera.Instance;
     capWidth  = width;
     capHeight = height;
     camMode   = mode;
 }
Exemple #6
0
        public CameraController(ILogger <CameraController> logger, IOptionsSnapshot <Settings> optionsSettings)
        {
            _logger          = logger;
            _optionsSettings = optionsSettings;

            //configure
            MMALCameraConfig.Annotate = new AnnotateImage("Home Living Room", 18, System.Drawing.Color.Green)
            {
                ShowDateText = true,
                ShowTimeText = true,
                XOffset      = 100,
                YOffset      = 100
            };
            MMALCameraConfig.Annotate.ShowDateText = true;
            MMALCameraConfig.Annotate.ShowTimeText = true;
            MMAL_PARAM_MIRROR_T mirror = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_NONE;

            if (_optionsSettings.Value.FlipHorizontal && _optionsSettings.Value.FlipVertical)
            {
                mirror = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_BOTH;
            }
            else if (_optionsSettings.Value.FlipVertical)
            {
                mirror = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_VERTICAL;
            }
            else if (_optionsSettings.Value.FlipHorizontal)
            {
                mirror = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_HORIZONTAL;
            }
            MMALCameraConfig.Flips           = mirror;
            MMALCameraConfig.StillResolution = Resolution.As1080p;
            _camera = MMALCamera.Instance;
        }
Exemple #7
0
        /// <summary>
        /// Takes a picture and saves that in the default location
        /// </summary>
        /// <returns>The filename of the picture,
        /// without path or extension</returns>
        public async Task <string> TakePicture()
        {
            // Instantiate the camera, if needed
            // In my demos I always have the cam upside down. Fix that (not needed
            // for analyzing, just for the user...)
            if (_cameraDevice == null)
            {
                MMALCameraConfig.Flips = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_BOTH;
                _cameraDevice          = MMALCamera.Instance;
            }

            // Create the handler that will receive the data
            using (var imgCaptureHandler = new ImageStreamCaptureHandler(
                       "/home/pi/images/",
                       "jpg"))
            {
                // Call the camera and collect bytes
                await _cameraDevice.TakePicture(
                    imgCaptureHandler,
                    MMALEncoding.JPEG,
                    MMALEncoding.I420);

                // Get the last generated filename
                var fileName = imgCaptureHandler.GetFilename();

                return(fileName);
            }
        }
        public async Task TakeVideoAsync(string filePath)
        {
            try
            {
                // Singleton initialized lazily. Reference once in your application.
                MMALCamera cam = this.MMALSharpCameraInstance;

                // using (var vidCaptureHandler = new VideoStreamCaptureHandler("/home/pi/videos/", "avi"))
                using (var vidCaptureHandler = new VideoStreamCaptureHandler(filePath))
                {
                    var cts   = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                    var split = new Split
                    {
                        Mode  = TimelapseMode.Second,
                        Value = 15,
                    };
                    await cam.TakeVideo(vidCaptureHandler, cts.Token, split);
                }

                // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
                // on the camera.
//                cam.Cleanup();
                Console.WriteLine($"Wrote video to: {filePath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakeVideoAsync)} Failed");
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakeVideoAsync)} {ex.ToString()}");
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakeVideoAsync)} Failed");
            }
        }
Exemple #9
0
        private void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                _cameraDevice.Cleanup();
                _cameraDevice = null;
            }

            GC.SuppressFinalize(this);
        }
 public async Task EnableAsync(CancellationToken cancellationToken)
 {
     try
     {
         this.camera = MMALCamera.Instance;
         await ConfigureCameraForCurrentLightingAsync(cancellationToken);
     }
     catch (Exception ex)
     {
         log.LogError(ex, "Could not enable camera.");
     }
 }
Exemple #11
0
        static void Main(string[] args)
        {
            MMALCamera cam = MMALCamera.Instance;

            // Create observable that will generate an incrementing number every second
            var observable = Observable.Generate(1, x => true, x => x + 1, x => x, x => TimeSpan.FromSeconds(1));

            var relay  = OutputPort.Create(17, OutputPort.InitialValue.Low).Result;
            var light1 = OutputPort.Create(27, OutputPort.InitialValue.Low).Result;
            var light2 = OutputPort.Create(22, OutputPort.InitialValue.Low).Result;
            var button = InputPort.Create(24, GpioEdge.Both).Result;

            // Write true whenever the number is even and odd when the number is odd
            using (var imgCaptureHandler = new ImageStreamCaptureHandler("/home/pi/images/", "jpg"))
                using (observable.Select(x => x % 2 == 0).Subscribe(relay))
                    using (observable.Select(x => x % 2 == 0).Subscribe(light1))
                        //using (observable.Select(x => x % 2 != 0).Subscribe(light2))
                        //using (button.Do(pressed => Console.WriteLine(pressed)).Subscribe())
                        using (button.Subscribe(light2))
                            using (var i2cBus = new I2CBusPI("/dev/i2c-1"))
                            {
                                var takePictureTask = cam.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);

                                var i2cDevice = new I2CDevicePI(i2cBus, Display.DefaultI2CAddress);

                                var sensor = new BME280Sensor(i2cBus, 1014);

                                var display = new SSD1306.Display(i2cDevice, 128, 64);
                                display.Init();

                                var dfont = new AdafruitSinglePageFont();

                                for (int i = 0; i < 100; i++)
                                {
                                    display.WriteLineBuff(dfont, $"Temperature: {sensor.ReadTemperature().Result} °C", $"Pressure: {sensor.ReadPressure().Result} Pa", $"Humidity: {sensor.ReadHumidity().Result} %", $"Altitude: {sensor.ReadAltitude().Result} m", "Line 5", "Line 6", "Line 7", "Line 8");
                                    display.DisplayUpdate();
                                }

                                //for (int i = 0; i < 100; i++)
                                //    display.DrawPixel(i, i);

                                takePictureTask.Wait();
                                display.ClearDisplay();
                            }
            // releasing relay
            relay.Write(true);
            // turning of light
            light1.Write(false);
            light2.Write(false);
            // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
            // on the camera.
            cam.Cleanup();
        }
Exemple #12
0
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    this.camera?.Cleanup();
                    this.camera = null;
                }

                disposedValue = true;
            }
        }
        private void InitializeCamera()
        {
            this.camera = MMALCamera.Instance;

            // Attempt to prevent blurry photos taking during motion by adjusting shutter speed
            MMALCameraConfig.ExposureCompensation
                = (int)MMAL_PARAM_EXPOSUREMODE_T.MMAL_PARAM_EXPOSUREMODE_SPORTS;

            if (!Directory.Exists(this.settings.MediaPath))
            {
                Directory.CreateDirectory(this.settings.MediaPath);
            }
        }
Exemple #14
0
        //   private string UploadUrl = "https://westeurope.api.cognitive.microsoft.com/customvision/v3.0/Prediction/aeeb0af8-9c49-45d3-8419-9c76485c1fdf/detect/iterations/Iteration1/image";

        public async Task <string> TakePicture()
        {
            if (_mmalCamera == null)
            {
                MMALCameraConfig.Flips = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_BOTH;
                _mmalCamera            = MMALCamera.Instance;
            }

            using (var imgCaptureHandler = new ImageStreamCaptureHandler("/home/pi/images/", "jpg"))
            {
                await _mmalCamera.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);

                var fileName = imgCaptureHandler.GetFilename();

                return(fileName);
            }
        }
Exemple #15
0
        public static async Task TakePictureAsync()
        {
            MMALCameraConfig.Annotate = new AnnotateImage
            {
                ShowDateText = true,
                ShowTimeText = true
            };
            MMALCameraConfig.StatsPass = true;
            // Singleton initialized lazily. Reference once in your application.
            MMALCamera cam = MMALCamera.Instance;

            using (var imgCaptureHandler = new ImageStreamCaptureHandler("/home/pi/images/", "jpg"))
            {
                await cam.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);
            }

            // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
            // on the camera.
            cam.Cleanup();
        }
Exemple #16
0
        public static async Task TakeVideoAsync()
        {
            MMALCameraConfig.VideoResolution = new Resolution(640, 480);
            MMALCameraConfig.Flips           = MMAL_PARAM_MIRROR_T.MMAL_PARAM_MIRROR_VERTICAL;
            MMALCameraConfig.InlineHeaders   = true;
            MMALCameraConfig.VideoProfile    = MMAL_VIDEO_PROFILE_T.MMAL_VIDEO_PROFILE_H264_HIGH;
            // Singleton initialized lazily. Reference once in your application.
            MMALCamera cam = MMALCamera.Instance;

            using (var vidCaptureHandler = new VideoStreamCaptureHandler("/home/pi/videos/", "avi"))
            {
                var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

                await cam.TakeVideo(vidCaptureHandler, cts.Token);
            }

            // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
            // on the camera.
            cam.Cleanup();
        }
Exemple #17
0
        public bool Initialize()
        {
            try
            {
                camera = MMALCamera.Instance;
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Failed to obtain camera. Ensure module is running with createOptions: \"HostConfig\": { \"Privileged\": true }");
                return(false);
            }

            if (camera == null)
            {
                Logger.Log("Failed to obtain camera. Ensure module is running with createOptions: \"HostConfig\": { \"Privileged\": true }");
                return(false);
            }

            return(true);
        }
Exemple #18
0
        public Camera(NetworkStream outputStream, Vector2 resolution, int bitrate = 1300000, int frameRate = 25, int quality = 0, EventHandler <byte[]> frameCaptured = null)
        {
            OnFrameCaptured = frameCaptured;

            MMALCameraConfig.VideoResolution = new Resolution((int)resolution.X, (int)resolution.Y);
            MMALCameraConfig.VideoFramerate  = new MMAL_RATIONAL_T(frameRate, 1);

            OutputHandler = new NetworkStreamCaptureHandler(outputStream);
            VideoEncoder  = new MMALVideoEncoder();

            // Create our component pipeline. Here we are using the H.264 standard with a YUV420 pixel format. The video will be taken at 25Mb/s.
            Instance = MMALCamera.Instance;
            Instance.ConfigureCameraSettings();

            MMALPortConfig portConfig = new MMALPortConfig(MMALEncoding.H264, MMALEncoding.I420, quality, bitrate, null);

            VideoEncoder.ConfigureOutputPort(portConfig, OutputHandler);

            nullSink = new MMALNullSinkComponent();
            Instance.Camera.PreviewPort.ConnectTo(nullSink);
            Instance.Camera.VideoPort.ConnectTo(VideoEncoder);
        }
Exemple #19
0
        static async Task Main(string[] args)
        {
            System.Console.WriteLine("Starting");
            const int lightCount = 12;
            var       settings   = new SpiConnectionSettings(0, 0)
            {
                ClockFrequency = 2_400_000,
                Mode           = SpiMode.Mode0,
                DataBitLength  = 8
            };

            // Create a Neo Pixel x8 stick on spi 0.0
            var spi = SpiDevice.Create(settings);

            var neo = new Ws2812b(spi, lightCount);

            var img = neo.Image;

            img.Clear();
            for (var x = 0; x < lightCount; x++)
            {
                img.SetPixel(x, 0, Color.White);
            }
            neo.Update();

            MMALCamera cam = MMALCamera.Instance;

            for (var y = 0; y < 50; y++)
            {
                using (var imgCaptureHandler = new ImageStreamCaptureHandler($"_testing{y}.jpg")){
                    await cam.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);
                }
                Step();
            }

            img.Clear();
            neo.Update();
            cam.Cleanup();
        }
        public async Task TakePictureAsync(string filePath)
        {
            try
            {
                // Singleton initialized lazily. Reference once in your application.
                MMALCamera cam = this.MMALSharpCameraInstance;

                using (var imgCaptureHandler = new ImageStreamCaptureHandler(filePath))
                {
                    await cam.TakePicture(imgCaptureHandler, MMALEncoding.JPEG, MMALEncoding.I420);
                }

                // Cleanup disposes all unmanaged resources and unloads Broadcom library. To be called when no more processing is to be done
                // on the camera.
                Console.WriteLine($"Wrote picture to: {filePath}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakePictureAsync)} Failed");
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakePictureAsync)} {ex.ToString()}");
                Console.WriteLine($"{nameof(MMALSharpCamera)} {nameof(TakePictureAsync)} Failed");
            }
        }
Exemple #21
0
 public PiCameraService()
 {
     MMALCamera = MMALCamera.Instance;
     //Setting the Average resolution for reducing the file size
     MMALCameraConfig.StillResolution = new Resolution(640, 480);
 }
Exemple #22
0
        static void Main(string[] args)
        {
            //load app properties
            ReadConfigFile();
            idScope = GetProperty("idScope");
            enrollmentGroupPrimaryKey   = GetProperty("enrollmentGroupPrimaryKey");
            enrollmentGroupSecondaryKey = GetProperty("enrollmentGroupSecondaryKey");
            registrationId         = GetProperty("registrationId");
            deviceStringConnection = GetProperty("deviceStringConnection");
            pathToSavePicture      = GetProperty("pathToSavePicture");

            bool dpsInfoOk = !string.IsNullOrWhiteSpace(idScope) && !string.IsNullOrWhiteSpace(enrollmentGroupPrimaryKey) &&
                             !string.IsNullOrWhiteSpace(enrollmentGroupSecondaryKey) && !string.IsNullOrWhiteSpace(registrationId);
            bool directConnection = !string.IsNullOrWhiteSpace(deviceStringConnection);

            if (!(dpsInfoOk || directConnection))
            {
                Console.WriteLine("ID Scope, Keys and Registration ID must be provided if using DPS, otherwise fill the Device Connection String");
                Console.ReadLine();
            }
            else
            {
                //connect device directly if device string connection is known
                if (!string.IsNullOrWhiteSpace(deviceStringConnection))
                {
                    //this install a root certificate in the OS - applicable if you using this device as a downstream to connect through a Edge Gateway.
                    if (deviceStringConnection.Contains("GatewayHostName"))
                    {
                        InstallCACert();
                    }

                    deviceClient = DeviceClient.CreateFromConnectionString(deviceStringConnection, TransportType.Mqtt_Tcp_Only);
                }
                else
                {
                    //Provision through DPS and return DeviceClient object
                    ProvisioningDeviceClientWrapper provisionWrapper = new ProvisioningDeviceClientWrapper(
                        idScope, registrationId, enrollmentGroupPrimaryKey, enrollmentGroupSecondaryKey);

                    deviceClient = provisionWrapper.RunAsync().GetAwaiter().GetResult();
                }

                // Create a handler for the direct method call
                deviceClient.SetMethodHandlerAsync("TakePicture", TakePicture, null).Wait();

                //Initiate camera (singleton pattern) - must be executed just once - Attention - while this app is running the camera can´t be used by another program
                cam = MMALCamera.Instance;

                //open device connection
                deviceClient.OpenAsync().ConfigureAwait(false);

                //execute this method to program continue running
                Console.ReadLine();

                //close device connection
                deviceClient.CloseAsync().ConfigureAwait(false);

                // Only call when you no longer require the camera, i.e. on app shutdown.
                cam.Cleanup();
            }
        }
Exemple #23
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public CameraStateManager()
 {
     Cam = MMALCamera.Instance;
 }
 public MMALSharpCamera()
 {
     this.MMALSharpCameraInstance = MMALCamera.Instance;
 }
Exemple #25
0
 public PiCamVideoStream()
 {
     _cam = MMALCamera.Instance;
 }