ifocus smart light sample v0.9

Dependencies:   MbedJSONValue MQTT

Revision:
4:dffb6c949dbf
Parent:
0:324ca5eb468c
Child:
5:9b664d736a6a
--- a/main.cpp	Tue Dec 10 04:08:05 2019 +0000
+++ b/main.cpp	Wed Dec 11 07:17:16 2019 +0000
@@ -1,19 +1,3 @@
-/* WiFi Example
- * Copyright (c) 2018 ARM Limited
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
 #include "mbed.h"
 #include "TCPSocket.h"
 #include "MQTTNetwork.h"
@@ -23,236 +7,125 @@
 #define WIFI_IDW0XX1    2
 #define MQTTCLIENT_QOS2 1
 
+#define RELAY_TIMEOUT 10
+#define RELAY_TIMEOUT 10
+
 #if (defined(TARGET_DISCO_L475VG_IOT01A) || defined(TARGET_DISCO_F413ZH))
 #include "ISM43362Interface.h"
-ISM43362Interface wifi(MBED_CONF_APP_WIFI_SPI_MOSI, MBED_CONF_APP_WIFI_SPI_MISO, MBED_CONF_APP_WIFI_SPI_SCLK, MBED_CONF_APP_WIFI_SPI_NSS, MBED_CONF_APP_WIFI_RESET, MBED_CONF_APP_WIFI_DATAREADY, MBED_CONF_APP_WIFI_WAKEUP, false);
 
-#else // External WiFi modules
-
-#if MBED_CONF_APP_WIFI_SHIELD == WIFI_IDW0XX1
-#include "SpwfSAInterface.h"
-SpwfSAInterface wifi(MBED_CONF_APP_WIFI_TX, MBED_CONF_APP_WIFI_RX);
-#endif // MBED_CONF_APP_WIFI_SHIELD == WIFI_IDW0XX1
+ISM43362Interface _Wifi(MBED_CONF_APP_WIFI_SPI_MOSI, MBED_CONF_APP_WIFI_SPI_MISO, MBED_CONF_APP_WIFI_SPI_SCLK, MBED_CONF_APP_WIFI_SPI_NSS, MBED_CONF_APP_WIFI_RESET, MBED_CONF_APP_WIFI_DATAREADY, MBED_CONF_APP_WIFI_WAKEUP, false);
+//
+//#else // External WiFi modules
+//
+//#if MBED_CONF_APP_WIFI_SHIELD == WIFI_IDW0XX1
+//#include "SpwfSAInterface.h"
+//SpwfSAInterface _Wifi(MBED_CONF_APP_WIFI_TX, MBED_CONF_APP_WIFI_RX);
+//
+//#endif // MBED_CONF_APP_WIFI_SHIELD == WIFI_IDW0XX1
 
 #endif
-int arrivedcount = 0;
+
+DigitalOut _pirSensorLed(LED1);
+DigitalOut _relayLed(LED2);
+DigitalOut _wiFiLED(LED3);
+
+DigitalOut _relay1(D7);
 
-DigitalOut led1(LED1);
-DigitalOut led2(LED2);
+InterruptIn _motionTrigger(D2);
+
+Thread _dioManagerThread;
+Thread _wifiManagerThread;
+
+int _currentRelayTimeout = RELAY_TIMEOUT;
 
-void messageArrived(MQTT::MessageData& md)
+typedef enum ServerConnectivity
 {
-    MQTT::Message &message = md.message;
-    printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\r\n", message.qos, message.retained, message.dup, message.id);
-    printf("Payload %.*s\r\n", message.payloadlen, (char*)message.payload);
-    arrivedcount++;
+    Disconnected,
+    Connected
+}ServerConnectivity;
+
+ServerConnectivity _brokerConnection;
+ServerConnectivity _pelionConnection;
+ 
+Timer _resetRelayTimer;
+
+bool _isRelayTriggered = false;
+
+void OnRelay()
+{
+    _relayLed = 1;
+    _relay1 = 1;
+    _isRelayTriggered = true;
 }
 
-const char *sec2str(nsapi_security_t sec)
+void OffRelay()
 {
-    switch (sec) {
-        case NSAPI_SECURITY_NONE:
-            return "None";
-        case NSAPI_SECURITY_WEP:
-            return "WEP";
-        case NSAPI_SECURITY_WPA:
-            return "WPA";
-        case NSAPI_SECURITY_WPA2:
-            return "WPA2";
-        case NSAPI_SECURITY_WPA_WPA2:
-            return "WPA/WPA2";
-        case NSAPI_SECURITY_UNKNOWN:
-        default:
-            return "Unknown";
+    _relayLed = 0;
+    _relay1 = 0;
+    _isRelayTriggered = false;
+}
+
+void OnTrigger()
+{
+    _pirSensorLed = 1;
+    _resetRelayTimer.reset();
+    
+    if(!_isRelayTriggered)
+    {
+        OnRelay();
+        _resetRelayTimer.start();
     }
 }
 
-int scan_demo(WiFiInterface *wifi)
-{
-    WiFiAccessPoint *ap;
-
-    printf("Scan:\n");
-
-    int count = wifi->scan(NULL,0);
-    printf("%d networks available.\n", count);
-
-    /* Limit number of network arbitrary to 15 */
-    count = count < 15 ? count : 15;
-
-    ap = new WiFiAccessPoint[count];
-    count = wifi->scan(ap, count);
-    for (int i = 0; i < count; i++)
-    {
-        printf("Network: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\n", ap[i].get_ssid(),
-               sec2str(ap[i].get_security()), ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
-               ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], ap[i].get_rssi(), ap[i].get_channel());
-    }
-
-    delete[] ap;
-    return count;
-}
-
-void http_demo(NetworkInterface *net)
+void OffTrigger()
 {
-    TCPSocket socket;
-    nsapi_error_t response;
-
-    printf("Sending HTTP request to www.arm.com...\n");
-
-    // Open a socket on the network interface, and create a TCP connection to www.arm.com
-    socket.open(net);
-    response = socket.connect("www.arm.com", 80);
-    if(0 != response) {
-        printf("Error connecting: %d\n", response);
-        socket.close();
-        return;
-    }
-
-    // Send a simple http request
-    char sbuffer[] = "GET / HTTP/1.1\r\nHost: www.arm.com\r\n\r\n";
-    nsapi_size_t size = strlen(sbuffer);
-    response = 0;
-    while(size)
-    {
-        response = socket.send(sbuffer+response, size);
-        if (response < 0) {
-            printf("Error sending data: %d\n", response);
-            socket.close();
-            return;
-        } else {
-            size -= response;
-            // Check if entire message was sent or not
-            printf("sent %d [%.*s]\n", response, strstr(sbuffer, "\r\n")-sbuffer, sbuffer);
-        }
-    }
-
-    // Recieve a simple http response and print out the response line
-    char rbuffer[64];
-    response = socket.recv(rbuffer, sizeof rbuffer);
-    if (response < 0) {
-        printf("Error receiving data: %d\n", response);
-    } else {
-        printf("recv %d [%.*s]\n", response, strstr(rbuffer, "\r\n")-rbuffer, rbuffer);
-    }
-
-    // Close the socket to return its memory and bring down the network interface
-    socket.close();
+    _pirSensorLed = 0;
 }
 
