Exemplo n.º 1
0
 static private void set_pin(OutputPinConfiguration pin, int state_to_be, int pinstate)
 {
     if (pinstate != state_to_be)
     {
         connection.Toggle(pin);
     }
 }
Exemplo n.º 2
0
        public static void Main3(string[] args)
        {
            var driver = GpioConnectionSettings.DefaultDriver;

            led1      = ConnectorPin.P1Pin11.Output();
            led2      = ConnectorPin.P1Pin13.Output();
            buttonPin = ProcessorPin.Pin18;
            var filename = @"/usr/share/scratch/Media/Sounds/Electronic/Whoop.wav";
            var stream   = new MemoryStream();

            using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                file.CopyTo(stream);
            }
            //var player = new SoundPlayer (stream);
            var isPlaying = false;

            driver.Allocate(buttonPin, PinDirection.Input);
            driver.Allocate(led1.Pin, PinDirection.Output);
            driver.Allocate(led2.Pin, PinDirection.Output);


            bool toggle = true;

            while (true)
            {
                var pressed = !driver.Read(buttonPin);
                if (pressed)
                {
                    if (!isPlaying)
                    {
                        isPlaying = true;
                        //stream.Position = 0;
                        //player.Dispose ();
                        //player.Stream.Seek (0, SeekOrigin.Begin);
                        //player.Play ();
                        Task.Run(() => {
                            player.Stream.Position = 0;
                            player.PlaySync();
                            //	isPlaying = false;
                        });
                    }
                    driver.Write(led1.Pin, toggle);
                    toggle = !toggle;
                    driver.Write(led2.Pin, toggle);
                    Console.WriteLine("pushed");
                }
                else
                {
                    if (isPlaying)
                    {
                        player.Stop();
                        isPlaying = false;
                    }
                    driver.Write(led1.Pin, false);
                    driver.Write(led2.Pin, false);
                }
                System.Threading.Thread.Sleep(200);
            }
            driver.Release(ProcessorPin.Pin18);
        }
        static bool ConnectPort(string[] args)
        {
            //Connect to the right UART port (may be USB in Windows/Unix/Mac or a Raspberry Mainboard)
            if (g_bIoTBoard)
            {
                //Define pins to control baudrate (GPIO2 on Pin21) and force a HW reset of the MWSUB3G (Pin12)
                OutputPinConfiguration pinGPIO2 = ConnectorPin.P1Pin21.Output();
                m_pinConnection = new GpioConnection(pinGPIO2);
                OutputPinConfiguration pinRESET = ConnectorPin.P1Pin12.Output();
                m_pinConnection.Add(pinRESET);

                //Reset sequence
                m_pinConnection[pinRESET] = false;
                Thread.Sleep(100);
                m_pinConnection[pinGPIO2] = true; //true for 500Kbps, change to false for 2400bps low speed
                m_pinConnection[pinRESET] = true;
                Thread.Sleep(2500);               //wait for initialization firmware code to finish startup

                //Open COM port from Raspberry mainboard
                string sCOMPort = "/dev/ttyAMA0";
                g_objRFE.ConnectPort(sCOMPort, g_nBaudrate, true);
                Console.WriteLine("Connected to port " + sCOMPort);
            }
            else if (args.Contains("/p:AUTO", StringComparer.Ordinal))
            {
                //This is any non-IoT platform with a single device connected to USB
                if (g_objRFE.GetConnectedPorts())
                {
                    if (g_objRFE.ValidCP2101Ports.Length == 1)
                    {
                        bool bForceBaudrate = (RFECommunicator.IsRaspberry() && g_nBaudrate > 115200);
                        g_objRFE.ConnectPort(g_objRFE.ValidCP2101Ports[0], g_nBaudrate, RFECommunicator.IsUnixLike() && !RFECommunicator.IsMacOS(), bForceBaudrate);
                    }
                }
                if (g_objRFE.PortConnected)
                {
                    Console.WriteLine("Connected to port " + g_objRFE.ValidCP2101Ports[0]);
                }
                else
                {
                    Console.WriteLine("ERROR: no port available, please review your connection");
                    return(false);
                }
            }
            else
            {
                //Use specified port from command line
                int nPos = Array.FindIndex(args, x => x.StartsWith("/p:"));
                if (nPos >= 0)
                {
                    string sCOMPort = args[nPos].Replace("/p:", "");
                    Console.WriteLine("Trying manual port: " + sCOMPort);
                    g_objRFE.ConnectPort(sCOMPort, g_nBaudrate, RFECommunicator.IsUnixLike() && !RFECommunicator.IsMacOS());
                    Console.WriteLine("Connected to port " + sCOMPort);
                }
            }

            return(g_objRFE.PortConnected);
        }
