Exemple #1
0
 public void Dispose()
 {
     if (gpioConnection != null && gpioConnection.IsOpened)
     {
         gpioConnection.Close();
     }
 }
Exemple #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Gpio Monitor Sample");
            Console.WriteLine("Press X to close");
            Console.WriteLine("===============");

            Start();

            //var pin = (ProcessorPins)((ulong)1 << (int)testPin);
            //long pp = (long)ProcessorPins.Pin33;
            //ulong pins2 = (ulong)pin >> 32;
            //Console.WriteLine(pin);


            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey(true);
                switch (key.Key)
                {
                case ConsoleKey.X:
                    Console.WriteLine("Exiting...");
                    _conPin.Close();
                    Environment.Exit(0);
                    break;
                }
            }
        }
 public static void CloseGpio()
 {
     if (gpio != null)
     {
         gpio.Close();
         gpio = null;
     }
 }
Exemple #4
0
 /// <summary>
 /// Formを閉じる時に後始末
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
 {
     server.Close();
     connection.Remove(GPIO2);
     connection.Remove(GPIO3);
     connection.Remove(GPIO4);
     connection.Close();
 }
Exemple #5
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            ILog log = LogManager.GetLogger("GPIO");

            log.Debug("Start");

            PinConfiguration output = ConnectorPin.P1Pin36.Output().Name("Output1");

            PinConfiguration[] outputs = new PinConfiguration[]
            {
                output
            };

            GpioConnection gpio = new GpioConnection(outputs);
            //gpio.Open();

            ElectricPotential referenceVoltage = ElectricPotential.FromVolts(3.3);

            var driver = new MemoryGpioConnectionDriver(); //GpioConnectionSettings.DefaultDriver;

            Mcp3008SpiConnection spi = new Mcp3008SpiConnection(
                driver.Out(adcClock),
                driver.Out(adcCs),
                driver.In(adcMiso),
                driver.Out(adcMosi));

            IInputAnalogPin inputPin = spi.In(Mcp3008Channel.Channel0);

            gpio.Open();
            ElectricPotential volts = ElectricPotential.FromVolts(0);

            while (!Console.KeyAvailable)
            {
                var v = referenceVoltage * (double)inputPin.Read().Relative;
                Console.WriteLine("{0} mV", v.Millivolts);
                if ((Math.Abs(v.Millivolts - volts.Millivolts) > 100))
                {
                    volts = ElectricPotential.FromMillivolts(v.Millivolts);
                    Console.WriteLine("Voltage ch0: {0}", volts.Millivolts.ToString());
                }
                gpio.Toggle("Output1");
                Thread.Sleep(2000);
            }
            gpio.Close();

            //bool bShutdown = false;
            //while(!bShutdown)
            //{

            //    gpio.Toggle(output);
            //    log.Debug("Toggle output");

            //    Thread.Sleep(5000);

            //}
        }
Exemple #6
0
 public void Dispose()
 {
     KeepRunning = false;
     HookListenerThread.Abort();
     NumberDialed     = null;
     HookSwitchChange = null;
     HookWaitEvent.Close();
     DialWaitEvent.Close();
     GPIO.Close();
 }
 /// <summary>
 /// Close specific serial port and finish
 /// </summary>
 static void ClosePort()
 {
     if (m_pinConnection != null)
     {
         m_pinConnection.Close();
         m_pinConnection = null;
     }
     g_objRFE.Close();
     g_objRFE.Dispose();
     //g_objRFE = null;
 }
Exemple #8
0
        static void Main(string[] args)
        {
            var led1       = ConnectorPin.P1Pin11.Output();
            var connection = new GpioConnection(led1);

            for (var i = 0; i < 100; i++)
            {
                connection.Toggle(led1);
                System.Threading.Thread.Sleep(250);
            }
            connection.Close();
        }
