Exemple #1
0
        static void Main(string[] args)
        {
            using var module = new PiTopModule();

            var display = module.Display;

            Console.WriteLine("press enter key to render square");
            Console.ReadLine();
            display.Draw((d, cr) =>
            {
                var square = new RectangularPolygon(0, 0, cr.Width / 2, cr.Height / 2);

                d.Fill(Color.White, square);
            });

            Console.WriteLine("press enter key to render text");
            Console.ReadLine();

            var font = SystemFonts.Collection.Find("Roboto").CreateFont(10);

            module.Display.Draw((context, cr) => {
                context.Clear(Color.Black);
                var rect = TextMeasurer.Measure("Diego was here", new RendererOptions(font));
                var x    = (cr.Width - rect.Width) / 2;
                var y    = (cr.Height + (rect.Height)) / 2;
                context.DrawText("Hello\nWorld", font, Color.White, new PointF(0, 0));
            });

            Console.WriteLine("press enter key to exit");
            Console.ReadLine();
        }
Exemple #2
0
        static void Main(string[] args)
        {
            using var pipeline = Pipeline.Create("PiTop", true);
            using var module   = new PiTopModule();
            var plate = module.GetOrCreatePlate <FoundationPlate>();

            var threshold = plate
                            .GetOrCreateDevice <Potentiometer>(AnaloguePort.A0)
                            .CreateComponent(pipeline, TimeSpan.FromSeconds(0.5));

            var distance = plate
                           .GetOrCreateDevice <UltrasonicSensor>(DigitalPort.D3)
                           .CreateComponent(pipeline, TimeSpan.FromSeconds(0.2));

            var alert = new ValueAlertComponent(pipeline,
                                                new[]
            {
                plate.GetOrCreateDevice <Led>(DigitalPort.D0),
                plate.GetOrCreateDevice <Led>(DigitalPort.D1),
                plate.GetOrCreateDevice <Led>(DigitalPort.D2)
            });

            threshold
            .Select(t => t * 50)
            .PipeTo(alert.Threshold);

            distance
            .Select(d => d.Value)
            .PipeTo(alert.Value);

            pipeline.Run();
        }
Exemple #3
0
        private static async Task TestLed01()
        {
            var module = new PiTopModule();
            var plate  = module.GetOrCreatePlate <FoundationPlate>();

            var ports = DigitalPort.D0.GetDigitalPortRange(3);
            var leds  = ports
                        .Select(p => plate.GetOrCreateDevice(p, (dp, c) => new Led(dp, c)))
                        .ToArray();

            foreach (var led in leds)
            {
                led.Off();
            }

            var pos = 0;

            for (var i = 0; i < (leds.Length * 10); i++)
            {
                leds[pos].Toggle();
                pos = (pos + 1) % 3;
                await Task.Delay(300);
            }

            foreach (var led in leds)
            {
                led.Off();
            }
        }
Exemple #4
0
        public FoundationPlate(PiTopModule module) : base(module)
        {
            _digitalConnectedDeviceFactory = new ConnectedDeviceFactory <DigitalPort, DigitalPortDeviceBase>(deviceType =>
            {
                var ctorSignature = new[] { typeof(DigitalPort), typeof(IGpioControllerFactory) };
                var ctor          = deviceType.GetConstructor(ctorSignature);
                if (ctor != null)
                {
                    return(devicePort => (DigitalPortDeviceBase)Activator.CreateInstance(deviceType, devicePort, module) !);
                }

                throw new InvalidOperationException(
                    $"Cannot find suitable constructor for type {deviceType}, looking for signature {ctorSignature}");
            });

            _analogueConnectedDeviceFactory = new ConnectedDeviceFactory <AnaloguePort, AnaloguePortDeviceBase>(
                deviceType =>
            {
                var ctorSignature = new[] { typeof(AnaloguePort), typeof(int), typeof(II2CDeviceFactory) };
                var ctor          = deviceType.GetConstructor(ctorSignature);
                if (ctor != null)
                {
                    return(devicePort =>
                           (AnaloguePortDeviceBase)Activator.CreateInstance(deviceType, devicePort, DefaultI2CAddress, module) !);
                }

                throw new InvalidOperationException(
                    $"Cannot find suitable constructor for type {deviceType}, looking for signature {ctorSignature}");
            });

            RegisterForDisposal(_digitalConnectedDeviceFactory);
            RegisterForDisposal(_analogueConnectedDeviceFactory);
        }
