Esempio n. 1
0
/*JSON{
  "type"     : "method",
  "class"    : "Pin",
  "name"     : "getInfo",
  "ifndef"   : "SAVE_ON_FLASH",
  "generate" : "jswrap_pin_getInfo",
  "return"   : ["JsVar","An object containing information about this pins"]
}
Get information about this pin and its capabilities. Of the form:

```
{
  "port"      : "A", // the Pin's port on the chip
  "num"       : 12, // the Pin's number
  "in_addr"   : 0x..., // (if available) the address of the pin's input address in bit-banded memory (can be used with peek)
  "out_addr"  : 0x..., // (if available) the address of the pin's output address in bit-banded memory (can be used with poke)
  "analog"    : { ADCs : [1], channel : 12 }, // If analog input is available
  "functions" : {
    "TIM1":{type:"CH1, af:0},
    "I2C3":{type:"SCL", af:1}
  }
}
```
Will return undefined if pin is not valid.
*/
JsVar *jswrap_pin_getInfo(
    JsVar *parent //!< The class instance representing the pin.
  ) {
  Pin pin = jshGetPinFromVar(parent);
  if (!jshIsPinValid(pin)) return 0;
  const JshPinInfo *inf = &pinInfo[pin];
  JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
  if (!obj) return 0;

  char buf[2];
  buf[0] = (char)('A'+(inf->port-JSH_PORTA));
  buf[1] = 0;
  jsvObjectSetChildAndUnLock(obj, "port", jsvNewFromString(buf));
  jsvObjectSetChildAndUnLock(obj, "num", jsvNewFromInteger(inf->pin-JSH_PIN0));
#ifdef STM32
  volatile uint32_t *addr;
  addr = jshGetPinAddress(pin, JSGPAF_INPUT);
  if (addr) jsvObjectSetChildAndUnLock(obj, "in_addr", jsvNewFromInteger((JsVarInt)addr));
  addr = jshGetPinAddress(pin, JSGPAF_OUTPUT);
  if (addr) jsvObjectSetChildAndUnLock(obj, "out_addr", jsvNewFromInteger((JsVarInt)addr));
#endif
  // ADC
  if (inf->analog) {
    JsVar *an = jsvNewWithFlags(JSV_OBJECT);
    if (an) {
      JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
      if (arr) {
        int i;
        for (i=0;i<ADC_COUNT;i++)
          if (inf->analog&(JSH_ANALOG1<<i))
            jsvArrayPushAndUnLock(arr, jsvNewFromInteger(1+i));
        jsvObjectSetChildAndUnLock(an, "ADCs", arr);
      }
      jsvObjectSetChildAndUnLock(obj, "channel", jsvNewFromInteger(inf->analog & JSH_MASK_ANALOG_CH));
    }
  }
  JsVar *funcs = jsvNewWithFlags(JSV_OBJECT);
  if (funcs) {
    int i;
    for (i=0;i<JSH_PININFO_FUNCTIONS;i++) {
      if (inf->functions[i]) {
        JsVar *func = jsvNewWithFlags(JSV_OBJECT);
        if (func) {
          char buf[16];
          jshPinFunctionToString(inf->functions[i], JSPFTS_TYPE, buf, sizeof(buf));
          jsvObjectSetChildAndUnLock(func, "type", jsvNewFromString(buf));
          jsvObjectSetChildAndUnLock(func, "af", jsvNewFromInteger(inf->functions[i] & JSH_MASK_AF));

          jshPinFunctionToString(inf->functions[i], JSPFTS_DEVICE|JSPFTS_DEVICE_NUMBER, buf, sizeof(buf));
          jsvObjectSetChildAndUnLock(funcs, buf, func);
        }
      }
    }
    jsvObjectSetChildAndUnLock(obj, "functions", funcs);
  }

  return obj;
}
Esempio n. 2
0
/*JSON{
  "type" : "staticmethod",
  "ifndef" : "SAVE_ON_FLASH",
  "class" : "E",
  "name" : "getErrorFlags",
  "generate" : "jswrap_espruino_getErrorFlags",
  "return" : ["JsVar","An array of error flags"]
}
Get and reset the error flags. Returns an array that can contain:

`'FIFO_FULL'`: The receive FIFO filled up and data was lost. This could be state transitions for setWatch, or received characters.

`'BUFFER_FULL'`: A buffer for a stream filled up and characters were lost. This can happen to any stream - Serial,HTTP,etc.

`'CALLBACK'`: A callback (s`etWatch`, `setInterval`, `on('data',...)`) caused an error and so was removed.

`'LOW_MEMORY'`: Memory is running low - Espruino had to run a garbage collection pass or remove some of the command history

`'MEMORY'`: Espruino ran out of memory and was unable to allocate some data that it needed.
*/
JsVar *jswrap_espruino_getErrorFlags() {
  JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  if (!arr) return 0;
  if (jsErrorFlags&JSERR_RX_FIFO_FULL) jsvArrayPushAndUnLock(arr, jsvNewFromString("FIFO_FULL"));
  if (jsErrorFlags&JSERR_BUFFER_FULL) jsvArrayPushAndUnLock(arr, jsvNewFromString("BUFFER_FULL"));
  if (jsErrorFlags&JSERR_CALLBACK) jsvArrayPushAndUnLock(arr, jsvNewFromString("CALLBACK"));
  if (jsErrorFlags&JSERR_LOW_MEMORY) jsvArrayPushAndUnLock(arr, jsvNewFromString("LOW_MEMORY"));
  if (jsErrorFlags&JSERR_MEMORY) jsvArrayPushAndUnLock(arr, jsvNewFromString("MEMORY"));
  jsErrorFlags = JSERR_NONE;
  return arr;
}
Esempio n. 3
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "getStationConfig",
  "generate" : "jswrap_ESP8266WiFi_getStationConfig",
  "return"   : ["JsVar","A Station Config"],
  "return_object" : "StationConfig"
}*/
JsVar *jswrap_ESP8266WiFi_getStationConfig() {
  struct station_config config;
  wifi_station_get_config(&config);
  JsVar *jsConfig = jspNewObject(NULL, "StationConfig");
  //char ssid[33];
  //nullTerminateString(ssid, (char *)config.ssid, 32);
  jsvUnLock(jsvObjectSetChild(jsConfig, "ssid", jsvNewFromString((char *)config.ssid)));
  //char password[65];
  //nullTerminateString(password, (char *)config.password, 64);
  jsvUnLock(jsvObjectSetChild(jsConfig, "password", jsvNewFromString((char *)config.password)));
  return jsConfig;
}
Esempio n. 4
0
/*JSON{
  "type" : "staticproperty",
  "class" : "process",
  "name" : "env",
  "generate" : "jswrap_process_env",
  "return" : ["JsVar","An object"]
}
Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION
 */
