public static bool WaitOne(this GpioPin pin, GpioPinEdge edge, TimeSpan timeout)
 {
     using (var pinEvent = new PinEvent(pin, edge))
     {
         return(pinEvent.WaitOne(timeout));
     }
 }
Exemplo n.º 2
0
        private void MotionSensorPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
            if (currentValue == args.Edge) //TODO: Is it needed? the same edge should not happend twice, it is not state value but state change
            {
                return;
            }

            switch (args.Edge)
            {
            case GpioPinEdge.RisingEdge:
                if (MotionDetected == null)
                {
                    return;
                }
                MotionDetected.Invoke(this, null);
                break;

            case GpioPinEdge.FallingEdge:
                if (MotionUndetected == null)
                {
                    return;
                }
                MotionUndetected.Invoke(this, null);
                break;
            }

            currentValue = args.Edge;
        }
Exemplo n.º 3
0
        public GpioPin CreateDigitalInputPort(
            int pin,
            GpioPinEdge interruptMode     = GpioPinEdge.FallingEdge,
            ResistorMode resistorMode     = ResistorMode.Disabled,
            double debounceDuration       = 0,
            double glitchFilterCycleCount = 0)
        {
            if (IsValidPin(pin))
            {
                if (resistorMode == ResistorMode.PullDown)
                {
                    Debug.WriteLine("Pull-down resistor mode is not supported.");
                    throw new Exception("Pull-down resistor mode is not supported.");
                }
                var enablePullUp = resistorMode == ResistorMode.PullUp ? true : false;
                this.ConfigureInputPort(pin, enablePullUp, interruptMode);
                var gpio = GpioController.GetDefault();
                var port = gpio.OpenPin(pin);
                port.SetDriveMode(GpioPinDriveMode.InputPullUp);

                //var port = new DigitalInputPort(this, pin, interruptMode);
                _inputPorts.Add(pin, port);
                return(port);
            }
            throw new Exception("Pin is out of range");
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="pin">oin the value is for.</param>
 /// <param name="interruptOccurred">True when interrupt occurs, false otherwise.</param>
 /// <param name="edge">Edge that occurred</param>
 /// <param name="currentValue">Current value.</param>
 internal PinInterruptValue(int pin, bool interruptOccurred, GpioPinEdge edge, GpioPinValue currentValue)
 {
     this.Pin = pin;
     this.InterruptOccurred = interruptOccurred;
     this.Edge = edge;
     this.CurrentValue = currentValue;
 }
Exemplo n.º 5
0
        void AddBit(GpioPinEdge edge, Pulse pulse = Pulse.Data0)
        {
            if (edge != GpioPinEdge.FallingEdge)
            {
                return;
            }

            if (!swReadingTimer.IsRunning)
            {
                swReadingTimer.Start();
                timerWatcher = CreateWatcherTimer();
            }

            if (isAddBitMethodLocked == false)
            {
                isAddBitMethodLocked = true;

                //left-shift bits
                valueBuffer <<= 1;

                if (pulse == Pulse.Data1)
                {
                    valueBuffer |= 1;
                }

                bitCount++;

                timerWatcher.Change(TIME_IDLEFLAG, TimeSpan.FromMilliseconds(-1));
                isAddBitMethodLocked = false;
            }

            CheckReceivedData();
        }
Exemplo n.º 6
0
 public static GPIOPinEdge ToGPIOPinEdge(this GpioPinEdge pinEdge)
 {
     return(pinEdge switch
     {
         GpioPinEdge.FallingEdge => GPIOPinEdge.FallingEdge,
         GpioPinEdge.RisingEdge => GPIOPinEdge.RisingEdge,
         _ => GPIOPinEdge.None,
     });
Exemplo n.º 7
0
 public GpioPin CreateDigitalInputPort(int pin,
                                       GpioPinEdge interruptMode     = GpioPinEdge.FallingEdge,
                                       ResistorMode resistorMode     = ResistorMode.Disabled,
                                       double debounceDuration       = 0,
                                       double glitchFilterCycleCount = 0)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="pin"></param>
        /// <param name="mode">The drive mode of the pin. When inputPullUp is used, the pressed state will be true when a falling edge is detected.</param>
        public Button(IGpioPin pin, GpioPinDriveMode mode)
        {
            if (pin == null) throw new ArgumentNullException("pin");
            if (mode != GpioPinDriveMode.Input && mode != GpioPinDriveMode.InputPullDown && mode != GpioPinDriveMode.InputPullUp) throw new ArgumentOutOfRangeException("mode", "Drive mode should be an input drive type.");

            _pin = pin;
            _pressedEdge = mode == GpioPinDriveMode.InputPullUp ? GpioPinEdge.FallingEdge : GpioPinEdge.RisingEdge;
            _pin.SetDriveMode(mode);
            _pin.ValueChanged += _pin_ValueChanged;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Creates a new DipSwitch connected to the specified switchPins, with the InterruptMode and ResisterMode specified by the type parameters.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="switchPins"></param>
        /// <param name="interruptMode"></param>
        /// <param name="resistorMode"></param>
        /// <param name="debounceDuration"></param>
        /// <param name="glitchFilterCycleCount"></param>
        public DipSwitch(int[] switchPins, GpioPinEdge interruptMode, GpioPinDriveMode resistorMode, int debounceDuration = 20, int glitchFilterCycleCount = 0)
        {
            Switches = new ISwitch[switchPins.Length];

            for (int i = 0; i < switchPins.Length; i++)
            {
                Switches[i] = new SpstSwitch(switchPins[i], interruptMode, resistorMode, debounceDuration, glitchFilterCycleCount);
                int index = i;
                Switches[i].Changed += (s, e) => HandleSwitchChanged(index);
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Create a new Parallax PIR object connected to an input pin and IO Device.
        /// </summary>
        /// <param name="device"></param>
        /// <param name="inputPin"></param>
        public ParallaxPir(int pin, GpioPinEdge interruptMode, ResistorMode resistorMode, int debounceDuration = 20, int glitchFilterCycleCount = 0)
        {
            // this (device.CreateDigitalInputPort(pin, interruptMode, resistorMode, debounceDuration, glitchFilterCycleCount))
            var gpio = GpioController.GetDefault();

            var Dpin = gpio.OpenPin(pin);

            Dpin.SetDriveMode(resistorMode == ResistorMode.PullUp ? GpioPinDriveMode.InputPullUp : GpioPinDriveMode.InputPullDown);
            Dpin.DebounceTimeout  = new TimeSpan(0, 0, 0, debounceDuration);
            Dpin.ValueChangedEdge = interruptMode;
            Setup(Dpin);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Handles internal events and re-dispatches them to the publicly subscribed delegates.
        /// </summary>
        /// <param name="edge">The state transition for this event.</param>
        internal void OnPinChangedInternal(GpioPinEdge edge)
        {
            GpioPinValueChangedEventHandler callbacks = null;

            lock (_syncLock)
            {
                if (!_disposedValue)
                {
                    callbacks = _callbacks;
                }
            }

            callbacks?.Invoke(this, new GpioPinValueChangedEventArgs(edge));
        }
Exemplo n.º 12
0
 public DigitalInputPort(
     Mcp23x08 mcpController,
     int pin,
     GpioPinEdge interruptMode = GpioPinEdge.FallingEdge)
 //: base(pin, (IDigitalChannelInfo)pin.SupportedChannels[0], interruptMode)
 {
     Pin           = pin;
     _mcp          = mcpController;
     _pin          = pin;
     InterruptMode = interruptMode;
     //if (interruptMode != InterruptMode.None)
     {
         _mcp.InputChanged += PinChanged;
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Constructs a motion sensor device.
        /// </summary>
        /// <param name="sensorPin">
        /// The GPIO number of the pin used for the motion sensor.
        /// </param>
        /// <param name="sensorType">
        /// The motion sensor type: Active low or active high
        /// </param>
        public PirSensor(int sensorPin, SensorType sensorType)
        {
            var gpioController = GpioController.GetDefault();

            if (gpioController != null)
            {
                pirSensorEdge = sensorType == SensorType.ActiveLow ? GpioPinEdge.FallingEdge : GpioPinEdge.RisingEdge;
                pirSensorPin  = gpioController.OpenPin(sensorPin);
                pirSensorPin.SetDriveMode(GpioPinDriveMode.Input);
                pirSensorPin.ValueChanged += PirSensorPin_ValueChanged;
            }
            else
            {
                Debug.WriteLine("Error: GPIO controller not found.");
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Handles internal events and re-dispatches them to the publicly subsribed delegates.
        /// </summary>
        /// <param name="edge">The state transition for this event.</param>
        internal void OnPinChangedInternal(GpioPinEdge edge)
        {
            GpioPinValueChangedEventHandler callbacks = null;

            lock (m_syncLock)
            {
                if (!m_disposed)
                {
                    callbacks = m_callbacks;
                }
            }

            if (callbacks != null)
            {
                callbacks(this, new GpioPinValueChangedEventArgs(edge));
            }
        }
Exemplo n.º 15
0
        public PirSensorService(int sensorPin, SensorType sensorType, int debounceTimeout = 1000)
        {
            var gpioController = GpioController.GetDefault();

            if (gpioController != null)
            {
                pirSensorEdge = sensorType == SensorType.ActiveLow ? GpioPinEdge.FallingEdge : GpioPinEdge.RisingEdge;
                pirSensorPin  = gpioController.OpenPin(sensorPin);
                pirSensorPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                pirSensorPin.DebounceTimeout = TimeSpan.FromMilliseconds(debounceTimeout);
                pirSensorPin.ValueChanged   += PirSensorPin_ValueChanged;
            }
            else
            {
                Debug.WriteLine("Error: GPIO controller not found.");
            }
        }
Exemplo n.º 16
0
        public void ConfigureInputPort(int pin, bool enablePullUp = false, GpioPinEdge interruptMode = GpioPinEdge.FallingEdge)
        {
            if (IsValidPin(pin))
            {
                // set the port direction
                this.SetPortDirection(pin, GpioPinDriveMode.Input);

                _gppu = _mcpDevice.ReadRegister(RegisterAddresses.PullupResistorConfigurationRegister);
                _gppu = BitHelpers.SetBit(_gppu, (byte)pin, enablePullUp);
                _mcpDevice.WriteRegister(RegisterAddresses.PullupResistorConfigurationRegister, _gppu);

                //if (interruptMode != null)
                {
                    // interrupt on change (whether or not we want to raise an interrupt on the interrupt pin on change)
                    byte gpinten = _mcpDevice.ReadRegister(RegisterAddresses.InterruptOnChangeRegister);
                    gpinten = BitHelpers.SetBit(gpinten, (byte)pin, true);
                    _mcpDevice.WriteRegister(RegisterAddresses.InterruptOnChangeRegister, gpinten);

                    // Set the default value for the pin for interrupts.
                    var  interruptValue = interruptMode == GpioPinEdge.FallingEdge;
                    byte defVal         = _mcpDevice.ReadRegister(RegisterAddresses.DefaultComparisonValueRegister);
                    defVal = BitHelpers.SetBit(defVal, (byte)pin, interruptValue);
                    _mcpDevice.WriteRegister(RegisterAddresses.DefaultComparisonValueRegister, defVal);

                    // Set the input polarity of the pin. Basically if its normally high, we want to flip the polarity.
                    var pol = _mcpDevice.ReadRegister(RegisterAddresses.InputPolarityRegister);
                    pol = BitHelpers.SetBit(pol, (byte)pin, !interruptValue);
                    _mcpDevice.WriteRegister(RegisterAddresses.InputPolarityRegister, pol);

                    // interrupt control register; whether or not the change is based
                    // on default comparison value, or if a change from previous. We
                    // want to raise on change, so we set it to 0, always.
                    var interruptControl = interruptMode != GpioPinEdge.RisingEdge;  //both
                    var intCon           = _mcpDevice.ReadRegister(RegisterAddresses.InterruptControlRegister);
                    intCon = BitHelpers.SetBit(intCon, (byte)pin, interruptControl);
                    _mcpDevice.WriteRegister(RegisterAddresses.InterruptControlRegister, intCon);
                }
            }
            else
            {
                throw new Exception("Pin is out of range");
            }
        }
Exemplo n.º 17
0
		public PinChangedStatus GetChangedStatus(GpioPinEdge edge)
		{
			PinChangedStatus returnValue = PinChangedStatus.None;
			GpioPinValue currentValue = this.GpioPin.Read();

			try
			{
				if (edge == GpioPinEdge.RisingEdge && this.PreviousValue == GpioPinValue.Low && currentValue != this.PreviousValue)
				{
					returnValue = PinChangedStatus.WentHigh;
				}
				else if (edge == GpioPinEdge.FallingEdge && this.PreviousValue == GpioPinValue.High && currentValue != this.PreviousValue)
				{
					returnValue = PinChangedStatus.WentLow;
				}
			}
			finally
			{
				this.PreviousValue = currentValue;
			}

			return returnValue;
		}
Exemplo n.º 18
0
        public PinChangedStatus GetChangedStatus(GpioPinEdge edge)
        {
            PinChangedStatus returnValue  = PinChangedStatus.None;
            GpioPinValue     currentValue = this.GpioPin.Read();

            try
            {
                if (edge == GpioPinEdge.RisingEdge && this.PreviousValue == GpioPinValue.Low && currentValue != this.PreviousValue)
                {
                    returnValue = PinChangedStatus.WentHigh;
                }
                else if (edge == GpioPinEdge.FallingEdge && this.PreviousValue == GpioPinValue.High && currentValue != this.PreviousValue)
                {
                    returnValue = PinChangedStatus.WentLow;
                }
            }
            finally
            {
                this.PreviousValue = currentValue;
            }

            return(returnValue);
        }
Exemplo n.º 19
0
 internal GpioPinValueChangedEventArgs(GpioPinEdge edge)
 {
     _edge = edge;
 }
Exemplo n.º 20
0
 public PinEvent(GpioPin pin, GpioPinEdge edge)
 {
     _pin   = pin;
     _edge  = edge;
     _event = new AutoResetEvent(false);
 }
Exemplo n.º 21
0
 public async Task NotifyPinEdge(string device, int pinNumber, GpioPinEdge edge)
 {
     await Clients.All.NotifyPinEdge(device, pinNumber, edge);
 }
Exemplo n.º 22
0
 /// <summary>
 /// Creats a new instance of the GpioPinValueChangedEventArgs class
 /// </summary>
 /// <param name="edge">An enumeration value that indicates the type of change that occurred to the value of the GPIO pin for the GpioPin.ValueChanged event.</param>
 public GpioPinValueChangedEventArgs(GpioPinEdge edge)
 {
     _edge = edge;
 }
Exemplo n.º 23
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            TimeSpan      imageUpdateDue;
            TimeSpan      imageUpdatePeriod;

            this.logging.LogEvent("Application starting");

            // Log the Application build, OS version information etc.
            LoggingFields startupInformation = new LoggingFields();

            startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            startupInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));

            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();
                }

                IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build();

                this.interruptPinNumber = int.Parse(configuration.GetSection("InterruptPinNumber").Value);
                startupInformation.AddInt32("Interrupt pin", this.interruptPinNumber);

                this.interruptTriggerOn = (GpioPinEdge)Enum.Parse(typeof(GpioPinEdge), configuration.GetSection("interruptTriggerOn").Value);
                startupInformation.AddString("Interrupt Trigger on", this.interruptTriggerOn.ToString());

                this.displayPinNumber = int.Parse(configuration.GetSection("DisplayPinNumber").Value);
                startupInformation.AddInt32("Display pin", this.interruptPinNumber);

                this.azureIoTHubConnectionString = configuration.GetSection("AzureIoTHubConnectionString").Value;
                startupInformation.AddString("AzureIoTHubConnectionString", this.azureIoTHubConnectionString);

                this.transportType = (TransportType)Enum.Parse(typeof(TransportType), configuration.GetSection("TransportType").Value);
                startupInformation.AddString("TransportType", this.transportType.ToString());
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load or settings retrieval failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            #region AzureIoT Hub connection string creation
            try
            {
                this.azureIoTHubClient = DeviceClient.CreateFromConnectionString(this.azureIoTHubConnectionString, this.transportType);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("AzureIOT Hub DeviceClient.CreateFromConnectionString failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Report device and application properties to AzureIoT Hub
            try
            {
                TwinCollection reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                this.azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client UpdateReportedPropertiesAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Retrieve device twin settings
            try
            {
                LoggingFields configurationInformation = new LoggingFields();

                Twin deviceTwin = this.azureIoTHubClient.GetTwinAsync().GetAwaiter().GetResult();

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdateDue") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdateDue"].value.ToString(), out imageUpdateDue))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdateDue setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdateDue", imageUpdateDue);

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdatePeriod") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdatePeriod"].value.ToString(), out imageUpdatePeriod))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdatePeriod setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdatePeriod", imageUpdatePeriod);

                if (!deviceTwin.Properties.Desired.Contains("ModelType") || (!Enum.TryParse(deviceTwin.Properties.Desired["ModelType"].value.ToString(), out modelType)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ModelType setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddString("ModelType", modelType.ToString());

                if (!deviceTwin.Properties.Desired.Contains("ModelPublishedName") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["ModelPublishedName"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ModelPublishedName setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                modelPublishedName = deviceTwin.Properties.Desired["ModelPublishedName"].value.ToString();
                configurationInformation.AddString("ModelPublishedName", modelPublishedName);

                if (!deviceTwin.Properties.Desired.Contains("ProjectID") || (!Guid.TryParse(deviceTwin.Properties.Desired["ProjectID"].value.ToString(), out projectId)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ProjectId setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddGuid("ProjectID", projectId);

                if (!deviceTwin.Properties.Desired.Contains("ProbabilityThreshold") || (!Double.TryParse(deviceTwin.Properties.Desired["ProbabilityThreshold"].value.ToString(), out probabilityThreshold)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ProbabilityThreshold setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddDouble("ProbabilityThreshold", probabilityThreshold);

                if (!deviceTwin.Properties.Desired.Contains("AzureCognitiveServicesEndpoint") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["AzureCognitiveServicesEndpoint"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureCognitiveServicesEndpoint setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                azureCognitiveServicesEndpoint = deviceTwin.Properties.Desired["AzureCognitiveServicesEndpoint"].value.ToString();
                configurationInformation.AddString("AzureCognitiveServicesEndpoint", modelPublishedName);

                if (!deviceTwin.Properties.Desired.Contains("AzureCognitiveServicesSubscriptionKey") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["AzureCognitiveServicesSubscriptionKey"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureCognitiveServicesSubscriptionKey setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                azureCognitiveServicesSubscriptionKey = deviceTwin.Properties.Desired["AzureCognitiveServicesSubscriptionKey"].value.ToString();
                configurationInformation.AddString("AzureCognitiveServicesSubscriptionKey", azureCognitiveServicesSubscriptionKey);

                if (!deviceTwin.Properties.Desired.Contains("DebounceTimeout") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["DebounceTimeout"].value.ToString(), out debounceTimeout))
                {
                    this.logging.LogMessage("DeviceTwin.Properties DebounceTimeout setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("DebounceTimeout", debounceTimeout);

                this.logging.LogEvent("Configuration settings", configurationInformation);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client GetTwinAsync failed or property missing/invalid" + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            try
            {
                this.customVisionClient = new CustomVisionPredictionClient(new System.Net.Http.DelegatingHandler[] { })
                {
                    ApiKey   = this.azureCognitiveServicesSubscriptionKey,
                    Endpoint = this.azureCognitiveServicesEndpoint,
                };
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure Cognitive Services Custom Vision Client configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            this.displayOffTimer = new Timer(this.TimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            #region Wire up interupt handler for image capture request
            if (this.interruptPinNumber != 0)
            {
                try
                {
                    GpioController gpioController = GpioController.GetDefault();
                    this.interruptGpioPin = gpioController.OpenPin(this.interruptPinNumber);
                    this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                    this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged;

                    this.displayGpioPin = gpioController.OpenPin(this.displayPinNumber);
                    this.displayGpioPin.SetDriveMode(GpioPinDriveMode.Output);
                    this.displayGpioPin.Write(GpioPinValue.Low);
                }
                catch (Exception ex)
                {
                    this.logging.LogMessage("Digital input configuration failed " + ex.Message, LoggingLevel.Error);
                    return;
                }
            }
            #endregion

            #region Wire up command handler for image capture request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("ImageCapture", this.ImageUpdateHandler, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client ImageCapture SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Wire up command handler for device reboot request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("DeviceReboot", this.DeviceRebootAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client DeviceReboot SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            if ((imageUpdateDue != TimeSpan.MinValue) || (imageUpdatePeriod != TimeSpan.MinValue))
            {
                this.imageUpdatetimer = new Timer(this.ImageUpdateTimerCallback, null, imageUpdateDue, imageUpdatePeriod);
            }

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Exemplo n.º 24
0
 public GPinEventArgs(GpioPinEdge edge)
 {
     this.edge = edge;
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="edge">Edge of the event that occurred.</param>
 public ValueChangedEventArgs(GpioPinEdge edge)
 {
     this.Edge = edge;
 }
Exemplo n.º 26
0
 public static int ConvertToLedValue(GpioPinEdge edge)
 {
     return(edge == GpioPinEdge.RisingEdge ? 0 : 1);
 }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ButtonPressedEventArgs"/> class.
 /// </summary>
 /// <param name="gpioPinEdge">Rising or falling edge</param>
 public ButtonPressedEventArgs(GpioPinEdge gpioPinEdge)
 {
     Edge = gpioPinEdge;
 }
 internal GpioPinValueChangedEventArgs(GpioPinEdge edge)
 {
     m_edge = edge;
 }
Exemplo n.º 29
0
 internal GpioPinValueChangedEventArgs(GpioPinEdge edge, DateTime timestamp)
 {
     this.Edge      = edge;
     this.Timestamp = timestamp;
 }
Exemplo n.º 30
0
 private void GpioTrigger_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
 {
     triggerEdge = args.Edge;
 }
Exemplo n.º 31
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            this.logging.LogEvent("Application starting");

            // Log the Application build, OS version information etc.
            LoggingFields startupInformation = new LoggingFields();

            startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            startupInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));

            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();
                }

                IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build();

                this.azureCognitiveServicesEndpoint = configuration.GetSection("AzureCognitiveServicesEndpoint").Value;
                startupInformation.AddString("AzureCognitiveServicesEndpoint", this.azureCognitiveServicesEndpoint);

                this.azureCognitiveServicesSubscriptionKey = configuration.GetSection("AzureCognitiveServicesSubscriptionKey").Value;
                startupInformation.AddString("AzureCognitiveServicesSubscriptionKey", this.azureCognitiveServicesSubscriptionKey);

                this.interruptPinNumber = int.Parse(configuration.GetSection("InterruptPinNumber").Value);
                startupInformation.AddInt32("Interrupt pin", this.interruptPinNumber);

                this.interruptTriggerOn = (GpioPinEdge)Enum.Parse(typeof(GpioPinEdge), configuration.GetSection("interruptTriggerOn").Value);
                startupInformation.AddString("Interrupt Trigger on", this.interruptTriggerOn.ToString());

                this.displayPinNumber = int.Parse(configuration.GetSection("DisplayPinNumber").Value);
                startupInformation.AddInt32("Display pin", this.interruptPinNumber);

                this.debounceTimeout = TimeSpan.Parse(configuration.GetSection("debounceTimeout").Value);
                startupInformation.AddTimeSpan("Debounce timeout", this.debounceTimeout);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load or settings retrieval failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                this.faceClient = new FaceClient(
                    new Microsoft.Azure.CognitiveServices.Vision.Face.ApiKeyServiceClientCredentials(this.azureCognitiveServicesSubscriptionKey),
                    new System.Net.Http.DelegatingHandler[] { })
                {
                    Endpoint = this.azureCognitiveServicesEndpoint,
                };
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure Cognitive Services Face Client configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            this.displayOffTimer = new Timer(this.TimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            try
            {
                GpioController gpioController = GpioController.GetDefault();
                this.interruptGpioPin = gpioController.OpenPin(this.interruptPinNumber);
                this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged;

                this.displayGpioPin = gpioController.OpenPin(this.displayPinNumber);
                this.displayGpioPin.SetDriveMode(GpioPinDriveMode.Output);
                this.displayGpioPin.Write(GpioPinValue.Low);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Digital input configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Exemplo n.º 32
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            this.logging.LogEvent("Application starting");

            // Log the Application build, OS version information etc.
            LoggingFields startupInformation = new LoggingFields();

            startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            startupInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));

            // ethernet mac address
            this.deviceMacAddress = NetworkInterface.GetAllNetworkInterfaces()
                                    .Where(i => i.NetworkInterfaceType.ToString().ToLower().Contains("ethernet"))
                                    .FirstOrDefault()
                                    ?.GetPhysicalAddress().ToString();

            // remove unsupported charachers from MacAddress
            this.deviceMacAddress = this.deviceMacAddress.Replace("-", string.Empty).Replace(" ", string.Empty).Replace(":", string.Empty);
            startupInformation.AddString("MacAddress", this.deviceMacAddress);

            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();

                    this.logging.LogMessage("JSON configuration file missing, templated created", LoggingLevel.Warning);
                    return;
                }

                IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build();

                this.azureStorageConnectionString = configuration.GetSection("AzureStorageConnectionString").Value;
                startupInformation.AddString("AzureStorageConnectionString", this.azureStorageConnectionString);

                this.azureStorageContainerNameLatestFormat = configuration.GetSection("AzureContainerNameFormatLatest").Value;
                startupInformation.AddString("ContainerNameLatestFormat", this.azureStorageContainerNameLatestFormat);

                this.azureStorageimageFilenameLatestFormat = configuration.GetSection("AzureImageFilenameFormatLatest").Value;
                startupInformation.AddString("ImageFilenameLatestFormat", this.azureStorageimageFilenameLatestFormat);

                this.azureStorageContainerNameHistoryFormat = configuration.GetSection("AzureContainerNameFormatHistory").Value;
                startupInformation.AddString("ContainerNameHistoryFormat", this.azureStorageContainerNameHistoryFormat);

                this.azureStorageImageFilenameHistoryFormat = configuration.GetSection("AzureImageFilenameFormatHistory").Value;
                startupInformation.AddString("ImageFilenameHistoryFormat", this.azureStorageImageFilenameHistoryFormat);

                this.interruptPinNumber = int.Parse(configuration.GetSection("InterruptPinNumber").Value);
                startupInformation.AddInt32("Interrupt pin", this.interruptPinNumber);

                this.interruptTriggerOn = (GpioPinEdge)Enum.Parse(typeof(GpioPinEdge), configuration.GetSection("interruptTriggerOn").Value);
                startupInformation.AddString("Interrupt Trigger on", this.interruptTriggerOn.ToString());

                this.debounceTimeout = TimeSpan.Parse(configuration.GetSection("debounceTimeout").Value);
                startupInformation.AddTimeSpan("Debounce timeout", this.debounceTimeout);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load or settings retrieval failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                GpioController gpioController = GpioController.GetDefault();
                this.interruptGpioPin = gpioController.OpenPin(this.interruptPinNumber);
                this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged;
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Digital input configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Exemplo n.º 33
0
        /// <summary>
        /// Handles internal events and re-dispatches them to the publicly subsribed delegates.
        /// </summary>
        /// <param name="edge">The state transition for this event.</param>
        internal void OnPinChangedInternal(GpioPinEdge edge)
        {
            GpioPinValueChangedEventHandler callbacks = null;

            lock (m_syncLock)
            {
                if (!m_disposed)
                {
                    callbacks = m_callbacks;
                }
            }

            if (callbacks != null)
            {
                callbacks(this, new GpioPinValueChangedEventArgs(edge));
            }
        }