Пример #1
0
        public override async Task Start()
        {
            switch (SelectedSensor)
            {
            case "LM75":
                Sensor = new Lm75(Board.I2c);
                break;

            case "DS18B20":
                Sensor = new Ds18b20(Board.Uart);
                break;

            case "MCP9808":
                Sensor = new Mcp9808(Board.I2c);
                break;

            case "MLX90614":
                var mlx90614 = new Mlx90614(Board.I2c);
                Sensor = mlx90614.Object;
                break;

            case "MLX90615":
                var mlx90615 = new Mlx90615(Board.I2c);
                Sensor = mlx90615.Object;
                break;
            }

            Sensor.AutoUpdateWhenPropertyRead = false;
            OnPropertyChanged(nameof(Sensor));
        }
        public TemperatureControlService(IOutputHelper helper, ITemperatureSensor sensor, Settings systemSettings)
        {
            SystemSettings = systemSettings;

            _outputHelper = helper;

            _thermistor = sensor;

            _pid = new PIDController(PinManagement.currentTemperatureSensor, _output, PinManagement.setTemperature, SystemSettings.PIDKp, SystemSettings.PIDKi, SystemSettings.PIDKd, PIDController.PID_Direction.DIRECT);

            _pid.SetOutputLimits(0, 100);

            _pid.SampleTime = _windowSize;

            _pid.Mode = PIDController.PID_Mode.AUTOMATIC;

            _windowStartTime = DateTime.Now.Ticks;

            _pidAutoTune = new PIDAutoTune();

            if (_tuning)
            {
                _tuning = false;

                ChangeAutoTune();

                _tuning = true;
            }
        }
Пример #3
0
        private void Temperature_ReadingChanged(ITemperatureSensor sender, ITemperatureReading args)
        {
            // Get reading
            var t = args.Temperature;

            Debug.WriteLine($"F: {t.DegreesFahrenheit}  C: {t.DegreesCelsius}");
        }
Пример #4
0
 public MachineMonitor(
     IConcurrencyProvider concurrencyProvider,
     ITemperatureSensor temperatureSensor,
     IProximitySensor proximitySensor)
 {
     _concurrencyProvider = concurrencyProvider;
     _temperatureSensor   = temperatureSensor;
     _proximitySensor     = proximitySensor;
 }
Пример #5
0
 public MachineMonitor(
     IConcurrencyProvider concurrencyProvider,
     ITemperatureSensor temperatureSensor, 
     IProximitySensor proximitySensor)
 {
     _concurrencyProvider = concurrencyProvider;
     _temperatureSensor = temperatureSensor;
     _proximitySensor = proximitySensor;
 }
Пример #6
0
        public static ITrigger GetTemperatureUnderranTrigger(this ITemperatureSensor sensor, float target, float delta)
        {
            if (sensor == null)
            {
                throw new ArgumentNullException(nameof(sensor));
            }

            return(new SensorValueUnderranTrigger(sensor).WithTarget(target).WithDelta(delta));
        }
 /// <summary>
 /// Setup the sensors
 /// </summary>
 public void Initialise()
 {
     AudioInSensor = new NullMicrophone();
     AudioOut = new NullSpeaker();
     HumiditySensor = new NullHumiditySensor();
     KeyPad = new SingleKeyPad(new InputPort(Pins.ONBOARD_SW1, true, Port.ResistorMode.PullUp));
     LedController = new LedController(new OutputPort(Pins.ONBOARD_LED, true));
     TemperatureSensor = new NullTemperatureSensor();
 }