JsVar *jswrap_process_env() {
  JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
  jsvObjectSetChildAndUnLock(obj, "VERSION", jsvNewFromString(JS_VERSION));
  jsvObjectSetChildAndUnLock(obj, "BUILD_DATE", jsvNewFromString(__DATE__));
  jsvObjectSetChildAndUnLock(obj, "BUILD_TIME", jsvNewFromString(__TIME__));
#ifdef GIT_COMMIT
  jsvObjectSetChildAndUnLock(obj, "GIT_COMMIT", jsvNewFromString(STRINGIFY(GIT_COMMIT)));
#endif
  jsvObjectSetChildAndUnLock(obj, "BOARD", jsvNewFromString(PC_BOARD_ID));
  jsvObjectSetChildAndUnLock(obj, "CHIP", jsvNewFromString(PC_BOARD_CHIP));
  jsvObjectSetChildAndUnLock(obj, "CHIP_FAMILY", jsvNewFromString(PC_BOARD_CHIP_FAMILY));
  jsvObjectSetChildAndUnLock(obj, "FLASH", jsvNewFromInteger(FLASH_TOTAL));
  jsvObjectSetChildAndUnLock(obj, "RAM", jsvNewFromInteger(RAM_TOTAL));
  jsvObjectSetChildAndUnLock(obj, "SERIAL", jswrap_interface_getSerial());
  jsvObjectSetChildAndUnLock(obj, "CONSOLE", jsvNewFromString(jshGetDeviceString(jsiGetConsoleDevice())));
  JsVar *arr = jsvNewWithFlags(JSV_OBJECT);
  if (arr) {
    const char *s = exportNames;
    void **p = (void**)exportPtrs;
    while (*s) {
      jsvObjectSetChildAndUnLock(arr, s, jsvNewFromInteger((JsVarInt)(size_t)*p));
      p++;
      while (*s) s++; // skip until 0
      s++; // skip over 0
    }
    jsvObjectSetChildAndUnLock(obj, "EXPORTS", arr);
  }  

  return obj;
}
Esempio n. 5
0
/*JSON{
  "type" : "method",
  "class" : "Number",
  "name" : "toFixed",
  "generate" : "jswrap_number_toFixed",
  "params" : [
    ["decimalPlaces","int32","A number between 0 and 20 specifying the number of decimal digits after the decimal point"]
  ],
  "return" : ["JsVar","A string"]
}
Format the number as a fixed point number
 */