Exemplo n.º 4
0
 public void Setup()
 {
     redLed    = ConnectorPin.P1Pin12.Output();
     yellowLed = ConnectorPin.P1Pin16.Output();
     greenLed  = ConnectorPin.P1Pin18.Output();
     leds      = new OutputPinConfiguration[] { redLed, greenLed, yellowLed };
     conn      = new GpioConnection(leds);
 }
Exemplo n.º 5
0
        public void Setup()
        {
            _redLed    = ConnectorPin.P1Pin12.Output();
            _yellowLed = ConnectorPin.P1Pin16.Output();
            _greenLed  = ConnectorPin.P1Pin18.Output();
            _leds      = new OutputPinConfiguration[] { _redLed, _greenLed, _yellowLed };
            _conn      = new GpioConnection(_leds);

            _conn[_greenLed]  = true;
            _conn[_yellowLed] = true;
            _conn[_redLed]    = true;
        }
Exemplo n.º 6
0
        private void Blink(OutputPinConfiguration _ledPin, int count)
        {
            // GpioConnection.Blink does not work (on rpi2 at least?), so this is my own implementation
            bool enable = true;

            for (int i = 0; i < count * 2; i++)
            {
                _conn[_ledPin] = enable;
                Thread.Sleep(250);
                enable = !enable;
            }
            _conn[_ledPin] = false;
        }
Exemplo n.º 7
0
 public Lighting(ConfigurationObject.DevicesConfig.LightingConfig config, GpioConnection gpioConnection)
     : base(gpioConnection)
 {
     Description     = config.Description;
     Floor           = config.Floor;
     _timerEnabled   = config.TimerEnabled;
     _offTime        = config.OffTime;
     _onTime         = config.OnTime;
     _switchPin      = config.SwitchPin.Output().Disable();
     _switchPin.Name = config.Description;
     _deviceStatus   = config.DeviceStatus;
     Disabled        = config.Disabled;
 }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            OutputPinConfiguration pin12 = ConnectorPin.P1Pin12.Output();

            pin12.Enabled = false;

            using (GpioConnection connection = new GpioConnection(pin12))
            {
                while (!Console.KeyAvailable)
                {
                    connection.Toggle(pin12);
                    Thread.Sleep(250);
                }
            }
        }
Exemplo n.º 9
0
        static StatusLED()
        {
            try
            { RED_PIN = ConnectorPin.P1Pin12.Output();
              GREEN_PIN = ConnectorPin.P1Pin16.Output();
              BLUE_PIN  = ConnectorPin.P1Pin21.Output();

              pins     = new OutputPinConfiguration[3];
              pins [0] = RED_PIN;
              pins [1] = GREEN_PIN;
              pins [2] = BLUE_PIN;
              cnx      = new GpioConnection(pins);
              cnx.Open(); }
            catch {
            }
        }