Пример #8
0
 public KettleController(IPowerSwitch powerSwitch, IPowerLamp powerLamp, ITemperatureSensor temperatureSensor,
                         IWaterSensor waterSensor, IHeatingElement heatingElement)
 {
     this._powerSwitch             = powerSwitch;
     this._powerLamp               = powerLamp;
     this._temperatureSensor       = temperatureSensor;
     this._waterSensor             = waterSensor;
     this._heatingElement          = heatingElement;
     this._isComponentsInitialized = false;
 }
 public void Update(ITemperatureSensor temperatureSensor)
 {
     Console.WriteLine($"The temperature is {(temperatureSensor as TemperatureSensor).Current.Degrees}°C at {(temperatureSensor as TemperatureSensor).Current.Date:g}");
     if (first)
     {
         last  = (temperatureSensor as TemperatureSensor).Current;
         first = false;
     }
     else
     {
         Console.WriteLine($"   Change: {(temperatureSensor as TemperatureSensor).Current.Degrees - last.Degrees}° in " +
                           $"{(temperatureSensor as TemperatureSensor).Current.Date.ToUniversalTime() - last.Date.ToUniversalTime():g}");
     }
 }
Пример #10
0
        //constructor
        public KettleController( IPowerSwitch ps, IPowerLamp pl, IHeatingElement he, ITemperatureSensor ts, IWaterSensor ws)
        {
            this.powerSwitch = ps;
            this.powerSwitch.SwitchedOn+=new EventHandler( powerSwitch_SwitchedOn);
            this.powerSwitch.SwitchedOff+=new EventHandler( powerSwitch_SwitchedOff);

            this.powerLamp = pl;
            this.powerLamp.SwitchedOn+=new EventHandler (powerLamp_SwitchedOn);
               this.powerLamp.SwitchedOff+=new EventHandler (powerLamp_SwitchedOff);

               this.heatingElement = he;
               this.temperatureSensor = ts;
               this.waterSensor = ws;
        }
Пример #11
0
        private void SetupDemo()
        {
            // Get the area from the controller.
            IArea area = this.GetArea(Room.ExampleRoom);

            // Get the single motion detector from the controller.
            IMotionDetector motionDetector        = GetComponent <IMotionDetector>();
            ITrigger        motionDetectedTrigger = motionDetector.GetMotionDetectedTrigger();

            // Get the single temperature and humidity sensor from the controller.
            ITemperatureSensor temperatureSensor = GetComponent <ITemperatureSensor>();
            IHumiditySensor    humiditySensor    = GetComponent <IHumiditySensor>();

            // Get the button with the specified ID from the area (not globally).
            IButton  button        = area.GetButton(ExampleRoom.Button1);
            ITrigger buttonTrigger = button.GetPressedShortlyTrigger();

            // Get a test lamp from the area (not globally).
            ILamp lamp2 = area.GetLamp(ExampleRoom.Lamp2);
            ILamp lamp3 = area.GetLamp(ExampleRoom.Lamp3);

            // Integrate the twitter client if the configuration file is available.
            TwitterClient twitterClient;

            if (TwitterClientFactory.TryCreateFromDefaultConfigurationFile(out twitterClient))
            {
                RegisterService(new TwitterClient());

                IAction tweetAction = twitterClient.GetTweetAction($"Someone is here ({DateTime.Now})... @chkratky");

                motionDetectedTrigger.Attach(tweetAction);
                buttonTrigger.Attach(tweetAction);
            }

            // An automation is "Fulfilled" per default.
            ////var automation = new Automation(new AutomationId("DemoAutomation"))
            ////    .WithTrigger(motionDetectedTrigger)
            ////    .WithActionIfConditionsFulfilled(lamp3.GetTurnOnAction())
            ////    .WithCondition(ConditionRelation.And, new ComponentIsInStateCondition(lamp2, BinaryStateId.Off))
            ////    .WithCondition(ConditionRelation.And, new NumericValueSensorHasValueGreaterThanCondition(humiditySensor, 80));

            //AddAutomation(automation);

            SetupTelegramBot();

            new PersonalAgentToApiDispatcher(this).ExposeToApi(ApiController);
        }
        public KettleController(IPowerSwitch powerSwitch,
                                IPowerLamp powerLamp,
                                IHeatingElement heatingElement,
                                IWaterSensor waterSensor,
                                ITemperatureSensor temperatureSensor)
        {
            this.powerSwitch       = powerSwitch ?? throw new ArgumentNullException(nameof(powerSwitch));
            this.powerLamp         = powerLamp ?? throw new ArgumentNullException(nameof(powerLamp));
            this.heatingElement    = heatingElement ?? throw new ArgumentNullException(nameof(heatingElement));
            this.waterSensor       = waterSensor ?? throw new ArgumentNullException(nameof(waterSensor));
            this.temperatureSensor = temperatureSensor ?? throw new ArgumentNullException(nameof(temperatureSensor));

            this.powerSwitch.SwitchedOn         += PowerSwitch_SwitchedOn;
            this.powerSwitch.SwitchedOff        += PowerSwitch_SwitchedOff;
            this.temperatureSensor.ValueChanged += TemperatureSensor_ValueChanged;
            this.waterSensor.ValueChanged       += WaterSensor_ValueChanged;
        }
