コード例 #1
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            hubUser           = $"{cm.hubAddress}/{cm.hubName}";
            hubTopicPublish   = $"devices/{cm.hubName}/messages/events/";
            hubTopicSubscribe = $"devices/{cm.hubName}/messages/devicebound/#";

            this.hat = await FEZHAT.CreateAsync();

            // https://m2mqtt.wordpress.com/m2mqtt_doc/
            client = new MqttClient(cm.hubAddress, 8883, true, MqttSslProtocols.TLSv1_2);
            client.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
            client.Subscribe(new string[] { hubTopicSubscribe }, new byte[] { 0 });

            var result = Task.Run(async() => {
                while (true)
                {
                    if (!client.IsConnected)
                    {
                        client.Connect(cm.hubName, hubUser, cm.hubPass);
                    }
                    if (client.IsConnected)
                    {
                        client.Publish(hubTopicPublish, temperature.ToJson(hat.GetTemperature()));
                        client.Publish(hubTopicPublish, light.ToJson(hat.GetLightLevel()));
                    }
                    await Task.Delay(30000); // don't leave this running for too long at this rate as you'll quickly consume your free daily Iot Hub Message limit
                }
            });
        }
コード例 #2
0
 public IAsyncOperation <FezHatGetLightSensorValueResult> GetLightSensorValueAsync(AllJoynMessageInfo info)
 {
     return(
         Task.Run(() =>
     {
         var lightLevel = 0.0;
         if (_isRunningOnPi && _fezhat != null)
         {
             lightLevel = _fezhat.GetLightLevel();
         }
         return FezHatGetLightSensorValueResult.CreateSuccessResult(lightLevel);
     }).AsAsyncOperation());
 }
コード例 #3
0
        public void ReadSensors(out double temperature, out double humidity)
        {
            isLightOn = !isLightOn;
            if (isLightOn)
            {
                FezHat.D3.Color = FEZHAT.Color.Green;
            }
            else
            {
                FezHat.D3.TurnOff();
            }

            temperature = FezHat.GetTemperature();
            humidity    = 20 + FezHat.GetLightLevel() * 25;
        }
コード例 #4
0
        private async void SensorTimer_Tick(object sender, object e)
        {
            var message = new SensorMessage();

            message.Temperature = hat.GetTemperature();
            message.LightLevel  = hat.GetLightLevel();

            try
            {
                await deviceClient.SendEventAsync(message.ToIoTMessage());
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error sending message: " + ex.ToString());
            }
        }
コード例 #5
0
        private static void Timer_Elapsed(object source, ElapsedEventArgs e)
        {
            // Light Sensor
            ConnectTheDotsSensor lightSensor = ctdHelper.Sensors.Find(item => item.MeasureName == "Light");

            lightSensor.Value = hat.GetLightLevel();

            Program.ctdHelper.SendSensorData(lightSensor);

            // Temperature Sensor
            var tempSensor = ctdHelper.Sensors.Find(item => item.MeasureName == "Temperature");

            tempSensor.Value = hat.GetTemperature();
            Program.ctdHelper.SendSensorData(tempSensor);

            Program.logger.Info("Temperature: {0} °C, Light {1}", tempSensor.Value.ToString("N2", CultureInfo.InvariantCulture), lightSensor.Value.ToString("P2", CultureInfo.InvariantCulture));
        }
コード例 #6
0
        async void Publish()
        {
            if (hat == null || deviceClient == null)
            {
                return;
            }

            try {
                hat.D3.Color = new FEZHAT.Color(0, 255, 0);

                var content = new Message(telemetry.ToJson(hat.GetTemperature(), hat.GetLightLevel(), 0, 0));
                await deviceClient.SendEventAsync(content);

                hat.D3.TurnOff();
            }
            catch { telemetry.Exceptions++; }
        }