Exemplo n.º 10
0
        public CommandExecuter(Settings setting)
        {
            this.setting = setting;

            servo = new ProcessStartInfo("/bin/bash");
            servo.UseShellExecute        = false;
            servo.CreateNoWindow         = true;
            servo.RedirectStandardOutput = true;
            servo.RedirectStandardError  = true;

#if !DEBUG
            pin1       = ConnectorPin.P1Pin38.Output();
            pin2       = ConnectorPin.P1Pin40.Output();
            connection = new GpioConnection(pin1, pin2);
#endif
        }
Exemplo n.º 11
0
        /// <summary>
        /// Add a gpio to the global connection if not already added setting direction
        /// </summary>
        /// <param name="processorPin"></param>
        /// <param name="output"></param>
        public static void Add(ProcessorPin processorPin, bool output)
        {
            //if (!CommonHelper.IsBoard)
            //    return;

            if (output)
            {
                OutputPinConfiguration opc = processorPin.Output();
                ConnectionGlobalPinAdd(opc);
            }
            else
            {
                InputPinConfiguration ipc = processorPin.Input();
                ConnectionGlobalPinAdd(ipc);
            }
        }
Exemplo n.º 12
0
 private static void InitBoardGpio()
 {
     try
     {
         _pin11 = ConnectorPin.P1Pin11.Output();
         _gpio  = new GpioConnection(_pin11);
     }
     catch (Exception ex)
     {
         Logger.Error("Error initializing GPIO: " + ex.Message);
         if (ex.InnerException != null)
         {
             Logger.Error(ex.InnerException.Message);
         }
     }
 }
Exemplo n.º 13
0
 public Shutter(ConfigurationObject.DevicesConfig.ShutterConfig config, GpioConnection gpioConnection)
     : base(gpioConnection)
 {
     Description          = config.Description;
     Floor                = config.Floor;
     EmergencyEnabled     = config.EmergencyEnabled;
     CompleteWayInSeconds = config.CompleteWayInSeconds;
     _timerEnabled        = config.TimerEnabled;
     _onTime              = config.OpenTime;
     _offTime             = config.CloseTime;
     _openPin             = config.OpenPin.Output().Disable();
     _closePin            = config.ClosePin.Output().Disable();
     _openPin.Name        = $"{config.Description}_openPin";
     _closePin.Name       = $"{config.Description}_closePin";
     _deviceStatus        = config.DeviceStatus;
     Disabled             = config.Disabled;
 }
Exemplo n.º 14
0
        public FormBatteryGauge()
        {
            //ushort d = 0x7fff;
            //byte[] byteArray = BitConverter.GetBytes(d).Reverse().ToArray();

            //var p = 0.34E-3;

            InitializeComponent();
            _LTC2943Service = new LTC2943Service();
            _LTC2943Service.OnGaugeChanged += _LTC2943Service_OnGaugeChanged;
            _LTC2943Service.OnUnderCharge  += _LTC2943Service_OnUnderCharge;

            _gpioConnectionGlobalPin = new GpioConnection();
            OutputPinConfiguration opc = ProcessorPin.Gpio06.Output();

            _gpioConnectionGlobalPin.Add(opc);
            _modemResetPin = _gpioConnectionGlobalPin.Pins[ProcessorPin.Gpio06];
        }
Exemplo n.º 15
0
        public clsRinger(OutputPinConfiguration RingerPower, OutputPinConfiguration RingerOscillator, float[] RingPattern = null)
        {
            if (RingPattern == null)
            {
                RingPattern = ringPattern_UK;
            }
            ringPattern = RingPattern;

            RingerPowerPin      = RingerPower;
            RingerOscillatorPin = RingerOscillator;

            var GPIOconfig = new GpioConnectionSettings();

            GPIO = new GpioConnection(GPIOconfig, RingerPowerPin, RingerOscillatorPin);

            RingerThread = new Thread(Ring);
            RingerThread.IsBackground = true;
            RingerThread.Name         = "Ringer Thread";
        }