Exemple #5
0
        private static Task TestPotentiometer(AnaloguePort port)
        {
            var cancellationSource = new CancellationTokenSource();

            var module = new PiTopModule();
            var plate  = module.GetOrCreatePlate <FoundationPlate>();

            Task.Run(() =>
            {
                var potentiometer = plate.GetOrCreateDevice <Potentiometer>(port);

                Observable
                .Interval(TimeSpan.FromSeconds(0.5))
                .Select(_ => potentiometer.Position)
                .Subscribe(Console.WriteLine);

                Console.WriteLine("press enter key to exit");
            }, cancellationSource.Token);

            return(Task.Run(() =>
            {
                Console.ReadLine();
                module.Dispose();
                cancellationSource.Cancel(false);
            }, cancellationSource.Token));
        }
        public static void DisposeDevice(this PiTopModule module, FileSystemCamera device)
        {
            var factory = module.GetDeviceFactory <FileSystemCameraSettings, FileSystemCamera>();

            AssertFactory(factory);
            factory.DisposeDevice(device);
        }
Exemple #7
0
        private static Task TestUltrasoundSensor()
        {
            var module = new PiTopModule();
            var plate  = module.GetOrCreatePlate <FoundationPlate>();

            var cancellationSource = new CancellationTokenSource();

            Task.Run(() =>
            {
                var sensor =
                    plate.GetOrCreateDevice <UltrasonicSensor>(DigitalPort.D3, (dp, c) => new UltrasonicSensor(dp, c));
                Observable
                .Interval(TimeSpan.FromSeconds(0.5))
                .Subscribe(_ => { Console.WriteLine(sensor.Distance); });

                Console.WriteLine("press enter key to exit");
            }, cancellationSource.Token);

            return(Task.Run(() =>
            {
                Console.ReadLine();
                module.Dispose();
                cancellationSource.Cancel(false);
            }, cancellationSource.Token));
        }
        public static void DisposeDevice <T>(this PiTopModule module, T device)
            where T : ICamera
        {
            var factory = module.GetDeviceFactory <int, ICamera>();

            AssertFactory(factory);
            factory.DisposeDevice(device);
        }
Exemple #9
0
        public void can_obtain_plate_from_module()
        {
            using var module = new PiTopModule(new DummyGpioController());

            using var plate = module.GetOrCreatePlate <FoundationPlate>();

            plate.Should().NotBeNull();
        }
        public void can_be_created_via_factory()
        {
            using var module = new PiTopModule(new DummyGpioController());
            module.UseCamera();
            using var camera = module.GetOrCreateCamera <FileSystemCamera>(new DirectoryInfo(Path.GetTempPath()));

            camera.Should()
            .NotBeNull();
        }
        public void can_load_images()
        {
            using var dir    = DisposableDirectory.CreateTemp();
            using var module = new PiTopModule(new DummyGpioController());
            module.UseCamera();
            using var camera = module.GetOrCreateCamera <FileSystemCamera>(dir.Root);

            camera.FrameCount.Should()
            .Be(3);
        }
Exemple #12
0
        public void plate_can_create_led()
        {
            using var module = new PiTopModule(new DummyGpioController());

            using var plate = module.GetOrCreatePlate <FoundationPlate>();

            using var led = plate.GetOrCreateDevice <Led>(DigitalPort.D0);

            led.Should().NotBeNull();
        }
Exemple #13
0
        public Potentiometer(AnaloguePort port, int deviceAddress, bool normalizeValue = true) : base(port, deviceAddress)
        {
            _normalizeValue = normalizeValue;
            var(pin1, _)    = Port.ToPinPair();
            var bus = PiTopModule.CreateI2CDevice(deviceAddress);

            _adc = new AnalogueDigitalConverter(bus, pin1);

            AddToDisposables(_adc);
        }
Exemple #14
0
        public void plate_returns_previously_created_devices()
        {
            using var module = new PiTopModule(new DummyGpioController());

            using var plate = module.GetOrCreatePlate <FoundationPlate>();

            var led1 = plate.GetOrCreateDevice <Led>(DigitalPort.D0);
            var led2 = plate.GetOrCreateDevice <Led>(DigitalPort.D0);

            led2.Should().BeSameAs(led1);
        }
        public void cannot_use_factory_if_is_not_initialised()
        {
            using var module = new PiTopModule(new DummyGpioController());
            var action = new Action(() =>
                module.GetOrCreateCamera<FileSystemCamera>(new DirectoryInfo(Path.GetTempPath()))
            );

            action.Should().Throw<InvalidOperationException>()
                .Which
                .Message
                .Should()
                .Match("Cannot find a factory if type PiTop.Abstractions.IConnectedDeviceFactory<PiTop.Camera.FileSystemCameraSettings, PiTop.Camera.FileSystemCamera>, make sure to configure the module calling UseCamera first.");
        }