JsVar *jswrap_number_toFixed(JsVar *parent, int decimals) {
  if (decimals<0) decimals=0;
  if (decimals>20) decimals=20;
  char buf[JS_NUMBER_BUFFER_SIZE];
  ftoa_bounded_extra(jsvGetFloat(parent), buf, sizeof(buf), 10, decimals);
  return jsvNewFromString(buf);
}
Esempio n. 6
0
// For internal use - like jswrap_object_removeAllListeners but takes a C string
void jswrap_object_removeAllListeners_cstr(JsVar *parent, const char *event) {
  JsVar *s = jsvNewFromString(event);
  if (s) {
    jswrap_object_removeAllListeners(parent, s);
    jsvUnLock(s);
  }
}
Esempio n. 7
0
/** A convenience function for adding event listeners */
void jswrap_object_addEventListener(JsVar *parent, const char *eventName, void (*callback)(), JsnArgumentType argTypes) {
  JsVar *n = jsvNewFromString(eventName);
  JsVar *cb = jsvNewNativeFunction(callback, argTypes);
  jswrap_object_on(parent, n, cb);
  jsvUnLock(cb);
  jsvUnLock(n);
}
Esempio n. 8
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "getDHCPHostname",
  "generate" : "jswrap_ESP8266WiFi_getDHCPHostname",
  "return"   : ["JsVar", "The current DHCP hostname."]
}
 * Get the current DHCP hostname.
