Espruino Wifi - Dropped characters at runtime

Posted on
  • Simple programs such as blink seem to transfer and run just fine, but I'm working with some Wifi and Http code that is significantly longer and it doesn't seem to transfer correctly. Log is below. The hardware is relatively new, but it worked correctly for about a day.

    Steps I've tried so far to resolve:

    • Unplugged it and plugged it back in again (yea, I worked in IT, gotta start there)
    • Used another USB cable
    • Turned on "Throttle Send" in the settings
    • Commented out large chunks, and the error moved to another line

    Environment:

    • Espruino Web IDE used as Chrome App
    • Mac OSX 10.12.6

      >
      Connected
      >echo(1)
      =undefined
      >< << {"VERSION":"1v91","BUILD_DATE":"Jan 12 2017","BUILD_TIME":"10:55:52","GIT_COMMI­T":"a6300790b771b7afffdb2bb2d8c5d0607f79­77ef","BOARD":"ESPRUINOWIFI","CHIP":"STM­32F411CEU6","CHIP_FAMILY":"STM32F4","FLA­SH":524288,"RAM":131072,"SERIAL":"43001d­00-0b513532-39333638","CONSOLE":"USB","E­XPORTS":{"jsvLock":336089,"jsvLockAgainS­afe":336075,"jsvUnLock":336049,"jsvSkipN­ame":184381,"jsvMathsOp":141949,"jsvMath­sOpSkipNames":141995,"jsvNewFromFloat":3­36405,"jsvNewFromInteger":336441,"jsvNew­FromString":339205,"jsvNewFromBool":3364­25,"jsvGetFloat":184749,"jsvGetInteger":­180485,"jsvGetBool":185337,"jspeiFindInS­copes":145525,"jspReplaceWith":154073,"j­speFunctionCall":150877,"jspGetNamedVari­able":145585,"jspGetNamedField":146857,"­jspGetVarNamedField":146449,"jsvNewWithF­lags":336245}} >> >
      >
      =undefined
      >
      _____                 _
      |   __|___ ___ ___ _ _|_|___ ___
      |   __|_ -| . |  _| | | |   | . |
      |_____|___|  _|_| |___|_|_|_|___|
            |_| http://espruino.com
      1v91 Copyright 2016 G.Williams
      >Connecting to sensor
      >Starting Wifi connection
      Uncaught SyntaxError: Got '(' expected ','
      at line 1 col 22
      function start(equire('http');
                       ^
      ERROR: Prompt not detected - upload failed. Trying to recover...
      =undefined
      >echo(1)
      =undefined
      Connected!
      Uncaught Error: Function "start" not found!
      at line 6 col 3
      start() 
      
      // Constants
      var DEVICE_ID = "1234";
      var WIFI_NAME = "*********";
      var WIFI_OPTIONS = {
      password : "*********"
      };
      var SERVER_ADDRESS = '*********';
      var SERVER_PORT = 3000;
      
      // Connect to Sensor
      var ow = new OneWire(A0);
      var sensor;
      console.log('Connecting to sensor');
      try {
      sensor = require("DS18B20").connect(ow);
      } catch (e) {
      console.log('Unable to connect to sensor \n', e.message); 
      }
      
      // Connect to Wifi
      console.log('Starting Wifi connection');
      var wifi = require("EspruinoWiFi");
      wifi.connect(WIFI_NAME, WIFI_OPTIONS, function(err) {
      if (err) {
      console.log("Wifi Connection error: "+err);
      return;
      }
      console.log("Connected!");
      start();
      });
      
      var http;
      function start() {
      http = require('http');
      if (sensor) {
      getTemp();
      //setInterval(getTemp, 60000);
      } else {
      // TODO: Report failure to somewhere
      }
      }
      
      function getTemp() {
      sensor.getTemp(function(temp) {
      console.log("Temp is "+temp+"°C"); 
      sendTemp(temp);
      });
      }
      
      function sendTemp(temp) {
      
      var postData = {
      value: {
       temperature: temp,
       unit: 'celsius'
      },
      };
      
      var reqPath= '/api/devices/' + DEVICE_ID;
      
      var req = http.request({
      host: SERVER_ADDRESS,
      port: SERVER_PORT,
      path: reqPath,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
      }, function(res) {
      console.log("STATUS: " + res.statusCode);
      console.log("HEADERS: " + JSON.stringify(res.headers));
      res.setEncoding('utf8');
      res.on('data', function(data) {
        console.log("HTTP> "+data);
      });
      res.on('close', function(data) {
        console.log("Connection closed");
      });
      });
      req.on('error', function(e) {
      console.log("ERROR: problem with request: " + e.message);
      });
      req.write(postData);
      req.end();
      }
      
      
      
  • Here is the console output for debug:

    Initialising CodeLink
    Initialising Project
    Initialising Testing
    Initialising Notification_Sound
    Initialising Tern
    Initialising Debugger
    Initialising Tour
    Initialising SettingsProfile
    Initialising HelpLinks
    Initialising Offline
    Loaded code from storage.
    GET chrome.storage.local.OFFLINE_DATA = 0 bytes
    >>> Connecting...
    ForceThrottle option is set - set Slow Write = true
    [object Object]
    Connected [object Object]
    Found a prompt... great!
    >>> Sending...
    ---> "\u0010console.log(\"<\",\"<<\",JSON.str­ingify(process.env),\">>\",\">\")\n"
    >>> Sent
    WARNING: No result found - just got "<- Serial1\r\n>< << {\"VERSION\":\"1v91\",\"BUILD_DATE\":\"J­an 12 2017\",\"BUILD_TIME\":\"10:55:52\",\"GIT­_COMMIT\":\"a6300790b771b7afffdb2bb2d8c5­d0607f7977ef\",\"BOARD\":\"ESPRUINOWIFI\­",\"CHIP\":\"STM32F411CEU6\",\"CHIP_FAMI­LY\":\"STM32F4\",\"FLASH\":524288,\"RAM\­":131072,\"SERIAL\":\"43001d00-0b513532-­39333638\",\"CONSOLE\":\"USB\",\"EXPORTS­\":{\"jsvLock\":336089,\"jsvLockAgainSaf­e\":336075,\"jsvUnLock\":336049,\"jsvSki­pName\":184381,\"jsvMathsOp\":141949,\"j­svMathsOpSkipNames\":141995,\"jsvNewFrom­Float\":336405,\"jsvNewFromInteger\":336­441,\"jsvNewFromString\":339205,\"jsvNew­FromBool\":336425,\"jsvGetFloat\":184749­,\"jsvGetInteger\":180485,\"jsvGetBool\"­:185337,\"jspeiFindInScopes\":145525,\"j­spReplaceWith\":154073,\"jspeFunctionCal­l\":150877,\"jspGetNamedVariable\":14558­5,\"jspGetNamedField\":146857,\"jspGetVa­rNamedField\":146449,\"jsv"
    Device found (connectionId=1)
    [success] Connected to port /dev/tty.usbmodem1421
    >>> Connected to port /dev/tty.usbmodem1421
    Disconnect callback...
    WARNING: [notify_warn] Disconnected
    >>> Disconnected
    >>> Connecting...
    ForceThrottle option is set - set Slow Write = true
    [object Object]
    Connected [object Object]
    Found a prompt... great!
    >>> Sending...
    ---> "\u0010console.log(\"<\",\"<<\",JSON.str­ingify(process.env),\">>\",\">\")\n"
    >>> Sent
    WARNING: No result found - just got "NewWithFlags\":336245}} >> >\r\n>< << {\"VERSION\":\"1v91\",\"BUILD_DATE\":\"J­an 12 2017\",\"BUILD_TIME\":\"10:55:52\",\"GIT­_COMMIT\":\"a6300790b771b7afffdb2bb2d8c5­d0607f7977ef\",\"BOARD\":\"ESPRUINOWIFI\­",\"CHIP\":\"STM32F411CEU6\",\"CHIP_FAMI­LY\":\"STM32F4\",\"FLASH\":524288,\"RAM\­":131072,\"SERIAL\":\"43001d00-0b513532-­39333638\",\"CONSOLE\":\"USB\",\"EXPORTS­\":{\"jsvLock\":336089,\"jsvLockAgainSaf­e\":336075,\"jsvUnLock\":336049,\"jsvSki­pName\":184381,\"jsvMathsOp\":141949,\"j­svMathsOpSkipNames\":141995,\"jsvNewFrom­Float\":336405,\"jsvNewFromInteger\":336­441,\"jsvNewFromString\":339205,\"jsvNew­FromBool\":336425,\"jsvGetFloat\":184749­,\"jsvGetInteger\":180485,\"jsvGetBool\"­:185337,\"jspeiFindInScopes\":145525,\"j­spReplaceWith\":154073,\"jspeFunctionCal­l\":150877,\"jspGetNamedVariable\":14558­5,\"jspGetNamedField\":146857,\"jspGetVa­rNamedField\":146449,\"jsv"
    Device found (connectionId=2)
    [success] Connected to port /dev/tty.usbmodem1421
    >>> Connected to port /dev/tty.usbmodem1421
    loadModule(DS18B20)
    loadModule(EspruinoWiFi)
    loadModule(http)
     - DS18B20 requires []
     - EspruinoWiFi requires ["AT","NetworkJS"]
       Queueing AT
       Queueing NetworkJS
    ERROR: Not Found
    loadModule(AT)
    loadModule(NetworkJS)
    ERROR: Not Found
    WARNING: [notify_warn] Module http not found
     - AT requires []
    ERROR: Not Found
    ERROR: Not Found
    WARNING: [notify_warn] Module NetworkJS not found
    Received a prompt after sending newline... good!
    >>> Sending...
    ---> "\u0010reset();\n\u0010setTime(150507649­2.952);\n\u0010Modules.removeAllCached()­;\n\u0010Modules.addCached(\"AT\",\"expo­rts.connect=function(l){var m=!1,a=\\\"\\\",d,b={},e={},g=[];l.on(\\­\"data\\\",function(f){a+=f;m&&console.l­og(\\\"] \\\"+JSON.stringify(a)+\\\" <--- \\\"+JSON.stringify(f));\\\"\\\\n\\\"==a­[0]&&(a=a.substr(1));if(b){b[\\\">\\\"]&­&\\\">\\\"==a[0]&&(a=b[\\\">\\\"](a));fo­r(var c in b)a.substr(0,c.length)==c&&(a=b[c](a))}f­or(f=a.indexOf(\\\"\\\\r\\\");0<=f;){var­ k=a.substr(0,f);if(0<k.length){var n=!1;for(c in e)k.substr(0,c.length)==c&&(e[c](k),n=!0­);n||d&&d(k)}a=a.substr(f+1);\\\"\\\\n\\­\"==a[0]&&(a=a.substr(1));if(a.length&&b­)for(c in b[\\\">\\\"]&&\\\">\\\"==\\na[0]&&(a=b[\­\\">\\\"](a)),b)a.substr(0,c.length)==c&­&(a=b[c](a));f=a.indexOf(\\\"\\\\r\\\")}­});var h={debug:function(){m=!0;return{line:a,l­ineCallback:d,handlers:b,lineHandlers:e,­waiting:g}},cmd:function(a,c,b){if(d)g.p­ush([a,c,b]);else if(m&&console.log(\\\"[\\\"+JSON.stringi­fy(a)),l.write(a),c){var e=setTimeout(function(){d=void 0;b&&b()},c),p=function(a){d=void 0;var f;b&&(f=b(a))?(d=p,b=f):clearTimeout(e);­void 0===d&&0<g.length&&(a=g.shift(),h.cmd(a[­0],a[1],a[2]))};d=p}},write:function(a){­l.write(a)},cmdReg:function(a,\\nb,d,e,g­){h.registerLine(d,e);h.cmd(a,b,function­(a){h.unregisterLine(d);g(a)})},register­Line:function(a,b){if(e[a])throw Error(a+\\\" already registered\\\");e[a]=b},unregisterLine:f­unction(a){delete e[a]},register:function(a,c){if(b[a])thr­ow Error(a+\\\" already registered\\\");b[a]=c},unregister:funct­ion(a){delete b[a]},isBusy:function(){return void 0!==d}};return h}\");\n\u0010Modules.addCached(\"Esprui­noWiFi\",\"function v(a){var b=a.indexOf(\\\":\\\");if(0>b)return a;var d=a.substring(5,b).split(\\\",\\\");d[1]­|=0;var c=a.length-(b+1);if(c>=d[1])return f[d[0]]+=a.substr(b+1,d[1]),a.substr(b+d­[1]+1);f[d[0]]+=a.substr(b+1,c);return\\­\"+IPD,\\\"+d[0]+\\\",\\\"+(d[1]-c)+\\\"­:\\\"}function n(a,b){if(b)return a(b);c.cmd(\\\"AT+CWMODE=\\\"+g+\\\"\\\\­r\\\\n\\\",1E3,function(b){\\\"no change\\\"!=b&&\\\"OK\\\"!=b&&\\\"WIFI DISCONNECT\\\"!=b?a(\\\"CWMODE failed: \\\"+(b?b:\\\"Timeout\\\")):a(null)})}fu­nction h(a){e[a[0]]=\\\"Wait\\\"==e[a[0]]?!0:\\­\"Accept\\\"}function k(a){e[a[0]]=\\\"\\\"!=f[a[0]]?\\n\\\"Da­taClose\\\":void 0}function p(a,b){var d=0==g;g|=a;d?(q.setup(115200,{rx:A3,tx:­A2}),c=require(\\\"AT\\\").connect(q),c.­register(\\\"+IPD\\\",v),c.registerLine(­\\\"0,CONNECT\\\",h),c.registerLine(\\\"­1,CONNECT\\\",h),c.registerLine(\\\"2,CO­NNECT\\\",h),c.registerLine(\\\"3,CONNEC­T\\\",h),c.registerLine(\\\"4,CONNECT\\\­",h),c.registerLine(\\\"0,CLOSED\\\",k),­c.registerLine(\\\"1,CLOSED\\\",k),c.reg­isterLine(\\\"2,CLOSED\\\",k),c.register­Line(\\\"3,CLOSED\\\",k),c.registerLine(­\\\"4,CLOSED\\\",k),exports.at=c,require­(\\\"NetworkJS\\\").create(t),c.cmd(\\\"­\\\\r\\\\nAT+RST\\\\r\\\\n\\\",1E4,funct­ion l(a){if(\\\"ready\\\"==\\na||\\\"Ready.\­\\"==a)setTimeout(function(){c.cmd(\\\"A­TE0\\\\r\\\\n\\\",1E3,function w(a){if(\\\"ATE0\\\"==a)return w;\\\"OK\\\"==a?c.cmd(\\\"AT+CIPMUX=1\\\­\r\\\\n\\\",1E3,function(a){\\\"OK\\\"!=­a?b(\\\"CIPMUX failed: \\\"+(a?a:\\\"Timeout\\\")):n(b)}):b(\\\­"ATE0 failed: \\\"+(a?a:\\\"Timeout\\\"))})},500);else­ if(void 0===a)b(\\\"No 'ready' after AT+RST\\\");else return l}),digitalWrite(x,1),digitalWrite(r,1))­:n(b)}function u(a){(g&=~a)?n(function(){},null):(q.rem­oveAllListeners(),c=void 0,exports.at=void 0,digitalWrite(r,0),e=[])}var x=A13,r=A14,q=Serial2;digitalWrite(r,\\n­0);var y=[\\\"open\\\",\\\"wep\\\",\\\"wpa_psk\­\\",\\\"wpa2_psk\\\",\\\"wpa_wpa2_psk\\\­"],g=0,c,e=[],f=[\\\"\\\",\\\"\\\",\\\"\­\\",\\\"\\\",\\\"\\\"],t={create:functio­n(a,b){if(!c)return-1;if(void 0===a){var d=5;e[d]=\\\"Wait\\\";f[d]=\\\"\\\";c.cm­d(\\\"AT+CIPSERVER=1,\\\"+b+\\\"\\\\r\\\­\n\\\",1E4,function(a){\\\"OK\\\"==a?e[d­]=!0:(e[d]=void 0,setTimeout(function(){throw Error(\\\"CIPSERVER failed (\\\"+(a?a:\\\"Timeout\\\")+\\\")\\\");}­,0))});return 5}for(d=0;void 0!==e[d];)d++;if(5<=d)return-7;e[d]=\\\"­Wait\\\";f[d]=\\\"\\\";c.cmd(\\\"AT+CIPS­TART=\\\"+d+',\\\"TCP\\\",'+JSON.stringi­fy(a)+\\\",\\\"+b+\\\"\\\\r\\\\n\\\",1E4­,function(a){\\\"OK\\\"!=a&&(e[d]=\\n-6)­});return d},close:function(a){\\\"Wait\\\"==e[a]?­e[a]=\\\"WaitClose\\\":void 0!==e[a]&&(0>e[a]?e[a]=void 0:c.cmd((5==a?\\\"AT+CIPSERVER=0\\\":\\\­"AT+CIPCLOSE=\\\"+a)+\\\"\\\\r\\\\n\\\",­1E3,function(b){e[a]=void 0}))},accept:function(a){for(a=0;5>a;a++­)if(\\\"Accept\\\"==e[a])return e[a]=!0,a;return-1},recv:function(a,b){i­f(f[a]){if(f[a].length>b){var d=f[a].substr(0,b);f[a]=f[a].substr(b)}e­lse d=f[a],f[a]=\\\"\\\",\\\"DataClose\\\"==­e[a]&&(e[a]=void 0);return d}return 0>e[a]?e[a]:e[a]?\\\"\\\":-1},send:funct­ion(a,b){if(!c)return-1;if(c.isBusy()||\­\\"Wait\\\"==\\ne[a])return 0;if(0>e[a])return e[a];if(!e[a])return-1;c.cmd(\\\"AT+CIPS­END=\\\"+a+\\\",\\\"+b.length+\\\"\\\\r\­\\\n\\\",1E4,function m(l){if(\\\"OK\\\"==l)return c.register(\\\"> \\\",function(){c.unregister(\\\"> \\\");c.write(b);return\\\"\\\"}),m;if(l­==\\\"Recv \\\"+b.length+\\\" bytes\\\")return m;\\\"SEND OK\\\"==l?(\\\"WaitClose\\\"==e[a]&&t.cl­ose(a),e[a]=!0):(e[a]=void 0,c.unregister(\\\"> \\\"))});e[a]=\\\"Wait\\\";return b.length}};exports.connect=function(a,b,­d){var e=\\\"\\\";d=d||function(){};void 0!==b.password&&(e=b.password);p(1,funct­ion(b){if(b)return d(b);c.cmd(\\\"AT+CWJAP=\\\"+\\nJSON.str­ingify(a)+\\\",\\\"+JSON.stringify(e)+\\­\"\\\\r\\\\n\\\",2E4,function z(a){if(0<=[\\\"WIFI DISCONNECT\\\",\\\"WIFI CONNECTED\\\",\\\"WIFI GOT IP\\\",\\\"+CWJAP:1\\\"].indexOf(a))retu­rn z;\\\"OK\\\"!=a?setTimeout(d,0,\\\"WiFi connect failed: \\\"+(a?a:\\\"Timeout\\\")):setTimeout(d­,0,null)})})};exports.disconnect=functio­n(){u(1)};exports.getIP=function(a){var b={};c.cmd(\\\"AT+CIFSR\\\\r\\\\n\\\",1E­3,function m(c){if(void 0===c)a(\\\"Timeout\\\");else{if(\\\"+CI­FSR:STAIP\\\"==c.substr(0,12))b.ip=c.sli­ce(14,-1);else if(\\\"+CIFSR:STAMAC\\\"==c.substr(0,13)­)b.mac=c.slice(15,-1);else if(\\\"OK\\\"==\\nc){a(null,b);return}re­turn m}})};exports.startAP=function(a,b,d){b=­b||{};if(!b.password||8>b.password.lengt­h)throw Error(\\\"Password must be at least 8 characters\\\");var e=b.password?\\\"3\\\":\\\"0\\\";if(b.au­thMode&&(e={open:0,wpa:2,wpa2:3,wpa_wpa2­:4}[b.authMode],void 0===e))throw Error(\\\"Unknown authMode \\\"+b.authMode);void 0===b.channel&&(b.channel=5);p(2,functio­n(f){if(f)return d(f);c.cmd(\\\"AT+CWSAP=\\\"+JSON.string­ify(a)+\\\",\\\"+JSON.stringify(b.passwo­rd)+\\\",\\\"+b.channel+\\\",\\\"+e+\\\"­\\\\r\\\\n\\\",5E3,function(a){\\\"OK\\\­"!=a?d(\\\"CWSAP failed: \\\"+\\n(a?a:\\\"Timeout\\\")):d(null)})­})};exports.stopAP=function(){u(2)};expo­rts.scan=function(a){var b=[];p(1,function(d){if(d)return a(d);c.cmdReg(\\\"AT+CWLAP\\\\r\\\\n\\\"­,5E3,\\\"+CWLAP:\\\",function(a){a=a.sli­ce(8,-1).split(\\\",\\\");b.push({ssid:J­SON.parse(a[1]),authMode:y[a[0]],rssi:pa­rseInt(a[2]),mac:JSON.parse(a[3]),channe­l:JSON.parse(a[4])})},function(c){a(null­,b)})})};exports.debug=function(){return­{wifiMode:g,socks:e,sockData:f}}\");\n\u­0010Modules.addCached(\"DS18B20\",\"func­tion c(b,a){this.bus=b;void 0===a?this.sCode=this.bus.search()[0]:pa­rseInt(a).toString()==a&&0<=a&&126>=a?th­is.sCode=this.bus.search()[a]:this.sCode­=a;if(!this.sCode)throw Error(\\\"No DS18B20 found\\\");this.type=parseInt(this.sCode­[0]+this.sCode[1])}c.prototype._r=functi­on(){var b=this.bus;b.select(this.sCode);b.write(­190);return b.read(9)};c.prototype._w=function(b,a,c­){var f=this.bus;f.select(this.sCode);f.write(­[78,b,a,c]);f.select(this.sCode);f.write­(72);f.reset()};c.prototype.setRes=\\nfu­nction(b){var a=this._r();b=[31,63,95,127][E.clip(b,9,­12)-9];this._w(a[2],a[3],b)};c.prototype­.getRes=function(){return[31,63,95,127].­indexOf(this._r()[4])+9};c.prototype.isP­resent=function(){return-1!==this.bus.se­arch().indexOf(this.sCode)};c.prototype.­getTemp=function(b){function a(a){for(var c=a._r(),e=0,d=0;8>d;d++)for(var e=e^c[d],g=0;8>g;g++)e=e>>1^140*(e&1);d=­null;e==c[8]&&(d=c[0]+(c[1]<<8),d&32768&­&(d-=65536),d/=10==a.type?2:16);b&&b(d);­return d}this.bus.select(this.sCode);this.bus.w­rite(68,\\n!0);if(!b)return a(this);setTimeout(a,{9:94,10:188,11:375­,12:750}[this.getRes()],this)};c.prototy­pe.searchAlarm=function(){return this.bus.search(236)};c.prototype.setAla­rm=function(b,a){b--;0>b&&(b+=256);0>a&&­(a+=256);var c=this._r();this._w(a,b,c[4])};exports.c­onnect=function(b,a){return new c(b,a)}\");\n\u0010var DEVICE_ID = \"1234\";\n\u0010var WIFI_NAME = \"Aeris\";\n\u0010var WIFI_OPTIONS = {\u001b\n  password : \"interare!domus42\"\u001b\n};\n\u0010va­r KNIT_ADDRESS = '192.168.1.64';\n\u0010var KNIT_PORT = 3000;\n\u0010var ow = new OneWire(A0);\n\u0010var sensor;\n\u0010console.log('Connecting to sensor');\n\u0010try {\u001b\n  sensor = require(\"DS18B20\").connect(ow);\u001b\­n} catch (e) {\u001b\n  console.log('Unable to connect to sensor \\n', e.message); \u001b\n}\n\u0010console.log('Starting Wifi connection');\n\u0010var wifi = require(\"EspruinoWiFi\");\n\u0010wifi.c­onnect(WIFI_NAME, WIFI_OPTIONS, function(err) {\u001b\n  if (err) {\u001b\n    console.log(\"Wifi Connection error: \"+err);\u001b\n    return;\u001b\n  }\u001b\n  console.log(\"Connected!\");\u001b\n  start();\u001b\n});\n\u0010var http;\n\u0010function start() {\u001b\n  http = require('http');\u001b\n  if (sensor) {\u001b\n    getTemp();\u001b\n    //setInterval(getTemp, 60000);\u001b\n  } else {\u001b\n    // TODO: Report failure to somewhere\u001b\n  }\u001b\n}\n\u0010function getTemp() {\u001b\n  sensor.getTemp(function(temp) {\u001b\n    console.log(\"Temp is \"+temp+\"°C\"); \u001b\n    sendTemp(temp);\u001b\n  });\u001b\n}\n\u0010function sendTemp(temp) {\u001b\n\u001b\n  var postData = {\u001b\n   value: {\u001b\n     temperature: temp,\u001b\n     unit: 'celsius'\u001b\n   },\u001b\n  };\u001b\n\u001b\n  var reqPath= '/api/devices/' + DEVICE_ID;\u001b\n\u001b\n  var req = http.request({\u001b\n    host: KNIT_ADDRESS,\u001b\n    port: KNIT_PORT,\u001b\n    path: reqPath,\u001b\n    method: 'POST',\u001b\n    headers: {\u001b\n      'Content-Type': 'application/json'\u001b\n    }\u001b\n  }, function(res) {\u001b\n    console.log(\"STATUS: \" + res.statusCode);\u001b\n    console.log(\"HEADERS: \" + JSON.stringify(res.headers));\u001b\n    res.setEncoding('utf8');\u001b\n    res.on('data', function(data) {\u001b\n      //console.log(\"HTTP> \"+data);\u001b\n    });\u001b\n    res.on('close', function(data) {\u001b\n      console.log(\"Connection closed\");\u001b\n    });\u001b\n  });\u001b\n  req.on('error', function(e) {\u001b\n    console.log(\"ERROR: problem with request: \" + e.message);\u001b\n  });\u001b\n  req.write(postData);\u001b\n  req.end();\u001b\n}\n\n"
    Splitting at "reset();\n", delay 250
    >>> Sent
    Splitting at "\u0003", delay 250
    Splitting at "\u0003", delay 250
    Disconnect callback...
    WARNING: [notify_warn] Disconnected
    >>> Disconnected
    >>> Connecting...
    ForceThrottle option is set - set Slow Write = true
    [object Object]
    Connected [object Object]
    Found a prompt... great!
    >>> Sending...
    ---> "\u0010console.log(\"<\",\"<<\",JSON.str­ingify(process.env),\">>\",\">\")\n"
    >>> Sent
    WARNING: No result found - just got "echo(1)\r\n=undefined\r\n>< << {\"VERSION\":\"1v91\",\"BUILD_DATE\":\"J­an 12 2017\",\"BUILD_TIME\":\"10:55:52\",\"GIT­_COMMIT\":\"a6300790b771b7afffdb2bb2d8c5­d0607f7977ef\",\"BOARD\":\"ESPRUINOWIFI\­",\"CHIP\":\"STM32F411CEU6\",\"CHIP_FAMI­LY\":\"STM32F4\",\"FLASH\":524288,\"RAM\­":131072,\"SERIAL\":\"43001d00-0b513532-­39333638\",\"CONSOLE\":\"USB\",\"EXPORTS­\":{\"jsvLock\":336089,\"jsvLockAgainSaf­e\":336075,\"jsvUnLock\":336049,\"jsvSki­pName\":184381,\"jsvMathsOp\":141949,\"j­svMathsOpSkipNames\":141995,\"jsvNewFrom­Float\":336405,\"jsvNewFromInteger\":336­441,\"jsvNewFromString\":339205,\"jsvNew­FromBool\":336425,\"jsvGetFloat\":184749­,\"jsvGetInteger\":180485,\"jsvGetBool\"­:185337,\"jspeiFindInScopes\":145525,\"j­spReplaceWith\":154073,\"jspeFunctionCal­l\":150877,\"jspGetNamedVariable\":14558­5,\"jspGetNamedField\":146857,\"jspGetVa­rNamedField\":146449,\"jsv"
    Device found (connectionId=3)
    [success] Connected to port /dev/tty.usbmodem1421
    >>> Connected to port /dev/tty.usbmodem1421
    loadModule(DS18B20)
    loadModule(EspruinoWiFi)
    loadModule(http)
     - DS18B20 requires []
     - EspruinoWiFi requires ["AT","NetworkJS"]
       Queueing AT
       Queueing NetworkJS
    ERROR: Not Found
    loadModule(AT)
    loadModule(NetworkJS)
    ERROR: Not Found
    WARNING: [notify_warn] Module http not found
     - AT requires []
    ERROR: Not Found
    ERROR: Not Found
    WARNING: [notify_warn] Module NetworkJS not found
    Received a prompt after sending newline... good!
    >>> Sending...
    ---> "\u0010reset();\n\u0010setTime(150507683­3.293);\n\u0010Modules.removeAllCached()­;\n\u0010Modules.addCached(\"AT\",\"expo­rts.connect=function(l){var m=!1,a=\\\"\\\",d,b={},e={},g=[];l.on(\\­\"data\\\",function(f){a+=f;m&&console.l­og(\\\"] \\\"+JSON.stringify(a)+\\\" <--- \\\"+JSON.stringify(f));\\\"\\\\n\\\"==a­[0]&&(a=a.substr(1));if(b){b[\\\">\\\"]&­&\\\">\\\"==a[0]&&(a=b[\\\">\\\"](a));fo­r(var c in b)a.substr(0,c.length)==c&&(a=b[c](a))}f­or(f=a.indexOf(\\\"\\\\r\\\");0<=f;){var­ k=a.substr(0,f);if(0<k.length){var n=!1;for(c in e)k.substr(0,c.length)==c&&(e[c](k),n=!0­);n||d&&d(k)}a=a.substr(f+1);\\\"\\\\n\\­\"==a[0]&&(a=a.substr(1));if(a.length&&b­)for(c in b[\\\">\\\"]&&\\\">\\\"==\\na[0]&&(a=b[\­\\">\\\"](a)),b)a.substr(0,c.length)==c&­&(a=b[c](a));f=a.indexOf(\\\"\\\\r\\\")}­});var h={debug:function(){m=!0;return{line:a,l­ineCallback:d,handlers:b,lineHandlers:e,­waiting:g}},cmd:function(a,c,b){if(d)g.p­ush([a,c,b]);else if(m&&console.log(\\\"[\\\"+JSON.stringi­fy(a)),l.write(a),c){var e=setTimeout(function(){d=void 0;b&&b()},c),p=function(a){d=void 0;var f;b&&(f=b(a))?(d=p,b=f):clearTimeout(e);­void 0===d&&0<g.length&&(a=g.shift(),h.cmd(a[­0],a[1],a[2]))};d=p}},write:function(a){­l.write(a)},cmdReg:function(a,\\nb,d,e,g­){h.registerLine(d,e);h.cmd(a,b,function­(a){h.unregisterLine(d);g(a)})},register­Line:function(a,b){if(e[a])throw Error(a+\\\" already registered\\\");e[a]=b},unregisterLine:f­unction(a){delete e[a]},register:function(a,c){if(b[a])thr­ow Error(a+\\\" already registered\\\");b[a]=c},unregister:funct­ion(a){delete b[a]},isBusy:function(){return void 0!==d}};return h}\");\n\u0010Modules.addCached(\"Esprui­noWiFi\",\"function v(a){var b=a.indexOf(\\\":\\\");if(0>b)return a;var d=a.substring(5,b).split(\\\",\\\");d[1]­|=0;var c=a.length-(b+1);if(c>=d[1])return f[d[0]]+=a.substr(b+1,d[1]),a.substr(b+d­[1]+1);f[d[0]]+=a.substr(b+1,c);return\\­\"+IPD,\\\"+d[0]+\\\",\\\"+(d[1]-c)+\\\"­:\\\"}function n(a,b){if(b)return a(b);c.cmd(\\\"AT+CWMODE=\\\"+g+\\\"\\\\­r\\\\n\\\",1E3,function(b){\\\"no change\\\"!=b&&\\\"OK\\\"!=b&&\\\"WIFI DISCONNECT\\\"!=b?a(\\\"CWMODE failed: \\\"+(b?b:\\\"Timeout\\\")):a(null)})}fu­nction h(a){e[a[0]]=\\\"Wait\\\"==e[a[0]]?!0:\\­\"Accept\\\"}function k(a){e[a[0]]=\\\"\\\"!=f[a[0]]?\\n\\\"Da­taClose\\\":void 0}function p(a,b){var d=0==g;g|=a;d?(q.setup(115200,{rx:A3,tx:­A2}),c=require(\\\"AT\\\").connect(q),c.­register(\\\"+IPD\\\",v),c.registerLine(­\\\"0,CONNECT\\\",h),c.registerLine(\\\"­1,CONNECT\\\",h),c.registerLine(\\\"2,CO­NNECT\\\",h),c.registerLine(\\\"3,CONNEC­T\\\",h),c.registerLine(\\\"4,CONNECT\\\­",h),c.registerLine(\\\"0,CLOSED\\\",k),­c.registerLine(\\\"1,CLOSED\\\",k),c.reg­isterLine(\\\"2,CLOSED\\\",k),c.register­Line(\\\"3,CLOSED\\\",k),c.registerLine(­\\\"4,CLOSED\\\",k),exports.at=c,require­(\\\"NetworkJS\\\").create(t),c.cmd(\\\"­\\\\r\\\\nAT+RST\\\\r\\\\n\\\",1E4,funct­ion l(a){if(\\\"ready\\\"==\\na||\\\"Ready.\­\\"==a)setTimeout(function(){c.cmd(\\\"A­TE0\\\\r\\\\n\\\",1E3,function w(a){if(\\\"ATE0\\\"==a)return w;\\\"OK\\\"==a?c.cmd(\\\"AT+CIPMUX=1\\\­\r\\\\n\\\",1E3,function(a){\\\"OK\\\"!=­a?b(\\\"CIPMUX failed: \\\"+(a?a:\\\"Timeout\\\")):n(b)}):b(\\\­"ATE0 failed: \\\"+(a?a:\\\"Timeout\\\"))})},500);else­ if(void 0===a)b(\\\"No 'ready' after AT+RST\\\");else return l}),digitalWrite(x,1),digitalWrite(r,1))­:n(b)}function u(a){(g&=~a)?n(function(){},null):(q.rem­oveAllListeners(),c=void 0,exports.at=void 0,digitalWrite(r,0),e=[])}var x=A13,r=A14,q=Serial2;digitalWrite(r,\\n­0);var y=[\\\"open\\\",\\\"wep\\\",\\\"wpa_psk\­\\",\\\"wpa2_psk\\\",\\\"wpa_wpa2_psk\\\­"],g=0,c,e=[],f=[\\\"\\\",\\\"\\\",\\\"\­\\",\\\"\\\",\\\"\\\"],t={create:functio­n(a,b){if(!c)return-1;if(void 0===a){var d=5;e[d]=\\\"Wait\\\";f[d]=\\\"\\\";c.cm­d(\\\"AT+CIPSERVER=1,\\\"+b+\\\"\\\\r\\\­\n\\\",1E4,function(a){\\\"OK\\\"==a?e[d­]=!0:(e[d]=void 0,setTimeout(function(){throw Error(\\\"CIPSERVER failed (\\\"+(a?a:\\\"Timeout\\\")+\\\")\\\");}­,0))});return 5}for(d=0;void 0!==e[d];)d++;if(5<=d)return-7;e[d]=\\\"­Wait\\\";f[d]=\\\"\\\";c.cmd(\\\"AT+CIPS­TART=\\\"+d+',\\\"TCP\\\",'+JSON.stringi­fy(a)+\\\",\\\"+b+\\\"\\\\r\\\\n\\\",1E4­,function(a){\\\"OK\\\"!=a&&(e[d]=\\n-6)­});return d},close:function(a){\\\"Wait\\\"==e[a]?­e[a]=\\\"WaitClose\\\":void 0!==e[a]&&(0>e[a]?e[a]=void 0:c.cmd((5==a?\\\"AT+CIPSERVER=0\\\":\\\­"AT+CIPCLOSE=\\\"+a)+\\\"\\\\r\\\\n\\\",­1E3,function(b){e[a]=void 0}))},accept:function(a){for(a=0;5>a;a++­)if(\\\"Accept\\\"==e[a])return e[a]=!0,a;return-1},recv:function(a,b){i­f(f[a]){if(f[a].length>b){var d=f[a].substr(0,b);f[a]=f[a].substr(b)}e­lse d=f[a],f[a]=\\\"\\\",\\\"DataClose\\\"==­e[a]&&(e[a]=void 0);return d}return 0>e[a]?e[a]:e[a]?\\\"\\\":-1},send:funct­ion(a,b){if(!c)return-1;if(c.isBusy()||\­\\"Wait\\\"==\\ne[a])return 0;if(0>e[a])return e[a];if(!e[a])return-1;c.cmd(\\\"AT+CIPS­END=\\\"+a+\\\",\\\"+b.length+\\\"\\\\r\­\\\n\\\",1E4,function m(l){if(\\\"OK\\\"==l)return c.register(\\\"> \\\",function(){c.unregister(\\\"> \\\");c.write(b);return\\\"\\\"}),m;if(l­==\\\"Recv \\\"+b.length+\\\" bytes\\\")return m;\\\"SEND OK\\\"==l?(\\\"WaitClose\\\"==e[a]&&t.cl­ose(a),e[a]=!0):(e[a]=void 0,c.unregister(\\\"> \\\"))});e[a]=\\\"Wait\\\";return b.length}};exports.connect=function(a,b,­d){var e=\\\"\\\";d=d||function(){};void 0!==b.password&&(e=b.password);p(1,funct­ion(b){if(b)return d(b);c.cmd(\\\"AT+CWJAP=\\\"+\\nJSON.str­ingify(a)+\\\",\\\"+JSON.stringify(e)+\\­\"\\\\r\\\\n\\\",2E4,function z(a){if(0<=[\\\"WIFI DISCONNECT\\\",\\\"WIFI CONNECTED\\\",\\\"WIFI GOT IP\\\",\\\"+CWJAP:1\\\"].indexOf(a))retu­rn z;\\\"OK\\\"!=a?setTimeout(d,0,\\\"WiFi connect failed: \\\"+(a?a:\\\"Timeout\\\")):setTimeout(d­,0,null)})})};exports.disconnect=functio­n(){u(1)};exports.getIP=function(a){var b={};c.cmd(\\\"AT+CIFSR\\\\r\\\\n\\\",1E­3,function m(c){if(void 0===c)a(\\\"Timeout\\\");else{if(\\\"+CI­FSR:STAIP\\\"==c.substr(0,12))b.ip=c.sli­ce(14,-1);else if(\\\"+CIFSR:STAMAC\\\"==c.substr(0,13)­)b.mac=c.slice(15,-1);else if(\\\"OK\\\"==\\nc){a(null,b);return}re­turn m}})};exports.startAP=function(a,b,d){b=­b||{};if(!b.password||8>b.password.lengt­h)throw Error(\\\"Password must be at least 8 characters\\\");var e=b.password?\\\"3\\\":\\\"0\\\";if(b.au­thMode&&(e={open:0,wpa:2,wpa2:3,wpa_wpa2­:4}[b.authMode],void 0===e))throw Error(\\\"Unknown authMode \\\"+b.authMode);void 0===b.channel&&(b.channel=5);p(2,functio­n(f){if(f)return d(f);c.cmd(\\\"AT+CWSAP=\\\"+JSON.string­ify(a)+\\\",\\\"+JSON.stringify(b.passwo­rd)+\\\",\\\"+b.channel+\\\",\\\"+e+\\\"­\\\\r\\\\n\\\",5E3,function(a){\\\"OK\\\­"!=a?d(\\\"CWSAP failed: \\\"+\\n(a?a:\\\"Timeout\\\")):d(null)})­})};exports.stopAP=function(){u(2)};expo­rts.scan=function(a){var b=[];p(1,function(d){if(d)return a(d);c.cmdReg(\\\"AT+CWLAP\\\\r\\\\n\\\"­,5E3,\\\"+CWLAP:\\\",function(a){a=a.sli­ce(8,-1).split(\\\",\\\");b.push({ssid:J­SON.parse(a[1]),authMode:y[a[0]],rssi:pa­rseInt(a[2]),mac:JSON.parse(a[3]),channe­l:JSON.parse(a[4])})},function(c){a(null­,b)})})};exports.debug=function(){return­{wifiMode:g,socks:e,sockData:f}}\");\n\u­0010Modules.addCached(\"DS18B20\",\"func­tion c(b,a){this.bus=b;void 0===a?this.sCode=this.bus.search()[0]:pa­rseInt(a).toString()==a&&0<=a&&126>=a?th­is.sCode=this.bus.search()[a]:this.sCode­=a;if(!this.sCode)throw Error(\\\"No DS18B20 found\\\");this.type=parseInt(this.sCode­[0]+this.sCode[1])}c.prototype._r=functi­on(){var b=this.bus;b.select(this.sCode);b.write(­190);return b.read(9)};c.prototype._w=function(b,a,c­){var f=this.bus;f.select(this.sCode);f.write(­[78,b,a,c]);f.select(this.sCode);f.write­(72);f.reset()};c.prototype.setRes=\\nfu­nction(b){var a=this._r();b=[31,63,95,127][E.clip(b,9,­12)-9];this._w(a[2],a[3],b)};c.prototype­.getRes=function(){return[31,63,95,127].­indexOf(this._r()[4])+9};c.prototype.isP­resent=function(){return-1!==this.bus.se­arch().indexOf(this.sCode)};c.prototype.­getTemp=function(b){function a(a){for(var c=a._r(),e=0,d=0;8>d;d++)for(var e=e^c[d],g=0;8>g;g++)e=e>>1^140*(e&1);d=­null;e==c[8]&&(d=c[0]+(c[1]<<8),d&32768&­&(d-=65536),d/=10==a.type?2:16);b&&b(d);­return d}this.bus.select(this.sCode);this.bus.w­rite(68,\\n!0);if(!b)return a(this);setTimeout(a,{9:94,10:188,11:375­,12:750}[this.getRes()],this)};c.prototy­pe.searchAlarm=function(){return this.bus.search(236)};c.prototype.setAla­rm=function(b,a){b--;0>b&&(b+=256);0>a&&­(a+=256);var c=this._r();this._w(a,b,c[4])};exports.c­onnect=function(b,a){return new c(b,a)}\");\n\u0010var DEVICE_ID = \"1234\";\n\u0010var WIFI_NAME = \"Aeris\";\n\u0010var WIFI_OPTIONS = {\u001b\n  password : \"interare!domus42\"\u001b\n};\n\u0010va­r KNIT_ADDRESS = '192.168.1.64';\n\u0010var KNIT_PORT = 3000;\n\u0010var ow = new OneWire(A0);\n\u0010var sensor;\n\u0010console.log('Connecting to sensor');\n\u0010try {\u001b\n  sensor = require(\"DS18B20\").connect(ow);\u001b\­n} catch (e) {\u001b\n  console.log('Unable to connect to sensor \\n', e.message); \u001b\n}\n\u0010console.log('Starting Wifi connection');\n\u0010var wifi = require(\"EspruinoWiFi\");\n\u0010wifi.c­onnect(WIFI_NAME, WIFI_OPTIONS, function(err) {\u001b\n  if (err) {\u001b\n    console.log(\"Wifi Connection error: \"+err);\u001b\n    return;\u001b\n  }\u001b\n  console.log(\"Connected!\");\u001b\n  start();\u001b\n});\n\u0010var http;\n\u0010function start() {\u001b\n  http = require('http');\u001b\n  if (sensor) {\u001b\n    getTemp();\u001b\n    //setInterval(getTemp, 60000);\u001b\n  } else {\u001b\n    // TODO: Report failure to somewhere\u001b\n  }\u001b\n}\n\u0010function getTemp() {\u001b\n  sensor.getTemp(function(temp) {\u001b\n    console.log(\"Temp is \"+temp+\"°C\"); \u001b\n    sendTemp(temp);\u001b\n  });\u001b\n}\n\u0010function sendTemp(temp) {\u001b\n\u001b\n  var postData = {\u001b\n   value: {\u001b\n     temperature: temp,\u001b\n     unit: 'celsius'\u001b\n   },\u001b\n  };\u001b\n\u001b\n  var reqPath= '/api/devices/' + DEVICE_ID;\u001b\n\u001b\n  var req = http.request({\u001b\n    host: KNIT_ADDRESS,\u001b\n    port: KNIT_PORT,\u001b\n    path: reqPath,\u001b\n    method: 'POST',\u001b\n    headers: {\u001b\n      'Content-Type': 'application/json'\u001b\n    }\u001b\n  }, function(res) {\u001b\n    console.log(\"STATUS: \" + res.statusCode);\u001b\n    console.log(\"HEADERS: \" + JSON.stringify(res.headers));\u001b\n    res.setEncoding('utf8');\u001b\n    res.on('data', function(data) {\u001b\n      //console.log(\"HTTP> \"+data);\u001b\n    });\u001b\n    res.on('close', function(data) {\u001b\n      console.log(\"Connection closed\");\u001b\n    });\u001b\n  });\u001b\n  req.on('error', function(e) {\u001b\n    console.log(\"ERROR: problem with request: \" + e.message);\u001b\n  });\u001b\n  req.write(postData);\u001b\n  req.end();\u001b\n}\n\n"
    Splitting at "reset();\n", delay 250
    >>> Sent
    Splitting at "\u0003", delay 250
    Splitting at "\u0003", delay 250
    
  • edit: remove dupe post

  • ...this seems to be a recurring issue... I'm sure you found this conversation about Espruino Serial Terminal drops characters., and you find more posts.

    I suspect the issue is that Espruino is already working on some code while the upload is still going on. Therefore I always and strongly suggest not to do anything directly executing, such as .connect() and setInterval() in upload... sometimes even not require(). All the execution stuff goes into the onInit() or a function that is called from within onInit().

    I don't know what board you are on, but sometimes processing resources get scarce.

    Another option to speed-up your upload is to make modules out of pieces of your code and stick them into the modules folder in your sandbox folder - mified... (using google's online Web service, where you paste the module source code and you get back the minified code, which you stick into the same named file with .min.js suffix).

    I hope this helps... I just recently made a similar app where an Espruino-Wifi is the sensor operating application, stepper motor controlling application, the Wifi Access Point, AND the http/s Web server... and it all works just perfect.

  • I'm pretty sure it's exactly as @allObjects says... Keep all your function declarations where they are, but stick the code that does stuff (Wifi connection, OneWire) in a function called onInit and then call that with setTimeout(onInit, 1000) right at the end of your code.

    It's a bit strange I know, but it's probably what you'll have to do when you go to save code to Flash memory, because you'll want certain bits of code (like Wifi connect) to run when power is applied (in onInit) rather than at upload time, which is where they're running at the moment.

  • This might also help to give you some explanation: http://www.espruino.com/Saving

  • Thanks for the thoughtful replies, totally cleared things up. I was just thrown off a bit by the docs. I only had a brief introduction to arduino itself, so I had totally blanked out on the lifecycle event handling on board power on and jumped right into the code.

    That said, I think the espruino docs themselves are a bit light on the reminders to put more than the most bare bones examples into a proper init method and make sure things are loaded. Was there a tech article that I missed that gives some advice there that I missed? If not I'd be game to try and write one out myself, are open source contributions to the docs encouraged?

  • @KevinJ, you are right that in the docs the simple example code doe somewhat solicit a practice that then fails on larger applications. Initially though, I'm sure @Gordon had in mind it would work all the way thru, because last but not least, he went thru all the hoops to save the system's state down to the configuration and active timeouts, intervals, and watches. As said, with small things and simple one-time initializations this works all just fine... Complicating the examples is not the answer, but doing nothing either. May be adding a page with multiple things that need initialization and initializations with dependencies and adding a link in the simple examples to that page would be nice. All Espruino sub projects - including the documentation - is on github... you can clone it, make additions and enhancements and ask for merge requests.

    May be you came across the conversation about simple explanation how to save code that espruino run on start?, where pist #8 and #18 contribaute 2 times 2 cents about code life cycle in Espruino environment.

    Espruino programming concept is quite different from Arduino... even though deep under the hood both work with events, but only Espruino brings it 'easy' (easier?) to understand into the application realm.

    Coming from Browser / JavaScript programming with interfacing with DOM and XHTML Request and Sockets, Espruiono is not much different. It is just not common place to have such a high-level and easy-going language available to deal with micro controller hardware.

  • I think there's a bit at the end of the 'quick start' about onInit and initialisation, but yes - the docs are a bit light on reminders. Especially for the Wifi board, the documentation should really start off using onInit.

    If you find something particular that you think should change, it'd be great to get some ideas. If you want to make some edits, down the bottom of the page there's usually a GitHub link. If you click on that then you can actually go to GitHub, make some edits to the page, and then suggest them as changes (a pull request).

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Espruino Wifi - Dropped characters at runtime

Posted by Avatar for KevinJ @KevinJ

Actions