Пример #13
0
        //this is a temp depedency, until we get the feature extraction module
        public Orchestrator(ITemperatureSensor temperatureProxy, IModelTraining trainerProxy)
        {
            temperatureProxy.Temperature.Subscribe(this, async signal =>
            {
                OrchestratorTwin twin;

                lock (_twinLock)
                {
                    twin = _lastTwin;
                }

                if (twin == null)
                {
                    return(MessageResult.Ok);
                }
                if (twin.Scale == TemperatureScale.Celsius)
                {
                    signal.Value = signal.Value * 9 / 5 + 32;
                }

                await BroadcastMessage(signal, twin);

                return(MessageResult.Ok);
            });

            trainerProxy.Model.Subscribe(this, async model =>
            {
                Logger.LogInformation(
                    $"New Trained Model for {model.Algorithm}. Updating the model in {model.Algorithm}");
                await Model.PublishAsync(model);
                return(MessageResult.Ok);
            });

            Twin.Subscribe(async twin =>
            {
                lock (_twinLock)
                {
                    _lastTwin = twin;
                }

                Logger.LogInformation($"Twin update. Routing  = {twin.RoutingMode.ToString()}");
                await Twin.ReportAsync(twin);
                return(TwinResult.Ok);
            });
        }
        public Orchestrator(ITemperatureSensor proxy)
        {
            proxy.Temperature.Subscribe(this, async signal =>
            {
                var twin = Twin.LastKnownTwin;
                if (twin != null)
                {
                    if (signal.Scale != twin.Scale)
                    {
                        if (twin.Scale == TemperatureScale.Celsius)
                        {
                            signal.Value = signal.Value * 9 / 5 + 32;
                        }
                    }

                    List <Task> messages = new List <Task>();
                    foreach (Routing item in Enum.GetValues(typeof(Routing)))
                    {
                        if (twin.RoutingMode.HasFlag(item))
                        {
                            messages.Add(RouteMessage(signal, item));
                        }
                    }

                    if (messages.Count > 0)
                    {
                        await Task.WhenAll(messages);
                    }
                }
                return(MessageResult.Ok);
            });

            Twin.Subscribe(async twin =>
            {
                System.Console.WriteLine($"Preprocessor: new routing : { twin.RoutingMode.ToString()}");
                await Twin.ReportAsync(twin);
                return(TwinResult.Ok);
            });
        }
Пример #15
0
        protected override void ConfigureSensor()
        {
            var device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin0, TemperatureSensorModel.OnePointTwo);

            if (device != null)
            {
                _sensor = device;
            }

            device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin1, TemperatureSensorModel.OnePointTwo);

            if (device != null)
            {
                _sensor = device;
            }

            device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin2, TemperatureSensorModel.OnePointTwo);

            if (device != null)
            {
                _sensor = device;
            }
        }