Exemple #9
0
        private static void TestDrive()
        {
            Console.WriteLine("Testing arrows with car driving");
            ConsoleKeyInfo cki;

            var connection = new GpioConnection(driveForward, driveBackward, driveTurnLeft, driveTurnRight);

            Console.WriteLine("Press the Escape (Esc) key to quit: \n");
            do
            {
                cki = Console.ReadKey();
                Console.Write(" ---   You pressed ");
                Console.WriteLine(cki.Key.ToString());
                switch (cki.Key)
                {
                case ConsoleKey.UpArrow:
                    //connection.Blink(driveForward, new TimeSpan(0, 0, 0, 0, 300)); //Hack as we don't have immediate mode in managed code //Blink appears to have issues as it uses Timer
                    connection.Toggle(driveForward);
                    System.Threading.Thread.Sleep(300);
                    connection.Toggle(driveForward);
                    break;

                case ConsoleKey.DownArrow:
                    connection.Toggle(driveBackward);
                    System.Threading.Thread.Sleep(300);
                    connection.Toggle(driveBackward);
                    break;

                case ConsoleKey.LeftArrow:
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnLeft);
                    System.Threading.Thread.Sleep(400);
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnLeft);
                    break;

                case ConsoleKey.RightArrow:
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnRight);
                    System.Threading.Thread.Sleep(400);
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnRight);
                    break;

                default:
                    break;
                }
            } while (cki.Key != ConsoleKey.Escape);
            connection.Close();
        }
Exemple #10
0
        protected void turnOffAllPumps(object sender, EventArgs e)
        {
            var ssr1 = ConnectorPin.P1Pin36.Output();
            var ssr2 = ConnectorPin.P1Pin22.Output();

            var connection1 = new GpioConnection(ssr1);
            var connection2 = new GpioConnection(ssr2);

            connection1.Close();
            connection2.Close();

            Pump1Status.Text = "Off";
            Pump2Status.Text = "Off";
        }
Exemple #11
0
        static void Main(string[] args)
        {
            var led1 = ConnectorPin.P1Pin07.Output();

            using (var connection = new GpioConnection(led1))
            {
                for (var i = 0; i < 100; i++)
                {
                    Console.Write(".");
                    connection.Toggle(led1);
                    System.Threading.Thread.Sleep(2000);
                }

                connection.Close();
            }
        }
        private void BlinkTest()
        {
            var led1Config = ConnectorPin.P1Pin11.Output();

            var led1Con = new GpioConnection(led1Config);

            led1Con.Open();

            for (var i = 0; i < 30; i++)
            {
                led1Con.Toggle(led1Config);
                System.Threading.Thread.Sleep(1000);
            }

            led1Con.Close();
        }
Exemple #13
0
        protected void togglePump2SSR(object sender, EventArgs e)
        {
            var ssr        = ConnectorPin.P1Pin36.Output();
            var connection = new GpioConnection(ssr);

            if (Pump2Status.Text == "Off")
            {
                Pump2Status.Text = "On";
                connection.Toggle(ssr);
            }
            else
            {
                Pump2Status.Text = "Off";
                connection.Close();
            }
        }
Exemple #14
0
        private static void TestLEDs()
        {
            Console.WriteLine("Test GPIO");
            var led1       = ConnectorPin.P1Pin31.Output();
            var led2       = ConnectorPin.P1Pin33.Output();
            var led3       = ConnectorPin.P1Pin35.Output();
            var led4       = ConnectorPin.P1Pin37.Output();
            var connection = new GpioConnection(led1, led2, led3, led4);


            for (int i = 0; i < 5; i++)
            {
                connection.Blink(led1, new TimeSpan(0, 0, 1));
                connection.Blink(led2, new TimeSpan(0, 0, 1));
                connection.Blink(led3, new TimeSpan(0, 0, 1));
                connection.Blink(led4, new TimeSpan(0, 0, 1));
            }
            connection.Close();
        }
    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();
    }
Exemple #16
0
        protected void toggleHeatSSR(int ssrNumber, string onOff)
        {
            var ssr = ConnectorPin.P1Pin31.Output();

            onOff = onOff.ToLower();

            if (ssrNumber == 1)
            {
                ssr = ConnectorPin.P1Pin33.Output();
            }


            var connection = new GpioConnection(ssr);

            if (onOff == "on")
            {
                connection.Toggle(ssr);
            }
            else
            {
                connection.Close();
            }
        }
 public void Dispose()
 {
     conn.Close();
 }