Exemplo n.º 16
0
    static void Main()
    {
        Console.WriteLine("Initializing GPIO Connection...");
        //create a connection to the desired GPIO pins
        //refer to the pinouts diagram for the correct pin
        OutputPinConfiguration red   = ConnectorPin.P1Pin36.Output();
        OutputPinConfiguration green = ConnectorPin.P1Pin32.Output();

        var connection = new GpioConnection(green, red);

        Console.Write("1. Who is the President of the United States? ");

        Console.WriteLine("a. Puff Daddy");
        Console.WriteLine("b. Hillary Clinton");
        Console.WriteLine("c. Barack Obama");
        Console.WriteLine("d. George Bush");
        string ans = Console.ReadLine().ToLower();

        /*if (ans == "c") {
         *      OutputPinConfiguration led = green;
         * }else {
         *      OutputPinConfiguration led = red;
         * }*/
        OutputPinConfiguration led = ans == "c" ? green : red;

        for (int ctr = 0; ctr < 10; ctr++)
        {
            connection.Toggle(led);
            Thread.Sleep(150);
        }
        /*Console.WriteLine("Answer: ");*/

        /*Console.Write("2. Summer Solstice is the shortest day of the year.");
         * Console.WriteLine("a. True");
         * Console.WriteLine("b. False");
         * string ans = Console.ReadLine().ToLower();
         *
         * OutputPinConfiguration led = ans == "a" ? green : red;*/

        //TODO: Add program code here
        connection.Close();
    }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Max9744Device" /> class.
        /// </summary>
        /// <param name="i2cAddress">The i2c address.</param>
        /// <param name="mutePin">The mute pin.</param>
        /// <param name="shutdownPin">The shutdown pin.</param>
        /// <param name="sdaPin">The sda pin.</param>
        /// <param name="sclPin">The SCL pin.</param>
        /// <param name="gpioConnectionDriverFactory">The gpio connection driver factory.</param>
        /// <param name="i2CDeviceConnectionReporter">The i2 c device connection reporter.</param>
        public Max9744Device(
            byte i2cAddress,
            ConnectorPin mutePin,
            ConnectorPin shutdownPin,
            ProcessorPin sdaPin,
            ProcessorPin sclPin,
            IGpioConnectionDriverFactory? gpioConnectionDriverFactory,
            II2cDeviceConnectionReporter? i2CDeviceConnectionReporter = null)
        {
            this.gpioConnectionDriverFactory = GpioConnectionDriverFactory.EnsureGpioConnectionDriverFactory(gpioConnectionDriverFactory);
            this.gpioConnectionDriver = this.gpioConnectionDriverFactory.Get();

            // connect volume via i2c
            this.i2CDriver = new I2cDriver(sdaPin, sclPin);
            this.connection = this.i2CDriver.Connect(i2cAddress, i2CDeviceConnectionReporter);

            // connect shutdown via gpio
            this.mutePin = mutePin.Output().Revert();
            this.shutdownPin = shutdownPin.Output().Revert();
            this.gpioConnection = new GpioConnection(this.gpioConnectionDriverFactory, this.shutdownPin, this.mutePin);
        }
		private void Run(string[] args)
		{
			Console.WriteLine("Press any key to exit...");

			var leds = new OutputPinConfiguration[]
			{
				ProcessorPin.Pin17.Output(),
				ProcessorPin.Pin18.Output(),
				ProcessorPin.Pin27.Output(),
			};

			using (var connection = new GpioConnection(leds))
			{
				while (!Console.KeyAvailable)
				{
					foreach (var led in leds)
					{
						connection.Pins[led].Toggle();
						System.Threading.Thread.Sleep(500);
						connection.Pins[led].Toggle();
					}
				}
			}
		}
