Example #1
0
        private static bool SubscribeTopic(byte address, bool type)
        {
            // When we found given device in device list, generate MQTT vendor(s)
            for (ushort index = 0; index < Slave.Length; index++)
            {
                if (address == Slave[index].Address)
                {
                    string   convertedAddress = "0x" + GenerateHexadecimal(address);
                    string[] topicList        = { "isConnected", "brand", "model", "version" };
                    string[] messageList      = { type ? "1" : "0", Slave[index].Vendor.Brand, Slave[index].Vendor.Model, Slave[index].Vendor.Version };

                    for (int iterator = 0; iterator < topicList.Length; iterator++)
                    {
                        string[] data   = { convertedAddress, topicList[iterator] };
                        string   result = '/' + Serializer.Encode('/', data);

                        if (type || iterator == 0)
                        {
                            NetduinoMQTT.PublishMQTT(Socket, result, messageList[iterator]);
                        }
                    }

                    // -----

                    for (ushort subindex = 0; subindex < Slave[index].Function.Length; subindex++)
                    {
                        if (!Slave[index].Function[subindex].Request)
                        {
                            continue;
                        }

                        string[] data   = { convertedAddress, Slave[index].Function[subindex].Name };
                        string   result = '/' + Serializer.Encode('/', data);

                        // Looking good, inline if-loop
                        if (type)
                        {
                            NetduinoMQTT.SubscribeMQTT(Socket, new string[] { result }, new int[] { 0 }, 1);
                        }
                        else
                        {
                            NetduinoMQTT.UnsubscribeMQTT(Socket, new string[] { result }, new int[] { 0 }, 1);
                        }
                    }

                    // Do not need to search all data, we are OK now
                    return(true);
                }
            }

            // Worst case, when not find anything we will arrive there
            return(false);
        }
Example #2
0
        // the interrupt handler
        static void button_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            int returnCode      = 0;
            int connectionError = 0;
            // Get broker's IP address.
            IPHostEntry hostEntry = Dns.GetHostEntry("192.168.1.106");
            // Create socket and connect to the broker's IP address and port
            Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                mySocket.Connect(new IPEndPoint(hostEntry.AddressList[0], 1883));
            }
            catch (SocketException SE)
            {
                Debug.Print("Connection Error");
                connectionError = 1;
            }
            if (connectionError != 1)
            {
                // Send the connect message
                returnCode = NetduinoMQTT.ConnectMQTT(mySocket, "tester\u00A5", 2, true, "roger\u00A5", "password\u00A5");
                if (returnCode != 0)
                {
                    Debug.Print("Connection Error:");
                    Debug.Print(returnCode.ToString());
                }
                else
                {
                    // Send our message
                    NetduinoMQTT.PublishMQTT(mySocket, "test", "Ow! Quit it!");

                    for (int i = 0; i < 11; i++)
                    {
                        returnCode = NetduinoMQTT.PingMQTT(mySocket);
                        if (returnCode == 0)
                        {
                            Debug.Print("Ping Received");
                            Thread.Sleep(1000);
                        }
                    }
                    Thread.Sleep(3000);
                    // Send the disconnect message
                    NetduinoMQTT.DisconnectMQTT(mySocket);
                }
                // Close the socket
                mySocket.Close();
            }
        }