Пример #16
0
        public static void CreateThingsTopology()
        {
            Idegree_Celsius degreeCelius = context.Create <Idegree_Celsius>(new Uri(clientURI + "#1"));

            IMeasurement indoorTemperature = context.Create <IMeasurement>(new Uri(clientURI + "#2"));

            indoorTemperature.AddIsmeasuredin_Only_UnitOfMeasure.Add(degreeCelius);
            indoorTemperature.Hasvalue     = 32;
            indoorTemperature.Hastimestamp = DateTime.UtcNow;

            ITemperature temperature = context.Create <ITemperature>(new Uri(clientURI + "#3"));

            temperature.AddRelatestomeasurement_Only_Measurement.Add(indoorTemperature);

            ITemperatureSensor temperatureSensor = context.Create <ITemperatureSensor>(new Uri(clientURI + "#4"));

            temperatureSensor.Hasmanufacturer = "CompanyA";
            temperatureSensor.Hasmodel        = "M321";
            temperatureSensor.Hasdescription  = "Low range Zigee temperature sensor";
            temperatureSensor.AddMakesmeasurement_Only_Measurement.Add(indoorTemperature);

            // commit data to store
            context.Commit();
        }
        //this is a temp depedency, until we get the feature extraction module
        public Orchestrator(ITemperatureSensor temperatureProxy)
        {
            temperatureProxy.Temperature.Subscribe(this, async signal =>
            {
                var twin = Twin.LastKnownTwin;
                if (twin != null)
                {
                    if (twin.Scale == TemperatureScale.Celsius)
                    {
                        signal.Value = signal.Value * 9 / 5 + 32;
                    }

                    await BroadcastMessage(signal, twin);
                }
                return(MessageResult.Ok);
            });

            Twin.Subscribe(async twin =>
            {
                Console.WriteLine($"{typeof(OrchestratorTwin).Name}::Twin update. Routing  = { twin.RoutingMode.ToString()}");
                await Twin.ReportAsync(twin);
                return(TwinResult.Ok);
            });
        }
Пример #18
0
		public ThermostatController(IDataContext context, ITemperatureSensor sensor, IAppSettings settings)
		{
			this.context = context;
			this.sensor = sensor;
			this.settings = settings;
		}
Пример #19
0
        public static void Main()
        {
            mainThread = Thread.CurrentThread;

            // create the LCD interface
            var lcd = new SPI_VFDisplay(SPI.SPI_module.SPI1, SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_D10, SPI_VFDisplay.Brightness.VFD_BRIGHTNESS25);

            // set up the LCD's number of columns and rows:
            lcd.begin(20, 2, SPI_VFDisplay.Brightness.VFD_BRIGHTNESS25);
            // set up the LCD's number of columns and rows:
            lcd.clear();
            // create the output helper and attach tot he LCD Display
            _displayHelper = new OutputHelper();
            _displayHelper.DisplayController = lcd;

            // Print a message to the LCD.
            _displayHelper.DisplayText("The DIY Brewery|Brew Controller");

            Thread.Sleep(5000);

            _displayHelper.DisplayText("Loading|Settings");

            Settings settings = new Settings();
            settings.loadSettings();

            _displayHelper.HistoryFileName = settings.HistoryFilename;

            UpdateSettingsMethod.UpdateNetworkConfiguration(settings);

            _displayHelper.DisplayText("Network|Started");

            _displayHelper.DisplayText(UpdateSettingsMethod.GetNetworkIP(settings));

            Thread.Sleep(5000);

            Server WebServer = new Server(80);
            WebServer.AddResponse(new JSONResponse("temperature", new JSONResponseCheck(GetTemperatureMethod.GetTemperature)));
            WebServer.AddResponse(new JSONResponse("settings", new JSONResponseCheck(GetSettingsMethod.GetSettings)));
            WebServer.AddResponse(new JSONResponse("updateSettings", new JSONResponseCheck(UpdateSettingsMethod.UpdateSettings)));
            WebServer.AddResponse(new JSONResponse("updateMashProfile", new JSONResponseCheck(UpdateMashProfileMethod.UpdateMashProfile)));

            _displayHelper.DisplayText("Web Server|Started");

            Thread.Sleep(5000);

            NTPTimeService timeService = new NTPTimeService();
            timeService.SystemSettings = settings;
            timeService.Start();

            _displayHelper.DisplayText("Internet Time|Service Started");

            Thread.Sleep(5000);

            MashProfileControlService mashProfileService = new MashProfileControlService(_displayHelper);
            mashProfileService.SystemSettings = settings;
            mashProfileService.Start();

            _displayHelper.DisplayText("Mash Profile|Service Started");

            Thread.Sleep(5000);

            _thermistor = new Thermistor(SecretLabs.NETMF.Hardware.NetduinoPlus.Pins.GPIO_PIN_A0);
            _thermistor.ResistanceReference = settings.PadResistance;
            _thermistor.VoltageReference = settings.VoltageReference;

            TemperatureControlService tempLogger = new TemperatureControlService(_displayHelper, _thermistor, settings);
            tempLogger.Start();

            _displayHelper.DisplayText("Temp Monitor|Started");

            Thread.Sleep(5000);

            PinManagement.engageHeaterButton.OnInterrupt += new NativeEventHandler(EngageHeaterButton_OnInterrupt);
            PinManagement.setTemperatureUpButton.OnInterrupt += new NativeEventHandler(TemperatureSetUp_OnInterrupt);
            PinManagement.setTemperatureUpDown.OnInterrupt += new NativeEventHandler(TemperatureSetDown_OnInterrupt);
            PinManagement.allStopButton.OnInterrupt += new NativeEventHandler(AllStop_OnInterrupt);

            _displayHelper.DisplayText("Inputs|Active");

            mainThread.Suspend();
        }
Пример #20
0
        public Orchestrator(ITemperatureSensor temperatureProxy, IDataAggregator aggregatorProxy)
        {
            temperatureProxy.Temperature.Subscribe(this, async signal =>
            {
                var twin = Twin.LastKnownTwin;
                if (twin != null)
                {
                    Preprocess(signal, twin);
                    List <Task> messages = new List <Task>();
                    foreach (Routing item in Enum.GetValues(typeof(Routing)))
                    {
                        if (twin.RoutingMode.HasFlag(item))
                        {
                            switch (item)
                            {
                            case Routing.Sampling:
                                Console.WriteLine("Aggregating");
                                messages.Add(Sampling.PublishAsync(signal));
                                break;

                            case Routing.Detect:
                                messages.Add(Detection.PublishAsync(signal));
                                break;

                            default:
                                continue;
                            }
                        }
                    }

                    if (messages.Count > 0)
                    {
                        await Task.WhenAll(messages);
                    }
                }
                return(MessageResult.Ok);
            });


            aggregatorProxy.Aggregate.Subscribe(this, async aggregate =>
            {
                if (aggregate == null)
                {
                    return(MessageResult.Ok);
                }

                var twin = Twin.LastKnownTwin;
                Console.WriteLine(twin);
                if (twin != null)
                {
                    List <Task> messages = new List <Task>();
                    foreach (Routing item in Enum.GetValues(typeof(Routing)))
                    {
                        if (twin.RoutingMode.HasFlag(item))
                        {
                            switch (item)
                            {
                            case Routing.Visualize:
                                Console.WriteLine("Visualizing");
                                messages.Add(Visualization.PublishAsync(
                                                 new GraphData()
                                {
                                    CorrelationID = aggregate.Message.CorrelationID,
                                    Values        = aggregate.Message.Values
                                }
                                                 ));
                                break;

                            case Routing.FeatureExtraction:
                                //messages.Add(FeatureExtraction.PublishAsync(new DataAggregate()
                                //{
                                //    CorrelationID = aggregate.Message.CorrelationID,
                                //    Values = aggregate.Message.Values
                                //}));
                                break;

                            default:
                                continue;
                            }
                        }
                    }

                    if (messages.Count > 0)
                    {
                        await Task.WhenAll(messages);
                    }
                }
                return(MessageResult.Ok);
            });

            Twin.Subscribe(async twin =>
            {
                System.Console.WriteLine($"Preprocessor: new routing : { twin.RoutingMode.ToString()}");
                await Twin.ReportAsync(twin);
                return(TwinResult.Ok);
            });
        }
