├── .gitignore ├── LICENSE ├── README.md ├── android └── WiFiDemo │ ├── .gitignore │ ├── .idea │ ├── .name │ ├── compiler.xml │ ├── copyright │ │ └── profiles_settings.xml │ ├── dictionaries │ │ └── hayk.xml │ ├── encodings.xml │ ├── gradle.xml │ ├── inspectionProfiles │ │ ├── Project_Default.xml │ │ └── profiles_settings.xml │ ├── misc.xml │ ├── modules.xml │ ├── scopes │ │ └── scope_settings.xml │ └── vcs.xml │ ├── WiFiDemo.iml │ ├── app │ ├── .gitignore │ ├── app.iml │ ├── build.gradle │ ├── proguard-rules.pro │ └── src │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── java │ │ └── edu │ │ │ └── stanford │ │ │ └── me202 │ │ │ └── wifidemo │ │ │ └── WiFiActivity.java │ │ └── res │ │ ├── drawable-hdpi │ │ └── ic_launcher.png │ │ ├── drawable-mdpi │ │ └── ic_launcher.png │ │ ├── drawable-xhdpi │ │ └── ic_launcher.png │ │ ├── drawable-xxhdpi │ │ └── ic_launcher.png │ │ ├── layout │ │ └── activity_wi_fi.xml │ │ ├── menu │ │ └── wi_fi.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ ├── build.gradle │ ├── gradle.properties │ ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ └── settings.gradle ├── arduino └── wifi_demo │ ├── Credentials.h │ └── wifi_demo.ino └── presentation.pdf /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | 19 | # Local configuration file (sdk path, etc) 20 | local.properties 21 | 22 | # Proguard folder generated by Eclipse 23 | proguard/ 24 | 25 | # Log Files 26 | *.log 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Hayk Martirosyan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | android-arduino-wifi 2 | ==================== 3 | 4 | Demo of a clear and robust way of creating a serial communication 5 | link between an Arduino and an Android device using WiFi. 6 | 7 | **Features:** 8 | 9 | * WiFi server using the [WiFly Shield](https://www.sparkfun.com/products/9954) 10 | and associated library on Arduino 11 | * WiFi client socket implemented using AsyncTask in Android 12 | * UI for connecting, disconnecting, reading, and writing 13 | * Exception handling and error management to prevent crashes 14 | * Parsing of complete newline-delimited messages from the stream 15 | * Timeout detection using a ping system 16 | * Lots of comments 17 | 18 | **Requirements:** 19 | 20 | * Android device with WiFi enabled 21 | * Arduino with a WiFly shield 22 | * Android Studio and an Arduino IDE 23 | * A WiFi network to connect to and a not-blocked port 24 | 25 | **Usage:** 26 | 27 | * Arduino - set your WiFi network name and password in `Credentials.h`. 28 | * Arduino - set your desired port number in `wifi_demo.ino`. 29 | * Flash the Arduino, then turn it on and open the serial monitor at 115200bps. 30 | * Wait for the WiFly to get an IP address. 31 | * Open the Android app, enter the address and port, and hit connect. 32 | * You should now be able to send messages and have them echoed back. 33 | * You can also type messages into the Aruino serial monitor to send them 34 | to the Android device (select newline endings). 35 | 36 | **Important files:** 37 | 38 | * `WiFiActivity.java` 39 | * `activity_wi_fi.xml` 40 | * `wifi_demo.ino` 41 | 42 | **Issues:** 43 | 44 | * WiFly takes a long time (~20s) to connect to a network on startup (watch the LEDs). 45 | * After disconnecting from a client, the WiFly takes about 6 seconds before 46 | it can connect to another client (again, watch the LEDs). 47 | * I had an issue with a version of the WiFly library where it would not 48 | initialize until it heard a `*READY*` message from the chip, which never came. 49 | If you get stuck at WiFly.begin(), look into this. 50 | -------------------------------------------------------------------------------- /android/WiFiDemo/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | /local.properties 3 | /.idea/workspace.xml 4 | /.idea/libraries 5 | .DS_Store 6 | /build 7 | *.iws 8 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/.name: -------------------------------------------------------------------------------- 1 | WiFi Demo -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/dictionaries/hayk.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 15 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/scopes/scope_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /android/WiFiDemo/.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /android/WiFiDemo/WiFiDemo.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/app.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 20 5 | buildToolsVersion "20.0.0" 6 | 7 | defaultConfig { 8 | applicationId "edu.stanford.me202.wifidemo" 9 | minSdkVersion 15 10 | targetSdkVersion 20 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | buildTypes { 15 | release { 16 | runProguard false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(dir: 'libs', include: ['*.jar']) 24 | } 25 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /usr/local/android-studio/sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/java/edu/stanford/me202/wifidemo/WiFiActivity.java: -------------------------------------------------------------------------------- 1 | package edu.stanford.me202.wifidemo; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | import android.view.View; 7 | import android.widget.Button; 8 | import android.widget.EditText; 9 | import android.widget.TextView; 10 | 11 | import android.os.AsyncTask; 12 | import java.net.InetSocketAddress; 13 | import java.net.Socket; 14 | import java.io.BufferedReader; 15 | import java.io.InputStreamReader; 16 | import java.io.OutputStream; 17 | 18 | /** 19 | * Simple UI demonstrating how to open a serial communication link to a 20 | * remote host over WiFi, send and receive messages, and update the display. 21 | * 22 | * Author: Hayk Martirosyan 23 | */ 24 | public class WiFiActivity extends Activity { 25 | 26 | // Tag for logging 27 | private final String TAG = getClass().getSimpleName(); 28 | 29 | // AsyncTask object that manages the connection in a separate thread 30 | WiFiSocketTask wifiTask = null; 31 | 32 | // UI elements 33 | TextView textStatus, textRX, textTX; 34 | EditText editTextAddress, editTextPort, editSend; 35 | Button buttonConnect, buttonSend; 36 | 37 | @Override 38 | protected void onCreate(Bundle savedInstanceState) { 39 | 40 | super.onCreate(savedInstanceState); 41 | setContentView(R.layout.activity_wi_fi); 42 | 43 | // Save references to UI elements 44 | textStatus = (TextView)findViewById(R.id.textStatus); 45 | textRX = (TextView)findViewById(R.id.textRX); 46 | textTX = (TextView)findViewById(R.id.textTX); 47 | editTextAddress = (EditText)findViewById(R.id.address); 48 | editTextPort = (EditText)findViewById(R.id.port); 49 | editSend = (EditText)findViewById(R.id.editSend); 50 | buttonConnect = (Button)findViewById(R.id.connect); 51 | buttonSend = (Button)findViewById(R.id.buttonSend); 52 | 53 | // Disable send button until a connection is made 54 | buttonSend.setEnabled(false); 55 | } 56 | 57 | /** 58 | * Helper function, print a status to both the UI and program log. 59 | */ 60 | void setStatus(String s) { 61 | Log.v(TAG, s); 62 | textStatus.setText(s); 63 | } 64 | 65 | /** 66 | * Try to start a connection with the specified remote host. 67 | */ 68 | public void connectButtonPressed(View v) { 69 | 70 | if(wifiTask != null) { 71 | setStatus("Already connected!"); 72 | return; 73 | } 74 | 75 | try { 76 | // Get the remote host from the UI and start the thread 77 | String host = editTextAddress.getText().toString(); 78 | int port = Integer.parseInt(editTextPort.getText().toString()); 79 | 80 | // Start the asyncronous task thread 81 | setStatus("Attempting to connect..."); 82 | wifiTask = new WiFiSocketTask(host, port); 83 | wifiTask.execute(); 84 | 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | setStatus("Invalid address/port!"); 88 | } 89 | } 90 | 91 | /** 92 | * Disconnect from the connection. 93 | */ 94 | public void disconnectButtonPressed(View v) { 95 | 96 | if(wifiTask == null) { 97 | setStatus("Already disconnected!"); 98 | return; 99 | } 100 | 101 | wifiTask.disconnect(); 102 | setStatus("Disconnecting..."); 103 | } 104 | 105 | /** 106 | * Invoked by the AsyncTask when the connection is successfully established. 107 | */ 108 | private void connected() { 109 | setStatus("Connected."); 110 | buttonSend.setEnabled(true); 111 | } 112 | 113 | /** 114 | * Invoked by the AsyncTask when the connection ends.. 115 | */ 116 | private void disconnected() { 117 | setStatus("Disconnected."); 118 | buttonSend.setEnabled(false); 119 | textRX.setText(""); 120 | textTX.setText(""); 121 | wifiTask = null; 122 | } 123 | 124 | /** 125 | * Invoked by the AsyncTask when a newline-delimited message is received. 126 | */ 127 | private void gotMessage(String msg) { 128 | textRX.setText(msg); 129 | Log.v(TAG, "[RX] " + msg); 130 | } 131 | 132 | /** 133 | * Send the message typed in the input field using the AsyncTask. 134 | */ 135 | public void sendButtonPressed(View v) { 136 | 137 | if(wifiTask == null) return; 138 | 139 | String msg = editSend.getText().toString(); 140 | if(msg.length() == 0) return; 141 | 142 | wifiTask.sendMessage(msg); 143 | editSend.setText(""); 144 | 145 | textTX.setText(msg); 146 | Log.v(TAG, "[TX] " + msg); 147 | } 148 | 149 | /** 150 | * AsyncTask that connects to a remote host over WiFi and reads/writes the connection 151 | * using a socket. The read loop of the AsyncTask happens in a separate thread, so the 152 | * main UI thread is not blocked. However, the AsyncTask has a way of sending data back 153 | * to the UI thread. Under the hood, it is using Threads and Handlers. 154 | */ 155 | public class WiFiSocketTask extends AsyncTask { 156 | 157 | // Location of the remote host 158 | String address; 159 | int port; 160 | 161 | // Special messages denoting connection status 162 | private static final String PING_MSG = "SOCKET_PING"; 163 | private static final String CONNECTED_MSG = "SOCKET_CONNECTED"; 164 | private static final String DISCONNECTED_MSG = "SOCKET_DISCONNECTED"; 165 | 166 | Socket socket = null; 167 | BufferedReader inStream = null; 168 | OutputStream outStream = null; 169 | 170 | // Signal to disconnect from the socket 171 | private boolean disconnectSignal = false; 172 | 173 | // Socket timeout - close if no messages received (ms) 174 | private int timeout = 5000; 175 | 176 | // Constructor 177 | WiFiSocketTask(String address, int port) { 178 | this.address = address; 179 | this.port = port; 180 | } 181 | 182 | /** 183 | * Main method of AsyncTask, opens a socket and continuously reads from it 184 | */ 185 | @Override 186 | protected Void doInBackground(Void... arg) { 187 | 188 | try { 189 | 190 | // Open the socket and connect to it 191 | socket = new Socket(); 192 | socket.connect(new InetSocketAddress(address, port), timeout); 193 | 194 | // Get the input and output streams 195 | inStream = new BufferedReader(new InputStreamReader(socket.getInputStream())); 196 | outStream = socket.getOutputStream(); 197 | 198 | // Confirm that the socket opened 199 | if(socket.isConnected()) { 200 | 201 | // Make sure the input stream becomes ready, or timeout 202 | long start = System.currentTimeMillis(); 203 | while(!inStream.ready()) { 204 | long now = System.currentTimeMillis(); 205 | if(now - start > timeout) { 206 | Log.e(TAG, "Input stream timeout, disconnecting!"); 207 | disconnectSignal = true; 208 | break; 209 | } 210 | } 211 | } else { 212 | Log.e(TAG, "Socket did not connect!"); 213 | disconnectSignal = true; 214 | } 215 | 216 | // Read messages in a loop until disconnected 217 | while(!disconnectSignal) { 218 | 219 | // Parse a message with a newline character 220 | String msg = inStream.readLine(); 221 | 222 | // Send it to the UI thread 223 | publishProgress(msg); 224 | } 225 | 226 | } catch (Exception e) { 227 | e.printStackTrace(); 228 | Log.e(TAG, "Error in socket thread!"); 229 | } 230 | 231 | // Send a disconnect message 232 | publishProgress(DISCONNECTED_MSG); 233 | 234 | // Once disconnected, try to close the streams 235 | try { 236 | if (socket != null) socket.close(); 237 | if (inStream != null) inStream.close(); 238 | if (outStream != null) outStream.close(); 239 | } catch (Exception e) { 240 | e.printStackTrace(); 241 | } 242 | 243 | return null; 244 | } 245 | 246 | /** 247 | * This function runs in the UI thread but receives data from the 248 | * doInBackground() function running in a separate thread when 249 | * publishProgress() is called. 250 | */ 251 | @Override 252 | protected void onProgressUpdate(String... values) { 253 | 254 | String msg = values[0]; 255 | if(msg == null) return; 256 | 257 | // Handle meta-messages 258 | if(msg.equals(CONNECTED_MSG)) { 259 | connected(); 260 | } else if(msg.equals(DISCONNECTED_MSG)) 261 | disconnected(); 262 | else if(msg.equals(PING_MSG)) 263 | {} 264 | 265 | // Invoke the gotMessage callback for all other messages 266 | else 267 | gotMessage(msg); 268 | 269 | super.onProgressUpdate(values); 270 | } 271 | 272 | /** 273 | * Write a message to the connection. Runs in UI thread. 274 | */ 275 | public void sendMessage(String data) { 276 | 277 | try { 278 | outStream.write(data.getBytes()); 279 | outStream.write('\n'); 280 | } catch (Exception e) { 281 | e.printStackTrace(); 282 | } 283 | } 284 | 285 | /** 286 | * Set a flag to disconnect from the socket. 287 | */ 288 | public void disconnect() { 289 | disconnectSignal = true; 290 | } 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hmartiro/android-arduino-wifi/61a68dee9226d32354d7177de8a64faab9bd40b5/android/WiFiDemo/app/src/main/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hmartiro/android-arduino-wifi/61a68dee9226d32354d7177de8a64faab9bd40b5/android/WiFiDemo/app/src/main/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hmartiro/android-arduino-wifi/61a68dee9226d32354d7177de8a64faab9bd40b5/android/WiFiDemo/app/src/main/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hmartiro/android-arduino-wifi/61a68dee9226d32354d7177de8a64faab9bd40b5/android/WiFiDemo/app/src/main/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/WiFiDemo/app/src/main/res/layout/activity_wi_fi.xml: -------------------------------------------------------------------------------- 1 | 12 | 13 | 19 | 20 | 25 | 26 | 32 | 33 | 39 | 40 | 46 | 47 | 48 | 53 | 54 |