-void connectMqttBroker(NetworkInterface *net)
+void HandlePIR()
 {
-    float version = 0.6;
-    char* topic = "testing123";
-
-    printf("HelloMQTT: version is %.2f\r\n", version);
-
-    MQTTNetwork mqttNetwork(net);
-
-    MQTT::Client<MQTTNetwork, Countdown> client(mqttNetwork);
-
-    const char* hostname = "ec2-3-0-92-18.ap-southeast-1.compute.amazonaws.com";
-    int port = 1883;
-    printf("Connecting to %s:%d\r\n", hostname, port);
-    int rc = mqttNetwork.connect(hostname, port);
-    if (rc != 0)
-        printf("rc from TCP connect is %d\r\n", rc);
-
-    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
-    data.MQTTVersion = 3;
-    data.clientID.cstring = "mbed-sample";
-    data.username.cstring = "testuser";
-    data.password.cstring = "testpassword";
-    if ((rc = client.connect(data)) != 0)
-        printf("rc from MQTT connect is %d\r\n", rc);
-
-    if ((rc = client.subscribe(topic, MQTT::QOS2, messageArrived)) != 0)
-        printf("rc from MQTT subscribe is %d\r\n", rc);
-
-    MQTT::Message message;
-
-    // QoS 0
-    char buf[100];
-    sprintf(buf, "Hello World!  QoS 0 message from app version %f\r\n", version);
-    message.qos = MQTT::QOS0;
-    message.retained = false;
-    message.dup = false;
-    message.payload = (void*)buf;
-    message.payloadlen = strlen(buf)+1;
-    rc = client.publish(topic, message);
-    while (arrivedcount < 1)
-        client.yield(100);
+    _motionTrigger.rise(&OnTrigger); 
+    _motionTrigger.fall(&OffTrigger);
+    
+    while(true)
+    {
+        if(_isRelayTriggered)
+        {
+            if(_resetRelayTimer.read() > _currentRelayTimeout)
+            {                
+                OffRelay();
+                _resetRelayTimer.stop();
+            }
+        }
+        wait(0.5);
+    }
+}
 