Exemplo n.º 19
0
        private void ToogleGPIO(ProcessorPin selectedGPIO)
        {
            OutputPinConfiguration _gpio = selectedGPIO.Output();

            try
            {
                if (_connectionGlobalPin == null)
                {
                    _connectionGlobalPin = new GpioConnection(_gpio);
                }

                if (!_connectionGlobalPin.Contains(_gpio))
                {
                    _connectionGlobalPin.Add(_gpio);
                }

                _connectionGlobalPin.Pins[_gpio].Enabled = !_connectionGlobalPin.Pins[_gpio].Enabled;
                CommonHelper.Logger.Info("GPIO {0}: enabled", _connectionGlobalPin.Pins[_gpio].Enabled);
            }
            catch (Exception e)
            {
                CommonHelper.Logger.Error(e, "GPIO Error : {0}", e.Message);
            }
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            //create instance of settings object to get settings from config file
            Properties.Settings settings = new Properties.Settings();

            //set idleTimout to value from PLCupdater.exe.config file
            idleTimeout = settings.idleTimeout;

            //Initialize timer to shutdown device when idle
            timer = new Timer(new TimerCallback(idleShutdown), null, idleTimeout, Timeout.Infinite);

            //flag to prevent triggering update while one is already in progress
            bool updating = false;

            //pin definitions

            //blue LED on pin 12, provision as a low-level pin
            ProcessorPin blueLED = ConnectorPin.P1Pin12.ToProcessor();

            //red LED on pin 18, provision as a low-level pin
            ProcessorPin redLED = ConnectorPin.P1Pin18.ToProcessor();

            //green LED on pin 16, provision as a managed output
            OutputPinConfiguration greenLED = ConnectorPin.P1Pin16.Output();

            //create a low-level connection driver for red LED and blue LED
            IGpioConnectionDriver driver = GpioConnectionSettings.DefaultDriver;

            driver.Allocate(redLED, PinDirection.Output);
            driver.Allocate(blueLED, PinDirection.Output);

            //turn blue LED on to indicate program is ready
            driver.Write(blueLED, true);

            //create instance of DF1 protocol serial connection class
            DF1Comm.DF1Comm df1 = new DF1Comm.DF1Comm();

            //create high-level connection for green LED and buttons
            //allows for blinking LEDs and OnStatusChanged events for buttons
            GpioConnection gpioConnection = new GpioConnection(greenLED);

            //Program A download on pin 15, reverse input so that it's normally open instead of normally closed
            //Download program A to PLC when pressed
            InputPinConfiguration A_Down = ConnectorPin.P1Pin15.Input()
                                           .Revert()
                                           .OnStatusChanged(a =>
            {
                //if the button is pressed and update is not currently running, start update
                if (a && !updating)
                {
                    //set updating flag to true
                    updating = true;

                    //start update to transfer program A to the PLC using serial port from the config
                    DownloadProgram(df1, driver, gpioConnection, redLED, greenLED, settings.FileA, settings.SerialPort);

                    //set updating flag back to false
                    updating = false;
                }
            });

            //Program B download on pin 7, reverse input so that it's normally open instead of normally closed
            //Download program B to PLC when pressed
            InputPinConfiguration B_Down = ConnectorPin.P1Pin7.Input()
                                           .Revert()
                                           .OnStatusChanged(a =>
            {
                //if the button is pressed and update is not currently running, start update
                if (a && !updating)
                {
                    //set updating flag to true
                    updating = true;

                    //start update to transfer program A to the PLC using serial port from the config
                    DownloadProgram(df1, driver, gpioConnection, redLED, greenLED, settings.FileB, settings.SerialPort);

                    //set updating flag back to false
                    updating = false;
                }
            });

            //Progam A upload on pin 13, reverse input so that it's normally open instead of normally closed
            //Upload program A from PLC when pressed
            var A_Up = ConnectorPin.P1Pin13.Input()
                       .Revert()
                       .OnStatusChanged(b =>
            {
                //if the button is pressed and update is not currently running, start update
                if (b && !updating)
                {
                    //set updating flag to true
                    updating = true;

                    //start update to transfer program B to the PLC using serial port from the config
                    //DownloadProgram(df1, driver, gpioConnection, redLED, greenLED, settings.FileB, settings.SerialPort);
                    UploadProgram(df1, driver, gpioConnection, redLED, greenLED, settings.FileA, settings.SerialPort);

                    //set updating flag back to false
                    updating = false;
                }
            });

            //Progam B upload on pin 11, reverse input so that it's normally open instead of normally closed
            //Upload program B from PLC when pressed
            var B_Up = ConnectorPin.P1Pin11.Input()
                       .Revert()
                       .OnStatusChanged(b =>
            {
                //if the button is pressed and update is not currently running, start update
                if (b && !updating)
                {
                    //set updating flag to true
                    updating = true;

                    //start update to transfer program B to the PLC using serial port from the config
                    //DownloadProgram(df1, driver, gpioConnection, redLED, greenLED, settings.FileB, settings.SerialPort);
                    UploadProgram(df1, driver, gpioConnection, redLED, greenLED, settings.FileB, settings.SerialPort);

                    //set updating flag back to false
                    updating = false;
                }
            });

            //add the button configurations to the high-level connection
            gpioConnection.Add(A_Up);
            gpioConnection.Add(B_Up);
            gpioConnection.Add(A_Down);
            gpioConnection.Add(B_Down);

            //prevent program from exiting
            Console.ReadKey();
        }