Exemple #18
0
        static void Main(string[] args)
        {
            Console.Write("start");
            Console.Write("Hello worlds");

            initIO();


            Console.WriteLine("RPI inited");


            for (var i = 0; i < 2; i++)
            {
                // Toggle() switches the high/low (on/off) status of the pin
                Console.WriteLine("ON");
                ALLON();
                Console.Write("BLUE SWITCHES\n");
                Console.Write(connection [Blue1]);
                Console.Write(connection [Blue2]);
                Console.Write(connection [Blue3]);
                Console.Write(connection [Blue4]);
                Console.WriteLine("ROCKER SWITCHES\n");
                Console.Write(connection [Rocker1]);
                Console.Write(connection [Rocker2]);
                Console.Write(connection [Rocker3]);
                Console.Write(connection [Rocker4]);
                Console.WriteLine("KEY\n");
                Console.Write(connection [KEY1A]);
                Console.Write(connection [KEY1B]);
                Console.WriteLine("POSITION\n");
                Console.Write(connection [POS1A]);
                Console.Write(connection [POS1B]);
                Console.Write(connection [POS1C]);

                Console.WriteLine("FIREPULL\n");
                Console.Write(connection [FIREPULL]);

                //				led4Pin.Output().Enable;
                System.Threading.Thread.Sleep(1000);
                Console.WriteLine("OFF");
                ALLOFF();
                System.Threading.Thread.Sleep(500);
            }

            redbeacon(false);
            greenbeacon(false);
            bluebeacon(false);
            boxarmed      = false;
            boxfirepulled = false;
            sound         = false;
            food          = false;

            //MAIN LOOP
            while (true)
            {
                ALLOFF();
                if (connection [KEY1A])
                {
                    boxarmed = false;
                    noKey();
                }

                else if (connection [Rocker1])
                {
                    if (!boxarmed)                       //BOX GETTING ARMED NOW
                    {
                        ringbell(25);
                        redbeacon(true);
                        boxarmed = true;
                        if (connection [FIREPULL])
                        {
                            Console.WriteLine("ALARM ALREADY PULLED ERROR");
                            boxfirepulled = true;
                        }
                    }
                    if (connection [FIREPULL])                       //IT's HAPPENING
                    {
                        if (!boxfirepulled)
                        {
                            Console.WriteLine("FIRED ORDER PIZZA");
                            boxfired();
                            boxfirepulled = true;
                        }
                        else
                        {
                            ALLOFF();

                            System.Threading.Thread.Sleep(5000);
                            connection [RedNav] = false;
                            System.Threading.Thread.Sleep(5000);
                            connection [RedNav] = true;
                        }
                    }

                    armedBlink();
                }
                else
                {
                    if (boxarmed)                       //BOX GETTING DEARMED NOW
                    {
                        redbeacon(false);
                        greenbeacon(false);
                        bluebeacon(false);
                        food          = false;
                        boxfirepulled = false;
                        Console.WriteLine("DEARMED");
                    }
                    boxarmed = false;
                    standbyBlink();
                }
            }


//				Console.Write ("\n"+connection [Rocker1]);
//				Console.Write (connection [Rocker2]);
//				Console.Write (connection [Rocker3]);
//				Console.Write (connection [Rocker4]);
//
//				System.Threading.Thread.Sleep (10000);

//			}



            connection.Close();
        }
