diff --git a/bin/espruino-cli.js b/bin/espruino-cli.js index 63e2ccc..b52e51f 100755 --- a/bin/espruino-cli.js +++ b/bin/espruino-cli.js @@ -47,6 +47,12 @@ function getHelp() { " (bluetooth is not currently supported).", " Optionally skip N first bytes of the bin file.", "", + " --loglevel 0 : Set loglevel (0-3). Default is 3", + " 0 = Log errors", + " 1 = Log errors and non-debug messages", + " 2 = Log errors, non-debug messages and warnings", + " 3 = Log errors, non-debug messages, warnings and debug messages", + "", "If no file, command, or firmware update is specified, this will act", "as a terminal for communicating directly with Espruino. Press Ctrl-C", "twice to exit.", @@ -167,6 +173,9 @@ for (var i=2;i255) && ch!=9/*Tab*/ && ch!=10/*LF*/ && ch!=13/*CR*/) { - console.warn("Funky character code "+ch+" at position "+i+". Replacing with ?"); + logger.warn("Funky character code "+ch+" at position "+i+". Replacing with ?"); code = code.substr(0,i)+"?"+code.substr(i+1); } } diff --git a/core/config.js b/core/config.js index 5fb71f7..b967533 100644 --- a/core/config.js +++ b/core/config.js @@ -38,17 +38,17 @@ if (typeof chrome !== 'undefined' && chrome.storage) { chrome.storage.sync.get( "CONFIGS", function (data) { var value = data["CONFIGS"]; - console.log("GET chrome.storage.sync = "+JSON.stringify(value)); + logger.debug("GET chrome.storage.sync = "+JSON.stringify(value)); callback(value); }); } else if (typeof window !== 'undefined' && window.localStorage) { var data = {}; var value = window.localStorage.getItem("CONFIG"); - console.log("GET window.localStorage = "+JSON.stringify(value)); + logger.debug("GET window.localStorage = "+JSON.stringify(value)); try { data = JSON.parse(value); } catch (e) { - console.log("Invalid config data"); + logger.error("Invalid config data"); } callback(data); } else if (typeof document != "undefined") { @@ -61,7 +61,7 @@ var json = atob(cookie); data = JSON.parse(json); } catch (e) { - console.log("Got ", e, " while reading info"); + logger.error("Got ", e, " while reading info"); } } callback(data); @@ -72,10 +72,10 @@ function _set(data) { if (typeof chrome !== 'undefined' && chrome.storage) { - console.log("SET chrome.storage.sync = "+JSON.stringify(data,null,2)); + logger.debug("SET chrome.storage.sync = "+JSON.stringify(data,null,2)); chrome.storage.sync.set({ CONFIGS : data }); } else if (typeof window !== 'undefined' && window.localStorage) { - console.log("SET window.localStorage = "+JSON.stringify(data,null,2)); + logger.debug("SET window.localStorage = "+JSON.stringify(data,null,2)); window.localStorage.setItem("CONFIG",JSON.stringify(data)); } else if (typeof document != "undefined") { document.cookie = "CONFIG="+btoa(JSON.stringify(data)); @@ -88,7 +88,7 @@ if (key=="set") continue; Espruino.Config[key] = value[key]; if (Espruino.Core.Config.data[key] !== undefined && - Espruino.Core.Config.data[key].onChange !== undefined) + Espruino.Core.Config.data[key].onChange !== undefined) Espruino.Core.Config.data[key].onChange(value[key]); } if (callback!==undefined) @@ -146,7 +146,7 @@ found = true; if (!found) { - console.warn("Section named "+c.section+" was not added with Config.addSection"); + logger.warn("Section named "+c.section+" was not added with Config.addSection"); sections[c.section] = { name : c.section, sortOrder : 0 diff --git a/core/env.js b/core/env.js index 19dafce..1ff74af 100644 --- a/core/env.js +++ b/core/env.js @@ -57,7 +57,7 @@ try { json = JSON.parse(result); } catch (e) { - console.log("JSON parse failed - " + e + " in " + JSON.stringify(result)); + logger.error("JSON parse failed - " + e + " in " + JSON.stringify(result)); } } if (Object.keys(json).length==0) { diff --git a/core/flasher.js b/core/flasher.js index abaa9a6..56881db 100644 --- a/core/flasher.js +++ b/core/flasher.js @@ -33,18 +33,18 @@ callback("Can't find STM32 bootloader. Make sure the chip is reset into bootloader mode by holding down BTN1 while pressing RST"); }, (timeout==undefined)?10000:timeout); var iPoll = setInterval(function() { - console.log("Sending... 0x7F"); + logger.debug("Sending... 0x7F"); Espruino.Core.Serial.write("\x7f", false); }, 70); dataReceived = function (c) { - console.log("got "+c); + logger.debug("got "+c); if (c==ACK || c==NACK) { clearTimeout(iTimeout); clearInterval(iPoll); setStatus("Initialised."); // wait for random extra data... dataReceived = function(c){ - console.log("Already ACKed but got "+c); + logger.debug("Already ACKed but got "+c); }; setTimeout(function() { dataReceived = undefined; @@ -114,7 +114,7 @@ // Extended erase sendCommand(0x44, function(err) { if (err) { callback(err); return; } - console.log("We may be some time..."); + logger.debug("We may be some time..."); sendData([0xFF,0xFF], function(err) { if (err) { callback(err); return; } callback(undefined); @@ -123,25 +123,25 @@ }; var readData = function(callback, addr, readBytes) { - console.log("Reading "+readBytes+" bytes from 0x"+addr.toString(16)+"..."); + logger.debug("Reading "+readBytes+" bytes from 0x"+addr.toString(16)+"..."); // send read command sendCommand(0x11, function(err) { if (err) { - console.log("Error sending command ("+err+")."); + logger.error("Error sending command ("+err+")."); callback(err); return; } // send address sendData([(addr>>24)&0xFF,(addr>>16)&0xFF,(addr>>8)&0xFF,addr&0xFF], function(err) { if (err) { - console.log("Error sending address. ("+err+")"); + logger.error("Error sending address. ("+err+")"); callback(err); return; } // send amount of bytes we want sendData([readBytes-1], function(err) { if (err) { - console.log("Error while reading. ("+err+")"); + logger.error("Error while reading. ("+err+")"); callback(err); return; } @@ -170,13 +170,13 @@ readData(function(err, data) { if (err) return callback(err); var word = (data[3]<<24) | (data[2]<<16) | (data[1]<<8) | data[0]; - console.log("RCC->CFGR = "+word); + logger.debug("RCC->CFGR = "+word); var newword = (word&0xFFFFF8FF) | 0x00000400; if (newword==word) { - console.log("RCC->CFGR is correct"); + logger.debug("RCC->CFGR is correct"); callback(undefined); } else { - console.log("Setting RCC->CFGR to "+newword); + logger.debug("Setting RCC->CFGR to "+newword); writeData(callback, RCC_CFGR, [newword&0xFF, (newword>>8)&0xFF, (newword>>16)&0xFF, (newword>>24)&0xFF]); } }, RCC_CFGR, 4); @@ -184,11 +184,11 @@ var writeData = function(callback, addr, data) { if (data.length>256) callback("Writing too much data"); - console.log("Writing "+data.length+" bytes at 0x"+addr.toString(16)+"..."); + logger.debug("Writing "+data.length+" bytes at 0x"+addr.toString(16)+"..."); // send write command sendCommand(0x31, function(err) { if (err) { - console.log("Error sending command ("+err+"). retrying..."); + logger.error("Error sending command ("+err+"). retrying..."); initialiseChip(function (err) { if (err) callback(err); else writeData(callback, addr, data); @@ -198,7 +198,7 @@ // send address sendData([(addr>>24)&0xFF,(addr>>16)&0xFF,(addr>>8)&0xFF,addr&0xFF], function(err) { if (err) { - console.log("Error sending address ("+err+"). retrying..."); + logger.error("Error sending address ("+err+"). retrying..."); initialiseChip(function (err) { if (err) callback(err); else writeData(callback, addr, data); @@ -212,7 +212,7 @@ // send data sendData(sData, function(err) { if (err) { - console.log("Error while writing ("+err+"). retrying..."); + logger.error("Error while writing ("+err+"). retrying..."); initialiseChip(function (err) { if (err) callback(err); else writeData(callback, addr, data); @@ -227,7 +227,7 @@ var writeAllData = function(binary, flashOffset, callback) { var chunkSize = 256; - console.log("Writing "+binary.byteLength+" bytes"); + logger.debug("Writing "+binary.byteLength+" bytes"); Espruino.Core.Status.setStatus("Writing flash...", binary.byteLength); var writer = function(offset) { if (offset>=binary.byteLength) { @@ -250,7 +250,7 @@ var readAllData = function(binaryLength, flashOffset, callback) { var data = new Uint8Array(flashOffset); var chunkSize = 256; - console.log("Reading "+binaryLength+" bytes"); + logger.debug("Reading "+binaryLength+" bytes"); Espruino.Core.Status.setStatus("Reading flash...", binaryLength); var reader = function(offset) { if (offset>=binaryLength) { @@ -302,7 +302,7 @@ for (var i=0;i1) { var a = l.shift(); - console.log(">>>",a); + logger.debug(">>>",a); try { if (packetHandler) packetHandler(Espruino.Core.Utils.parseJSONish(a)); - } catch(e) { console.log("Unable to decode"); } + } catch(e) { logger.error("Unable to decode"); } } uartLine = l[0]; }); @@ -74,11 +74,11 @@ then(() => cmdFlash(options)). then(() => unsetupEspruino(options)). then(function() { - console.log("Complete!"); + logger.debug("Complete!"); finish(); if (options.cbDone) options.cbDone(); }).catch(function(error) { - console.log("Error!", error); + logger.log("Error!", error); finish(); if (options.cbDone) options.cbDone(error); }); @@ -117,7 +117,7 @@ function setupEspruino(options) { return new Promise((resolve,reject)=>{ Espruino.Core.Serial.write('\x03\x10reset()\n', false, function() { setTimeout(function() { - console.log("Start Wifi, add handler"); + logger.debug("Start Wifi, add handler"); Espruino.Core.Serial.write(`\x10${options.serialDevice}.setup(115200, { rx: ${options.serialRx}, tx : ${options.serialTx} }); \x10var packetHandler, packetData="", OUT=eval(process.env.CONSOLE); \x10${options.serialDevice}.on('data', function(d) { @@ -144,7 +144,7 @@ function setupEspruino(options) { \x10${options.chBoot?`digitalWrite(${options.chBoot}, 0);`:`` /* into of boot mode */} \x10${options.chPD?`digitalWrite(${options.chPD}, 1);`:`` /* turn on wifi */} `, false, function() { - console.log("Handler added"); + logger.debug("Handler added"); resolve(); }); }, 1000); @@ -164,7 +164,7 @@ function unsetupEspruino(options) { } function cmdSync(options) { - console.log("Syncing..."); + logger.debug("Syncing..."); return new Promise((resolve,reject)=>{ var success = false; var interval; @@ -175,7 +175,7 @@ function cmdSync(options) { interval = undefined; } packetHandler = undefined; - console.log("Sync complete!"); + logger.debug("Sync complete!"); setTimeout(function() { // allow time for other responses resolve(); @@ -202,7 +202,7 @@ function cmdSync(options) { function cmdFlash(options) { var binary = new Uint8Array(options.binary); var blockCount = Math.floor((binary.length + (BLOCK_SIZE-1)) / BLOCK_SIZE); - console.log(`Start Flashing, ${blockCount} blocks of ${BLOCK_SIZE} bytes`); + logger.debug(`Start Flashing, ${blockCount} blocks of ${BLOCK_SIZE} bytes`); var d = new Uint32Array([ blockCount*BLOCK_SIZE, // erase size blockCount, // # packets @@ -211,7 +211,7 @@ function cmdFlash(options) { ]); var idx = 0; return sendCmd(options, 2 /* FLASH_BEGIN */, new Uint8Array(d.buffer)).then(function flash() { - console.log("Block "+idx); + logger.debug("Block "+idx); if (options.cbStatus) options.cbStatus(`Writing Block ${idx} / ${blockCount}`, idx / blockCount); if (idx>=blockCount) return true; d = new Uint8Array(16 + BLOCK_SIZE); diff --git a/core/modules.js b/core/modules.js index c7c38fb..9c5ab5b 100644 --- a/core/modules.js +++ b/core/modules.js @@ -123,7 +123,7 @@ var fullModuleName = data.moduleName; // try and load the module the old way... - console.log("loadModule("+fullModuleName+")"); + logger.debug("loadModule("+fullModuleName+")"); var urls = []; // Array of where to look for this module var modName; // Simple name of the module @@ -167,16 +167,16 @@ function moduleLoaded(resolve, requires, modName, data, loadedModuleData, alreadyMinified){ // Check for any modules used from this module that we don't already have var newRequires = getModulesRequired(data); - console.log(" - "+modName+" requires "+JSON.stringify(newRequires)); + logger.debug(" - "+modName+" requires "+JSON.stringify(newRequires)); // if we need new modules, set them to load and get their promises var newPromises = []; for (var i in newRequires) { if (requires.indexOf(newRequires[i])<0) { - console.log(" Queueing "+newRequires[i]); + logger.debug(" Queueing "+newRequires[i]); requires.push(newRequires[i]); newPromises.push(loadModule(requires, newRequires[i], loadedModuleData)); } else { - console.log(" Already loading "+newRequires[i]); + logger.debug(" Already loading "+newRequires[i]); } } diff --git a/core/serial.js b/core/serial.js index 310a4a4..eff572b 100644 --- a/core/serial.js +++ b/core/serial.js @@ -78,7 +78,7 @@ To add a new serial device, you must add an object to var devices = Espruino.Core.Serial.devices; for (var i=0;i0) { - console.log("Port "+JSON.stringify(serialPort)+" not found - checking ports again ("+attempts+" attempts left)"); + logger.warn("Port "+JSON.stringify(serialPort)+" not found - checking ports again ("+attempts+" attempts left)"); setTimeout(function() { getPorts(function() { openSerialInternal(serialPort, connectCallback, disconnectCallback, attempts-1); @@ -169,7 +169,7 @@ To add a new serial device, you must add an object to }, 500); return; } else { - console.error("Port "+JSON.stringify(serialPort)+" not found"); + logger.error("Port "+JSON.stringify(serialPort)+" not found"); return connectCallback(undefined); } } @@ -186,13 +186,13 @@ To add a new serial device, you must add an object to currentDevice.open(serialPort, function(cInfo) { // CONNECT if (!cInfo) { // Espruino.Core.Notifications.error("Unable to connect"); - console.error("Unable to open device (connectionInfo="+cInfo+")"); + logger.error("Unable to open device (connectionInfo="+cInfo+")"); connectCallback(undefined); connectCallback = undefined; } else { connectionInfo = cInfo; connectedPort = serialPort; - console.log("Connected", cInfo); + logger.debug("Connected", cInfo); if (connectionInfo.portName) portInfo.portName = connectionInfo.portName; Espruino.callProcessor("connected", portInfo, function() { @@ -201,12 +201,12 @@ To add a new serial device, you must add an object to }); } }, function(data) { // RECEIEVE DATA - if (!(data instanceof ArrayBuffer)) console.warn("Serial port implementation is not returning ArrayBuffers"); + if (!(data instanceof ArrayBuffer)) logger.warn("Serial port implementation is not returning ArrayBuffers"); if (Espruino.Config.SERIAL_FLOW_CONTROL) { var u = new Uint8Array(data); for (var i=0;i resume upload"); + logger.debug("XON received => resume upload"); flowControlXOFF = false; if (flowControlTimeout) { clearTimeout(flowControlTimeout); @@ -214,12 +214,12 @@ To add a new serial device, you must add an object to } } if (u[i]==19) { // XOFF - console.log("XOFF received => pause upload"); + logger.debug("XOFF received => pause upload"); flowControlXOFF = true; if (flowControlTimeout) clearTimeout(flowControlTimeout); flowControlTimeout = setTimeout(function() { - console.log("XOFF timeout => resume upload anyway"); + logger.debug("XOFF timeout => resume upload anyway"); flowControlXOFF = false; flowControlTimeout = undefined; }, FLOW_CONTROL_RESUME_TIMEOUT); @@ -260,7 +260,7 @@ To add a new serial device, you must add an object to for (var i=0; i=256) { - console.warn("Attempted to send non-8 bit character - code "+ch); + logger.warn("Attempted to send non-8 bit character - code "+ch); ch = "?".charCodeAt(0); } bufView[i] = ch; @@ -273,7 +273,7 @@ To add a new serial device, you must add an object to currentDevice.close(); currentDevice = undefined; } else - console.error("Close called, but serial port not open"); + logger.error("Close called, but serial port not open"); }; var isConnected = function() { @@ -327,7 +327,7 @@ To add a new serial device, you must add an object to writeData[0].showStatus &= writeData[0].data.length>writeData[0].blockSize; if (writeData[0].showStatus) { Espruino.Core.Status.setStatus("Sending...", writeData[0].data.length); - console.log("---> "+JSON.stringify(writeData[0].data)); + logger.debug("---> "+JSON.stringify(writeData[0].data)); } } @@ -362,7 +362,7 @@ To add a new serial device, you must add an object to if (split.match) writeData[0].nextSplit = split; split = { start:0, end:writeData[0].blockSize, delay:0 }; } - if (split.match) console.log("Splitting for "+split.reason+", delay "+split.delay); + if (split.match) logger.debug("Splitting for "+split.reason+", delay "+split.delay); // Only send some of the data if (writeData[0].data.length>split.end) { if (slowWrite && split.delay==0) split.delay=50; @@ -424,10 +424,10 @@ To add a new serial device, you must add an object to "isSlowWrite": function() { return slowWrite; }, "setSlowWrite": function(isOn, force) { if ((!force) && Espruino.Config.SERIAL_THROTTLE_SEND) { - console.log("ForceThrottle option is set - set Slow Write = true"); + logger.debug("ForceThrottle option is set - set Slow Write = true"); isOn = true; } else - console.log("Set Slow Write = "+isOn); + logger.debug("Set Slow Write = "+isOn); slowWrite = isOn; }, "setBinary": function(isOn) { diff --git a/core/serial_chrome_serial.js b/core/serial_chrome_serial.js index 8950626..dfce371 100644 --- a/core/serial_chrome_serial.js +++ b/core/serial_chrome_serial.js @@ -20,12 +20,12 @@ Author: Gordon Williams (gw@pur3.co.uk) (function() { if (typeof chrome === 'undefined' || chrome.serial===undefined) { - console.log("No chrome.serial - Chrome Serial disabled"); + logger.debug("No chrome.serial - Chrome Serial disabled"); return; } if (chrome.serial.getDevices===undefined) { // wrong chrome version - console.log("Chrome does NOT have post-M33 serial API"); + logger.debug("Chrome does NOT have post-M33 serial API"); return; } @@ -61,12 +61,12 @@ Author: Gordon Williams (gw@pur3.co.uk) chrome.serial.connect(serialPort, {bitrate: parseInt(Espruino.Config.BAUD_RATE)}, function(cInfo) { if (!cInfo) { - console.log("Unable to open device (connectionInfo="+cInfo+")"); + logger.error("Unable to open device (connectionInfo="+cInfo+")"); openCallback(undefined); } else { connectionInfo = cInfo; connectedPort = serialPort; - console.log(cInfo); + logger.debug(cInfo); openCallback(cInfo); } }); @@ -91,7 +91,7 @@ Author: Gordon Williams (gw@pur3.co.uk) }); chrome.serial.onReceiveError.addListener(function(errorInfo) { - console.error("RECEIVE ERROR:", JSON.stringify(errorInfo)); + logger.error("RECEIVE ERROR:", JSON.stringify(errorInfo)); closeSerial(); }); diff --git a/core/serial_chrome_socket.js b/core/serial_chrome_socket.js index 7c458a6..427629d 100644 --- a/core/serial_chrome_socket.js +++ b/core/serial_chrome_socket.js @@ -18,7 +18,7 @@ Author: Patrick Van Oosterwijck (patrick@silicognition.com) (function() { if (typeof chrome === 'undefined' || chrome.sockets===undefined) { - console.log("No chrome.sockets - Chrome Socket disabled"); + logger.debug("No chrome.sockets - Chrome Socket disabled"); return; } @@ -52,7 +52,7 @@ Author: Patrick Van Oosterwijck (patrick@silicognition.com) var openSerial=function(serialPort, openCallback, receiveCallback, disconnectCallback) { if (serialPort.substr(0,8)!='TCP/IP: ') { - console.error("Invalid connection "+JSON.stringify(serialPort)); + logger.error("Invalid connection "+JSON.stringify(serialPort)); return; } var host = serialPort.substr(8); @@ -70,7 +70,7 @@ Author: Patrick Van Oosterwijck (patrick@silicognition.com) chrome.sockets.tcp.connect(createInfo.socketId, host, port, function (result) { if (result < 0) { - console.log("Failed to open socket " + host+":"+port); + logger.error("Failed to open socket " + host+":"+port); openCallback(undefined); } else { connectionInfo = { socketId: createInfo.socketId }; @@ -106,7 +106,7 @@ Author: Patrick Van Oosterwijck (patrick@silicognition.com) chrome.sockets.tcp.onReceiveError.addListener(function(info) { if (info.socketId != connectionInfo.socketId) return; - console.error("RECEIVE ERROR:", JSON.stringify(info)); + logger.error("RECEIVE ERROR:", JSON.stringify(info)); connectionDisconnectCallback(); }); diff --git a/core/serial_frame.js b/core/serial_frame.js index 92fb605..9c4d007 100644 --- a/core/serial_frame.js +++ b/core/serial_frame.js @@ -9,12 +9,12 @@ Use embed.js on the client side to link this in. (function() { if (typeof navigator == "undefined" || typeof window == "undefined") { - console.log("serial_frame: Not running in a browser"); + logger.debug("serial_frame: Not running in a browser"); return; } if (typeof window.parent == undefined || window.parent === window) { - console.log("serial_frame: Not running inside an iframe"); + logger.debug("serial_frame: Not running inside an iframe"); return; } @@ -50,10 +50,10 @@ Use embed.js on the client side to link this in. } break; case "connect": if (Espruino.Core.Serial.isConnected()) - console.error("serial_frame: already connected"); + logger.debug("serial_frame: already connected"); Espruino.Core.MenuPortSelector.connectToPort(event.data, function() { - console.log("serial_frame: connected"); + logger.debug("serial_frame: connected"); }); break; case "connected": if (callbacks.connected) { @@ -70,7 +70,7 @@ Use embed.js on the client side to link this in. } break; case "receive": if (callbacks.receive) { if (typeof event.data!="string") - console.error("serial_frame: receive event expecting data string"); + logger.warn("serial_frame: receive event expecting data string"); callbacks.receive(Espruino.Core.Utils.stringToArrayBuffer(event.data)); } break; case "setMaxWriteLength": { @@ -78,7 +78,7 @@ Use embed.js on the client side to link this in. device.maxWriteLength = parseInt(event.data); } break; default: - console.error("Unknown event type ",event.type); + logger.error("Unknown event type ",event.type); break; } }); @@ -105,11 +105,11 @@ Use embed.js on the client side to link this in. callbacks.ports = undefined; callback([], false/*instantPorts*/); ERROR = "getPorts timeout, disabling"; - console.error("serial_frame: "+ERROR); + logger.error("serial_frame: "+ERROR); },100); callbacks.ports = function(d) { if (!timeout) { - console.error("serial_frame: ports received after timeout"); + logger.error("serial_frame: ports received after timeout"); return; } clearTimeout(timeout); diff --git a/core/serial_noble.js b/core/serial_noble.js index 7618a6b..48662c7 100644 --- a/core/serial_noble.js +++ b/core/serial_noble.js @@ -50,7 +50,7 @@ function nobleExceptionHandler(err) { if (err.toString().includes("ENODEV")) { process.removeListener('uncaughtException', nobleExceptionHandler); - console.log("Noble: "+err.toString()+" - disabling."); + logger.error("Noble: "+err.toString()+" - disabling."); errored = true; } else throw err; } @@ -64,7 +64,7 @@ noble = require('@abandonware/noble'); } } catch (e) { - console.log("Noble: module couldn't be loaded, no node.js Bluetooth Low Energy\n", e); + logger.error("Noble: module couldn't be loaded, no node.js Bluetooth Low Energy\n", e); // super nasty workaround for https://github.com/sandeepmistry/noble/issues/502 process.removeAllListeners('exit'); errored = true; @@ -73,12 +73,12 @@ noble.on('stateChange', function(state) { process.removeListener('uncaughtException', nobleExceptionHandler); - console.log("Noble: stateChange -> "+state); + logger.debug("Noble: stateChange -> "+state); if (state=="poweredOn") { if (Espruino.Config.WEB_BLUETOOTH) { // Everything has already initialised, so we must disable // web bluetooth this way instead - console.log("Noble: Disable Web Bluetooth as we have Noble instead"); + logger.debug("Noble: Disable Web Bluetooth as we have Noble instead"); Espruino.Config.WEB_BLUETOOTH = false; } initialised = true; @@ -103,16 +103,16 @@ dev.advertisement.serviceUuids.indexOf(NORDIC_SERVICE)>=0; if (hasUartService || Espruino.Core.Utils.isRecognisedBluetoothDevice(name)) { - console.log("Noble: Found UART device:", name, dev.address); + logger.debug("Noble: Found UART device:", name, dev.address); newDevices.push({ path: dev.address, description: name, type: "bluetooth", rssi: dev.rssi }); btDevices[dev.address] = dev; - } else console.log("Noble: Found device:", name, dev.address); + } else logger.debug("Noble: Found device:", name, dev.address); }); // if we didn't initialise for whatever reason, keep going anyway setTimeout(function() { if (initialised) return; - console.log("Noble: Didn't initialise in 10 seconds, disabling."); + logger.error("Noble: Didn't initialise in 10 seconds, disabling."); errored = true; }, 10000); return true; @@ -123,24 +123,24 @@ clearTimeout(scanStopTimeout); scanStopTimeout = undefined; } else { - console.log("Noble: Starting scan"); + logger.debug("Noble: Starting scan"); lastDevices = []; newDevices = []; noble.startScanning([], true); } scanStopTimeout = setTimeout(function () { scanStopTimeout = undefined; - console.log("Noble: Stopping scan"); + logger.debug("Noble: Stopping scan"); noble.stopScanning(); }, 3000); } var getPorts = function (callback) { if (errored || !Espruino.Config.BLUETOOTH_LOW_ENERGY) { - console.log("Noble: getPorts - disabled"); + logger.error("Noble: getPorts - disabled"); callback([], true/*instantPorts*/); } else if (!initialised) { - console.log("Noble: getPorts - initialising..."); + logger.debug("Noble: getPorts - initialising..."); if (!noble) if (!startNoble()) return callback([], true/*instantPorts*/); @@ -175,13 +175,13 @@ if (scanStopTimeout) { clearTimeout(scanStopTimeout); scanStopTimeout = undefined; - console.log("Noble: Stopping scan (openSerial)"); + logger.debug("Noble: Stopping scan (openSerial)"); noble.stopScanning(); } txInProgress = false; - console.log("BT> Connecting"); + logger.debug("BT> Connecting"); btDevice.on('disconnect', function() { txCharacteristic = undefined; rxCharacteristic = undefined; @@ -192,21 +192,21 @@ btDevice.connect(function (error) { if (error) { - console.log("BT> ERROR Connecting"); + logger.error("BT> ERROR Connecting"); btDevice = undefined; return openCallback(); } - console.log("BT> Connected"); + logger.debug("BT> Connected"); btDevice.discoverAllServicesAndCharacteristics(function(error, services, characteristics) { var btUARTService = findByUUID(services, NORDIC_SERVICE); txCharacteristic = findByUUID(characteristics, NORDIC_TX); rxCharacteristic = findByUUID(characteristics, NORDIC_RX); if (error || !btUARTService || !txCharacteristic || !rxCharacteristic) { - console.log("BT> ERROR getting services/characteristics"); - console.log("Service "+btUARTService); - console.log("TX "+txCharacteristic); - console.log("RX "+rxCharacteristic); + logger.error("BT> ERROR getting services/characteristics"); + logger.error("Service "+btUARTService); + logger.error("TX "+txCharacteristic); + logger.error("RX "+rxCharacteristic); btDevice.disconnect(); txCharacteristic = undefined; rxCharacteristic = undefined; @@ -235,15 +235,15 @@ if (txCharacteristic === undefined) return; if (data.length>NORDIC_TX_MAX_LENGTH) { - console.error("BT> TX length >"+NORDIC_TX_MAX_LENGTH); + logger.error("BT> TX length >"+NORDIC_TX_MAX_LENGTH); return callback(); } if (txInProgress) { - console.error("BT> already sending!"); + logger.error("BT> already sending!"); return callback(); } - console.log("BT> send "+JSON.stringify(data)); + logger.debug("BT> send "+JSON.stringify(data)); txInProgress = true; try { txCharacteristic.write(Espruino.Core.Utils.stringToBuffer(data), false, function() { @@ -251,7 +251,7 @@ return callback(); }); } catch (e) { - console.log("BT> SEND ERROR " + e); + logger.error("BT> SEND ERROR " + e); closeSerial(); } }; diff --git a/core/serial_node_serial.js b/core/serial_node_serial.js index 1b994f5..da7cca1 100644 --- a/core/serial_node_serial.js +++ b/core/serial_node_serial.js @@ -4,7 +4,7 @@ Gordon Williams (gw@pur3.co.uk) (function() { // Are we on nw.js with chrome.serial? No need for serialport then! if (typeof chrome !== 'undefined' && chrome.serial) { - console.log("We have chrome.serial - not using 'serialport' module"); + logger.debug("We have chrome.serial - not using 'serialport' module"); return; } if (typeof require === 'undefined') return; @@ -12,13 +12,13 @@ Gordon Williams (gw@pur3.co.uk) try { require.resolve('serialport'); } catch (e) { - console.log("No 'serialport' module found"); + logger.error("No 'serialport' module found"); return; } try { serialport = require('serialport').SerialPort; } catch (e) { - console.log("Error initialising 'serialport':" + e.toString()); + logger.error("Error initialising 'serialport':" + e.toString()); return; } @@ -63,7 +63,7 @@ Gordon Williams (gw@pur3.co.uk) }), true/*instantPorts*/ ); }).catch(function(err) { - console.log("serialport error: "+err.toString()); + logger.error("serialport error: "+err.toString()); return callback([], true/*instantPorts*/); }); }; diff --git a/core/serial_node_socket.js b/core/serial_node_socket.js index 11d347b..315290f 100644 --- a/core/serial_node_socket.js +++ b/core/serial_node_socket.js @@ -25,7 +25,7 @@ Author: Alfie Kirkpatrick (jugglingcats@akirkpatrick.com) try { net = require("net"); } catch (e) { - console.log("Require net failed - Node Socket disabled"); + logger.error("Require net failed - Node Socket disabled"); return; } @@ -43,7 +43,7 @@ Author: Alfie Kirkpatrick (jugglingcats@akirkpatrick.com) var openSerial = function (serialPort, openCallback, receiveCallback, disconnectCallback) { if (serialPort.substr(0, 6) != 'tcp://') { - console.error("Invalid connection " + JSON.stringify(serialPort)); + logger.error("Invalid connection " + JSON.stringify(serialPort)); return; } var host = serialPort.substr(6); @@ -67,7 +67,7 @@ Author: Alfie Kirkpatrick (jugglingcats@akirkpatrick.com) } }); socket.on("error", function (info) { - console.error("RECEIVE ERROR:", JSON.stringify(info)); + logger.error("RECEIVE ERROR:", JSON.stringify(info)); // node will close the connection }); socket.on("end", function () { diff --git a/core/serial_web_audio.js b/core/serial_web_audio.js index f2695b6..64f3a3e 100644 --- a/core/serial_web_audio.js +++ b/core/serial_web_audio.js @@ -81,10 +81,10 @@ inputNode = context.createScriptProcessor(4096, 1/*in*/, 1/*out*/); window.dontGarbageCollectMePlease = inputNode; inputNode.onaudioprocess = audioProcessor; - console.log("serial_audio: Audio Sample rate : "+context.sampleRate); + logger.debug("serial_audio: Audio Sample rate : "+context.sampleRate); bitTime = context.sampleRate / BAUD; // intentionally a float - console.log("serial_audio: Audio Serial Baud", BAUD, "Bit time", bitTime); + logger.debug("serial_audio: Audio Serial Baud", BAUD, "Bit time", bitTime); } navigator.getUserMedia({ @@ -101,7 +101,7 @@ connected = true; openCallback("Hello"); }, function(e) { - console.log('serial_audio: getUserMedia error', e); + logger.error('serial_audio: getUserMedia error', e); openCallback(undefined); }); }; diff --git a/core/serial_web_bluetooth.js b/core/serial_web_bluetooth.js index 64aee9f..cb66ce4 100644 --- a/core/serial_web_bluetooth.js +++ b/core/serial_web_bluetooth.js @@ -78,7 +78,7 @@ }); // If we're ok and have the getDevices extension, use it to remember previously paired devices if (getStatus(true)===true && navigator.bluetooth.getDevices) { - console.log("BT> bluetooth.getDevices exists - grab known devices"); + logger.debug("BT> bluetooth.getDevices exists - grab known devices"); navigator.bluetooth.getDevices().then(devices=>{ pairedDevices = devices; }); @@ -118,7 +118,7 @@ // Check for pre-paired devices btDevice = pairedDevices.find(dev=>dev.name == serialPort); if (btDevice) { - console.log("BT> Pre-paired Web Bluetooth device already found"); + logger.debug("BT> Pre-paired Web Bluetooth device already found"); promise = Promise.resolve(btDevice); } else { var filters = []; @@ -126,7 +126,7 @@ filters.push({ namePrefix: namePrefix }); }); filters.push({ services: [ NORDIC_SERVICE ] }); - console.log("BT> Starting device chooser"); + logger.debug("BT> Starting device chooser"); promise = navigator.bluetooth.requestDevice({ filters: filters, optionalServices: [ NORDIC_SERVICE ]}); @@ -134,35 +134,35 @@ promise.then(function(device) { btDevice = device; Espruino.Core.Status.setStatus("Connecting to "+btDevice.name); - console.log('BT> Device Name: ' + btDevice.name); - console.log('BT> Device ID: ' + btDevice.id); + logger.debug('BT> Device Name: ' + btDevice.name); + logger.debug('BT> Device ID: ' + btDevice.id); // Was deprecated: Should use getPrimaryServices for this in future //console.log('BT> Device UUIDs: ' + device.uuids.join('\n' + ' '.repeat(21))); btDevice.addEventListener('gattserverdisconnected', function() { - console.log("BT> Disconnected (gattserverdisconnected)"); + logger.debug("BT> Disconnected (gattserverdisconnected)"); closeSerial(); }, {once:true}); return btDevice.gatt.connect(); }).then(function(server) { Espruino.Core.Status.setStatus("Connected to BLE"); - console.log("BT> Connected"); + logger.debug("BT> Connected"); btServer = server; return server.getPrimaryService(NORDIC_SERVICE); }).then(function(service) { Espruino.Core.Status.setStatus("Configuring BLE..."); - console.log("BT> Got service"); + logger.debug("BT> Got service"); btService = service; return btService.getCharacteristic(NORDIC_RX); }).then(function (characteristic) { Espruino.Core.Status.setStatus("Configuring BLE...."); rxCharacteristic = characteristic; setMaxPacketLength(NORDIC_DEFAULT_TX_LENGTH); // set default packet length - console.log("BT> RX characteristic:"+JSON.stringify(rxCharacteristic)); + logger.debug("BT> RX characteristic:"+JSON.stringify(rxCharacteristic)); rxCharacteristic.addEventListener('characteristicvaluechanged', function(event) { // In Chrome 50+, a DataView is returned instead of an ArrayBuffer. var value = event.target.value.buffer; if (value.byteLength > maxPacketLength) { - console.log("BT> Received packet of length "+value.byteLength+" - assuming increased MTU"); + logger.debug("BT> Received packet of length "+value.byteLength+" - assuming increased MTU"); setMaxPacketLength(value.byteLength); } //console.log("BT> RX:"+JSON.stringify(Espruino.Core.Utils.arrayBufferToString(value))); @@ -175,7 +175,7 @@ }).then(function (characteristic) { Espruino.Core.Status.setStatus("Configuring BLE....."); txCharacteristic = characteristic; - console.log("BT> TX characteristic:"+JSON.stringify(txCharacteristic)); + logger.debug("BT> TX characteristic:"+JSON.stringify(txCharacteristic)); }).then(function() { Espruino.Core.Status.setStatus("Configuring BLE....."); txInProgress = false; @@ -187,7 +187,7 @@ openCallback({ portName : btDevice.name }); }, 500); }).catch(function(error) { - console.log('BT> ERROR: ' + error); + logger.error('BT> ERROR: ' + error); closeSerial({error:error.toString()}); }); } @@ -211,11 +211,11 @@ if (!txCharacteristic) return; if (data.length>maxPacketLength) { - console.error("BT> TX length >"+maxPacketLength); + logger.error("BT> TX length >"+maxPacketLength); return callback(); } if (txInProgress) { - console.error("BT> already sending!"); + logger.error("BT> already sending!"); return callback(); } @@ -224,7 +224,7 @@ txInProgress = false; callback(); }).catch(function(error) { - console.log('BT> SEND ERROR: ' + error); + logger.error('BT> SEND ERROR: ' + error); closeSerial(); }); } diff --git a/core/serial_web_serial.js b/core/serial_web_serial.js index 6cb7100..369ba70 100644 --- a/core/serial_web_serial.js +++ b/core/serial_web_serial.js @@ -48,12 +48,12 @@ }); // If we're ok and have the getDevices extension, use it to remember previously paired devices if (getStatus(true)===true && navigator.serial.getPorts) { - console.log("Serial> serial.getPorts exists - grab known devices"); + logger.debug("Serial> serial.getPorts exists - grab known devices"); navigator.serial.getPorts().then(devices=>{ pairedDevices = devices; }, err=>{ getPortsErrorMessage = err.toString(); - console.log("Serial> "+err.toString()); + logger.error("Serial> "+err.toString()); }); } } @@ -91,10 +91,10 @@ // Check for pre-paired devices serialPort = pairedDevices.find(dev=>getSerialDeviceInfo(dev).path == path); if (serialPort) { - console.log("Serial> Pre-paired Web Serial device already found"); + logger.debug("Serial> Pre-paired Web Serial device already found"); promise = Promise.resolve(serialPort); } else { - console.log("Serial> Starting device chooser"); + logger.debug("Serial> Starting device chooser"); promise = navigator.serial.requestPort({}); } promise.then(function(port) { @@ -124,7 +124,7 @@ openCallback({ portName : getSerialDeviceInfo(serialPort).path }); }).catch(function(error) { - console.log('Serial> ERROR: ' + error); + logger.error('Serial> ERROR: ' + error); disconnectCallback(); }); } @@ -148,7 +148,7 @@ writer.write(Espruino.Core.Utils.stringToArrayBuffer(data)).then(function() { callback(); }).catch(function(error) { - console.log('Serial> SEND ERROR: ' + error); + logger.error('Serial> SEND ERROR: ' + error); closeSerial(); }); writer.releaseLock(); diff --git a/core/serial_websocket_local.js b/core/serial_websocket_local.js index 7c5f188..fadc0ea 100644 --- a/core/serial_websocket_local.js +++ b/core/serial_websocket_local.js @@ -4,7 +4,7 @@ Gordon Williams (gw@pur3.co.uk) (function() { if (typeof window == "undefined" || typeof WebSocket == undefined) return; - console.log("WebSocket localhost support (EspruinoHost) enabled - running in web browser"); + logger.debug("WebSocket localhost support (EspruinoHost) enabled - running in web browser"); var WS_ENABLED = true; var ws; @@ -19,7 +19,7 @@ Gordon Williams (gw@pur3.co.uk) function ensureConnection(callback) { if (wsConnecting) { - console.log("Waiting for Websocket connection - queueing"); + logger.debug("Waiting for Websocket connection - queueing"); wsConnectCallbacks.push(callback); return; } @@ -48,7 +48,7 @@ Gordon Williams (gw@pur3.co.uk) } function wsMessage(event) { - console.log("Got "+event.data); + logger.debug("Got "+event.data); try { var j = JSON.parse(event.data); if (j.type=="list") { @@ -81,19 +81,19 @@ Gordon Williams (gw@pur3.co.uk) } } else if (j.type=="write") { dataWrittenCallbacks.forEach(function(cb) { - console.log("Calling data written cb"); + logger.debug("Calling data written cb"); cb(); }); dataWrittenCallbacks = []; } } catch (e) { - console.log("Error processing JSON response: "+event.data); + logger.error("Error processing JSON response: "+event.data); } } function wsClosed(event) { ws = undefined; - console.log("WebSocket closed"); + logger.debug("WebSocket closed"); disconnectCallback(); disconnectCallback = undefined; } @@ -103,7 +103,7 @@ Gordon Williams (gw@pur3.co.uk) ensureConnection(function(err) { if (err) { WS_ENABLED = false; - console.log("Couldn't connect to "+Espruino.Config.WEBSOCKET_URL+" - disabling websockets for this session"); + logger.error("Couldn't connect to "+Espruino.Config.WEBSOCKET_URL+" - disabling websockets for this session"); return callback([], false/*instantPorts*/); } else { listCallbacks.push(callback); @@ -115,7 +115,7 @@ Gordon Williams (gw@pur3.co.uk) var openSerial=function(serialPort, _connectCallback, _receiveCallback, _disconnectCallback) { var device = listOfDevices.find(dev=>dev.path==serialPort); if (!device) { - console.err("Tried to connect to "+serialPort+" but it didn't exist!"); + logger.err("Tried to connect to "+serialPort+" but it didn't exist!"); return openCallback(); // open failed } @@ -145,7 +145,7 @@ Gordon Williams (gw@pur3.co.uk) var writeSerial = function(data, callback) { if (!ws) return callback(); dataWrittenCallbacks.push(callback); - console.log(JSON.stringify({"type":"write", data:data})); + logger.debug(JSON.stringify({"type":"write", data:data})); ws.send(JSON.stringify({"type":"write", data:data})); }; diff --git a/core/serial_websocket_relay.js b/core/serial_websocket_relay.js index f984995..28f7554 100644 --- a/core/serial_websocket_relay.js +++ b/core/serial_websocket_relay.js @@ -10,10 +10,10 @@ Used for Relay service on espruino.com/ide as well as `npm espruino-web-ide`'s if (/*window.location.origin=="https://www.espruino.com" || */ window.location.origin=="https://espruino.github.io") { - console.log("Running from github - WebSocket support disabled"); + logger.debug("Running from github - WebSocket support disabled"); return; } - console.log("WebSocket relay support enabled - running in web browser"); + logger.debug("WebSocket relay support enabled - running in web browser"); var WS_ENABLED = true; var ws; @@ -26,7 +26,7 @@ Used for Relay service on espruino.com/ide as well as `npm espruino-web-ide`'s if (!WS_ENABLED) return callback([], true/*instantPorts*/); Espruino.Core.Utils.getJSONURL("/serial/ports", function(ports) { if (ports===undefined) { - console.log("/serial/ports doesn't exist - disabling WebSocket support"); + logger.error("/serial/ports doesn't exist - disabling WebSocket support"); WS_ENABLED = false; callback([]); return; diff --git a/core/serial_winnus.js b/core/serial_winnus.js index 8427d38..758aaa5 100644 --- a/core/serial_winnus.js +++ b/core/serial_winnus.js @@ -2,17 +2,17 @@ if (typeof require === 'undefined') return; var isWindows = /^win/.test(process.platform); if (!isWindows) { - console.log("Not on Windows, Winnus not needed"); + logger.debug("Not on Windows, Winnus not needed"); return; } var winnus = undefined; try { winnus = require('winnus'); } catch (e) { - console.log("'winnus' module not found, no Windows Bluetooth Low Energy", e); + logger.debug("'winnus' module not found, no Windows Bluetooth Low Energy", e); return; } - console.log("Disable Web Bluetooth as we have Winnus instead"); + logger.debug("Disable Web Bluetooth as we have Winnus instead"); Espruino.Core.Serial.NO_WEB_BLUETOOTH = true; var txDataQueue = undefined; @@ -30,7 +30,7 @@ devices.push({ description : dev.name, path: dev.address, type : "bluetooth" }); }); } catch (e) { - console.log(e); + logger.error(e); } callback(devices, false/*instantPorts*/); }; @@ -64,7 +64,7 @@ try { winnus.disconnect(); } catch (e) { - console.log("WINNUS ERROR:"+e.toString()); + logger.error("WINNUS ERROR:"+e.toString()); } if (onDisconnect) { onDisconnect(); @@ -94,7 +94,7 @@ txDataQueue = txDataQueue.substr(CHUNKSIZE); } txInProgress = true; - console.log("BT> Sending " + JSON.stringify(chunk)); + logger.debug("BT> Sending " + JSON.stringify(chunk)); try { winnus.write(chunk); setTimeout(function() { @@ -103,7 +103,7 @@ writeChunk(); }, 20); } catch (e) { - console.log("BT> ERROR " + e); + logger.error("BT> ERROR " + e); txDataQueue = undefined; } } diff --git a/core/terminal.js b/core/terminal.js index faed51c..09814f8 100644 --- a/core/terminal.js +++ b/core/terminal.js @@ -53,7 +53,7 @@ var terminal = document.getElementById("terminal"); var terminalfocus = document.getElementById("terminalfocus"); if (terminal === null) { - console.log("Terminal: terminal element not found, aborting."); + logger.error("Terminal: terminal element not found, aborting."); delete Espruino.Core.Terminal; return; } @@ -523,7 +523,7 @@ if (termControlChars[2]==63) { if (termControlChars[3]==55) { if (ch!=108) - console.log("Expected 27, 91, 63, 55, 108 - no line overflow sequence"); + logger.warn("Expected 27, 91, 63, 55, 108 - no line overflow sequence"); termControlChars = []; } else { if (ch==55) { @@ -697,7 +697,7 @@ updateTerminal(); if (options.buttonclick) { var btn = elements[line].find("button"); - if (!btn.length) console.error("Espruino.Core.Terminal buttonclick set but no button"); + if (!btn.length) logger.error("Espruino.Core.Terminal buttonclick set but no button"); btn.on('click', options.buttonclick); } } diff --git a/core/utils.js b/core/utils.js index cbfbd1a..561bfee 100644 --- a/core/utils.js +++ b/core/utils.js @@ -236,7 +236,7 @@ function getEspruinoPrompt(callback) { if (Espruino.Core.Terminal!==undefined && Espruino.Core.Terminal.getTerminalLine()==">") { - console.log("Found a prompt... great!"); + logger.debug("Found a prompt... great!"); return callback(); } @@ -248,13 +248,13 @@ } if (receivedData[receivedData.length-1] == ">") { if (receivedData.substr(-6)=="debug>") { - console.log("Got debug> - sending Ctrl-C to break out and we'll be good"); + logger.debug("Got debug> - sending Ctrl-C to break out and we'll be good"); Espruino.Core.Serial.write('\x03'); } else { if (receivedData == "\r\n=undefined\r\n>") receivedData=""; // this was just what we expected - so ignore it - console.log("Received a prompt after sending newline... good!"); + logger.debug("Received a prompt after sending newline... good!"); clearTimeout(timeout); nextStep(); } @@ -263,13 +263,13 @@ // timeout in case something goes wrong... var hadToBreak = false; var timeout = setTimeout(function() { - console.log("Got "+JSON.stringify(receivedData)); + logger.error("Got "+JSON.stringify(receivedData)); // if we haven't had the prompt displayed for us, Ctrl-C to break out of what we had - console.log("No Prompt found, got "+JSON.stringify(receivedData[receivedData.length-1])+" - issuing Ctrl-C to try and break out"); + logger.error("No Prompt found, got "+JSON.stringify(receivedData[receivedData.length-1])+" - issuing Ctrl-C to try and break out"); Espruino.Core.Serial.write('\x03'); hadToBreak = true; timeout = setTimeout(function() { - console.log("Still no prompt - issuing another Ctrl-C"); + logger.error("Still no prompt - issuing another Ctrl-C"); Espruino.Core.Serial.write('\x03'); nextStep(); },500); @@ -324,7 +324,7 @@ if(startProcess >= 0 && endProcess > 0){ // All good - get the data! var result = receivedData.substring(startProcess + 4,endProcess); - console.log("Got "+JSON.stringify(receivedData)); + logger.debug("Got "+JSON.stringify(receivedData)); // strip out the text we found receivedData = receivedData.substr(0,startProcess) + receivedData.substr(endProcess+4); // Now stop time timeout @@ -375,7 +375,7 @@ // No data yet... // OR we keep getting data for > options.maxTimeout seconds clearInterval(timeout); - console.warn("No result found for "+JSON.stringify(expressionToExecute)+" - just got "+JSON.stringify(receivedData)); + logger.warn("No result found for "+JSON.stringify(expressionToExecute)+" - just got "+JSON.stringify(receivedData)); nextStep(undefined); } }, pollInterval); @@ -388,7 +388,7 @@ getProcessInfo(expressionToExecute, callback); }); } else { - console.error("executeExpression called when not connected!"); + logger.error("executeExpression called when not connected!"); callback(undefined); } }; @@ -447,12 +447,12 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} if (xhr.status === 200) { callback(xhr.response.toString()); } else { - console.error("getURL("+JSON.stringify(url)+") error : HTTP "+xhr.status); + logger.error("getURL("+JSON.stringify(url)+") error : HTTP "+xhr.status); callback(undefined); } }); xhr.addEventListener("error", function (e) { - console.error("getURL("+JSON.stringify(url)+") error "+e); + logger.error("getURL("+JSON.stringify(url)+") error "+e); callback(undefined); }); xhr.open("GET", url, true); @@ -470,7 +470,7 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} require(m).get(http_options, function(res) { if (res.statusCode != 200) { - console.log("Espruino.Core.Utils.getURL: got HTTP status code "+res.statusCode+" for "+url); + logger.debug("Espruino.Core.Utils.getURL: got HTTP status code "+res.statusCode+" for "+url); return callback(undefined); } var data = ""; @@ -479,13 +479,13 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} callback(data); }); }).on('error', function(err) { - console.error("getURL("+JSON.stringify(url)+") error : "+err); + logger.error("getURL("+JSON.stringify(url)+") error : "+err); callback(undefined); }); } else { require("fs").readFile(resultUrl, function(err, d) { if (err) { - console.error(err); + logger.error(err); callback(undefined); } else callback(d.toString()); @@ -498,7 +498,7 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} /// Gets a URL as a Binary file, returning callback(err, ArrayBuffer) var getBinaryURL = function(url, callback) { - console.log("Downloading "+url); + logger.debug("Downloading "+url); Espruino.Core.Status.setStatus("Downloading binary..."); var xhr = new XMLHttpRequest(); xhr.responseType = "arraybuffer"; @@ -522,7 +522,7 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} getURL(url, function(d) { if (!d) return callback(d); var j; - try { j=JSON.parse(d); } catch (e) { console.error("Unable to parse JSON",d); } + try { j=JSON.parse(d); } catch (e) { logger.error("Unable to parse JSON",d); } callback(j); }); } @@ -629,14 +629,14 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} // when truncation has finished, write writer.onwriteend = function(e) { writer.onwriteend = function(e) { - console.log('FileWriter: complete'); + logger.debug('FileWriter: complete'); if (callback) callback(writableFileEntry.name); }; - console.log('FileWriter: writing'); + logger.debug('FileWriter: writing'); writer.write(fileBlob); }; // truncate - console.log('FileWriter: truncating'); + logger.debug('FileWriter: truncating'); writer.truncate(fileBlob.size); }, errorHandler); }); @@ -702,7 +702,7 @@ while (d!==undefined) {console.log(btoa(d));d=f.read(${CHUNKSIZE});} for (var i=0; i=256) { - console.warn("stringToArrayBuffer got non-8 bit character - code "+ch); + logger.warn("stringToArrayBuffer got non-8 bit character - code "+ch); ch = "?".charCodeAt(0); } buf[i] = ch; diff --git a/espruino.js b/espruino.js index 31dc195..178287c 100644 --- a/espruino.js +++ b/espruino.js @@ -45,12 +45,12 @@ var Espruino; Espruino.Core.Config.loadConfiguration(function() { // Initialise all modules function initModule(modName, mod) { - console.log("Initialising "+modName); + logger.debug("Initialising "+modName); if (mod.init !== undefined) { try { mod.init(); } catch (e) { - console.warn("Module initialisation failed for "+modName, e); + logger.warn("Module initialisation failed for "+modName, e); } } } diff --git a/index.js b/index.js index b3096bd..d3b2207 100644 --- a/index.js +++ b/index.js @@ -2,10 +2,17 @@ require('es6-shim'); /* Entrypoint for node module. Not used for Web IDE */ var fs = require("fs"); +var espruinoInitialised = false; +var logger; +var defaultOptions = { + logLevel: 3 +}; +var storedOptions = Object.assign({}, defaultOptions); + /* load all files in EspruinoTools... we do this so we can still use these files normally in the Web IDE */ function loadJS(filePath) { - console.log("Found "+filePath); + logger.debug("Found "+filePath); var contents = fs.readFileSync(filePath, {encoding:"utf8"}); var realExports = exports; exports = undefined; @@ -46,11 +53,60 @@ var jqShim = { }; // --------------- -var espruinoInitialised = false; +function createLogger(logLevel) { + var getFunc = function getFunc(type, method) { + var shouldLog = function() { + if (!logLevel && logLevel !== 0) { + logLevel = defaultOptions.logLevel; + } + if (logLevel >= 0 && type === 'error') return true; + if (logLevel >= 1 && type === 'log') return true; + if (logLevel >= 2 && type === 'warn') return true; + if (logLevel >= 3 && type === 'debug') return true; + return false; + }; + return function () { + if (shouldLog()) { + console[method || type].apply(console, arguments); + } + }; + }; + return { + error: getFunc('error'), + log: getFunc('log'), + warn: getFunc('warn'), + debug: getFunc('debug', 'log') + }; +}; + +function handleInitArguments(arg1, arg2) { + var callback; + var opts; + if (typeof arg1 === 'function') { + callback = arg1; + } else if (typeof arg2 === 'function') { + callback = arg2; + } + if (typeof arg1 === 'object') { + opts = arg1; + } else if (espruinoInitialised) { + opts = storedOptions; + } + storedOptions = Object.assign({}, defaultOptions, storedOptions, opts); + return { + callback: callback, + options: storedOptions + }; +}; + +function init(options, callback) { + var handled = handleInitArguments(options, callback); + options = handled.options; + callback = handled.callback; + logger = logger || createLogger(options.logLevel); -function init(callback) { if (espruinoInitialised) { - console.log("Already initialised."); + logger.debug("Already initialised."); return callback(); } espruinoInitialised = true; @@ -69,7 +125,7 @@ function init(callback) { global.acorn = require("acorn"); acorn.walk = require("acorn/util/walk"); // FIXME - Package subpath './util/walk' is not defined by "exports" in latest } catch(e) { - console.log("Acorn library not found - you'll need it for compiled code"); + logger.warn("Acorn library not found - you'll need it for compiled code"); } // Load each JS file... @@ -85,13 +141,13 @@ function init(callback) { // Bodge up notifications Espruino.Core.Notifications = { - success : function(e) { console.log(e); }, - error : function(e) { console.error(e); }, - warning : function(e) { console.warn(e); }, - info : function(e) { console.log(e); }, + success : function(e) { logger.debug(e); }, + error : function(e) { logger.error(e); }, + warning : function(e) { logger.warn(e); }, + info : function(e) { logger.debug(e); }, }; Espruino.Core.Status = { - setStatus : function(e,len) { console.log(e); }, + setStatus : function(e,len) { logger.debug(e); }, hasProgress : function() { return false; }, incrementProgress : function(amt) {} }; @@ -125,7 +181,7 @@ function sendCode(port, code, callback) { }); Espruino.Core.Serial.open(port, function(status) { if (status === undefined) { - console.error("Unable to connect!"); + logger.error("Unable to connect!"); return callback(); } Espruino.callProcessor("transformForEspruino", code, function(code) { @@ -149,7 +205,7 @@ exports.expr = function(port, expr, callback) { Espruino.Core.Serial.startListening(function(data) { }); Espruino.Core.Serial.open(port, function(status) { if (status === undefined) { - console.error("Unable to connect!"); + logger.error("Unable to connect!"); return callback(); } Espruino.Core.Utils.executeExpression(expr, function(result) { @@ -171,7 +227,7 @@ exports.statement = function(port, expr, callback) { Espruino.Core.Serial.startListening(function(data) { }); Espruino.Core.Serial.open(port, function(status) { if (status === undefined) { - console.error("Unable to connect!"); + logger.error("Unable to connect!"); return callback(); } Espruino.Core.Utils.executeStatement(expr, function(result) { @@ -199,13 +255,13 @@ exports.flash = function(port, filename, flashOffset, callback) { Espruino.Core.Serial.startListening(function(data) { }); Espruino.Core.Serial.open(port, function(status) { if (status === undefined) { - console.error("Unable to connect!"); + logger.error("Unable to connect!"); return callback(); } var bin = fs.readFileSync(filename, {encoding:"binary"}); Espruino.Core.Flasher.flashBinaryToDevice(bin, flashOffset, function(err) { - console.log(err ? "Error!" : "Success!"); - setTimeout(function() { + logger[err ? 'error' : 'log'](err ? "Error!" : "Success!"); + setTimeout(function () { Espruino.Core.Serial.close(); }, 500); }); diff --git a/libs/esprima/esmangle.js b/libs/esprima/esmangle.js index 6283f4b..bf05006 100644 --- a/libs/esprima/esmangle.js +++ b/libs/esprima/esmangle.js @@ -6980,7 +6980,7 @@ exports.deprecate = function(fn, msg) { } else if (process.traceDeprecation) { console.trace(msg); } else { - console.error(msg); + logger.error(msg); } warned = true; } @@ -7002,7 +7002,7 @@ exports.debuglog = function(set) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); + logger.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; @@ -7446,9 +7446,9 @@ function timestamp() { } -// log is just a thin wrapper to console.log that prepends a timestamp +// log is just a thin wrapper to logger.debug that prepends a timestamp exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); + logger.debug('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; diff --git a/plugins/assembler.js b/plugins/assembler.js index e97040a..ab5033e 100644 --- a/plugins/assembler.js +++ b/plugins/assembler.js @@ -362,7 +362,7 @@ }); // process assembly to grab labels var labels = assemble_internal(asmLines, function() {}, undefined); - console.log("Assembler Labels:",labels); + logger.debug("Assembler Labels:",labels); // process again to actually get an output assemble_internal(asmLines, wordCallback, labels); } @@ -390,7 +390,7 @@ try { assemble(asmLines, function(word) { machineCode.push("0x"+word.toString(16)); }); } catch (err) { - console.log("Assembler failed: "+err+description); + logger.error("Assembler failed: "+err+description); Espruino.Core.Notifications.error("Assembler failed: "+err+description); return undefined; } diff --git a/plugins/boardJSON.js b/plugins/boardJSON.js index c0f3d5c..20c16b0 100644 --- a/plugins/boardJSON.js +++ b/plugins/boardJSON.js @@ -32,9 +32,9 @@ } function loadJSON(env, jsonPath, callback) { - console.log("Loading "+jsonPath); + logger.debug("Loading "+jsonPath); Espruino.Core.Utils.getJSONURL(jsonPath, function(data){ - console.log("Board JSON loaded"); + logger.debug("Board JSON loaded"); for (var key in data) env[key] = data[key]; Espruino.callProcessor("boardJSONLoaded", env, callback); diff --git a/plugins/compiler.js b/plugins/compiler.js index 47e0052..5118481 100644 --- a/plugins/compiler.js +++ b/plugins/compiler.js @@ -147,7 +147,7 @@ }); } catch (err) { - console.log(err); + logger.error(err); Espruino.Core.Notifications.error("Error parsing JavaScript"+description+", but uploading anyway.
"+err.toString()); } if (tasks==0) diff --git a/plugins/getGitHub.js b/plugins/getGitHub.js index d9f3e85..9bd414f 100644 --- a/plugins/getGitHub.js +++ b/plugins/getGitHub.js @@ -27,7 +27,7 @@ }; var url = "https://raw.githubusercontent.com/"+git.owner+"/"+git.repo+"/"+git.branch+"/"+git.path; - console.log("Found GitHub", JSON.stringify(git)); + logger.debug("Found GitHub", JSON.stringify(git)); callback({url: url}); } else callback(data); // no match - continue as normal diff --git a/plugins/localModules.js b/plugins/localModules.js index c406fc5..77ae1c6 100644 --- a/plugins/localModules.js +++ b/plugins/localModules.js @@ -40,14 +40,14 @@ * */ function loadJSFile(x) { - console.log("Loading local module "+ x +" for " + data.moduleName); + logger.debug("Loading local module "+ x +" for " + data.moduleName); data.moduleCode = fs.readFileSync(x).toString(); return true; } function loadJSONFile(x) { - console.log("Loading local module "+ x +" for " + data.moduleName); - console.log('module.exports=' + JSON.stringify(JSON.parse(fs.readFileSync(x).toString())) + ';'); + logger.debug("Loading local module "+ x +" for " + data.moduleName); + logger.debug('module.exports=' + JSON.stringify(JSON.parse(fs.readFileSync(x).toString())) + ';'); data.moduleCode = 'module.exports=' + JSON.stringify(JSON.parse(fs.readFileSync(x).toString())) + ';'; return true; } diff --git a/plugins/minify.js b/plugins/minify.js index 5f70308..8ed28ef 100644 --- a/plugins/minify.js +++ b/plugins/minify.js @@ -74,7 +74,7 @@ if ((typeof esprima == "undefined") || (typeof esmangle == "undefined") || (typeof escodegen == "undefined")) { - console.warn("esprima/esmangle/escodegen not defined - not minifying") + logger.warn("esprima/esmangle/escodegen not defined - not minifying") return callback(code); } @@ -106,7 +106,7 @@ callback(code); } catch (e) { Espruino.Core.Notifications.error(e.toString()+description); - console.error(e.stack); + logger.error(e.stack); callback(code); } finally { } } @@ -131,7 +131,7 @@ for (var i in minifyCache) { var item = minifyCache[i]; if (item.code==code && item.level==minificationLevel) { - console.log("Found code in minification cache - using that"+description); + logger.debug("Found code in minification cache - using that"+description); // move to front of cache minifyCache.splice(i,1); // remove old minifyCache.push(item); // add at front diff --git a/plugins/pretokenise.js b/plugins/pretokenise.js index 8a7903b..5da8df3 100644 --- a/plugins/pretokenise.js +++ b/plugins/pretokenise.js @@ -12,7 +12,7 @@ "use strict"; (function(){ if (typeof acorn == "undefined") { - console.log("pretokenise: needs acorn, disabling."); + logger.debug("pretokenise: needs acorn, disabling."); return; } diff --git a/plugins/saveOnSend.js b/plugins/saveOnSend.js index 9cb6baf..364e33d 100644 --- a/plugins/saveOnSend.js +++ b/plugins/saveOnSend.js @@ -71,7 +71,7 @@ } // - console.log("Uploading "+code.length+" bytes to flash"); + logger.debug("Uploading "+code.length+" bytes to flash"); if (!hasStorage) { // old style if (isStorageUpload) { Espruino.Core.Notifications.error("You have pre-1v96 firmware - unable to upload to Storage"); diff --git a/plugins/unicode.js b/plugins/unicode.js index 67d1a1b..4012712 100644 --- a/plugins/unicode.js +++ b/plugins/unicode.js @@ -17,14 +17,14 @@ var utf8lib; if ("undefined"==typeof utf8) { if ("undefined"!=typeof require) { - console.log("Loading UTF8 with require"); + logger.debug("Loading UTF8 with require"); utf8lib = require('utf8'); } else { - console.log("WARNING: Loading placeholder UTF8"); + logger.warn("WARNING: Loading placeholder UTF8"); utf8lib = { encode : function(c){return c} }; } } else { - console.log("UTF8 Library loaded successfully"); + logger.debug("UTF8 Library loaded successfully"); utf8lib = utf8; } diff --git a/plugins/versionChecker.js b/plugins/versionChecker.js index 09bebd8..dd59c0a 100644 --- a/plugins/versionChecker.js +++ b/plugins/versionChecker.js @@ -58,7 +58,7 @@ if (vCurrent > 1.43 && (env.CONSOLE=="USB"||env.CONSOLE=="Bluetooth"||env.CONSOLE=="Telnet")) { - console.log("Firmware >1.43 supports faster writes over USB"); + logger.debug("Firmware >1.43 supports faster writes over USB"); Espruino.Core.Serial.setSlowWrite(false); } else { Espruino.Core.Serial.setSlowWrite(true); @@ -69,14 +69,14 @@ var tAvailable = env.info.binary_version; var vAvailable = Espruino.Core.Utils.versionToFloat(tAvailable); - console.log("FIRMWARE: Current "+tCurrent+", Available "+tAvailable); + logger.debug("FIRMWARE: Current "+tCurrent+", Available "+tAvailable); if (vAvailable > vCurrent && (env.BOARD=="ESPRUINOBOARD" || env.BOARD.substr(0,4)=="PICO" || env.BOARD=="ESPRUINOWIFI" || env.BOARD=="PUCKJS")) { - console.log("New Firmware "+tAvailable+" available"); + logger.debug("New Firmware "+tAvailable+" available"); Espruino.Core.Notifications.info("New Firmware available ("+vCurrent+" installed, "+tAvailable+" available)"); if (Espruino.Core.App) Espruino.Core.App.addAlertIcon({