Exemplo n.º 21
0
        private static void UploadProgram(DF1Comm.DF1Comm df1, IGpioConnectionDriver driver, GpioConnection gpioConnection, ProcessorPin redLED, OutputPinConfiguration greenLED, string filename, string serialPort)
        {
            startIdleTimer();
            //turn on red LED while update is in progress
            driver.Write(redLED, true);

            //set serial port on DF1 class to serial port specified, e.g. "/dev/ttyUSB0"
            df1.ComPort = serialPort;

            //detectBaudRate(df1);

            //Create new PLCFileDetails object
            System.Collections.ObjectModel.Collection <DF1Comm.DF1Comm.PLCFileDetails> PLCFiles = new System.Collections.ObjectModel.Collection <DF1Comm.DF1Comm.PLCFileDetails>();

            //byte collection to hold raw data to send to PLC
            System.Collections.ObjectModel.Collection <byte> data = new System.Collections.ObjectModel.Collection <byte>();

            //try to upload the PLCfiles from the PLC
            try
            {
                PLCFiles = df1.UploadProgramData();
                try
                {
                    fileWriter = new System.IO.StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename));
                    for (int i = 0; i < PLCFiles.Count; i++)
                    {
                        fileWriter.WriteLine(String.Format("{0:x2}", PLCFiles[i].FileType));
                        fileWriter.WriteLine(String.Format("{0:x2}", PLCFiles[i].FileNumber));
                        for (int j = 0; j < PLCFiles[i].data.Length; j++)
                        {
                            fileWriter.Write(String.Format("{0:x2}", PLCFiles[i].data[j]));
                        }
                        fileWriter.WriteLine();
                    }
                    fileWriter.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Could not save PLC file. " + ex.Message + " " + ex.StackTrace);
                    rapidBlink(driver, redLED);
                    startIdleTimer();
                    if (fileWriter != null)
                    {
                        fileWriter.Close();
                    }
                    return;
                }
            }

            //write the error to the console if an error occurs uploading the program
            catch (Exception ex)
            {
                Console.WriteLine("Could not upload PLC file. " + ex.Message + " " + ex.StackTrace);
                rapidBlink(driver, redLED);
                startIdleTimer();
                return;
            }

            //turn off red LED when upload is complete
            driver.Write(redLED, false);

            //write a success message to the console if completed without errors
            Console.WriteLine("Successful Upload");

            //turn on green LED for 5 seconds when update is complete
            gpioConnection.Blink(greenLED, TimeSpan.FromSeconds(5));

            //reset the idle shutdown timer
            startIdleTimer();
            return;
        }