*/
JsVar *jswrap_ESP8266WiFi_getDHCPHostname() {
  char *hostname = wifi_station_get_hostname();
  if (hostname == NULL) {
    hostname = "";
  }
  return jsvNewFromString(hostname);
}
Esempio n. 9
0
/*JSON{ "type":"function", "name" : "require",
         "description" : "Load the given module, and return the exported functions",
         "generate" : "jswrap_require",
         "params" : [ [ "moduleName", "JsVar", "A String containing the name of the given module"] ],
         "return" : ["JsVar", "The result of evaluating the string"]
}*/
JsVar *jswrap_require(JsVar *moduleName) {
  if (!jsvIsString(moduleName)) {
    jsWarn("Expecting a module name as a string, but got %t", moduleName);
    return 0;
  }
  // Search to see if we have already loaded this module

  JsVar *moduleList = jswrap_modules_getModuleList();
  if (!moduleList) return 0; // out of memory
  JsVar *moduleExportName = jsvFindChildFromVar(moduleList, moduleName, true);
  jsvUnLock(moduleList);
  if (!moduleExportName) return 0; // out of memory
  JsVar *moduleExport = jsvSkipName(moduleExportName);
  if (moduleExport) {
    // Found the module!
    jsvUnLock(moduleExportName);
    return moduleExport;
  }

  // Now check if it is built-in
  char moduleNameBuf[32];
  jsvGetString(moduleName, moduleNameBuf, sizeof(moduleNameBuf));
  if (jswIsBuiltInLibrary(moduleNameBuf)) {
    // create a 'fake' module that Espruino can use to map its built-in functions against
    moduleExport = jspNewBuiltin(moduleNameBuf);
  } else {
    // Now try and load it
    JsVar *fileContents = 0;
    //if (jsvIsStringEqual(moduleName,"http")) {}
    //if (jsvIsStringEqual(moduleName,"fs")) {}
  #ifdef USE_FILESYSTEM
    JsVar *modulePath = jsvNewFromString(
  #ifdef LINUX
        "node_modules/"
  #else
        "NODE_M~1/"
  #endif
        );
    if (!modulePath) { jsvUnLock(moduleExportName); return 0; } // out of memory
    jsvAppendStringVarComplete(modulePath, moduleName);
    jsvAppendString(modulePath,".js");
    fileContents = wrap_fat_readFile(modulePath);
    jsvUnLock(modulePath);
  #endif
    if (!fileContents || jsvIsStringEqual(fileContents,"")) {
      jsvUnLock(moduleExportName);
      jsvUnLock(fileContents);
      jsWarn("Module not found");
      return 0;
    }
    moduleExport = jspEvaluateModule(jsiGetParser(), fileContents);
    jsvUnLock(fileContents);
  }

  assert(moduleExport);
  jsvSetValueOfName(moduleExportName, moduleExport); // save in cache
  jsvUnLock(moduleExportName);
  return moduleExport;
}
Esempio n. 10
0
static void cc3000_state_change(const char *data) {
  JsVar *wlanObj = jsvObjectGetChild(jsiGetParser()->root, CC3000_OBJ_NAME, 0);
  JsVar *dataVar = jsvNewFromString(data);
  if (wlanObj)
    jsiQueueObjectCallbacks(wlanObj, CC3000_ON_STATE_CHANGE, dataVar, 0);
  jsvUnLock(dataVar);
  jsvUnLock(wlanObj);
Esempio n. 11
0
void httpClientRequestWrite(JsVar *httpClientReqVar, JsVar *data) {
  // Append data to sendData
  JsVar *sendData = jsvObjectGetChild(httpClientReqVar, HTTP_NAME_SEND_DATA, false);
  if (!sendData) {
    JsVar *options = jsvObjectGetChild(httpClientReqVar, HTTP_NAME_OPTIONS_VAR, false);
    if (options) {
      sendData = jsvNewFromString("");
      JsVar *method = jsvObjectGetChild(options, "method", false);
      JsVar *path = jsvObjectGetChild(options, "path", false);
      jsvAppendPrintf(sendData, "%v %v HTTP/1.0\r\nUser-Agent: Espruino "JS_VERSION"\r\nConnection: close\r\n", method, path);
      jsvUnLock(method);
      jsvUnLock(path);
      JsVar *headers = jsvObjectGetChild(options, "headers", false);
      bool hasHostHeader = false;
      if (jsvIsObject(headers)) {
        JsVar *hostHeader = jsvObjectGetChild(headers, "Host", false);
        hasHostHeader = hostHeader!=0;
        jsvUnLock(hostHeader);
        httpAppendHeaders(sendData, headers);
      }
      jsvUnLock(headers);
      if (!hasHostHeader) {
        JsVar *host = jsvObjectGetChild(options, "host", false);
        JsVarInt port = jsvGetIntegerAndUnLock(jsvObjectGetChild(options, "port", false));
        if (port>0 && port!=80)
          jsvAppendPrintf(sendData, "Host: %v:%d\r\n", host, port);
        else
          jsvAppendPrintf(sendData, "Host: %v\r\n", host);
        jsvUnLock(host);
      }
      // finally add ending newline
      jsvAppendString(sendData, "\r\n");
    } else {
      sendData = jsvNewFromString("");
    }
    jsvObjectSetChild(httpClientReqVar, HTTP_NAME_SEND_DATA, sendData);
    jsvUnLock(options);
  }
  if (data && sendData) {
    JsVar *s = jsvAsString(data, false);
    if (s) jsvAppendStringVarComplete(sendData,s);
    jsvUnLock(s);
  }
  jsvUnLock(sendData);
}
Esempio n. 12
0
/*JSON{
  "type" : "staticproperty",
  "class" : "process",
  "name" : "env",
  "generate" : "jswrap_process_env",
  "return" : ["JsVar","An object"]
}
Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION, FLASH, RAM, MODULES.

For example, to get a list of built-in modules, you can use `process.env.MODULES.split(',')`
 */
JsVar *jswrap_process_env() {
  JsVar *obj = jsvNewObject();
  jsvObjectSetChildAndUnLock(obj, "VERSION", jsvNewFromString(JS_VERSION));
#ifdef GIT_COMMIT
  jsvObjectSetChildAndUnLock(obj, "GIT_COMMIT", jsvNewFromString(STRINGIFY(GIT_COMMIT)));
#endif
  jsvObjectSetChildAndUnLock(obj, "BOARD", jsvNewFromString(PC_BOARD_ID));
  jsvObjectSetChildAndUnLock(obj, "FLASH", jsvNewFromInteger(FLASH_TOTAL));
  jsvObjectSetChildAndUnLock(obj, "RAM", jsvNewFromInteger(RAM_TOTAL));
  jsvObjectSetChildAndUnLock(obj, "SERIAL", jswrap_interface_getSerial());
  jsvObjectSetChildAndUnLock(obj, "CONSOLE", jsvNewFromString(jshGetDeviceString(jsiGetConsoleDevice())));
  jsvObjectSetChildAndUnLock(obj, "MODULES", jsvNewFromString(jswGetBuiltInLibraryNames()));
#ifndef SAVE_ON_FLASH
  // Pointer to a list of predefined exports - eventually we'll get rid of the array above
  jsvObjectSetChildAndUnLock(obj, "EXPTR", jsvNewFromInteger((JsVarInt)(size_t)exportPtrs));
#endif
  return obj;
}
Esempio n. 13
0
JsVar *jslGetTokenValueAsVar() {
  if (lex->tokenValue) {
    return jsvLockAgain(lex->tokenValue);
  } else {
    assert(lex->tokenl < JSLEX_MAX_TOKEN_LENGTH);
    lex->token[lex->tokenl]  = 0; // add final null
    return jsvNewFromString(lex->token);
  }
}
Esempio n. 14
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP32",
  "name"     : "getState",
  "generate" : "jswrap_ESP32_getState",
  "return"   : ["JsVar", "The state of the ESP32"]
}
Returns an object that contains details about the state of the ESP32 with the following fields:

* `sdkVersion`   - Version of the SDK.
* `cpuFrequency` - CPU operating frequency in Mhz.
* `freeHeap`     - Amount of free heap in bytes.
* `maxCon`       - Maximum number of concurrent connections.
* `flashMap`     - Configured flash size&map: '512KB:256/256' .. '4MB:512/512'
* `flashKB`      - Configured flash size in KB as integer
* `flashChip`    - Type of flash chip as string with manufacturer & chip, ex: '0xEF 0x4016`