Exemple #19
0
        private static void TestDriveCommands(string[] args)
        {
            Console.WriteLine("Testing drive commands");
            if (args.Length <= 1)
            {
                Console.WriteLine("No commands provided");
            }
            var connection = new GpioConnection(driveForward, driveBackward, driveTurnLeft, driveTurnRight);
            var command    = "";

            for (int i = 1; i < args.Length - 1; i++)
            {
                command = args[i];
                switch (command)
                {
                case "U":
                    connection.Toggle(driveForward);
                    System.Threading.Thread.Sleep(300);
                    connection.Toggle(driveForward);
                    break;

                case "D":
                    connection.Toggle(driveBackward);
                    System.Threading.Thread.Sleep(300);
                    connection.Toggle(driveBackward);
                    break;

                case "UL":
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnLeft);
                    System.Threading.Thread.Sleep(400);
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnLeft);
                    break;

                case "UR":
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnRight);
                    System.Threading.Thread.Sleep(400);
                    connection.Toggle(driveForward);
                    connection.Toggle(driveTurnRight);
                    break;

                case "DL":
                    connection.Toggle(driveBackward);
                    connection.Toggle(driveTurnLeft);
                    System.Threading.Thread.Sleep(400);
                    connection.Toggle(driveBackward);
                    connection.Toggle(driveTurnLeft);
                    break;

                case "DR":
                    connection.Toggle(driveBackward);
                    connection.Toggle(driveTurnRight);
                    System.Threading.Thread.Sleep(400);
                    connection.Toggle(driveBackward);
                    connection.Toggle(driveTurnRight);
                    break;

                default: Console.WriteLine("Unknown command {0} Expected command to be one of U D UL UR DL DR", command);
                    break;
                }
            }
            connection.Close();
        }
Exemple #20
0
 public void Dispose()
 {
     connection?.Close();
 }
