├── README.md └── SocketIo-Example.ino /README.md: -------------------------------------------------------------------------------- 1 | # simple-socket-io-example-esp8266 2 | ESP8266 Arduino code for a simple socket.io client example 3 | 4 | Goes along with this: 5 | https://github.com/robojay/simple-socket-io-example 6 | 7 | And requires this: 8 | https://github.com/robojay/Socket.io-v1.x-Library 9 | 10 | Used in this presentation: 11 | https://www.dropbox.com/s/8wn100sbj7jpozi/NRB-socket-io.pdf?dl=0 12 | -------------------------------------------------------------------------------- /SocketIo-Example.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define LedPin 2 4 | #define ButtonPin 0 5 | 6 | #define SOFTAP_MODE 7 | 8 | #ifdef SOFTAP_MODE 9 | const char* password = "myMinion"; 10 | #else 11 | const char* ssid = "SkyNet"; 12 | const char* password = "myMaster"; 13 | #endif 14 | 15 | const char HexLookup[17] = "0123456789ABCDEF"; 16 | 17 | String host = "192.168.4.2"; 18 | int port = 3000; 19 | bool clicked = false; 20 | 21 | SocketIOClient socket; 22 | 23 | void setupNetwork() { 24 | 25 | #ifdef SOFTAP_MODE 26 | WiFi.disconnect(); 27 | byte mac[6]; 28 | WiFi.macAddress(mac); 29 | char ssid[14] = "Minion-000000"; 30 | ssid[7] = HexLookup[(mac[3] & 0xf0) >> 4]; 31 | ssid[8] = HexLookup[(mac[3] & 0x0f)]; 32 | ssid[9] = HexLookup[(mac[4] & 0xf0) >> 4]; 33 | ssid[10] = HexLookup[(mac[4] & 0x0f)]; 34 | ssid[11] = HexLookup[(mac[5] & 0xf0) >> 4]; 35 | ssid[12] = HexLookup[(mac[5] & 0x0f)]; 36 | ssid[13] = 0; 37 | WiFi.softAP(ssid, password); 38 | #else 39 | WiFi.begin(ssid, password); 40 | uint8_t i = 0; 41 | while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500); 42 | if(i == 21){ 43 | while(1) delay(500); 44 | } 45 | #endif 46 | 47 | } 48 | 49 | void click() { 50 | clicked = true; 51 | } 52 | 53 | void light(String state) { 54 | Serial.println("[light] " + state); 55 | if (state == "\"state\":true") { 56 | Serial.println("[light] ON"); 57 | digitalWrite(LedPin, HIGH); 58 | } 59 | else { 60 | Serial.println("[light] off"); 61 | digitalWrite(LedPin, LOW); 62 | } 63 | } 64 | 65 | // 66 | // This code runs only once 67 | // 68 | void setup() { 69 | 70 | // set up our pins 71 | pinMode(LedPin, OUTPUT); 72 | pinMode(ButtonPin, INPUT); 73 | 74 | digitalWrite(LedPin, LOW); 75 | 76 | Serial.begin(115200); 77 | 78 | setupNetwork(); 79 | 80 | attachInterrupt(digitalPinToInterrupt(ButtonPin), click, FALLING); 81 | 82 | socket.on("light", light); 83 | 84 | socket.connect(host, port); 85 | } 86 | 87 | void clickCheck() { 88 | if (clicked) { 89 | Serial.println("[click]"); 90 | socket.emit("toggle", "{\"state\":true}"); 91 | clicked = false; 92 | } 93 | } 94 | 95 | // 96 | // This code runs over and over again 97 | // 98 | void loop() { 99 | socket.monitor(); 100 | clickCheck(); 101 | } 102 | 103 | 104 | --------------------------------------------------------------------------------