Example #3
0
        public static void Main()
        {
            int ifttIntervalMinutes = 10;
            int mqttIntervalSeconds = 5;

            int sleepMS = 0;

            // Create an output port (a port that can be written to)
            // and wire it to the onboard LED
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

            HumiditySensorController sensorOne   = new HumiditySensorController(N.Pins.GPIO_PIN_A0, N.Pins.GPIO_PIN_D7);
            HumiditySensorController sensorTwo   = new HumiditySensorController(N.Pins.GPIO_PIN_A1, N.Pins.GPIO_PIN_D6);
            HumiditySensorController sensorThree = new HumiditySensorController(N.Pins.GPIO_PIN_A2, N.Pins.GPIO_PIN_D5);
            bool   hasSi7021 = false;
            SI7021 si7021    = null;

            try
            {
                si7021 = new SI7021(updateInterval: 0);
                Debug.Print("Serial number: " + si7021.SerialNumber);
                Debug.Print("Firmware revision: " + si7021.FirmwareRevision);
                Debug.Print("Sensor type: " + si7021.SensorType);
                hasSi7021 = true;
            }
            catch (Exception)
            {
                Debug.Print("Cannot find SI7021");
                hasSi7021 = false;
            }

            var lightSensor = new GUVAS12SD(N.Pins.GPIO_PIN_A3);

            DateTime uploadToIFTTTime = DateTime.Now.AddMinutes(-(ifttIntervalMinutes + 1));
            DateTime mqttMessageTime  = DateTime.Now.AddSeconds(-(mqttIntervalSeconds + 1));

            while (true)
            {
                Thread.Sleep(1000);

                string temp = "", hum = "", humAdjusted = "";
                if (hasSi7021)
                {
                    si7021.Reset();
                    temp        = si7021.Temperature.ToString("f2");
                    hum         = si7021.Humidity.ToString("f2");
                    humAdjusted = (si7021.Humidity / 2).ToString("f2");
                    Debug.Print("Temperature: " + temp + ", humidity: " + hum);
                }
                string soil1 = getReading(sensorOne).final.ToString();
                string soil2 = getReading(sensorTwo).final.ToString();
                string soil3 = getReading(sensorThree).final.ToString();

                var lightValue = lightSensor.Read();
                // string lightValue.sensorReading + " = " + lightValue.sensorVoltage + "v, UV: " + lightValue.uvIndex

                string csvDelim = "|";
                string csv      = soil1 + csvDelim + soil2 + csvDelim + soil3 + csvDelim + temp + csvDelim + hum + csvDelim + humAdjusted
                                  + csvDelim + lightValue.sensorReading + csvDelim + lightValue.sensorVoltage + csvDelim + lightValue.uvIndex;

                Debug.Print(csv);

                if (DateTime.Now > uploadToIFTTTime)
                {
                    led.Write(true); // turn on the LED
                    try
                    {
                        sleepMS = 1000 * ifttIntervalMinutes * 60;
                        sendToIFTT("living_room_window", csv);

                        //led.Write(false);
                        uploadToIFTTTime = DateTime.Now.AddMinutes(ifttIntervalMinutes);
                        Debug.Print("Next upload to IFFT: " + uploadToIFTTTime);
                    }
                    catch (Exception)
                    {
                        Debug.Print("Upload batch to IFTTT failed");
                    }
                    led.Write(false);
                }
                if (DateTime.Now > mqttMessageTime)
                {
                    led.Write(true); // turn on the LED
                    try
                    {
                        IPHostEntry hostEntry = Dns.GetHostEntry("192.168.0.63");
                        // Create socket and connect to the broker's IP address and port
                        var mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        try
                        {
                            mySocket.Connect(new IPEndPoint(hostEntry.AddressList[0], 1883));
                        }
                        catch (SocketException SE)
                        {
                            Debug.Print("Connection Error: " + SE.ErrorCode);
                            throw (SE);
                        }

                        int returnCode = NetduinoMQTT.ConnectMQTT(mySocket, "netduinoPlus", 500, true);
                        if (returnCode != 0)
                        {
                            var error = "Connection Error: " + returnCode.ToString();
                            Debug.Print(error);
                            throw new InvalidOperationException(error);
                        }


                        string windowLocation = "window";
                        if (hasSi7021)
                        {
                            NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic(windowLocation, "temperature"), temp);
                            NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic(windowLocation, "humidity"), hum);
                            NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic(windowLocation, "humidityAdjusted"), humAdjusted);
                        }
                        //lightValue.sensorReading + csvDelim + lightValue.sensorVoltage + csvDelim + lightValue.uvIndex
                        NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic(windowLocation, "lightReading"), lightValue.sensorReading.ToString());
                        NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic(windowLocation, "lightVoltage"), lightValue.sensorVoltage.ToString());
                        NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic(windowLocation, "uvIndex"), lightValue.uvIndex.ToString());

                        var metric = "soilmoisture";
                        NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic("aralia", metric), soil1);
                        NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic("bonsai", metric), soil2);
                        NetduinoMQTT.PublishMQTT(mySocket, buildMqttTopic("amaryllis", metric), soil3);



                        mqttMessageTime = DateTime.Now.AddSeconds(mqttIntervalSeconds);
                        Debug.Print("Next MQTT messaging: " + mqttMessageTime);
                    }
                    catch (Exception e)
                    {
                        Debug.Print("MQTT failed" + e.InnerException.Message);
                    }

                    led.Write(false); // turn off the LED
                }

                Thread.Sleep(500);
            }
        }