Exemple #21
0
        static void Main(string[] args)
        {
            Timer tokenRenewalTimer = null;
            var   signalEvent       = new ManualResetEvent(false);
            var   signalHandler     = new UnixSignalHandler {
                Logger = Logger
            };

            try
            {
                Logger.Info("LightNotificationClient starting...");

                // intercept Unix signals (ie. CTRL-C) so we can shut down gracefully
                signalHandler.HandleSignal(signal =>
                {
                    Logger.Info("Signal received: " + signal);
                    signalEvent.Set();
                });

                // connect to pin 11
                InitBoardGpio();

                // get the initial daylight state and turn the light on or off accordingly
                Logger.Info("Getting initial light state...");
                RetryUntilSuccess(() =>
                {
                    var lightState = (IsDaylight() ? Light.Off : Light.On);
                    Logger.Info("Setting light to " + lightState.ToString().ToLower());
                    ToggleLightSwitch(lightState);
                }, numRetries: 10, delayBetweenRetriesMs: 5000);

                // get service bus settings
                var serviceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"];
                var sasKeyName          = ConfigurationManager.AppSettings["SasKeyName"];
                var sasKey           = ConfigurationManager.AppSettings["SasKey"];
                var topicName        = ConfigurationManager.AppSettings["TopicName"];
                var subscriptionName = Dns.GetHostName();

                var topicAddress        = string.Format("https://{0}.servicebus.windows.net/{1}", serviceBusNamespace, topicName);
                var subscriptionAddress = string.Format("{0}/Subscriptions/{1}", topicAddress, subscriptionName);

                // create service bus http client with SAS credentials good for 60 minutes
                HttpClientHelper.DisableServerCertificateValidation = true;
                var httpClientHelper = new HttpClientHelper(
                    serviceBusNamespace, sasKeyName, sasKey, AuthTokenExpirationMinutes)
                {
                    Logger = Logger
                };

                // setup SAS token auto-renewal timer
                tokenRenewalTimer = new Timer(x =>
                {
                    httpClientHelper.RenewSasToken(AuthTokenExpirationMinutes);
                    Logger.Info("SAS token renewed");
                }, null, RenewalInterval, RenewalInterval);

                // verify the topic exists
                Logger.Info("Querying service bus topic \"{0}\"...", topicName);
                RetryUntilSuccess(() =>
                {
                    var queryTopicResponse = httpClientHelper.GetEntity(topicAddress).Result;
                    var content            = Encoding.UTF8.GetString(queryTopicResponse);
                    if (!content.Contains("TopicDescription"))
                    {
                        throw new Exception(string.Format("Service bus topic \"{0}\" does not exist.", topicName));
                    }
                }, (exception) =>
                {       // anonymous function to handle 401 unauthorized error, manually kick off the SAS renewal
                    if (exception is UnauthorizedAccessException)
                    {
                        HandleUnauthorizedAccessException(httpClientHelper, tokenRenewalTimer);
                    }
                });

                // get subscription configuration
                var subscriptionDescriptionPath = Path.Combine(Path.GetDirectoryName(
                                                                   Assembly.GetExecutingAssembly().Location), "SubscriptionDescription.xml");
                var subscriptionDescription = Encoding.UTF8.GetBytes(File.ReadAllText(subscriptionDescriptionPath));

                // create subscription
                Logger.Info("Registering subscription \"{0}\"...", subscriptionName);
                RetryUntilSuccess(() => httpClientHelper.CreateEntity(subscriptionAddress, subscriptionDescription).Wait(),
                                  (exception) =>
                {       // anonymous function to handle 401 unauthorized error, manually kick off the SAS renewal
                    if (exception is UnauthorizedAccessException)
                    {
                        HandleUnauthorizedAccessException(httpClientHelper, tokenRenewalTimer);
                    }
                });

                // delete current subscription rule
                Logger.Info("Deleting current subscription rule...");
                RetryUntilSuccess(() => httpClientHelper.DeleteEntity(subscriptionAddress + "/Rules/RecipientFilter").Wait(),
                                  (exception) =>
                {       // anonymous function to handle 401 unauthorized error, manually kick off the SAS renewal
                    if (exception is UnauthorizedAccessException)
                    {
                        HandleUnauthorizedAccessException(httpClientHelper, tokenRenewalTimer);
                    }
                });

                // create rule configuration
                var ruleDescriptionPath = Path.Combine(Path.GetDirectoryName(
                                                           Assembly.GetExecutingAssembly().Location), "RuleDescription.xml");
                var filterQuery     = string.Format("RecipientId = '*' OR RecipientId = '{0}'", Dns.GetHostName().ToLower());
                var ruleDescription = Encoding.UTF8.GetBytes(string.Format(File.ReadAllText(ruleDescriptionPath), filterQuery));

                // create subscription rule
                Logger.Info("Creating subscription rule...");
                RetryUntilSuccess(() => httpClientHelper.CreateEntity(subscriptionAddress + "/Rules/RecipientFilter", ruleDescription).Wait(),
                                  (exception) =>
                {       // anonymous function to handle 401 unauthorized error, manually kick off the SAS renewal
                    if (exception is UnauthorizedAccessException)
                    {
                        HandleUnauthorizedAccessException(httpClientHelper, tokenRenewalTimer);
                    }
                });

                // now delete default subscription rule
                Logger.Info("Deleting default subscription rule...");
                RetryUntilSuccess(() => httpClientHelper.DeleteEntity(subscriptionAddress + "/Rules/$Default").Wait(),
                                  (exception) =>
                {       // anonymous function to handle 401 unauthorized error, manually kick off the SAS renewal
                    if (exception is UnauthorizedAccessException)
                    {
                        HandleUnauthorizedAccessException(httpClientHelper, tokenRenewalTimer);
                    }
                });

                var       consecutiveErrors = 0;
                Exception lastError         = null;
                Logger.Info("Waiting for messages...");

                // start the message receiver loop
                while (!signalEvent.WaitOne(TimeSpan.Zero))
                {
                    try
                    {
#if DEBUG
                        const int timeoutInSeconds = 5;
#else
                        const int timeoutInSeconds = 60;
#endif
                        // Receive and delete message from the subscription.
                        var message = httpClientHelper.ReceiveAndDeleteMessage(subscriptionAddress, timeoutInSeconds).Result;
                        if (message != null)
                        {
                            Logger.Info("Received message: " + message.BrokerProperties.MessageId);
                            var light = (Light)Enum.Parse(typeof(Light), message.CustomProperties["LightState"]);
                            Logger.Info("Turning light " + light.ToString().ToLower());
                            ToggleLightSwitch(light);
                        }
                        consecutiveErrors = 0;
                    }
                    catch (AggregateException ae)
                    {
                        foreach (var ex in ae.InnerExceptions)
                        {
                            if (ex is UnauthorizedAccessException)
                            {
                                HandleUnauthorizedAccessException(httpClientHelper, tokenRenewalTimer);
                            }
                            else
                            {
                                Logger.Error(ex.Message);
                            }

                            lastError = ex;
                        }

                        Thread.Sleep(1000);
                        consecutiveErrors++;
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex.Message);
                        lastError = ex;
                        Thread.Sleep(1000);
                        consecutiveErrors++;
                    }

                    if (consecutiveErrors >= 100)
                    {
                        throw new Exception("Unrecoverable error, giving up", lastError); // something REALLY wrong, abort mission
                    }
                    if (consecutiveErrors >= 10)
                    {
                        Thread.Sleep(TimeSpan.FromMinutes(1)); // something wrong here (network issues?), let's throttle down
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Fatal error: " + ex.Message);
                var errorMessage = ex.Message;
                if (ex.InnerException != null)
                {
                    errorMessage += string.Format(": {0}", ex.InnerException.Message);
                }

                SendErrorMessage(errorMessage);
            }
            finally
            {
                if (tokenRenewalTimer != null)
                {
                    tokenRenewalTimer.Dispose();
                }

                if (_gpio != null)
                {
                    _gpio.Close();
                }

                signalHandler.Dispose();
                Logger.Info("Exiting program.");
            }
        }
        public void Dispose()
        {
#if !DEBUG
            connection.Close();
#endif
        }
 public void Close()
 {
     gpio.Close();
 }
Exemple #24
0
 public void Dispose()
 {
     RingerThread.Abort();
     GPIO.Close();
 }
Exemple #25
0
        static void Main(string[] args)
        {
            Console.WriteLine("GPIOTestHarness");
            bool Station1OutputState = false;
            bool Station2OutputState = false;
            bool Station3OutputState = false;
            bool Station4OutputState = false;

            //var Output1 = Station1OutputPin.Output();
            //var Output2 = Station2OutputPin.Output();
            //var Output3 = Station3OutputPin.Output();
            //var Output4 = Station4OutputPin.Output();
            var pins = new PinConfiguration[]
            {
                Station1OutputPin.Output().Name("Output1"),
                Station2OutputPin.Output().Name("Output2"),
                Station3OutputPin.Output().Name("Output3"),
                Station4OutputPin.Output().Name("Output4")
            };
            //var settings = new GpioConnectionSettings();
            var connection = new GpioConnection(pins);

            var Input1 = LowPressureFaultInputPin.Input().OnStatusChanged(b =>
            {
                Console.WriteLine("LowPressureFaultInput {0}", b ? "on" : "off");
                if (Station1OutputState != b)
                {
                    connection.Toggle("Output1"); Station1OutputState = b;
                }
            });

            connection.Add(Input1);
            var Input2 = HighPressureFaultInputPin.Input().OnStatusChanged(b =>
            {
                Console.WriteLine("HighPressureFaultInput {0}", b ? "on" : "off");
                if (Station2OutputState != b)
                {
                    connection.Toggle("Output2"); Station2OutputState = b;
                }
            });

            connection.Add(Input2);
            var Input3 = LowWellFaultInputPin.Input().OnStatusChanged(b =>
            {
                Console.WriteLine("LowWellFaultInput {0}", b ? "on" : "off");
                if (Station3OutputState != b)
                {
                    connection.Toggle("Output3"); Station3OutputState = b;
                }
            });

            connection.Add(Input3);
            var Input4 = OverloadFaultInputPin.Input().OnStatusChanged(b =>
            {
                Console.WriteLine("OverloadFaultInput {0}", b ? "on" : "off");
                if (Station4OutputState != b)
                {
                    connection.Toggle("Output4"); Station4OutputState = b;
                }
            });

            connection.Add(Input4);

            ElectricPotential referenceVoltage = ElectricPotential.FromVolts(3.3);

            var driver = new MemoryGpioConnectionDriver(); //GpioConnectionSettings.DefaultDriver;

            Mcp3008SpiConnection spi = new Mcp3008SpiConnection(
                driver.Out(adcClock),
                driver.Out(adcCs),
                driver.In(adcMiso),
                driver.Out(adcMosi));

            IInputAnalogPin inputPin = spi.In(Mcp3008Channel.Channel0);

            connection.Open();
            ElectricPotential volts = ElectricPotential.FromVolts(0);

            while (!Console.KeyAvailable)
            {
                var v = referenceVoltage * (double)inputPin.Read().Relative;
                if ((Math.Abs(v.Millivolts - volts.Millivolts) > 100))
                {
                    volts = ElectricPotential.FromMillivolts(v.Millivolts);
                    Console.WriteLine("Voltage ch0: {0}", volts.Millivolts.ToString());
                }
            }
            connection.Close();
        }
Exemple #26
0
        public async void Monitor()
        {
            log.Debug("Starting Monitor()");

            while (!bShutdown)
            {
                try
                {
                    //get SPI reading
                    ReadSPI();

                    switch (state)
                    {
                    case State.Monitor:

                        if (mode == Mode.Manual)
                        {
                            //check to see if we are in an irrigation window
                            if (ManualProgram.Start != null)
                            {
                                DateTime dtStart = (DateTime)ManualProgram.Start;
                                if (DateTime.Now > ManualProgram.Start && DateTime.Now < dtStart.AddMinutes(ManualProgram.Duration))
                                {
                                    //check to see that the correct outputs are on
                                    SwitchStation(ManualProgram.StationId);
                                    Irrigating = true;
                                }
                                else
                                {
                                    if (Irrigating)
                                    {
                                        //record end of manual program
                                        CreateEvent(EventType.IrrigationStop, string.Format("Station:{0} elapsed:{1} minutes", ManualProgram.StationId, (DateTime.Now - dtStart).TotalMinutes.ToString("N2")));
                                        bUpdateStatus = true;
                                    }
                                    SwitchStation(0);      //Station 0 - all stations off
                                    Irrigating = false;
                                    ManualProgram.StationId = 0;
                                    ManualProgram.Start     = null;
                                    ManualProgram.Duration  = 0;
                                }
                            }
                        }
                        if (mode == Mode.Auto)
                        {
                            //check to see if we are in a scheduled irrigation window
                        }
                        break;

                    case State.WaitForTimeout:
                        if (!bLowWellFaultState)
                        {
                            ResetRelay = false;
                            ChangeState(State.Monitor);
                        }
                        if (DateTime.Now > dtFaultStartDate.AddSeconds(TimeoutDelaySeconds))
                        {
                            ResetRelay = true;
                            ChangeState(State.ConfirmReset);
                        }
                        break;

                    case State.ConfirmReset:
                        if (!bLowWellFaultState)
                        {
                            ResetRelay = false;
                            ChangeState(State.Monitor);
                        }
                        break;

                    case State.WaitForReset:
                        if (!InFaultState())
                        {
                            ChangeState(State.Monitor);
                        }
                        break;

                    default:
                        break;
                    }

                    switch (mode)
                    {
                    case Mode.Auto:

                        break;

                    case Mode.Manual:

                        break;

                    case Mode.Off:

                        break;

                    default:
                        break;
                    }

                    // retrieve web commands every WebCommandQueryIntervalSeconds seconds
                    if (DateTime.Now > (dtLastCommandQuery.AddSeconds(WebCommandQueryIntervalSeconds)))
                    {
                        //get pending commands from web
                        await GetCommands();

                        //log.DebugFormat("{0} commands queued", WebCommands.Count());

                        //process pending commands from CommandHistory
                        await ProcessCommands();

                        dtLastCommandQuery = DateTime.Now;
                    }

                    if (DateTime.Now > (dtLastStatusUpdate.AddMinutes(MinUpdateIntervalMinutes)))
                    {
                        bUpdateStatus = true;
                    }

                    if (bUpdateStatus)
                    {
                        //heartbeat
                        RecordStatus();
                        bUpdateStatus      = false;
                        dtLastStatusUpdate = DateTime.Now;
                    }

                    Thread.Sleep(100);
                }
                catch (Exception ex)
                {
                    log.ErrorFormat(ex.Message);
                }
            }
            //end program
            connection.Close();
            log.Info("Shutting down");
            Console.WriteLine("Shutting down");
        }
Exemple #27
0
 /// <summary>
 /// Stop and close Gpio Connection
 /// </summary>
 public static void Stop()
 {
     _cancellationTokenSource.Cancel();
     //if (CommonHelper.IsBoard)
     _gpioConnectionGlobalPin.Close();
 }