Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Minimal WiFi Example
- *
- * John Chajecki, @February 2020
- *
- */
- //#define _DISABLE_TLS_
- #include <EEPROM.h>
- #include <ESP8266WiFi.h>
- #include <Hash.h>
- #include <ESP8266WebServerSecure.h>
- static const char serverCert[] PROGMEM = R"EOF(
- -----BEGIN CERTIFICATE-----
- MIIBZzCCARECFBro/mMMDId0k3BfQ245XI9re76GMA0GCSqGSIb3DQEBCwUAMDUx
- HDAaBgNVBAoME0FSNDg4X0VTUDgyNjZfQURET04xFTATBgNVBAMMDDE5Mi4xNjgu
- NC44ODAeFw0yMDAyMTcyMjIwMjdaFw00NjAyMDgyMjIwMjdaMDUxHDAaBgNVBAoM
- E0FSNDg4X0VTUDgyNjZfQURET04xFTATBgNVBAMMDDE5Mi4xNjguNC44ODBcMA0G
- CSqGSIb3DQEBAQUAA0sAMEgCQQDJbBC2h0pKzhPZVohGsGZHtwMEAex8e8sROZuB
- u4/Cp2dpSPeF2G3pH3HGC/owsVwocYsqF4PVgeBiSiNVn0b3AgMBAAEwDQYJKoZI
- hvcNAQELBQADQQCCH3KP0eUS4IZ+iZlJwwTVOwj3xlZG5pHeElOGnbFIaGSoLrnA
- pLm3exKS7NrAm09oxwz0LlzkF1fRvw+36Tel
- -----END CERTIFICATE-----
- )EOF";
- static const char serverKey[] PROGMEM = R"EOF(
- -----BEGIN RSA PRIVATE KEY-----
- MIIBOgIBAAJBAMlsELaHSkrOE9lWiEawZke3AwQB7Hx7yxE5m4G7j8KnZ2lI94XY
- bekfccYL+jCxXChxiyoXg9WB4GJKI1WfRvcCAwEAAQJAEYcU4T1eqqnKMmSEUVpy
- XBVB7uxX7vE615HixWRT+0U8hiCy0d37uNDemymOYkenQ40JHZjvOq1TrdhgkSDZ
- YQIhAONjoUoii8Im/SgMAEhPL5dWw5Ob1iHDL7aDHUFqf8LxAiEA4sQEjeVC0FoC
- tlsZUQS+Kh+jQOuToHv2wRgL9eqFWGcCIFsQXVmZOCtK/ft5wusyeza6kpycvkbL
- KmKHY8H86qmhAiEAj0bKmd0BGiPFEvL8S/RzMqpKu/ocjInGnrpS1E4ZcoECICIb
- aYuXsk+z1LDg9fffiClzZIy8iTQiZusNbBJShuGW
- -----END RSA PRIVATE KEY-----
- )EOF";
- ESP8266WebServerSecure *AR488srv;
- // EEPROM size and start address
- #define EESIZE 512
- #define EESTART 2
- /***** Parameter variables *****/
- #define BAUD 115200 // serial baud rate
- #define CR 0x13
- #define LF 0x10
- #define TXTSZ 32
- #define CHKSZ 20
- /***** Default WiFi AP mode config *****/
- const char *dfltSSID = "AR488wifi";
- const char *dfltPwd = "AR488-setup";
- /***** Parameters saved in EEPROM *****/
- union cfgObj {
- struct {
- uint16_t webp; // Web server port
- uint16_t gpibp; // GPIB passthrough port
- bool ssl; // SSL enabled switch state
- bool gpib; // GPIB passthrough enabled switch state
- bool wclient; // WiFi station (client) mode enabled
- bool dhcp; // Station mode DHCP enabled
- uint8_t addr[4]; // IP address
- uint8_t gate[4]; // IP gateway
- uint8_t mask[4]; // Subnet mask
- char pwdChk[CHKSZ]; // Admin password checksum
- };
- uint8_t db[CHKSZ+20];
- };
- union cfgObj AP;
- /***** Web server and client objects *****/
- WiFiServer *passSrv = new WiFiServer(8488);
- WiFiClient passCli;
- /***** Buffers *****/
- // HTML page buffer
- const uint16_t htmlSize = 4096;
- char html[htmlSize];
- // Serial buffer
- const uint16_t sbSize = 64;
- uint8_t sBuf[sbSize];
- uint16_t sbPtr = 0;
- /***** Buffers *****/
- uint8_t pktTmo = 5; // serial timout (milliseconds) to wait before sending TCP packet
- char curPage[10] = {'\0'};
- /*********************/
- /***** Web Pages *****/
- /*********************/
- /***** Main page *****/
- static const char wwwMainPage[] PROGMEM = R"EOF(
- <html>
- <head>
- <meta charset="utf-8">
- <title>Minimal Example Sketch</title>
- <link rel="stylesheet" href="style">
- <script defer src="/script"></script>
- </head>
- <body onload="getPage('%s')";>
- <div class="mpage">
- <div class="headr">WiFi Configuration</div>
- <div>
- <ul>
- <li><a id='seeStat' onclick="getPage('seeStat')">Status</a></li>
- <li><a id='cfgGen' onclick="getPage('cfgGen')">General</a></li>
- </ul>
- </div>
- <hr>
- <div id="cfgPage" class="conf">
- Loading...
- </div>
- <div>
- </div>
- </div>
- </body>
- </html>
- )EOF";
- /***** Status page *****/
- static const char seeStatPage[] PROGMEM = R"EOF(
- <table>
- <tr><th>WiFi mode:</th><td>%s</td></tr>
- <tr><th>WiFi status:</th><td>%s</td></tr>
- <tr %s><th>DHCP:</th><td>%s</td></tr>
- <tr><th>IP address:</th><td>%d.%d.%d.%d</td></tr>
- <tr %s><th>Gateway:</th><td>%d.%d.%d.%d</td></tr>
- <tr %s><th>Netmask:</th><td>%d.%d.%d.%d</td></tr>
- <tr><th>Mac addr:</th><td>%s</td></tr>
- <tr><th>ESSID:</th><td>%s</td></tr>
- </table>
- )EOF";
- /***** General configuration page *****/
- static const char cfgGenPage[] PROGMEM = R"EOF(
- <form method="post" action="/setGen" onchange="enableButton(0x1);"/>
- <table>
- <tr><th>SSL:</th><td>Off</td>
- <td><label class="switch">
- <input name="ssl" type="checkbox" onclick="toggleSSL(this);"/>
- <span class="slider"></span>
- </label></td>
- <td>On</td></tr>
- <tr><th>Passthrough:</th><td>Off</td>
- <td><label class="switch">
- <input name="pass" type="checkbox" onclick="togglePass(this);" %s/>
- <span class="slider"></span>
- </label></td>
- <td>On</td></tr>
- <tr><th>HTTP Port:</th><td colspan=3><input name="webp" value="%d"/></td></tr>
- <tr><th>PASS Port:</th><td colspan=3><input name="gpibp" value="%d" %s/></td></tr>
- </table>
- <input type="button" class="btn" id="btnApply" value="Apply" onclick="genValidate()" disabled/>
- </form>
- )EOF";
- /***** CSS definition *****/
- static const char css[] PROGMEM = R"EOF(
- body {width: 320; height: 424;}
- table {width: 100%%; font-size: 10pt; text-align: left;}
- th {width: 120px;}
- ul {list-style-type: none;
- margin: 0;
- padding: 0;
- height: 24px;
- font-size: 10pt;
- text-align: center;}
- li {float: left;width:20%%;}
- li a {display: block;
- border: 1px solid #777777;
- color: #333333;
- background-color: #FFEE77;
- text-decoration: none;}
- li a:hover:not(.active) {
- background-color: #777777;
- color: cyan;}
- .active {background-color:#77CCFF;}
- .headr {color: #0000AA;
- font-size: 14pt;
- font-weight: bold;
- width: 320;
- text-align: center;
- padding: 10px 0px 10px 0px;}
- .foot {font-size: 8pt;}
- .mpage {width: 320;
- height: 424;
- background-color: #EEEEEE;
- font-family: verdana;
- border: 1px solid #777777;
- margin: 7px;
- padding:7px;
- box-shadow: 3px 3px 3px #AAAAAA;
- }
- .conf {overflow-y: auto;
- height: 300px;
- }
- .ip {width: 40px; }
- .switch {
- position: relative;
- display: inline-block;
- width: 42px;
- height: 20px;
- }
- .slider {
- position: absolute;
- cursor: pointer;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background-color: #2196F3;
- }
- .slider:before {
- position: absolute;
- content: '';
- height: 16px;
- width: 16px;
- left: 2px;
- bottom: 2px;
- background-color: silver;
- }
- input:checked + .slider:before {
- -webkit-transform: translateX(22px);
- -ms-transform: translateX(22px);
- transform: translateX(22px);
- background-color: gold;
- }
- .btn {float: right;
- width: 90px;
- margin: 10px 5px 0px 0px;
- }
- )EOF";
- /***** Main linking JavaScript code *****/
- static const char lnkScriptJs[] PROGMEM = R"EOF(
- var curMnObj='';
- function getPage(url) {
- var cfgPage = document.querySelector('#cfgPage');
- var curPage;
- var obj;
- if (url=='txtErr'){
- alert("SSID/password is empty or too long!");
- url='cfgWifi';
- };
- if (url) {
- curPage = '#'+url;
- }else{
- curPage = '#seeStat';
- url = 'seeStat';
- }
- obj = document.querySelector(curPage);
- if (curMnObj) curMnObj.classList.remove('active');
- curMnObj = obj;
- curMnObj.classList.add('active');
- cfgPage.innerHTML = "Updating...";
- fetch(url, {method: "POST"} )
- .then((resp) => resp.text())
- .then(function(data){
- cfgPage.innerHTML = data;
- })
- .catch(function(error){
- alert("Unable to load page!");
- });
- if (url=='cfgWiFi') wifiMode();
- }
- function enableButton(sw){
- if (sw&0x1) document.querySelector('#btnApply').disabled = false;
- if (sw&0x2) document.querySelector('#btnSave').disabled = false;
- }
- )EOF";
- /***** General configuration page JavaScript *****/
- static const char cfgGenJs[] PROGMEM = R"EOF(
- function toggleSSL(ssl){
- var webp = document.querySelector('[name="webp"]');
- if (ssl.checked && webp.value == '80') webp.value = 443;
- if (ssl.checked==false && webp.value == '443') webp.value = 80;
- }
- function togglePass(pass){
- var gpibp = document.querySelector('[name="gpibp"]');
- if (pass.checked) {
- gpibp.disabled = false;
- }else{
- gpibp.disabled = true;
- }
- }
- function genValidate() {
- var form = document.querySelector('form');
- var adP = document.querySelector('[name="webp"]').value;
- var gpP = document.querySelector('[name="gpibp"]').value;
- if (adP==0||gpP==0 || adP>49151||gpP>49151) {
- alert("TCP port is out of range!\\nPlease set a port value between 1 and 49151.");
- }else{
- form.submit();
- }
- }
- )EOF";
- /***** Re-direct page *****/
- static const char redirectPage[] PROGMEM = R"EOF(
- <html>
- <head>
- <meta http-equiv="refresh" content="%d; URL='%s://%d.%d.%d.%d'"/>
- <style>
- body {width: 320; height: 424;}
- .mpage {width: 320;
- height: 424;
- background-color: #EEEEEE;
- font-family: verdana;
- border: 1px solid #777777;
- margin: 7px;
- padding:7px;
- box-shadow: 3px 3px 3px #AAAAAA;
- font-family: verdana;
- font-size: 12pt;
- font-weight: normal;
- }
- </style>
- </head>
- <body>
- <div class="mpage">
- <p>%s</p>
- <p>If you have switched to a DHCP assigned address, then manually
- enter the new IP address into your browswer.</p>
- <p>If you have switched from Station to AP mode, or have restarted
- AP mode, then you may have to re-connect to the WiFi SSID and then
- enter the new IP address in your browser.</p>
- <p>Otherwise, please wait a few seconds for the page to reload.<p>
- <p>If the page does not re-load within a few seconds, please try
- the back button in your browser or check your WiFi connection.</p>
- </div>
- </body>
- </html>
- )EOF";
- /**********************************/
- /***** MAIN PROGRAM *****/
- /**********************************/
- void setup() {
- #ifdef EEPROM_CLEAR
- epErase();
- #endif
- Serial.begin(BAUD);
- #ifdef DEBUG_0
- Serial.println();
- Serial.println(F("Starting WiFi..."));
- #endif
- #ifndef DISABLE_SSL
- configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
- #endif
- // Set config defaults
- setDefaultCfg();
- #ifdef DEBUG_0
- if (isEepromClear()){
- Serial.println(F("EEPROM is clear"));
- }else{
- Serial.println(F("EEPROM contains previous config"));
- }
- #endif
- // Check if previous config saved and load
- if (!isEepromClear()) {
- #ifdef DEBUG_0
- Serial.println("Loading saved config...");
- #endif
- // Load previous config else clear EEPROM
- if (!epReadData(EESTART, &AP, sizeof(AP))) {
- epErase();
- #ifdef DEBUG_0
- Serial.println("EEPROM erased. Reset to defaults.");
- #endif
- }
- }
- // Start WiFi and Web server
- if (startWifi()>-1) {
- #ifdef DEBUG_0
- Serial.println(F("Starting webserver..."));
- #endif
- startWebServer();
- if (AP.gpib) {
- passSrv = new WiFiServer(AP.gpibp);
- passSrv->begin();
- }
- }
- }
- void loop() {
- // Handle requests for web server
- AR488srv->handleClient();
- // Is GPIB passthrough enabled?
- if (AP.gpib) {
- // Handle incoming client connections
- if (passCli.connected()) {
- // Handle TCP connection, output to serial
- while (passCli.available()) {
- if (sbPtr < sbSize - 1) {
- sBuf[sbPtr] = passCli.read();
- sbPtr++;
- }else{
- break;
- }
- }
- if (sbPtr) {
- Serial.write(sBuf, sbPtr);
- clrSBuf(sbPtr);
- }
- // Handle serial input, output to TCP
- while (Serial.available()) {
- if (sbPtr < sbSize - 1) {
- sBuf[sbPtr] = Serial.read();
- sbPtr++;
- }
- }
- passCli.write((char*)sBuf, sbPtr);
- clrSBuf(sbPtr);
- #ifdef DEBUG_6
- if (!passCli.connected()) Serial.println("<= disconnected.");
- #endif
- } else {
- // Wait for a connection
- passCli = passSrv->available();
- if (passCli.connected()) {
- #ifdef DEBUG_6
- Serial.println("Connected =>");
- #endif
- // Initialise buffer
- clrSBuf(64);
- delay(50);
- // Clear spurious characters after connection established
- while (passCli.available()) { passCli.read(); }
- }
- }
- }
- }
- /*****************************/
- /***** PROGRAM FUNCTIONS *****/
- /*****************************/
- /***** Default configuration *****/
- void setDefaultCfg() {
- #ifdef DISABLE_SSL
- AP = {80,8488,false,false,false,false,{192,168,4,88},{192,168,4,88},{255,255,255,0},{'\0'}};
- #else
- AP = {443,8488,false,false,false,false,{192,168,4,88},{192,168,4,88},{255,255,255,0},{'\0'}};
- #endif
- }
- /***** Start WiFi *****/
- /*
- * Flag:
- * -1 : fail
- * 0 : fallback mode
- * 1 : Started in AP mode
- * 2 : Started in Client mode
- */
- int startWifi() {
- int stat=-1;
- // Check if already configured
- if (isEepromClear()) {
- Serial.println(F("Starting AP with defaults..."));
- setDefaultCfg();
- startWifiAP(dfltSSID, dfltPwd, AP.addr, AP.addr, AP.mask);
- stat = 0;
- }else{
- // Start mode
- if (AP.wclient) {
- // Start station (client) mode
- #ifdef DEBUG_1
- Serial.println(F("Starting WiFi client..."));
- #endif
- if (startWifiStn("", "", AP.addr, AP.gate, AP.mask)) {
- stat=2;
- }else{
- // Fallback to default AP configuration
- #ifdef DEBUG_1
- Serial.println(F("Falling back to AP with defaults..."));
- #endif
- setDefaultCfg();
- startWifiAP(dfltSSID, dfltPwd, AP.addr, AP.addr, AP.mask);
- stat=0;
- }
- }else{
- // Start AP mode
- startWifiAP("","",AP.addr,AP.addr,AP.mask);
- #ifdef DEBUG_1
- Serial.println(F("Starting AP..."));
- #endif
- stat=1;
- }
- }
- #ifdef DEBUG_1
- Serial.print(F("Wifi Start status: "));Serial.println(stat);
- #endif
- return stat;
- }
- /***** Check whether WiFi has started *****/
- bool hasWifiStarted() {
- uint16_t tmo = 60000;
- uint16_t dly = 500;
- // Wait for connection
- #ifdef DEBUG_1
- Serial.print(F("Waiting for connection."));
- #endif
- while ((WiFi.status() != WL_CONNECTED) && (tmo > 0)) {
- delay(dly);
- tmo = tmo - dly;
- #ifdef DEBUG_1
- Serial.print(".");
- #endif
- }
- #ifdef DEBUG_1
- Serial.print(F("\nWiFi status:"));
- Serial.println(WiFi.status());
- #endif
- if (WiFi.status() == WL_CONNECTED) {
- // Success!
- #ifdef DEBUG_1
- Serial.println(F("WiFi started."));
- Serial.print(F("Connected, IP address: "));
- Serial.println(WiFi.localIP());
- #endif
- return true;
- } else {
- // Timed out
- #ifdef DEBUG_1
- Serial.println(F("WiFi failed."));
- #endif
- return false;
- }
- }
- /***** Start WiFi in access point mode ****/
- void startWifiAP(String ssid, String psks, uint8_t addr[4], uint8_t gate[4], uint8_t mask[4]) {
- uint8_t gway[4];
- bool gws = true; // Set gateway to primary address (removes compiler warning)
- // If no SSID or password, then use the currently configure one
- if (ssid == NULL) ssid = WiFi.softAPSSID();
- if (psks == NULL) psks = WiFi.softAPPSK();
- // Stop and disable station mode
- if (WiFi.getMode()==WIFI_STA) {
- // Disconnect client from network
- WiFi.disconnect();
- WiFi.enableSTA(false);
- }
- // Gateway is primary address or separate address?
- for (uint8_t i=0; i<4; i++) {
- if (gws) {
- gway[i] = addr[i]; // Gateway set to primary address
- }else{
- gate[i] = gate[i]; // Gateway set to different IP address
- }
- }
- // Restart and configure the AP
- // if (!WiFi.enableAP()) WiFi.enableAP(true);
- WiFi.enableAP(true);
- WiFi.mode(WIFI_AP);
- WiFi.setSleepMode(WIFI_NONE_SLEEP);
- WiFi.softAPConfig(addr, gway, mask); // set IP address
- WiFi.softAP(ssid, psks); // set SSID and password
- delay(500);
- }
- /***** Start WiFi in station mode *****/
- bool startWifiStn(String ssid, String psks, uint8_t addr[4], uint8_t gate[4], uint8_t mask[4]) {
- if (ssid == NULL) ssid = WiFi.SSID();
- if (psks == NULL) psks = WiFi.psk();
- #ifdef DEBUG_1
- Serial.println(F("Station mode>"));
- #endif
- // Check whether in AP mode - is so, disconnect clients and turn off AP mode
- if (WiFi.getMode()==WIFI_AP) {
- // Disconnect clients and stop AP mode
- WiFi.softAPdisconnect(true);
- WiFi.enableAP(false);
- delay(500);
- }
- // Enable and start station mode
- // if (!WiFi.enableSTA()) WiFi.enableSTA(true);
- WiFi.enableSTA(true);
- WiFi.mode(WIFI_STA);
- WiFi.setSleepMode(WIFI_NONE_SLEEP);
- if (AP.dhcp) {
- // DHCP mode
- WiFi.config(0u, 0u, 0u);
- }else{
- // Static IP mode
- // wifi_station_dhcpc_stop();
- WiFi.config(addr, gate, mask);
- }
- // WiFi.setAutoConnect(true);
- // WiFi.setAutoReconnect(true);
- WiFi.begin(ssid, psks);
- return hasWifiStarted();
- }
- /***** Start the web server *****/
- void startWebServer() {
- delete AR488srv;
- // Create a new webserver instance
- AR488srv = new ESP8266WebServerSecure(AP.webp);
- // Apply certificate and key
- AR488srv->getServer().setRSACert(new BearSSL::X509List(serverCert), new BearSSL::PrivateKey(serverKey));
- // Pages being served
- AR488srv->on("/", wwwMain); // Default web page
- AR488srv->on("/cfgGen", cfgGen); // General options
- AR488srv->on("/seeStat", seeStat); // Status page
- AR488srv->on("/style", lnkStyle); // Stylesheet
- AR488srv->on("/script", lnkScript); // Main Script
- // Start the server
- AR488srv->begin(); // Start the HTTP server
- #ifdef DEBUG_2
- Serial.println("Web server started.");
- #endif
- }
- /***** Main page *****/
- void wwwMain() {
- snprintf(html, htmlSize, wwwMainPage, curPage);
- AR488srv->send(200, "text/html", html);
- }
- /***** Status page *****/
- void seeStat() {
- char wmodestr[8] = {0x53,0x74,0x6F,0x70,0x70,0x65,0x64,0x0};
- char wstatstr[14] = {0x52,0x75,0x6E,0x6E,0x69,0x6E,0x67,0x0};
- char dhcp[9] = {0x44,0x69,0x73,0x61,0x62,0x6C,0x65,0x64,0x0};
- char hide[7] = {'\0'};
- String ssid;
- uint8_t wmode = WiFi.getMode();
- int wstatus = WiFi.status();
- IPAddress addr = {0};
- IPAddress gate = {0};
- IPAddress mask = {0xFF,0xFF,0xFF,0x0};
- // AP mode
- if (wmode == 2) {
- strncpy(wmodestr, "Soft AP\0", 8);
- strncpy(hide, "hidden\0", 7);
- ssid = WiFi.softAPSSID();
- addr = WiFi.softAPIP();
- }
- // Station (client) mode
- if (wmode == 1) {
- strncpy(wmodestr, "Station\0", 8);
- ssid = WiFi.SSID();
- addr = WiFi.localIP();
- gate = WiFi.gatewayIP();
- mask = WiFi.subnetMask();
- if (AP.dhcp == true) strncpy(dhcp, "Enabled\0", 8);
- switch(wstatus) {
- case WL_CONNECTED:
- strncpy(wstatstr, "Connected\0", 14);
- break;
- case WL_CONNECTION_LOST:
- strncpy(wstatstr, "Conn. lost\0", 14);
- break;
- case WL_DISCONNECTED:
- strncpy(wstatstr, "Disconnected\0",14);
- break;
- default:
- strncpy(wstatstr, "Conn. failed\0",14);
- }
- }
- snprintf(html, htmlSize, seeStatPage,
- wmodestr,
- wstatstr,
- hide,
- dhcp,
- addr[0],
- addr[1],
- addr[2],
- addr[3],
- hide,
- gate[0],
- gate[1],
- gate[2],
- gate[3],
- hide,
- mask[0],
- mask[1],
- mask[2],
- mask[3],
- WiFi.macAddress().c_str(),
- ssid.c_str()
- );
- AR488srv->send(200, "text/html", html);
- }
- /***** General functions configuration page *****/
- void cfgGen() {
- // char chkd1[8] = {'\0'};
- char chkd2[8] = {'\0'};
- char disd[9] = {'\0'};
- if (AP.gpib) {
- strncpy(chkd2, "checked\0", 8);
- } else {
- strncpy(disd, "disabled\0", 9);
- }
- snprintf(html, htmlSize, cfgGenPage,
- chkd2,
- AP.webp,
- AP.gpibp,
- disd
- );
- AR488srv->send(200, "text/html", html);
- }
- /***** Return CSS stylesheet *****/
- void lnkStyle() {
- snprintf(html, htmlSize, css);
- AR488srv->send(200, "text/html", html);
- }
- /***** Return main JavaScript code *****/
- void lnkScript() {
- snprintf(html, htmlSize, lnkScriptJs);
- AR488srv->send(200, "text/html", html);
- }
- /***** JavaScript code for Ceneral config page *****/
- void cfgGenjs() {
- snprintf(html, htmlSize, cfgGenJs);
- AR488srv->send(200, "text/html", html);
- }
- /***** Set general configuration options *****/
- void setGen() {
- uint16_t webp;
- uint16_t gpibp;
- bool sc = false; // State change
- #ifdef DEBUG_2
- Serial.println(F("Received general config page..."));
- showArgs();
- #endif
- webp = AR488srv->arg("webp").toInt();
- if (webp != AP.webp) {
- AP.webp = webp;
- delete AR488srv;
- startWebServer();
- // ESP.reset();
- }
- if (AR488srv->arg("pass") == "on") {
- #ifdef DEBUG_2
- Serial.println(F("Passthrough turned on."));
- #endif
- if (!AP.gpib) sc = true;
- AP.gpib = true;
- gpibp = AR488srv->arg("gpibp").toInt();
- if (AP.gpibp != gpibp) {
- sc = true;
- AP.gpibp = gpibp;
- }
- if (sc) {
- #ifdef DEBUG_2
- Serial.print(F("Restarting TCP server on port: "));
- Serial.println(AP.gpibp);
- #endif
- if (passSrv) delete passSrv;
- passSrv = new WiFiServer(gpibp);
- passSrv->begin();
- }
- } else {
- if (AP.gpib) {
- AP.gpib = false;
- // Disconnect any client
- if (passCli.connected()) passCli.stop();
- // Kill the server (note: causes reboot!)
- passSrv->stop();
- // delete passSrv;
- }
- }
- epWriteData(EESTART, &AP, sizeof(AP));
- updatePage("cfgGen");
- }
- #ifdef DEBUG_2
- /***** Display submitted arguments *****/
- void showArgs() {
- uint8_t acnt = AR488srv->args();
- for (uint8_t i = 0; i < acnt; i++) {
- Serial.print(AR488srv->argName(i) + ":\t");
- Serial.println(AR488srv->arg(i));
- }
- }
- #endif
- /***** Return updated selected page *****/
- void updatePage(const char* page) {
- uint8_t len = strlen(page);
- strncpy(curPage, page, len);
- wwwMain();
- memset(curPage, '\0', len);
- }
- /***** Is the reply what we expected? *****/
- uint8_t getReply(const char* cmd, char *reply, int rsize) {
- uint8_t p = 0;
- // Clear the reply buffer
- memset(reply, '\0', rsize);
- // Send cmd to controller and get response
- Serial.println(cmd);
- p = Serial.readBytesUntil(LF, reply, rsize - 1);
- return p;
- }
- /***** Flush the incoming buffer *****/
- void flushIncoming() {
- while (Serial.available()) {
- Serial.read();
- };
- }
- /***** Clear buffer *****/
- void clrSBuf(uint8_t ptr) {
- memset(sBuf, '\0',ptr);
- sbPtr = 0;
- }
- /***************************/
- /***** EEPROM routines *****/
- /***************************/
- /***** Clear the EEPROM *****/
- void epErase() {
- int i = EESIZE;
- // Load EEPROM data from Flash
- EEPROM.begin(EESIZE);
- for (i=0; i<EESIZE; i++)
- EEPROM.write(i, 0xFF);
- EEPROM.commit();
- EEPROM.end();
- }
- /***** Write data to EEPROM (with CRC) *****/
- /*
- * addr = EEPROM address
- * cfg = config data union object
- * csize = size of config data object
- */
- void epWriteData(uint16_t addr, cfgObj * cptr, uint16_t csize) {
- uint16_t crc;
- // Load EEPROM data from Flash
- EEPROM.begin(EESIZE);
- // Write data
- EEPROM.put(addr,*cptr);
- // Write CRC
- crc = getCRC16(cptr->db, csize);
- EEPROM.put(0, crc);
- // Commit write to Flash
- EEPROM.commit();
- EEPROM.end();
- }
- /***** Read data from EEPROM (with CRC check) *****/
- /*
- * addr = EEPROM address
- * cfg = config data union object
- * csize = size of config data object
- */
- bool epReadData(uint16_t addr, cfgObj * cptr, uint16_t csize) {
- uint16_t crc1;
- uint16_t crc2;
- // Load EEPROM data from Flash
- EEPROM.begin(EESIZE);
- // Read CRC
- EEPROM.get(0,crc1);
- // Read data
- EEPROM.get(addr, *cptr);
- EEPROM.end();
- // Get CRC of config
- crc2 = getCRC16(cptr->db, csize);
- if (crc1==crc2) {
- return true;
- }else{
- return false;
- }
- }
- bool isEepromClear(){
- int16_t crc = 0;
- // Load data from EEPROM
- EEPROM.begin(EESIZE);
- // Read data
- EEPROM.get(0, crc);
- EEPROM.end();
- // Return result
- if (crc==-1) {
- return true;
- }else{
- return false;
- }
- }
- /***** Generate 16 bit CRC *****/
- uint16_t getCRC16(uint8_t bytes[], uint16_t bsize){
- uint8_t x;
- uint16_t crc = 0xFFFF;
- for (uint16_t idx=0; idx<bsize; ++idx) {
- x = crc >> 8 ^ bytes[idx];
- x ^= x>>4;
- crc = (crc << 8) ^ ((uint16_t)(x << 12)) ^ ((uint16_t)(x <<5)) ^ ((uint16_t)x);
- }
- return crc;
- }
- /**********************************/
- /***** End of EEPROM routines *****/
- /**********************************/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement