private static void OnCallback(object state) { switch ((ETimer)state) { case ETimer.Ping: if (NetduinoMQTT == null) { break; } lock (NetduinoMQTT) { // Our keep alive is 15 seconds - we ping again every 10, So we should live forever Debug.Print("Pinging <" + MQTT_PORT + "> port on <" + MQTT_SERVER + "> server..."); if (NetduinoMQTT.PingMQTT(Socket) == -1) { NetduinoMQTT.DisconnectMQTT(Socket); NetduinoMQTT = null; } } break; case ETimer.Scan: if (I2C == null) { break; } lock (I2C) lock (NetduinoMQTT) { Scanner.ScanSlaves(I2C); FetchFunction(); } break; case ETimer.RGB: if (LockRGB == null) { break; } lock (LockRGB) { if (Notify.Length != 0) { // Notify end user, status is reserved Debug.Print("Done! RGB LED status was changed from <" + NotifyFlag.ToString() + "> to <" + Notify.Peek().ToString() + "> status."); SetRGBStatus(Notify.Dequeue()); } } break; default: break; } }
// 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(); } }
private static bool InitializeMQTT() { // Wait a little bit, That will make better the next step Thread.Sleep(500); try { // Get broker's IP of MQTT address //IPHostEntry hostEntry = Dns.GetHostEntry(MQTT_SERVER); IPHostEntry hostEntry = Dns.GetHostEntry(MQTT_SERVER); // Create socket and connect to the broker's IP address and port Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp); Socket.Connect(new IPEndPoint(hostEntry.AddressList[0], MQTT_PORT)); // Create MQTT and connect to the broker's port with username and password NetduinoMQTT = new NetduinoMQTT(); if (NetduinoMQTT.ConnectMQTT(Socket, DEVICE_MODEL, MQTT_TIMEOUT, true, MQTT_USER, MQTT_PASSWORD) != 0) { throw new Exception(); } Debug.Print("Done! Socket Connection was established successfully."); // IMPORTANT NOTICE: First of all, we need to subscribe main device // We call it like XXXX/status and this broker is related with SSR // State of device. We will listen something about this and execute it string[] data = { DEVICE_MODEL, "status" }; string result = '/' + Serializer.Encode(new char[1] { '/' }, data); NetduinoMQTT.SubscribeMQTT(Socket, new string[] { result }, new int[] { 0 }, 1); Debug.Print("Done! MQTT Configuration was established successfully <" + MQTT_PORT + "> port on <" + MQTT_SERVER + "> server."); // Best case return(true); } catch (SocketException error) { // Worst case Debug.Print("Error! Unexpected Socket Error <" + error.ErrorCode + "> triggered."); return(false); } }
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); } }
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); }
// The function that the timer calls to ping the server // Our keep alive is 15 seconds - we ping again every 10. // So we should live forever. static void pingIt(object o) { Debug.Print("pingIT"); NetduinoMQTT.PingMQTT(mySocket); }
// The thread that listens for inbound messages private static void mylistenerThread() { NetduinoMQTT.listen(mySocket); }
// 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; }