コード例 #7
0
        internal CrossCuttingRT.Dto.SensorsDataDto ReadSensorData()
        {
            try
            {
                var dto = new CrossCuttingRT.Dto.SensorsDataDto();

                dto.Temperature = _instance.GetTemperature();

                dto.LightLevel = _instance.GetLightLevel();

                return(dto);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #8
0
        private void OnTick(object sender, object e)
        {
            // Status LEDs
            if (i++ % 5 == 0) // this is true every 500ms
            {
                // If you want an LED some where on the external enclosure, use a PWN PIN
                //hat.SetPwmDutyCycle(FEZHAT.PwmPin.Pwm6, AreLedsOn ? 1.0 : 0.0);

                // On-board LED
                hat.DIO24On = AreLedsOn;

                AreLedsOn = !AreLedsOn;
            }

            LightLevelReading = hat.GetLightLevel() * 100;

            TemperatureReading = ConvertTemp.ConvertCelsiusToFahrenheit(hat.GetTemperature());
        }
コード例 #9
0
        /// <summary>
        /// FEZからデータを取得して退避する。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MeasureTimer_Tick(object sender, object e)
        {
            double x, y, z;

            _fezhat.GetAcceleration(out x, out y, out z);
            double temp       = _fezhat.GetTemperature();
            double brightness = _fezhat.GetLightLevel();
            var    timestamp  = DateTime.Now;

            lock (this)
            {
                lastSensorReading.Add(new SensorReadingBuffer()
                {
                    AccelX      = x,
                    AccelY      = y,
                    AccelZ      = x,
                    Temperature = temp,
                    Brightness  = brightness,
                    Timestamp   = timestamp
                });
            }
            Debug.WriteLine("[" + timestamp.ToString("yyyyMMdd-hhmmss.fff") + "]T=" + temp + ",B=" + brightness + ",AccelX=" + x + ",AccelY=" + y + ",AccelZ=" + z);
        }
コード例 #10
0
        /// <summary>
        /// Tick every 100 milliseconds to retrieve the button's state
        /// but blink only every 1/2 second.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnTick(object sender, object e)
        {
            double x, y, z;

            hat.GetAcceleration(out x, out y, out z);

            LightTextBox.Text    = hat.GetLightLevel().ToString("P2");
            TempTextBox.Text     = hat.GetTemperature().ToString("N2");
            AccelTextBox.Text    = $"({x:N2}, {y:N2}, {z:N2})";
            Button18TextBox.Text = hat.IsDIO18Pressed().ToString();
            Button22TextBox.Text = hat.IsDIO22Pressed().ToString();

            if ((i++ % 5) == 0)
            {
                LedsTextBox.Text = next.ToString();

                hat.DIO24On  = next;
                hat.D2.Color = next ? FEZHAT.Color.White : FEZHAT.Color.Black;
                hat.D3.Color = next ? FEZHAT.Color.White : FEZHAT.Color.Black;

                next = !next;
            }
        }
コード例 #11
0
        private async void M_t_Tick(object sender, object e)
        {
            if (m_msgCount >= MaxMsgCount && MaxMsgCount != -1)
            {
                //No more than MaxMsgCount messages / run
                m_t.Stop(); return;
            }

            MAll m = new MAll();

            if (m_hat != null)
            {
                m.Light       = m_hat.GetLightLevel();
                m.Temperature = m_hat.GetTemperature();
                m.DIO18       = m_hat.IsDIO18Pressed();
                m.DIO22       = m_hat.IsDIO22Pressed();
            }
            m.MsgType = "FEZHATALL";
            m.Dt      = DateTime.UtcNow;
            var obj = JsonConvert.SerializeObject(m);

            try
            {
                if (m_clt != null)
                {
                    await m_clt.SendEventAsync(new Message(System.Text.Encoding.UTF8.GetBytes(obj)));

                    m_msgCount++;
                }
                txtState.Text = obj + $", MSG:{m_msgCount}";
            }
            catch (Exception ex)
            {
                txtState.Text = ex.ToString();
            }
            Debug.WriteLine(txtState.Text);
        }
コード例 #12
0
        private void Timer_Tick(object sender, object e)
        {
            // Store light sensor value
            var light = _hat.GetLightLevel();

            // Store motion sensor value
            var directHeat = _hat.ReadAnalog(FEZHAT.AnalogPin.Ain1);

            // if the current room is empty and lights are on
            if (light > 0.2 && directHeat <= 0.7)
            {
                // Generate event message
                var msg = new
                {
                    deviceid    = "119",
                    timecreated = DateTime.UtcNow.ToString("o"),
                    timespan    = "1 min",
                    message     = "Energy waste!"
                };

                // Send the message
                SendMessage(msg.ToString());
            }
        }
コード例 #13
0
        private async void _timer_Tick(object sender, object e)
        {
            if (_hat == null)
            {
                return;
            }

            //update UWP app UI
            double temp, light, x, y, z;

            temp  = _hat.GetTemperature();
            light = _hat.GetLightLevel();
            _hat.GetAcceleration(out x, out y, out z);

            Temp.Text  = $"{temp:N2} °C";
            Light.Text = $"{light:P2}";
            Accel.Text = $"x={x:N2} y={y:N2} z={z:N2}";

            //create message
            var message = new
            {
                deviceID          = "Batman",
                temperatureToSend = temp,
                lightToSend       = light,
                xToSend           = x,
                ytoSend           = y,
                zToSend           = z
            };

            var messageString = JsonConvert.SerializeObject(message);
            var messageToSend = new Message(Encoding.UTF8.GetBytes(messageString));


            //send message to IoTHub
            await _deviceClient.SendEventAsync(messageToSend);
        }