Imported Upstream version 1.0.0
[platform/upstream/iotivity.git] / service / easy-setup / sdk / enrollee / arduino / wifi / networkHandler.cpp
1 //******************************************************************
2 //
3 // Copyright 2015 Samsung Electronics All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20
21 #include "networkHandler.h"
22
23 // Arduino WiFi Shield includes
24 #include <SPI.h>
25 #include <WiFi.h>
26 #include <WiFiUdp.h>
27
28 #include <string.h>
29
30 #include "logger.h"
31
32 /**
33  * @var ES_NH_TAG
34  * @brief Logging tag for module name.
35  */
36 #define ES_NH_TAG "ES_NH"
37
38 //-----------------------------------------------------------------------------
39 // Defines
40 //-----------------------------------------------------------------------------
41 /**
42  *  ES_MAX_NETWORK_RETRY sets the default number of retry count for network connection.
43  */
44 #define ES_MAX_NETWORK_RETRY (5)
45
46 //-----------------------------------------------------------------------------
47 // Private variables
48 //-----------------------------------------------------------------------------
49 static IPAddress enrolleeIP;
50
51 /**
52  * @var g_retryCounter
53  * @brief Retry counter for cancelling network retry. Currently network retry is limited to 5 attempts
54  */
55 static uint16_t g_retryCounter = 0;
56
57
58
59 //-----------------------------------------------------------------------------
60 // Private internal function prototypes
61 //-----------------------------------------------------------------------------
62 int findNetwork(const char *ssid);
63 int ConnectToNetwork(const char *ssid, const char *pass);
64 void printEncryptionType(int thisType);
65
66 // Arduino WiFi Shield
67 // Note : Arduino WiFi Shield currently does NOT support multicast and therefore
68 // this server will NOT be listening on 224.0.1.187 multicast address.
69 static const char ARDUINO_WIFI_SHIELD_UDP_FW_VER[] = "1.1.0";
70
71 ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback cb)
72 {
73     char *fwVersion;
74     int status = WL_IDLE_STATUS;
75     int res;
76
77     // check for the presence of the shield:
78     if (WiFi.status() == WL_NO_SHIELD)
79     {
80         OC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present");
81         return ES_ERROR;
82     }
83
84     // Verify that WiFi Shield is running the firmware with all UDP fixes
85     fwVersion = WiFi.firmwareVersion();
86     OC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion);
87     if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER))
88             != 0)
89     {
90         OC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!");
91         return ES_ERROR;
92     }
93
94     //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
95     g_retryCounter = 0;
96
97     OC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid);
98
99     while ((findNetwork(ssid) == 0) && g_retryCounter < ES_MAX_NETWORK_RETRY) // found
100     {
101         delay(1000);
102         g_retryCounter++;
103     }
104
105     if(g_retryCounter == ES_MAX_NETWORK_RETRY){
106         OC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
107                                                                     g_retryCounter);
108         return ES_ERROR;
109     }
110
111     if (cb != NULL)
112     {
113         cb(ES_OK);
114     }
115
116     if (WiFi.status() == WL_CONNECTED)
117         WiFi.disconnect();
118
119     //Retry counter is reset everytime the ConnectToWiFiNetwork is invoked
120     g_retryCounter = 0;
121
122     res = ConnectToNetwork(ssid, pass);
123
124     if (res == 0)
125     {
126         return ES_NETWORKCONNECTED;
127     }
128     else
129     {
130         return ES_NETWORKNOTCONNECTED;
131     }
132 }
133
134 int findNetwork(const char *ssid)
135 {
136     int res = 0;
137     // scan for nearby networks:
138     Serial.println("** Scan Networks **");
139     int numSsid = WiFi.scanNetworks();
140     if (numSsid == -1)
141     {
142         Serial.println("Couldn't get a wifi connection");
143
144         return res;
145     }
146
147     // print the list of networks seen:
148     Serial.print("number of available networks:");
149     Serial.println(numSsid);
150
151     // print the network number and name for each network found:
152     for (int thisNet = 0; thisNet < numSsid; thisNet++)
153     {
154         Serial.print(thisNet);
155         Serial.print(") ");
156         Serial.print(WiFi.SSID(thisNet));
157         Serial.print("\tEncryption: ");
158         printEncryptionType(WiFi.encryptionType(thisNet));
159
160         if (strcmp(WiFi.SSID(thisNet), ssid) == 0)
161         {
162             res = 1;
163         }
164     }
165
166     return res;
167 }
168
169 int ConnectToNetwork(const char *ssid, const char *pass)
170 {
171     int status = WL_IDLE_STATUS;
172
173     // attempt to connect to Wifi network:
174     while (status != WL_CONNECTED && g_retryCounter < ES_MAX_NETWORK_RETRY)
175     {
176         OC_LOG_V(INFO, ES_NH_TAG, "Attempting to connect to SSID: %s", ssid);
177
178         status = WiFi.begin((char *) ssid, (char *) pass);
179
180         // wait 10 seconds for connection:
181         delay(10000);
182
183         g_retryCounter++;
184     }
185
186     if(g_retryCounter == ES_MAX_NETWORK_RETRY){
187         OC_LOG_V(ERROR, ES_NH_TAG, "Connection to network failed after %d attempts",
188                                                                     g_retryCounter);
189         return ES_ERROR;
190     }
191
192     OC_LOG(DEBUG, ES_NH_TAG, "Connected to wifi");
193
194     enrolleeIP = WiFi.localIP();
195     OC_LOG_V(INFO, ES_NH_TAG, "IP Address:  %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
196                                                           enrolleeIP[2], enrolleeIP[3]);
197
198     char buf[50];
199     sprintf(buf, "IP Address:  %d.%d.%d.%d", enrolleeIP[0], enrolleeIP[1],
200                                              enrolleeIP[2], enrolleeIP[3]);
201     Serial.println(buf);
202
203     return 0;
204 }
205
206 ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
207 {
208     if (targetType == CT_ADAPTER_IP && WiFi.status() == WL_CONNECTED)
209     {
210         info->type = CT_ADAPTER_IP;
211         info->ipaddr = WiFi.localIP();
212         if(strlen(WiFi.SSID())<=MAXSSIDLEN)
213         {
214             strcpy(info->ssid, WiFi.SSID());
215             return ES_OK;
216         }
217         else
218         {
219             return ES_ERROR;
220         }
221     }
222
223     return ES_ERROR;
224 }
225
226 void printEncryptionType(int thisType)
227 {
228     // read the encryption type and print out the name:
229     switch (thisType)
230     {
231         case ENC_TYPE_WEP:
232             Serial.println("WEP");
233             break;
234         case ENC_TYPE_TKIP:
235             Serial.println("WPA");
236             break;
237         case ENC_TYPE_CCMP:
238             Serial.println("WPA2");
239             break;
240         case ENC_TYPE_NONE:
241             Serial.println("None");
242             break;
243         case ENC_TYPE_AUTO:
244             Serial.println("Auto");
245             break;
246     }
247 }