Example #4
0
        public static void Main()
        {
            int returnCode = 0;

            // You can subscribe to multiple topics in one go
            // (If your broker supports this RSMB does, mosquitto does not)
            // Our examples use one topic per request.
            //
            //int[] topicQoS = { 0, 0 };
            //String[] subTopics = { "test", "test2" };
            //int numTopics = 2;

            int[]    topicQoS  = { 0 };
            String[] subTopics = { "test" };
            int      numTopics = 1;

            // Get broker's IP address.
            //IPHostEntry hostEntry = Dns.GetHostEntry("test.mosquitto.org");
            IPHostEntry hostEntry = Dns.GetHostEntry("192.168.1.106");

            // Create socket and connect to the broker's IP address and port
            mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                mySocket.Connect(new IPEndPoint(hostEntry.AddressList[0], 1883));
            }
            catch (SocketException SE)
            {
                Debug.Print("Connection Error: " + SE.ErrorCode);
                return;
            }

            // Send the connect message
            // You can use UTF8 in the clientid, username and password - be careful, this can be a pain
            //returnCode = NetduinoMQTT.ConnectMQTT(mySocket, "tester\u00A5", 2000, true, "roger\u00A5", "password\u00A5");
            returnCode = NetduinoMQTT.ConnectMQTT(mySocket, "tester402", 20, true, "roger", "password");
            if (returnCode != 0)
            {
                Debug.Print("Connection Error: " + returnCode.ToString());
                return;
            }

            // Set up so that we ping the server after 1 second, then every 10 seconds
            // First time is initial delay, Second is subsequent delays
            Timer pingTimer = new Timer(new TimerCallback(pingIt), null, 1000, 10000);

            // Setup and start a new thread for the listener
            listenerThread = new Thread(mylistenerThread);
            listenerThread.Start();

            // setup our interrupt port (on-board button)
            InterruptPort button = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);

            // assign our interrupt handler
            button.OnInterrupt += new NativeEventHandler(button_OnInterrupt);

            // Subscribe to our topic(s)
            returnCode = NetduinoMQTT.SubscribeMQTT(mySocket, subTopics, topicQoS, numTopics);

            //***********************************************
            // This is just some example stuff:
            //***********************************************

            // Publish a message
            NetduinoMQTT.PublishMQTT(mySocket, "test", "Testing from NetduinoMQTT");

            // Subscribe to "test/two"
            subTopics[0] = "test/two";
            returnCode   = NetduinoMQTT.SubscribeMQTT(mySocket, subTopics, topicQoS, numTopics);

            // Send a message to "test/two"
            NetduinoMQTT.PublishMQTT(mySocket, "test/two", "Testing from NetduinoMQTT to test/two");

            // Unsubscribe from "test/two"
            returnCode = NetduinoMQTT.UnsubscribeMQTT(mySocket, subTopics, topicQoS, numTopics);

            // go to sleep until the interrupt or the timer wakes us
            // (mylistenerThread is in a seperate thread that continues)
            Thread.Sleep(Timeout.Infinite);
        }
Example #5
0
 // the interrupt handler for the button
 static void button_OnInterrupt(uint data1, uint data2, DateTime time)
 {
     // Send our message
     NetduinoMQTT.PublishMQTT(mySocket, "test", "Ow! Quit it!");
     return;
 }