-    // QoS 1
-    sprintf(buf, "Hello World!  QoS 1 message from app version %f\r\n", version);
-    message.qos = MQTT::QOS1;
-    message.payloadlen = strlen(buf)+1;
-    rc = client.publish(topic, message);
-    while (arrivedcount < 2)
-        client.yield(100);
 
-    // QoS 2
-    sprintf(buf, "Hello World!  QoS 2 message from app version %f\r\n", version);
-    message.qos = MQTT::QOS2;
-    message.payloadlen = strlen(buf)+1;
-    rc = client.publish(topic, message);
-    while (arrivedcount < 3)
-        client.yield(100);
-
-    if ((rc = client.unsubscribe(topic)) != 0)
-        printf("rc from unsubscribe was %d\r\n", rc);
-
-    if ((rc = client.disconnect()) != 0)
-        printf("rc from disconnect was %d\r\n", rc);
-
-    mqttNetwork.disconnect();
-
-    printf("Version %.2f: finish %d msgs\r\n", version, arrivedcount);
-
-}
-int main()
+void ConnectWifi()
 {
-    int count = 0;
-    led1 = 0;
-    led2 = 0;
-    
-    printf("WiFi example\n\n");
+    _wiFiLED = 0;
     
-    //do
-    //{
-    //    wait(0.5);
-    //    count = scan_demo(&wifi);
-    //}while(count == 0);
-    
-    led1 = 1;
-    
-    printf("\nConnecting to %s...\n", MBED_CONF_APP_WIFI_SSID);
     int ret = 0;
     
     do
     {
         wait(0.5);
-        ret = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
+        ret = _Wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
     }while(ret != 0);
-
-    led2 = 1;
-    
-    printf("Success\n\n");
-    printf("MAC: %s\n", wifi.get_mac_address());
-    printf("IP: %s\n", wifi.get_ip_address());
-    printf("Netmask: %s\n", wifi.get_netmask());
-    printf("Gateway: %s\n", wifi.get_gateway());
-    printf("RSSI: %d\n\n", wifi.get_rssi());
     
-    wait(3);
+    _wiFiLED = 1;
 
-    led1 = 0;
-    led2 = 0;
-    
-    connectMqttBroker(&wifi);
+}
+
+int main()
+{
     
-    //http_demo(&wifi);
-
-    wifi.disconnect();
-
-    printf("\nDone\n");
-}
+    _dioManagerThread.start(callback(HandlePIR));
+    _wifiManagerThread.start(callback(ConnectWifi));
+    
+    while(true)
+    {
+        wait(0.5);
+    }
+}
\ No newline at end of file