Exemple #16
0
        public Wizard(PiTopModule module, IWizardStep <T>[] steps)
        {
            _steps   = steps;
            _display = module.Display;

            module.UpButton.PressedChanged += (sender, pressed) => {
                if (pressed)
                {
                    steps[_currentStep].Up();
                }
            };

            module.DownButton.PressedChanged += (sender, pressed) => {
                if (pressed)
                {
                    steps[_currentStep].Down();
                }
            };

            module.SelectButton.PressedChanged += (sender, pressed) => {
                steps[_currentStep].Confirm(_data);
                var nextStep = _currentStep + 1;
                if (nextStep < steps.Length)
                {
                    _currentStep = nextStep;
                    steps[_currentStep].Initialize(_display, _font);
                }
                else
                {
                    _display.Draw((context, cr) => {
                        context.Clear(Color.Black);
                        var rect = TextMeasurer.Measure("Done!", new RendererOptions(_font));
                        var x    = 1;
                        var y    = 1;
                        context.DrawText("Done!", _font, Color.Aqua, new PointF(x, y));
                    });
                    CurrentState = WizardState.Completed;
                }
            };

            module.CancelButton.PressedChanged += (sender, pressed) => {
                _display.Draw((context, cr) => {
                    context.Clear(Color.Black);
                    var rect = TextMeasurer.Measure("Cancelled.", new RendererOptions(_font));
                    var x    = 1;
                    var y    = 1;
                    context.DrawText("Cancelled.", _font, Color.Aqua, new PointF(x, y));
                });
                CurrentState = WizardState.Cancelled;
            };
        }
        public void can_scan_images()
        {
            using var dir    = DisposableDirectory.CreateTemp();
            using var module = new PiTopModule(new DummyGpioController());
            module.UseCamera();
            using var camera = module.GetOrCreateCamera <FileSystemCamera>(dir.Root);

            var source1 = camera.CurrentFrameSource;

            camera.Advance();
            var source2 = camera.CurrentFrameSource;

            source2.Name.Should().NotBe(source1.Name);
        }
Exemple #18
0
        private static Task TestButton(DigitalPort buttonPort, DigitalPort[] ledPorts)
        {
            var cancellationSource = new CancellationTokenSource();
            var module             = new PiTopModule();
            var plate = module.GetOrCreatePlate <FoundationPlate>();

            Task.Run(() =>
            {
                var button = plate.GetOrCreateDevice <Button>(buttonPort);

                foreach (var digitalPort in ledPorts)
                {
                    plate.GetOrCreateDevice <Led>(digitalPort);
                }

                var leds = plate.DigitalDevices.OfType <Led>().ToArray();

                var buttonStream = Observable
                                   .FromEventPattern <bool>(h => button.PressedChanged += h, h => button.PressedChanged -= h);
                var pos = -1;
                buttonStream
                .Where(e => e.EventArgs)
                .Select(_ =>
                {
                    var next = ((pos + 1) % leds.Length);
                    var pair = new { Prev = pos, Next = ((pos + 1) % leds.Length) };
                    pos      = next;
                    return(pair);
                })
                .Subscribe(p =>
                {
                    if (p.Prev >= 0)
                    {
                        leds[p.Prev].Off();
                    }
                    leds[p.Next].On();
                });

                Console.WriteLine("press enter key to exit");
            }, cancellationSource.Token);

            return(Task.Run(() =>
            {
                Console.ReadLine();
                module.Dispose();
                cancellationSource.Cancel(false);
            }, cancellationSource.Token));
        }
        public static T GetOrCreateCamera <T>(this PiTopModule module, FileSystemCameraSettings settings) where T : FileSystemCamera
        {
            IConnectedDeviceFactory <FileSystemCameraSettings, FileSystemCamera> factory = null !;

            try
            {
                factory = module.GetDeviceFactory <FileSystemCameraSettings, FileSystemCamera>();
            }
            catch (KeyNotFoundException

                   )
            {
            }

            AssertFactory(factory);
            return(factory.GetOrCreateDevice <T>(settings));
        }
Exemple #20
0
        public void cannot_create_a_different_device_on_allocated_pins()
        {
            using var module = new PiTopModule(new DummyGpioController());

            using var plate = module.GetOrCreatePlate <FoundationPlate>();

            plate.GetOrCreateDevice <Led>(DigitalPort.D0);

            var action = new Action(() =>
            {
                plate.GetOrCreateDevice <UltrasonicSensor>(DigitalPort.D0);
            });

            action.Should().Throw <InvalidOperationException>()
            .Which
            .Message
            .Should().Match("Connection D0 is already used by PiTopMakerArchitecture.Foundation.Components.Led device");
        }
        public static T GetOrCreateCamera <T>(this PiTopModule module, int index)
            where T : ICamera
        {
            IConnectedDeviceFactory <int, ICamera> factory = null !;

            try
            {
                factory = module.GetDeviceFactory <int, ICamera>();
            }
            catch (KeyNotFoundException

                   )
            {
            }

            AssertFactory(factory);
            return(factory.GetOrCreateDevice <T>(index));
        }