Пример #21
0
 public override async Task Stop()
 {
     Sensor = null;
 }
Пример #22
0
 public TemperatureSensor(ITemperatureSensor hardware)
 {
     _hardware = hardware;
     _hardware.TemperatureIsChanged += OnTemperatureChanged;
 }
Пример #23
0
        //// Create a file StartupTask.Secrets.cs with a partial class for this class and add following declaration with the value for the deviceid and the connection string.
        //private const string DeviceId = "";
        //private readonly static string ConnectionString = "";


        //private static DeviceClient s_deviceClient;
        //private readonly static string s_connectionString = "";

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            redLed            = DeviceFactory.Build.Led(Pin.DigitalPin2);
            greenLed          = DeviceFactory.Build.Led(Pin.DigitalPin3);
            angleSensor       = DeviceFactory.Build.RotaryAngleSensor(Pin.AnalogPin2);
            temperatureSensor = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin1);

            _deviceClient = DeviceClient.CreateFromConnectionString(ConnectionString, TransportType.Mqtt);

            //// Initial telemetry values
            //double minTemperature = 20;
            //double minHumidity = 60;
            //Random rand = new Random();

            //s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt);

            // Loop endlessly
            while (true)
            {
                try
                {
                    var angleValue         = angleSensor.SensorValue();
                    var desiredTemperature = MinDesiredTemperature + ((MaxDesiredTemperature - MinDesiredTemperature) * angleValue / 1024);
                    var currentTemperature = temperatureSensor.TemperatureInCelsius();

                    System.Diagnostics.Debug.WriteLine("temperature is :" + currentTemperature + ", desired is: " + desiredTemperature);
                    if (currentTemperature < desiredTemperature)
                    {
                        redLed.ChangeState(SensorStatus.On);
                        greenLed.ChangeState(SensorStatus.Off);
                    }
                    else
                    {
                        redLed.ChangeState(SensorStatus.Off);
                        greenLed.ChangeState(SensorStatus.On);
                    }

                    var telemetryDataPoint = new
                    {
                        messageId = _messageId++,
                        //deviceId = DeviceId,
                        temperature = currentTemperature,
                    };
                    var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                    var message       = new Message(System.Text.Encoding.ASCII.GetBytes(messageString));

                    _deviceClient.SendEventAsync(message).Wait();

                    //double currentTemperature = minTemperature + rand.NextDouble() * 15;
                    //double currentHumidity = minHumidity + rand.NextDouble() * 20;

                    //// Create JSON message
                    //var telemetryDataPoint = new
                    //{
                    //    temperature = currentTemperature,
                    //    humidity = currentHumidity
                    //};
                    //var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                    //var message = new Message(Encoding.ASCII.GetBytes(messageString));

                    //// Add a custom application property to the message.
                    //// An IoT hub can filter on these properties without access to the message body.
                    //message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");

                    //// Send the tlemetry message
                    //s_deviceClient.SendEventAsync(message).Wait();
                    //Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);

                    Task.Delay(1000).Wait();
                }
                catch (Exception ex)
                {
                    // NOTE: There are frequent exceptions of the following:
                    // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
                    // This appears to be caused by the rapid frequency of writes to the GPIO
                    // These are being swallowed here/

                    // If you want to see the exceptions uncomment the following:
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
        }
Пример #24
0
 public double Run(ITemperatureSensor temperatureSensor)
 {
     return(temperatureSensor.Measure());
 }
Пример #25
0
 public ECS(int threshold, IHeater heater, ITemperatureSensor temperatureSensor)
 {
     Threshold          = threshold;
     _heater            = heater;
     _temperatureSensor = temperatureSensor;
 }
Пример #26
0
        private void Temperature_ReadingChanged(ITemperatureSensor sender, ITemperatureReading args)
        {
            // Get reading
            var t = args.Temperature;

            Debug.WriteLine($"F: {t.DegreesFahrenheit}  C: {t.DegreesCelsius}");
        }