Exemplo n.º 22
0
 public Led(OutputPinConfiguration outputPin, IGpioConnectionDriver driver = null)
 {
     PinConfig = outputPin;
     Driver    = driver ?? GpioConnectionSettings.DefaultDriver;
     Driver.Allocate(PinConfig.Pin, PinDirection.Output);
 }
Exemplo n.º 23
0
 public void Connect()
 {
     pinConfig  = ConnectorPin.P1Pin18.Output();
     connection = new GpioConnection(pinConfig);
 }
Exemplo n.º 24
0
 public GpioCaller()
 {
     led1       = ConnectorPin.P1Pin11.Output();
     connection = new GpioConnection(led1);
 }
Exemplo n.º 25
0
        private static void Main(string[] args)
        {
            Console.CursorVisible = false;


            var driver = GpioConnectionSettings.DefaultDriver;

            led1      = ConnectorPin.P1Pin11.Output();
            led2      = ConnectorPin.P1Pin13.Output();
            buttonPin = ProcessorPin.Pin18;
            var filename = @"/usr/share/scratch/Media/Sounds/Electronic/ComputerBeeps1.wav";
            var stream   = new MemoryStream();

            using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                file.CopyTo(stream);
            }
            stream.Position = 0;
            //player = new SoundPlayer (filename);
            var isPlaying = false;

            driver.Allocate(buttonPin, PinDirection.Input);
            driver.Allocate(led1.Pin, PinDirection.Output);
            driver.Allocate(led2.Pin, PinDirection.Output);



            const ConnectorPin triggerPin = ConnectorPin.P1Pin10;
            const ConnectorPin echoPin    = ConnectorPin.P1Pin08;

            Console.WriteLine("HC-SR04 Sample: measure distance");
            Console.WriteLine();
            Console.WriteLine("\tTrigger: {0}", triggerPin);
            Console.WriteLine("\tEcho: {0}", echoPin);
            Console.WriteLine();

            var interval = GetInterval(args);
            //var driver = GpioConnectionSettings.DefaultDriver;
            bool toggle = true;

            using (var connection = new HcSr04Connection(
                       driver.Out(triggerPin.ToProcessor()),
                       driver.In(echoPin.ToProcessor()))) {
                while (true)
                {
                    try {
                        var distance = connection.GetDistance().Centimeters;
                        if (distance < 100)
                        {
                            if (!isPlaying)
                            {
                                isPlaying = true;
                                Task.Run(() => {
                                    stream.Position = 0;

                                    //player = new SoundPlayer(
                                    lock (stream) {
                                        using (player = new SoundPlayer(stream)) {
                                            try {
                                                player.PlaySync();
                                            } catch (Exception ex) {
                                                Console.WriteLine(ex.ToString());
                                            }
                                            Timer.Sleep(TimeSpan.FromSeconds(3));
                                        }
                                    }
                                    isPlaying = false;
                                });
                            }
                            driver.Write(led1.Pin, toggle);
                            toggle = !toggle;
                            driver.Write(led2.Pin, toggle);
                        }
                        else
                        {
                            if (isPlaying)
                            {
                                //lock (player) {
                                //	player.Stop ();
                                //}
                                //player.Dispose();
                                //	isPlaying = false;
                            }
                            driver.Write(led1.Pin, false);
                            driver.Write(led2.Pin, false);
                        }
                        //Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:0.0}cm", distance).PadRight(16));
                        //Console.CursorTop--;
                    } catch (TimeoutException e) {
                        Console.WriteLine("(Timeout): " + e.Message);
                    }

                    Timer.Sleep(interval);
                }
            }

            Console.CursorVisible = true;
        }