Exemple #22
0
        static void Main(string[] args)
        {
            using var module = new PiTopModule();

            var display = module.Display;

            Console.WriteLine("press enter key to render");
            Console.ReadLine();
            display.Draw(d =>
            {
                var square = new RectangularPolygon(display.Width / 4, display.Height / 4, display.Width / 2, display.Height / 2);

                d.Fill(Color.White, square);
            });

            Console.WriteLine("press enter key to exit");
            Console.ReadLine();
        }
Exemple #23
0
        public LEDService()
        {
            _module = new PiTopModule();

            _plate = _module.GetOrCreatePlate <FoundationPlate>();

            _green = _plate.GetOrCreateDevice <Led>(DigitalPort.D0);
            _green.DisplayProperties.Add(new NamedCssColor("green"));

            _amber = _plate.GetOrCreateDevice <Led>(DigitalPort.D1);
            _amber.DisplayProperties.Add(new NamedCssColor("gold"));

            _red = _plate.GetOrCreateDevice <Led>(DigitalPort.D2);
            _red.DisplayProperties.Add(new NamedCssColor("red"));

            _green.Off();
            _amber.Off();
            _red.Off();
        }
Exemple #24
0
        static void Main(string[] args)
        {
            using var module = new PiTopModule()
                               .UseCamera();

            var count = OpenCvCamera.GetCameraCount();

            Console.WriteLine($"Found {count} cameras available");

            var camera = module.GetOrCreateCamera <OpenCvCamera>(0);

            var file = new FileInfo("./test.png");

            var frame = camera.GetFrameAsMat();

            frame.SaveImage(file.FullName);

            module.DisposeDevice(camera);

            Console.WriteLine($"Dumping frame at {file.FullName}");
        }
        public static PiTopModule UseCamera(this PiTopModule module)
        {
            module.AddDeviceFactory <int, ICamera>(deviceType =>
            {
                var ctorSignature = new[] { typeof(int) };
                var ctor          = deviceType.GetConstructor(ctorSignature);

                if (ctor != null)
                {
                    return(cameraIndex =>
                           (ICamera)Activator.CreateInstance(deviceType, cameraIndex) !);
                }

                throw new InvalidOperationException(
                    $"Cannot find suitable constructor for type {deviceType}, looking for signature {ctorSignature}");
            });

            module.AddDeviceFactory <FileSystemCameraSettings, FileSystemCamera>(deviceType =>
            {
                return(settings => new FileSystemCamera(settings));
            });

            return(module);
        }
 public static T GetOrCreateCamera <T>(this PiTopModule module, DirectoryInfo directory, string imageFileSearchPattern = "*.png") where T : FileSystemCamera
 {
     return(module.GetOrCreateCamera <T>(
                new FileSystemCameraSettings(directory, imageFileSearchPattern)));
 }
Exemple #27
0
        private static Task TestSemaphore(DigitalPort ultrasonicSensorPort, DigitalPort greenLedPort, DigitalPort yellowLedPort, DigitalPort redLedPort, int greenThreshold, int yellowThreshold, int redThreshold)
        {
            var module = new PiTopModule();
            var plate  = module.GetOrCreatePlate <FoundationPlate>();

            var cancellationSource = new CancellationTokenSource();
            var greenLed           = plate.GetOrCreateDevice <Led>(greenLedPort);

            greenLed.DisplayProperties.Add(new NamedCssColor("green"));
            var yellowLed = plate.GetOrCreateDevice <Led>(yellowLedPort);

            yellowLed.DisplayProperties.Add(new NamedCssColor("yellow"));
            var redLed = plate.GetOrCreateDevice <Led>(redLedPort);

            redLed.DisplayProperties.Add(new NamedCssColor("red"));
            ClearLeds();
            Task.Run(() =>
            {
                var sensor = plate.GetOrCreateDevice <UltrasonicSensor>(ultrasonicSensorPort);
                Observable
                .Interval(TimeSpan.FromSeconds(0.5))
                .Subscribe(_ =>
                {
                    var distance = sensor.Distance.Value;


                    switch (distance)
                    {
                    case { } x when x > greenThreshold:
                        greenLed.On();
                        yellowLed.Off();
                        redLed.Off();
                        break;

                    case { } x when x <greenThreshold && x> yellowThreshold:
                        greenLed.Off();
                        yellowLed.On();
                        redLed.Off();
                        break;

                    case { } x when x < redThreshold:
                        greenLed.Off();
                        yellowLed.Off();
                        redLed.On();
                        break;
                    }
                });

                Console.WriteLine("press enter key to exit");
            }, cancellationSource.Token);


            return(Task.Run(() =>
            {
                Console.ReadLine();
                module.Dispose();
                ClearLeds();
                cancellationSource.Cancel(false);
            }, cancellationSource.Token));

            void ClearLeds()
            {
                greenLed.Off();
                yellowLed.Off();
                redLed.Off();
            }
        }