Exemple #1
1
void setup() {
  Serial.begin(115200);
  delay(10);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  Wire.begin(SDA, SCL); //sda,scl
  Serial.println("Sensor Test");
  if (!bmp.begin())
  {
    Serial.print("Ooops, no BMP180 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }
  else {
    Serial.println("BMP180 ready.");
    delay(1000);
  }

  /* OTA code */
  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();

  // Set up mDNS responder:
  // - first argument is the domain name, in this example
  //   the fully-qualified domain name is "esp8266.local"
  // - second argument is the IP address to advertise
  //   we send our IP address on the WiFi network
  if (!MDNS.begin(hostname, WiFi.localIP())) {
    Serial.println("Error setting up MDNS responder!");
    while(1) {
      delay(1000);
    }
  }
  Serial.print("mDNS responder started: ");
  Serial.print(hostname);
  Serial.println(".local");
  httpUpdater.setup(&httpServer);
  httpServer.begin();
  MDNS.addService("http", "tcp", 80);
}
void WEBINTERFACE_CLASS::WebServer()
{
  // Routing Table
  server.on("/wifisetup.html", handleWifi);
  server.on("/scan.json",handleScan);
  server.on("/", handleWifi);

  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}
Exemple #3
0
void setup() {
  pinMode(LDR, INPUT);
  pinMode(BUTTON, INPUT);
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);

  delay(1000);
  Serial.begin(115200);

  Serial.println("Wifi Connecting");

  WiFi.begin(wifiSSID, wifiPassword);
  wifi_station_set_auto_connect(true);
  wifi_station_set_hostname(wiFiHostname);
  wifiConnectCounter = 1;
  while (WiFi.status() != WL_CONNECTED) {
    delay(wifiRepeatInterval);
    wifiConnectCounter++;
    if (wifiConnectCounter > wifiMaxTries) {
      delay(wifiRepeatInterval * 1000 * 1000);
      wifiConnectCounter = 0;
    }
  }
  Serial.println("Wifi Connected");

  server.on("/", handleRoot);
  server.begin();
}
Exemple #4
0
void setup() {

  Serial.begin(115200);
  Serial.println();
  Serial.println("Starting WiFi...");

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() == WL_CONNECTED) {
    Serial.printf("OK\n");
    Serial.printf("Starting UPnP...");
    UPnPDevice device;

    device.setFriendlyName("Gateway LUPS");
    device.setDeviceVersion("1.0");
    device.setDeviceType("GatewayNativo");
    device.setManufacturer("LUPS");
    device.setManufacturerURL("http://lups.inf.ufpel.edu.br/");
    device.setModelDescription("versao 1");
    device.setModelName("Gateway Nativo");
    device.setModelNumber("1.0");
    device.setModelURL("http://lups.inf.ufpel.edu.br/");
    device.setSerialNumber("12002983");
    device.setPresentationURL("http://lups.inf.ufpel.edu.br/");

    // device.addDevice(UPnPDevice inputDevice);
    // device.addService(UPnPService inputService);
    // device.addIcon(UPnPIcon inputIcon);

    HTTP.on("/index.html", HTTP_GET, []() {
      HTTP.send(
          200, "text/plain",
          "ESP8266 - Gateway EXEHDA-IoT \n\n -> "
          "IP/temp?sensor=1 a 7 para "
          "ler temperatura DS18B20; \n -> IP/temp2438?sensor=1 a 7 para "
          "ler temperatura DS2438; \n -> IP/umidade?sensor=1 a 7 para ler "
          "umidade com HIH4000 e DS2438 \n -> IP/luz?sensor=1 a 7 para ler "
          "presenca de luz com LDR e DS2438.");
    });
    HTTP.on("/description.xml", HTTP_GET, []() { UPnP.schema(HTTP.client()); });
    HTTP.begin();

    UPnP.setDevice(device);
    UPnP.setSchemaURL("description.xml");
    UPnP.setHTTPPort(80);
    UPnP.begin();

    Serial.printf("OK");
    Serial.printf("Starting HTTP Server...");

    Serial.printf("OK\n");
  } else {
    Serial.printf("Failed\n");
    while (1)
      delay(100);
  }
}
void webServerSetup() {
  webServer.on("/status.json", handleStatus);
  webServer.serveStatic("/config.json", SPIFFS, "/config.json");
  webServer.serveStatic("/", SPIFFS, "/public/index.html");
  webServer.serveStatic("/assets/brewMonitor.js", SPIFFS, "/public/assets/brewMonitor.js");
  webServer.onNotFound(handleNotFound);

  webServer.begin();
}
Exemple #6
0
void setupAP(){
	WiFi.softAP(espssid);
  server.on("/", handleRoot);
  server.on("/config", handleConfig);
  server.on("/erase", handleErase);
	server.begin();
  Serial.println();
  Serial.print("connected as AP ");
  Serial.println(espssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.softAPIP()); 	
}
void SmartWifi::launchWeb(int webtype) {
  printer->println("");
  printer->println("WiFi connected");
  printer->print("Local IP: ");
  printer->println(WiFi.localIP());
  printer->print("SoftAP IP: ");
  printer->println(WiFi.softAPIP());
  createWebServer(webtype);
  // Start the server
  server.begin();
  printer->println("Server started"); 
}
Exemple #8
0
void setup()
{
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT);
  if (digitalRead(BUTTON_PIN) == 0)
  {
    Serial.println("Factory Reset");
  }

  WiFiManager wifi;
  wifi.autoConnect(DEVICE_NAME);

  if (!mdns.begin(DEVICE_NAME, WiFi.localIP()))
  {
    Serial.println("Error setting up MDNS responder!");
  }
  else
  {
    Serial.println("mDNS responder started");
  }

  // Start TCP (HTTP) server
  server.begin();
  Serial.println("TCP server started");

  Serial.println("Listening on port 8266");

  Serial.print("Sketch size: ");
  Serial.println(ESP.getSketchSize());
  Serial.print("Free size: ");
  Serial.println(ESP.getFreeSketchSpace());
  
  server.on("/", handle_root);
  server.on("/on", handle_on);
  server.on("/off", handle_off);

  httpUpdater.setup(&server);

  state = OFF;
  Serial.println("State: OFF");
  pinMode(LED_PIN, OUTPUT);
}
Exemple #9
0
void setup() {
	delay(1000);
	Serial.begin(115200);
	lightMeter.begin();
	delay(1000);
	Serial.println();
	Serial.print("Configuring access point...");
	/* You can remove the password parameter if you want the AP to be open. */
	WiFi.softAP(ssid, password);

	IPAddress myIP = WiFi.softAPIP();
	Serial.print("AP IP address: ");
	Serial.println(myIP);

	server.on("/",handleWebsite);
	server.on("/xml",handleXML);

	server.begin();
	Serial.println("HTTP server started");

}
void WifiServerinit(void){

  if (MDNS.begin(host)) {
    MDNS.addService("http", "tcp", 80);
    DBG_OUTPUT_PORT.println("MDNS responder started");
    DBG_OUTPUT_PORT.print("You can now connect to http://");
    DBG_OUTPUT_PORT.print(host);
    DBG_OUTPUT_PORT.println(".local");
  }

  // uri,HTTPメソッド,そのメソッドに対応する関数を指定する
  server.on("/list", HTTP_GET, printDirectory);
  server.on("/edit", HTTP_DELETE, handleDelete);
  server.on("/edit", HTTP_PUT, handleCreate);
  server.on("/edit", HTTP_POST, [](){ returnOK(); });
  server.onNotFound(handleNotFound); // ハンドラが割り当てられていない場合に呼び出す関数の設定
  server.onFileUpload(handleFileUpload); // ファイルアップロード

  server.begin();
  DBG_OUTPUT_PORT.println("HTTP server started");
}
void setup() {
  memset(voltsChr,0,sizeof(voltsChr));
  memset(amps0Chr,0,sizeof(amps0Chr));
  memset(amps1Chr,0,sizeof(amps1Chr));
  memset(tmpChr,0,sizeof(tmpChr));

    // if the program crashed, skip things that might make it crash
  String rebootMsg = ESP.getResetReason();
  if (rebootMsg=="Exception") safeMode=true;
  else if (rebootMsg=="Hardware Watchdog") safeMode=true;
  else if (rebootMsg=="Unknown") safeMode=true;
  else if (rebootMsg=="Software Watchdog") safeMode=true;

  if (sw1>=0) {
    pinMode(sw1, OUTPUT);
  }
  if (sw2>=0) {
    pinMode(sw2, OUTPUT);
  }
  if (sw3>=0) {
    pinMode(sw3, OUTPUT);
  }
  if (sw4>=0) {
    pinMode(sw4, OUTPUT);
  }

  // "mount" the filesystem
  bool success = SPIFFS.begin();
  if (!success) SPIFFS.format();

  if (!safeMode) fsConfig(); // read node config from FS

#ifdef _TRAILER
  wifiMulti.addAP("DXtrailer", "2317239216");
#else
  wifiMulti.addAP("Tell my WiFi I love her", "2317239216");
#endif

  int wifiConnect = 240;
  while ((wifiMulti.run() != WL_CONNECTED) && (wifiConnect-- > 0)) { // spend 2 minutes trying to connect to wifi
    // connecting to wifi
    delay(1000);
  }

  if (wifiMulti.run() != WL_CONNECTED ) { // still not connected? reboot!
    ESP.reset();
    delay(5000);
  }

  if (hasHostname) { // valid config found on FS, set network name
    WiFi.hostname(String(nodename)); // set network hostname
    ArduinoOTA.setHostname(nodename);  // OTA hostname defaults to esp8266-[ChipID]
    MDNS.begin(nodename); // set mDNS hostname
  }

  WiFi.macAddress(mac); // get esp mac address, store it in memory, build fw update url
  sprintf(macStr,"%x%x%x%x%x%x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  sprintf(theURL,"/iotfw?mac=%s", macStr);

  // request latest config from web api
  if (!safeMode) getConfig();

  // check web api for new firmware
  if (!safeMode) httpUpdater();

  // start UDP for ntp client
  udp.begin(localPort);

  updateNTP();

  setSyncProvider(getNtptime); // use NTP to get current time
  setSyncInterval(600); // refresh clock every 10 min

#ifndef _MINI
  // start the webserver
  httpd.onNotFound(handleNotFound);
  httpd.begin();
  // Add service to MDNS-SD
  MDNS.addService("http", "tcp", 80);
#endif

  // start websockets server
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);

  // setup other things
  setupOTA();
  setupMQTT();

  // setup i2c if configured, basic sanity checking on configuration
  if (hasI2C && iotSDA>=0 && iotSCL>=0 && iotSDA!=iotSCL) {
    sprintf(str,"I2C enabled, using SDA=%u SCL=%u", iotSDA, iotSCL);
    mqtt.publish(mqttpub, str);

    Wire.begin(iotSDA, iotSCL); // from api config file

    //Wire.begin(12, 14); // from api config file
    i2c_scan();

    printConfig();

    if (hasRGB) setupRGB();
    if (hasIout) setupADS();
    if (hasSpeed) setupSpeed();

  }

  // OWDAT = 4;
  if (OWDAT>0) { // setup onewire if data line is using pin 1 or greater
    sprintf(str,"Onewire Data OWDAT=%u", OWDAT);
    mqtt.publish(mqttpub, str);
    oneWire.begin(OWDAT);
    if (hasTout) {
      ds18b20 = DallasTemperature(&oneWire);
      ds18b20.begin(); // start one wire temp probe
    }
    if (hasTpwr>0) {
      pinMode(hasTpwr, OUTPUT); // onewire power pin as output
      digitalWrite(hasTpwr, LOW); // ow off
    }
  }


  if (useMQTT) {
    String rebootReason = String("Last reboot cause was ") + rebootMsg;
    rebootReason.toCharArray(str, rebootReason.length()+1);
    mqtt.publish(mqttpub, str);
  }
}
Exemple #12
0
void Threm::start() {
	_thremContext->isStarted = true;

#ifdef LOG
	LOG << "Threm::start" << endl;
	LOG << "Free heap " << ESP.getFreeHeap() << endl;
#endif

	spiffsOk = SPIFFS.begin();

	if (!spiffsOk) {
#ifdef LOG
		LOG << "SPIFFS failed" << endl;
#endif
	}

	ESP8266WebServer* server = _thremContext->getServer();

	IThremPlugin* plugin;
	PluginMeta* meta;

	for (int i = 0; i < _plugins->size(); i++) {
		plugin = _plugins->get(i);
		bool canEnable = true;
		int pluginId = plugin->getUniqueId();
		{
			String state = getJsonStateFor(pluginId);
			yield();

			StaticJsonBuffer<JSON_BUFFER_SIZE> jsonBuffer;
			JsonObject& root = jsonBuffer.parseObject(state);
			if (!root.success()) {
#ifdef LOG
				LOG << "Failed to parse config for " << String(plugin->getUniqueId()) << endl;
#endif
			}
			else {
				bool isDisabled = root["off"];
				if (isDisabled) {
					canEnable = false;
				}
			}

			if (canEnable) {
				canEnable = plugin->init(_thremContext, root);
			}
		}



		meta = _pluginMeta->get(i);
		meta->isEnabled = canEnable;
#ifdef DEBUG
		DEBUG << String(plugin->getName()) << " enabled=" << canEnable << endl;
#endif
		_pluginMeta->set(i, meta);

		yield();
	}
#ifdef DEBUG
	DEBUG << "Plugins declared: " << _plugins->size() << endl;
#endif

#ifdef LOG
	LOG << getJsonState() << endl;
#endif

#ifdef DEBUG
	DEBUG << "default callbacks setup." << endl;
#endif

	server->onNotFound([=](){
		IThremPlugin*plugin;
		PluginMeta* meta;

		String uri = server->uri();
		for (int i = 0; i < _plugins->size(); i++) {
			plugin = _plugins->get(i);
			meta = _pluginMeta->get(i);
			if (meta->isEnabled) {
				if (plugin->handleNotFound(_thremContext, uri)) {
#ifdef LOG
					LOG << "NotFound handled by: " << plugin->getName() << endl;
#endif
					return;
				}
			}
		}

		String message = "File Not Found\n\n";
		message += "URI: ";
		message += server->uri();
		message += "\nMethod: ";
		message += (server->method() == HTTP_GET) ? "GET" : "POST";
		message += "\nArguments: ";
		message += server->args();
		message += "\n";

		for (uint8_t i = 0; i < server->args(); i++) {
			message += " " + server->argName(i) + ": " + server->arg(i) + "\n";
		}
		server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		server->sendHeader("Pragma", "no-cache");
		server->sendHeader("Expires", "-1");
		server->send(404, "text/plain", message);
	});
#ifdef DEBUG
	DEBUG << "Starting webserver." << endl;
#endif
	server->begin();
#ifdef DEBUG
	DEBUG << "Web server started." << endl;
#endif
	}