*/
JsVar *jswrap_ESP32_getState() {
  // Create a new variable and populate it with the properties of the ESP32 that we
  // wish to return.
  JsVar *esp32State = jsvNewObject();
  // system_get_sdk_version() - is deprecated , need to find alternative
  jsvObjectSetChildAndUnLock(esp32State, "sdkVersion",   jsvNewFromString("1.0 2016-12-03"));
  //jsvObjectSetChildAndUnLock(esp32State, "cpuFrequency", jsvNewFromInteger(system_get_cpu_freq()));
  jsvObjectSetChildAndUnLock(esp32State, "freeHeap",     jsvNewFromInteger(esp_get_free_heap_size()));
  return esp32State;
} // End of jswrap_ESP32_getState
Esempio n. 15
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "getState",
  "generate" : "jswrap_ESP8266WiFi_getState",
  "return"   : ["JsVar","The state of the ESP8266"],
  "return_object" : "ESP8266State"
}*/
JsVar *jswrap_ESP8266WiFi_getState() {
  // Create a new variable and populate it with the properties of the ESP8266 that we
  // wish to return.
  JsVar *esp8266State = jspNewObject(NULL, "ESP8266State");
  jsvUnLock(jsvObjectSetChild(esp8266State, "sdkVersion",   jsvNewFromString(system_get_sdk_version())));
  jsvUnLock(jsvObjectSetChild(esp8266State, "cpuFrequency", jsvNewFromInteger(system_get_cpu_freq())));
  jsvUnLock(jsvObjectSetChild(esp8266State, "freeHeap",     jsvNewFromInteger(system_get_free_heap_size())));
  jsvUnLock(jsvObjectSetChild(esp8266State, "maxCon",       jsvNewFromInteger(espconn_tcp_get_max_con())));
  return esp8266State;
}
Esempio n. 16
0
/*JSON{ "type":"method", "class": "Array", "name" : "join",
         "description" : "Join all elements of this array together into one string, using 'separator' between them. eg. ```[1,2,3].join(' ')=='1 2 3'```",
         "generate" : "jswrap_array_join",
         "params" : [ [ "separator", "JsVar", "The separator"] ],
         "return" : ["JsVar", "A String representing the Joined array"]
}*/
JsVar *jswrap_array_join(JsVar *parent, JsVar *filler) {
  if (jsvIsUndefined(filler))
    filler = jsvNewFromString(","); // the default it seems
  else
    filler = jsvAsString(filler, false);
  if (!filler) return 0; // out of memory
  JsVar *str = jsvArrayJoin(parent, filler);
  jsvUnLock(filler);
  return str;
}
/*JSON{ "type":"method", "class": "Object", "name" : "toString",
         "description" : "Convert the Object to a string",
         "generate" : "jswrap_object_toString",
         "params" : [ [ "radix", "JsVar", "If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers."] ],
         "return" : ["JsVar", "A String representing the object"]
}*/
JsVar *jswrap_object_toString(JsVar *parent, JsVar *arg0) {
  if (jsvIsInt(arg0) && jsvIsInt(parent)) {
    JsVarInt radix = jsvGetInteger(arg0);
    if (radix>=2 && radix<=36) {
      char buf[JS_NUMBER_BUFFER_SIZE];
      itoa(parent->varData.integer, buf, (unsigned int)radix);
      return jsvNewFromString(buf);
    }
  }
  return jsvAsString(parent, false);
}
Esempio n. 18
0
JsVar *_jswrap_error_constructor(JsVar *msg, char *type) {
  JsVar *d = jspNewObject(0,type);
  if (!d) return 0;

  if (msg) {
    msg = jsvAsString(msg, false);
    jsvObjectSetChildAndUnLock(d, "msg", msg);
  }
  jsvObjectSetChildAndUnLock(d, "type", jsvNewFromString(type));

  return d;
}
Esempio n. 19
0
/*JSON{
  "type" : "method",
  "class" : "ReferenceError",
  "name" : "toString",
  "generate" : "jswrap_error_toString",
  "return" : ["JsVar","A String"]
}*/
JsVar *jswrap_error_toString(JsVar *parent) {
  JsVar *str = jsvObjectGetChild(parent, "type", 0);
  if (!str) str = jsvNewFromString("Error");
  if (!str) return 0;

  JsVar *msg = jsvObjectGetChild(parent, "msg", 0);
  if (msg) {
    JsVar *newStr = jsvVarPrintf("%v: %v", str, msg);
    jsvUnLock2(msg, str);
    str = newStr;
  }

  return str;
}
Esempio n. 20
0
/*JSON{
  "type" : "method",
  "class" : "Object",
  "name" : "toString",
  "generate" : "jswrap_object_toString",
  "params" : [
    ["radix","JsVar","If the object is an integer, the radix (between 2 and 36) to use. NOTE: Setting a radix does not work on floating point numbers."]
  ],
  "return" : ["JsVar","A String representing the object"]
}
Convert the Object to a string
 */