Exemplo n.º 26
0
        //Downloads program to PLC using specified file name and serial port
        private static void DownloadProgram(DF1Comm.DF1Comm df1, IGpioConnectionDriver driver, GpioConnection gpioConnection, ProcessorPin redLED, OutputPinConfiguration greenLED, string filename, string serialPort)
        {
            startIdleTimer();
            //turn on red LED while update is in progress
            driver.Write(redLED, true);

            //set serial port on DF1 class to serial port specified, e.g. "/dev/ttyUSB0"
            df1.ComPort = serialPort;

            //detectBaudRate(df1);

            //Create new PLCFileDetails object
            System.Collections.ObjectModel.Collection <DF1Comm.DF1Comm.PLCFileDetails> PLCFiles = new System.Collections.ObjectModel.Collection <DF1Comm.DF1Comm.PLCFileDetails>();

            //Create new PLCFile with the defaults
            DF1Comm.DF1Comm.PLCFileDetails PLCFile = default(DF1Comm.DF1Comm.PLCFileDetails);


            //try reading the program file using the filename specified
            try
            {
                //create fileReader to read from file
                fileReader = new System.IO.StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename));

                //initialize string to hold contents of each line
                string line = null;

                //byte collection to hold raw data to send to PLC
                System.Collections.ObjectModel.Collection <byte> data = new System.Collections.ObjectModel.Collection <byte>();

                //loop until the end of the file is reached
                //data is read in chunks of 3 lines
                //the first line is the FileType
                //the second line is the FileNumber
                //and the third line is the data
                //these are converted into a PLCFile and added to the PLCFiles collection
                while (!(fileReader.EndOfStream))
                {
                    //get the contents of the first line
                    line = fileReader.ReadLine();

                    //convert hex ascii to byte for FileType
                    PLCFile.FileType = Convert.ToByte(line, 16);

                    //get the contents of the second line
                    line = fileReader.ReadLine();

                    //convert hex ascii to byte for FileNumber
                    PLCFile.FileNumber = Convert.ToByte(line, 16);

                    //get the contents of the third line
                    line = fileReader.ReadLine();

                    //clear the data collection
                    data.Clear();

                    //loop through the entire line two characters at a time
                    for (int i = 0; i <= line.Length / 2 - 1; i++)
                    {
                        //convert each two character ascii hex byte into a byte and add to data collection
                        data.Add(Convert.ToByte(line.Substring(i * 2, 2), 16));
                    }

                    //create byte array the same length as data collection
                    byte[] dataC = new byte[data.Count];

                    //copy data collection to byte array
                    data.CopyTo(dataC, 0);

                    //assign byte array to PLCFile data property
                    PLCFile.data = dataC;

                    //add the PLCFile to the PLCFiles collection
                    PLCFiles.Add(PLCFile);
                }

                //try to download the PLCfiles to the PLC
                try
                {
                    df1.DownloadProgramData(PLCFiles);
                    //set the PLC back to Run mode when download is complete
                    df1.SetRunMode();
                }

                //write the error to the console if an error occurs downloading the program
                catch (Exception ex)
                {
                    Console.WriteLine("Error Downloading Program. " + ex.Message + " " + ex.StackTrace);
                    rapidBlink(driver, redLED);
                    startIdleTimer();
                    return;
                }

                //turn off red LED when update is complete
                driver.Write(redLED, false);

                //write a success message to the console if completed without errors
                Console.WriteLine("Successful Download");

                //turn on green LED for 5 seconds when update is complete
                gpioConnection.Blink(greenLED, TimeSpan.FromSeconds(5));

                //reset the idle shutdown timer
                startIdleTimer();
                fileReader.Close();
                return;
            }

            //catch errors reading the program file
            catch (Exception ex)
            {
                //write the error to the console if an error occurs reading the program file
                Console.WriteLine("Error Reading Program File for Download. " + ex.Message + " " + ex.StackTrace);

                //blink red LED to indicate problem with upload
                rapidBlink(driver, redLED);

                //reset the idle shutdown timer
                startIdleTimer();
                if (fileReader != null)
                {
                    fileReader.Close();
                }
                return;
            }
        }