Exemple #13
0
void Wifi::begin(Stream &s) {
    _s = &s;
    //USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);

    //USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    int n = WiFi.scanNetworks();
    Serial.println("[SETUP] SCANNING...");
    Serial.println("");
    if (n == 0)
      USE_SERIAL.println("no networks found");
    else
    {
      USE_SERIAL.print(n);
      USE_SERIAL.println(" networks found");
      for (int i = 0; i < n; ++i)
      {
        // Print SSID and RSSI for each network found
        USE_SERIAL.print(i + 1);
        USE_SERIAL.print(": ");
        USE_SERIAL.print(WiFi.SSID(i));
        USE_SERIAL.print(" (");
        USE_SERIAL.print(WiFi.RSSI(i));
        USE_SERIAL.print(")");
        USE_SERIAL.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
        delay(10);
      }
    }
    Serial.println("");

    WiFiMulti.addAP(NETWORKNAME, NETWORKPASS);

    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

    USE_SERIAL.print("IP address: ");
    USE_SERIAL.println(WiFi.localIP());
    USE_SERIAL.flush();

    // start webSocket server
    webSocket.begin();
    webSocket.onEvent(webSocketEvent);

    if(MDNS.begin("esp8266")) {
        USE_SERIAL.println("MDNS responder started");
    }

    // handle index
    server.on("/", []() {
        // send index.html
        server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':8899/', ['arduino']);connection.onopen = function () {  connection.send('Connect ' + new Date()); }; connection.onerror = function (error) {    console.log('WebSocket Error ', error);};connection.onmessage = function (e) {  console.log('Server: ', e.data);};function sendRGB() {  var r = parseInt(document.getElementById('r').value).toString(16);  var g = parseInt(document.getElementById('g').value).toString(16);  var b = parseInt(document.getElementById('b').value).toString(16);  if(r.length < 2) { r = '0' + r; }   if(g.length < 2) { g = '0' + g; }   if(b.length < 2) { b = '0' + b; }   var rgb = '#'+r+g+b;    console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/></body></html>");
    });

    server.begin();

    // Add service to MDNS
    MDNS.addService("http", "tcp", 80);
    MDNS.addService("ws", "tcp", 8899);

}
void setup(void){
  pinMode(led, OUTPUT);
  digitalWrite(led, LED_OFF);
  // Note the serial rate - if you don't match it when connecting you'll get garbage.
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // This tells the network that you can access the ip address of the esp8266 via 'esp8266.local'
  // The first arg is the hostname - '.local' will be appended to it, the second arg is the ip address
  if (mdns.begin("esp8266", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  
  server.on("/", handleRoot);

  server.on("/inline", [](){
    server.send(200, "text/plain", "this works as well");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started");
}