JsVar *jswrap_object_toString(JsVar *parent, JsVar *arg0) {
  if (jsvIsInt(arg0) && jsvIsNumeric(parent)) {
    JsVarInt radix = jsvGetInteger(arg0);
    if (radix>=2 && radix<=36) {
      char buf[JS_NUMBER_BUFFER_SIZE];
      if (jsvIsInt(parent))
        itostr(jsvGetInteger(parent), buf, (unsigned int)radix);
      else
        ftoa_bounded_extra(jsvGetFloat(parent), buf, sizeof(buf), (int)radix, -1);
      return jsvNewFromString(buf);
    }
  }
  return jsvAsString(parent, false);
}
Esempio n. 21
0
void _jswrap_object_keys_or_property_names_iterator(
    const JswSymList *symbols,
    void (*callback)(void *data, JsVar *name),
    void *data) {
  if (!symbols) return;
  unsigned int i;
  unsigned char symbolCount = READ_FLASH_UINT8(&symbols->symbolCount);
  for (i=0;i<symbolCount;i++) {
    unsigned short strOffset = READ_FLASH_UINT16(&symbols->symbols[i].strOffset);
#ifndef USE_FLASH_MEMORY
    JsVar *name = jsvNewFromString(&symbols->symbolChars[strOffset]);
#else
    // On the esp8266 the string is in flash, so we have to copy it to RAM first
    // We can't use flash_strncpy here because it assumes that strings start on a word
    // boundary and that's not the case here.
    char buf[64], *b = buf, c; const char *s = &symbols->symbolChars[strOffset];
    do { c = READ_FLASH_UINT8(s++); *b++ = c; } while (c && b != buf+64);
    JsVar *name = jsvNewFromString(buf);
#endif
    //os_printf_plus("OBJ cb %s\n", buf);
    callback(data, name);
    jsvUnLock(name);
  }
}
Esempio n. 22
0
// Fire error events on up to two objects if there is an error, returns true if there is an error
// The error events have a code field and a message field.
static bool fireErrorEvent(int error, JsVar *obj1, JsVar *obj2) {
    bool hadError = error < 0 && error != SOCKET_ERR_CLOSED;
    JsVar *params[1];
    if (hadError) {
        params[0] = jsvNewObject();
        jsvObjectSetChildAndUnLock(params[0], "code", jsvNewFromInteger(error));
        jsvObjectSetChildAndUnLock(params[0], "message",
                                   jsvNewFromString(socketErrorString(error)));
        if (obj1 != NULL)
            jsiQueueObjectCallbacks(obj1, HTTP_NAME_ON_ERROR, params, 1);
        if (obj2 != NULL)
            jsiQueueObjectCallbacks(obj2, HTTP_NAME_ON_ERROR, params, 1);
        jsvUnLock(params[0]);
    }
    return hadError;
}
Esempio n. 23
0
/*JSON{ "type":"staticproperty",
         "class" : "process", "name" : "env",
         "description" : "Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION",
         "generate" : "jswrap_process_env",
         "return" : ["JsVar", "An object"]
}*/
JsVar *jswrap_process_env() {
  JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
  jsvUnLock(jsvObjectSetChild(obj, "VERSION", jsvNewFromString(JS_VERSION)));
  jsvUnLock(jsvObjectSetChild(obj, "BUILD_DATE", jsvNewFromString(__DATE__)));
  jsvUnLock(jsvObjectSetChild(obj, "BUILD_TIME", jsvNewFromString(__TIME__)));
#ifdef GIT_COMMIT
  jsvUnLock(jsvObjectSetChild(obj, "GIT_COMMIT", jsvNewFromString(STRINGIFY(GIT_COMMIT))));
#endif
  jsvUnLock(jsvObjectSetChild(obj, "BOARD", jsvNewFromString(PC_BOARD_ID)));
  jsvUnLock(jsvObjectSetChild(obj, "CHIP", jsvNewFromString(PC_BOARD_CHIP)));
  jsvUnLock(jsvObjectSetChild(obj, "CHIP_FAMILY", jsvNewFromString(PC_BOARD_CHIP_FAMILY)));
  jsvUnLock(jsvObjectSetChild(obj, "FLASH", jsvNewFromInteger(FLASH_TOTAL)));
  jsvUnLock(jsvObjectSetChild(obj, "RAM", jsvNewFromInteger(RAM_TOTAL)));
  jsvUnLock(jsvObjectSetChild(obj, "SERIAL", jswrap_interface_getSerial()));
  jsvUnLock(jsvObjectSetChild(obj, "CONSOLE", jsvNewFromString(jshGetDeviceString(jsiGetConsoleDevice()))));

  return obj;
}
Esempio n. 24
0
/*JSON{ "type":"staticproperty",
         "class" : "process", "name" : "env",
         "description" : "Returns an Object containing various pre-defined variables. standard ones are BOARD, VERSION",
         "generate" : "jswrap_process_env",
         "return" : ["JsVar", "An object"]
}*/
JsVar *jswrap_process_env() {
    JsVar *obj = jsvNewWithFlags(JSV_OBJECT);
    jsvUnLock(jsvObjectSetChild(obj, "VERSION", jsvNewFromString(JS_VERSION)));
    jsvUnLock(jsvObjectSetChild(obj, "BUILD_DATE", jsvNewFromString(__DATE__)));
    jsvUnLock(jsvObjectSetChild(obj, "BUILD_TIME", jsvNewFromString(__TIME__)));
    jsvUnLock(jsvObjectSetChild(obj, "BOARD", jsvNewFromString(PC_BOARD_ID)));
    jsvUnLock(jsvObjectSetChild(obj, "CHIP", jsvNewFromString(PC_BOARD_CHIP)));
    jsvUnLock(jsvObjectSetChild(obj, "CHIP_FAMILY", jsvNewFromString(PC_BOARD_CHIP_FAMILY)));
    jsvUnLock(jsvObjectSetChild(obj, "FLASH", jsvNewFromInteger(FLASH_TOTAL)));
    jsvUnLock(jsvObjectSetChild(obj, "RAM", jsvNewFromInteger(RAM_TOTAL)));

    return obj;
}
Esempio n. 25
0
/*JSON{
  "type" : "staticmethod",
  "class" : "Trig",
  "name" : "getErrorArray",
  "generate" : "jswrap_trig_getErrorArray",
  "return" : ["JsVar","An array of error strings"]
}
Get the current error flags from the trigger wheel - and zero them
*/
JsVar* jswrap_trig_getErrorArray() {
  TriggerStruct *trig = &mainTrigger;
  TriggerError errors = trig->errors;
  trig->errors = 0;

  JsVar *arr = jsvNewWithFlags(JSV_ARRAY);
  if (arr) {
    int i;
    for (i=1;i<=errors;i<<=1) {
      if (errors & i) {
        const char *s = trigGetErrorString(i);
        if (s) {
          jsvArrayPushAndUnLock(arr, jsvNewFromString(s));
        }
      }
    }
  }
  return arr;
}
Esempio n. 26
0
/*JSON{
  "type"     : "staticmethod",
  "class"    : "ESP8266WiFi",
  "name"     : "getConnectStatus",
  "generate" : "jswrap_ESP8266WiFi_getConnectStatus",
  "return"   : ["JsVar","A connection status"]
}

Retrieve the connection status.  The return is an object that contains:

* status - The status code from ESP8266
* statusMsg - The description of the code

*/
JsVar *jswrap_ESP8266WiFi_getConnectStatus() {
  // Ask ESP8266 for the connection status
  uint8 status = wifi_station_get_connect_status();

  // Create a JS variable to return
  JsVar *var = jsvNewWithFlags(JSV_OBJECT);

  // Populate the return JS variable with a property called "status"
  JsVar *jsStatus = jsvNewFromInteger(status);
  //jsvUnLock(jsStatus);
  jsvUnLock(jsvObjectSetChild(var, "status", jsStatus));

  // Populate the return JS variable with a property called "statusMsg"
  char *statusMsg;
  switch(status) {
  case STATION_IDLE:
    statusMsg = "STATION_IDLE";
    break;
  case STATION_CONNECTING:
    statusMsg = "STATION_CONNECTING";
    break;
  case STATION_WRONG_PASSWORD:
    statusMsg = "STATION_WRONG_PASSWORD";
    break;
  case STATION_NO_AP_FOUND:
    statusMsg = "STATION_NO_AP_FOUND";
    break;
  case STATION_CONNECT_FAIL:
    statusMsg = "STATION_CONNECT_FAIL";
    break;
  case STATION_GOT_IP:
    statusMsg = "STATION_GOT_IP";
    break;
  default:
    statusMsg = "*** Unknown ***";
  }
  JsVar *jsStatusMsg = jsvNewFromString(statusMsg);
  //jsvUnLock(jsStatusMsg);
  jsvUnLock(jsvObjectSetChild(var, "statusMsg", jsStatusMsg));
  //jsvUnLock(var);
  return var;
}
Esempio n. 27
0
/*JSON{
  "type" : "staticmethod",
  "class" : "http",
  "name" : "get",
  "generate" : "jswrap_http_get",
  "params" : [
    ["options","JsVar","An object containing host,port,path,method fields"],
    ["callback","JsVar","A function(res) that will be called when a connection is made. You can then call `res.on('data', function(data) { ... })` and `res.on('close', function() { ... })` to deal with the response."]
  ],
  "return" : ["JsVar","Returns a new httpCRq object"],
  "return_object" : "httpCRq"
}
Create an HTTP Request - convenience function for ```http.request()```. `options.method` is set to 'get', and end is called automatically. See [the Internet page](/Internet) for more usage examples.
*/
JsVar *jswrap_http_get(JsVar *options, JsVar *callback) {
  JsNetwork net;
  if (!networkGetFromVarIfOnline(&net)) return 0;

  if (jsvIsObject(options)) {
    // if options is a string - it will be parsed, and GET will be set automatically
    JsVar *method = jsvNewFromString("GET");
    jsvUnLock2(jsvAddNamedChild(options, method, "method"), method);
  }
  JsVar *skippedCallback = jsvSkipName(callback);
  if (!jsvIsUndefined(skippedCallback) && !jsvIsFunction(skippedCallback)) {
    jsError("Expecting Callback Function but got %t", skippedCallback);
    jsvUnLock(skippedCallback);
    return 0;
  }
  jsvUnLock(skippedCallback);
  JsVar *cliReq = jswrap_net_connect(options, callback, ST_HTTP);
  if (cliReq) clientRequestEnd(&net, cliReq);
  networkFree(&net);
  return cliReq;
}
Esempio n. 28
0
// 'end' this connection
void clientRequestEnd(JsNetwork *net, JsVar *httpClientReqVar) {
    SocketType socketType = socketGetType(httpClientReqVar);
    if ((socketType&ST_TYPE_MASK) == ST_HTTP) {
        JsVar *finalData = 0;
        if (jsvGetBoolAndUnLock(jsvObjectGetChild(httpClientReqVar, HTTP_NAME_CHUNKED, 0))) {
            // If we were asked to send 'chunked' data, we need to finish up
            finalData = jsvNewFromString("");
        }
        // on HTTP, this actually means we connect
        // force sendData to be made
        clientRequestWrite(net, httpClientReqVar, finalData);
        jsvUnLock(finalData);
    } else {
        // on normal sockets, we actually request close after all data sent
        jsvObjectSetChildAndUnLock(httpClientReqVar, HTTP_NAME_CLOSE, jsvNewFromBool(true));
        // if we never sent any data, make sure we close 'now'
        JsVar *sendData = jsvObjectGetChild(httpClientReqVar, HTTP_NAME_SEND_DATA, 0);
        if (!sendData || jsvIsEmptyString(sendData))
            jsvObjectSetChildAndUnLock(httpClientReqVar, HTTP_NAME_CLOSENOW, jsvNewFromBool(true));
        jsvUnLock(sendData);
    }
}
Esempio n. 29
0
/*JSON{
  "type" : "staticmethod",
  "class" : "ESP8266",
  "name" : "connect",
  "generate" : "jswrap_esp8266_connect_device",
  "params" : [
    ["serial","JsVar","The Serial port used for communications with the ESP8266 (must already be setup)"],
    ["callback","JsVar","Function to call back when connected"]
  ],
  "return" : ["JsVar","An ESP8266 Object"],
  "return_object" : "ESP8266"
}
Initialise the WIZnet module and return an Ethernet object
*/
JsVar *jswrap_esp8266_connect_device(JsVar *usart, JsVar *callback) {

  IOEventFlags usartDevice;
  usartDevice = jsiGetDeviceFromClass(usart);
  if (!DEVICE_IS_USART(usartDevice)) {
    jsExceptionHere(JSET_ERROR, "Expecting USART device, got %q", usart);
    return 0;
  }

  JsNetwork net;
  networkCreate(&net, JSNETWORKTYPE_ESP8266);
  net.data.device = usartDevice;
  networkSet(&net);

  JsVar *wifiObj = 0;

  JsVar *cmd = jsvNewFromString("AT+RST\r\n");
  esp8266_send(cmd);
  jsvUnLock(cmd);
  if (esp8266_wait_for("OK", 100, false)) {
    if (esp8266_wait_for("ready", 4000, false)) {
      networkState = NETWORKSTATE_ONLINE;
      wifiObj = jspNewObject(0, "ESPWifi");
    } else {
      jsExceptionHere(JSET_ERROR, "Module not ready");
    }
  } else {
    jsExceptionHere(JSET_ERROR, "No Acknowledgement");
  }


  networkFree(&net);

  if (callback)
    jsiQueueEvents(callback, 0, 0);

  return wifiObj;
}
Esempio n. 30
0
void _wlan_getIP_get_address(JsVar *object, const char *name,  unsigned char *ip, int nBytes, int base, char separator) {
  char data[64] = "";
  int i, l = 0;
  for (i=nBytes-1;i>=0;i--) {
    itoa(ip[i], &data[l], base);
    l = strlen(data);
    if (i>0 && separator) {
      data[l++] = separator;
      data[l] = 0;
    }
  }

  JsVar *dataVar = jsvNewFromString(data);
  if (!dataVar) return;

  JsVar *v = jsvFindChildFromString(object, name, true);
  if (!v) {
    jsvUnLock(dataVar);
    return; // out of memory
  }
  jsvSetValueOfName(v, dataVar);
  jsvUnLock(dataVar);
  jsvUnLock(v);
}