add jerryscript source code

This commit is contained in:
wgzAIIT
2023-11-20 09:05:58 +08:00
parent d1d846184b
commit 516b8627f7
2062 changed files with 302866 additions and 0 deletions
@@ -0,0 +1,120 @@
### About Curie BSP port
[Intel® Curie BSP](https://github.com/CurieBSP/main/blob/master/README.rst) is the SDK that will help you developing software on Curie based boards, for example with the [Arduino 101 board (AKA Genuino 101)](https://www.arduino.cc/en/Main/ArduinoBoard101).
This folder contains necessary files to integrate JerryScript with Intel® Curie BSP, so that JavaScript can run on Arduino 101 board (AKA Genuino 101).
### How to build
#### 1. Preface
Curie BSP only support Ubuntu GNU/Linux as host OS envirenment.
Necessary hardwares
* [FlySwatter2 JTAG debugger](https://www.tincantools.com/wiki/Flyswatter2)
* [ARM-JTAG-20-10](https://www.amazon.com/PACK-ARM-JTAG-20-10-Micro-JTAG-adapter/dp/B010ATK9OC/ref=sr_1_1?ie=UTF8&qid=1469635131&sr=8-1&keywords=ARM+Micro+JTAG+Connector)
* [USB to TTL Serial Cable](https://www.adafruit.com/products/954)
#### 2. Prepare Curie BSP
You can refer to a detailed document [Curie BSP](https://github.com/CurieBSP/main/releases). But, we summary the main steps below:
##### 1. Get repo:
```
mkdir ~/bin
wget http://commondatastorage.googleapis.com/git-repo-downloads/repo -O ~/bin/repo
chmod a+x ~/bin/repo
```
##### 2. In ``~/.bashrc`` add:
```
PATH=$PATH:~/bin
```
##### 3. Create your directory for CurieBSP (eg. Curie_BSP):
```
mkdir Curie_BSP && cd $_
```
##### 4. Initialize your repo:
```
repo init -u https://github.com/CurieBSP/manifest
```
##### 5. Download the sources files:
```
repo sync -j 5 -d
```
##### 6. Get toolchain (compilation/debug):
Download [issm-toolchain-linux-2016-05-12.tar.gz](https://software.intel.com/en-us/articles/issm-toolchain-only-download), and uncompress it.
**TOOLCHAIN_DIR** environment variable needs to match the toolchain destination folder
You can use the command:``export TOOLCHAIN_DIR='path to files of the toolchain'``
Or you can just uncompress the toolchain tarball and copy the contents (`licensing readme.txt tools version.txt`) into `wearable_device_sw/external/toolchain`.
##### 7. Get BLE firmware:
Download [curie-ble-v3.1.1.tar.gz]( https://registrationcenter.intel.com/en/forms/?productid=2783) and uncompress the retrieved package into ``wearable_device_sw/packages`` folder
You will first register in the web page. Then you will receive an email where is a download link. Click the link in the mail, choose the `curie-ble-v3.1.1.tar.gz (118 KB)` and download.
##### 8. Get tools to flash the device:
[https://01.org/android-ia/downloads/intel-platform-flash-tool-lite](https://01.org/android-ia/downloads/intel-platform-flash-tool-lite)
#### 3. Build JerryScript and Curie BSP
##### 1. Generate makefiles
Run the Python script ``setup.py`` in ``jerryscript/targets/curie_bsp/`` with the full path or relative path of the ``Curie_BSP``:
```
python setup.py <path of Curie_BSP>
```
##### 2. One time setup. It will check/download/install the necessary tools, and must be run only once.
In the directory ``Curie_BSP``
```
make -C wearable_device_sw/projects/curie_bsp_jerry/ one_time_setup
```
##### 3. In the directory ``Curie_BSP``
```
mkdir out && cd $_
make -f ../wearable_device_sw/projects/curie_bsp_jerry/Makefile setup
make image
```
##### 4. Connect JTAG Debugger and TTL Serial Cable to Arduino 101 as below:
![](./image/connect.png)
##### 5. Flash the firmware
```
make flash FLASH_CONFIG=jtag_full
```
#### 4. Serial terminal
Assume the serial port is ``ttyUSB0`` in ``/dev`` directory, we can type command ``screen ttyUSB0 115200`` to open a serial terminal.
After the board boot successfully, you should see something like this:
```
Quark SE ID 16 Rev 0 A0
ARC Core state: 0000400
BOOT TARGET: 0
6135|QRK| CFW| INFO| GPIO service init in progress..
6307|ARC|MAIN| INFO| BSP init done
6315|ARC| CFW| INFO| ADC service init in progress..
6315|ARC| CFW| INFO| GPIO service init in progress...
6315|ARC| CFW| INFO| GPIO service init in progress...
6315|ARC|MAIN| INFO| CFW init done
```
To test the JavaScript command, you should add characters ``js e `` to the beginning of the JavaScript command, like this:
``js e print ('Hello World!');``
It is the uart command format of Curie BSP. `js` is cmd group, `e` is cmd name, which is short for eval, and `print ('Hello World!');` is the cmd parameters, which is the JavaScript code we want to run.
You can see the result through the screen:
```
js e print ('Hello World!');js e 1 ACK
Hello World!
undefined
js e 1 OK
```
`js e 1 ACK` and `js e 1 OK` are debug info of Curie BSP uart commands, which mean it receive and execute the command sucessfully. `Hello World!` is the printed content. `undefined` is the return value of the statement `print ('Hello World!')`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 575 KiB

@@ -0,0 +1,18 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INTTYPES_H
#define INTTYPES_H
#endif /* !INTTYPES_H */
@@ -0,0 +1,25 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SETJMP_H
#define SETJMP_H
#include <stdint.h>
typedef uint64_t jmp_buf[14];
int setjmp (jmp_buf env);
void longjmp (jmp_buf env, int val);
#endif /* !SETJMP_H */
@@ -0,0 +1,16 @@
CONFIG_AUTO_SERVICE_INIT=y
CONFIG_CFW_PROXY=y
CONFIG_CFW_QUARK_SE_HELPERS=y
CONFIG_LOG_SLAVE=y
CONFIG_MEM_POOL_DEF_PATH="$(PROJECT_PATH)/arc"
CONFIG_OS_ZEPHYR=y
CONFIG_SERVICES_QUARK_SE_ADC_IMPL=y
CONFIG_SERVICES_QUARK_SE_GPIO_IMPL=y
CONFIG_SOC_GPIO_AON=y
CONFIG_SOC_GPIO=y
CONFIG_SS_ADC=y
CONFIG_SS_GPIO=y
CONFIG_TCMD_SLAVE=y
CONFIG_TCMD=y
CONFIG_ZEPHYR_BOARD="arduino_101_sss"
CONFIG_CONSOLE_HANDLER_SHELL=y
@@ -0,0 +1,35 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* infra */
#include "infra/log.h"
#include "infra/bsp.h"
#include "infra/xloop.h"
#include "cfw/cfw.h"
static xloop_t loop;
void main (void)
{
T_QUEUE queue = bsp_init ();
pr_info (LOG_MODULE_MAIN, "BSP init done");
cfw_init (queue);
pr_info (LOG_MODULE_MAIN, "CFW init done");
xloop_init_from_queue (&loop, queue);
xloop_run (&loop);
}
@@ -0,0 +1,36 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Definition of the memory pools used by balloc/bfree:
* DECLARE_MEMORY_POOL( <index>, <size>, <count>, <align> )
* <index> : must start at 0 and be of consecutive values *
* <size> : size in bytes of each block from the pool
* <count> : number of blocks in the pool
*
* * Pool definitions must be sorted according the block size
* value: pool with <index> 0 must have the smallest <size>.
*/
DECLARE_MEMORY_POOL(0,8,32)
DECLARE_MEMORY_POOL(1,16,32)
DECLARE_MEMORY_POOL(2,32,48)
DECLARE_MEMORY_POOL(3,64,16)
DECLARE_MEMORY_POOL(4,96,24)
DECLARE_MEMORY_POOL(5,128,6)
DECLARE_MEMORY_POOL(6,256,5)
DECLARE_MEMORY_POOL(7,512,1)
#undef DECLARE_MEMORY_POOL
@@ -0,0 +1,30 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Allow project to override this partition scheme
* The following variables are allowed to be defined:
*
* QUARK_START_PAGE the first page where the QUARK code is located
* QUARK_NB_PAGE the number of pages reserved for the QUARK. The ARC gets the
* remaining pages (out of 148).
*/
#ifndef PROJECT_MAPPING_H
#define PROJECT_MAPPING_H
#define QUARK_NB_PAGE 125
#include "machine/soc/intel/quark_se/quark_se_mapping.h"
#endif /* !PROJECT_MAPPING_H */
@@ -0,0 +1,35 @@
CONFIG_AUTO_SERVICE_INIT=y
CONFIG_CFW_QUARK_SE_HELPERS=y
CONFIG_CONSOLE_MANAGER=y
CONFIG_DEBUG_PANIC_TCMD=y
CONFIG_FACTORY_DATA_WRITE=y
CONFIG_FACTORY_DATA=y
CONFIG_INTEL_QRK_AON_PT=y
CONFIG_INTEL_QRK_RTC=y
CONFIG_INTEL_QRK_SPI=y
CONFIG_INTEL_QRK_WDT=y
CONFIG_LOG_CBUFFER_SIZE=2048
CONFIG_LOG_CBUFFER=y
CONFIG_MEMORY_POOLS_BALLOC_STATISTICS=y
CONFIG_MEMORY_POOLS_BALLOC_TRACK_OWNER=y
CONFIG_MEM_POOL_DEF_PATH="$(PROJECT_PATH)/quark"
CONFIG_OS_ZEPHYR=y
CONFIG_PANIC_ON_BUS_ERROR=y
CONFIG_QUARK_SE_PROPERTIES_STORAGE=y
CONFIG_QUARK=y
CONFIG_SERVICES_QUARK_SE_ADC=y
CONFIG_SERVICES_QUARK_SE_GPIO_IMPL=y
CONFIG_SERVICES_QUARK_SE_GPIO=y
CONFIG_SOC_FLASH=y
CONFIG_SOC_GPIO_32=y
CONFIG_SOC_GPIO=y
CONFIG_SOC_ROM=y
CONFIG_SPI_FLASH_W25Q16DV=y
CONFIG_STORAGE_TASK=y
CONFIG_TCMD_CONSOLE=y
CONFIG_TCMD_MASTER=y
CONFIG_TCMD=y
CONFIG_UART_NS16550=y
CONFIG_UART_PM_NS16550=y
CONFIG_ZEPHYR_BOARD="arduino_101"
CONFIG_CONSOLE_HANDLER_SHELL=y
@@ -0,0 +1,170 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
/* Infra */
#include "infra/bsp.h"
#include "infra/reboot.h"
#include "infra/log.h"
#include "infra/time.h"
#include "infra/system_events.h"
#include "infra/tcmd/handler.h"
#include "cfw/cfw.h"
/* Watchdog helper */
#include "infra/wdt_helper.h"
#include "jerryscript.h"
#include "jerryscript-port.h"
#include "string.h"
#include "zephyr.h"
#include "microkernel/task.h"
#include "os/os.h"
#include "misc/printk.h"
static T_QUEUE queue;
jerry_value_t print_function;
void jerry_resolve_error (jerry_value_t ret_value)
{
if (jerry_value_is_error (ret_value))
{
ret_value = jerry_get_value_from_error (ret_value, true);
jerry_value_t err_str_val = jerry_value_to_string (ret_value);
jerry_size_t err_str_size = jerry_get_utf8_string_size (err_str_val);
jerry_char_t *err_str_buf = (jerry_char_t *) balloc (err_str_size, NULL);
jerry_size_t sz = jerry_string_to_utf8_char_buffer (err_str_val, err_str_buf, err_str_size);
err_str_buf[sz] = 0;
printk ("Script Error: unhandled exception: %s\n", err_str_buf);
bfree(err_str_buf);
jerry_release_value (err_str_val);
}
}
void help ()
{
printk ("Usage:\n");
printk ("js e 'JavaScript Command'\n");
printk ("eg. js e print ('Hello World');\n");
}
void eval_jerry_script (int argc, char *argv[], struct tcmd_handler_ctx *ctx)
{
if (argc < 3)
{
TCMD_RSP_ERROR (ctx, NULL);
help ();
return;
}
else
{
OS_ERR_TYPE err;
size_t str_total_length = 0;
size_t *str_lens = (size_t *) balloc ((argc - 2) * sizeof(size_t), &err);
if (str_lens == NULL || err != E_OS_OK)
{
printk ("%s: allocate memory failed!", __func__);
TCMD_RSP_ERROR (ctx, NULL);
return;
}
for (int i = 2; i < argc; ++i)
{
str_lens[i - 2] = strlen (argv[i]);
str_total_length += str_lens[i - 2] + 1;
}
err = E_OS_OK;
char *buffer = (char *) balloc (str_total_length, &err);
if (buffer == NULL || err != E_OS_OK)
{
printk ("%s: allocate memory failed!", __func__);
TCMD_RSP_ERROR (ctx, NULL);
return;
}
char *p = buffer;
for (int i = 2; i < argc; ++i)
{
for (int j =0; j < str_lens[i - 2]; ++j)
{
*p = argv[i][j];
++p;
}
*p = ' ';
++p;
}
*p = '\0';
jerry_value_t eval_ret = jerry_eval (buffer, str_total_length - 1, JERRY_PARSE_NO_OPTS);
if (jerry_value_is_error (eval_ret))
{
jerry_resolve_error (eval_ret);
TCMD_RSP_ERROR (ctx, NULL);
}
else
{
jerry_value_t args[] = {eval_ret};
jerry_value_t ret_val_print = jerry_call_function (print_function,
jerry_create_undefined (),
args,
1);
jerry_release_value (ret_val_print);
TCMD_RSP_FINAL (ctx, NULL);
}
jerry_release_value (eval_ret);
bfree (buffer);
bfree (str_lens);
}
}
void jerry_start ()
{
union { double d; unsigned u; } now = { .d = jerry_port_get_current_time () };
srand (now.u);
jerry_init (JERRY_INIT_EMPTY);
jerry_value_t global_obj_val = jerry_get_global_object ();
jerry_value_t print_func_name_val = jerry_create_string ((jerry_char_t *) "print");
print_function = jerry_get_property (global_obj_val, print_func_name_val);
jerry_release_value (print_func_name_val);
jerry_release_value (global_obj_val);
}
/* Application main entry point */
void main_task (void *param)
{
/* Init BSP (also init BSP on ARC core) */
queue = bsp_init ();
/* start Quark watchdog */
wdt_start (WDT_MAX_TIMEOUT_MS);
/* Init the CFW */
cfw_init (queue);
jerry_start ();
/* Loop to process message queue */
while (1)
{
OS_ERR_TYPE err = E_OS_OK;
/* Process message with a given timeout */
queue_process_message_wait (queue, 5000, &err);
/* Acknowledge the system watchdog to prevent panic and reset */
wdt_keepalive ();
}
}
DECLARE_TEST_COMMAND (js, e, eval_jerry_script);
@@ -0,0 +1,36 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Definition of the memory pools used by balloc/bfree:
* DECLARE_MEMORY_POOL( <index>, <size>, <count>, <align> )
* <index> : must start at 0 and be of consecutive values *
* <size> : size in bytes of each block from the pool
* <count> : number of blocks in the pool
*
* * Pool definitions must be sorted according the block size
* value: pool with <index> 0 must have the smallest <size>.
*/
DECLARE_MEMORY_POOL(0,8,32)
DECLARE_MEMORY_POOL(1,16,64)
DECLARE_MEMORY_POOL(2,32,64)
DECLARE_MEMORY_POOL(3,64,48)
DECLARE_MEMORY_POOL(4,128,8)
DECLARE_MEMORY_POOL(5,256,4)
DECLARE_MEMORY_POOL(6,512,3)
DECLARE_MEMORY_POOL(7,4096,1)
#undef DECLARE_MEMORY_POOL
@@ -0,0 +1,251 @@
#!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import fnmatch
import os
def build_soft_links(project_path, jerry_path):
""" Creates soft links into the @project_path. """
if not os.path.exists(project_path):
os.makedirs(project_path)
links = [
{ # arc
'src': os.path.join('targets', 'curie_bsp', 'jerry_app', 'arc'),
'link_name': 'arc'
},
{ # include
'src': os.path.join('targets', 'curie_bsp', 'jerry_app', 'include'),
'link_name': 'include'
},
{ # quark
'src': os.path.join('targets', 'curie_bsp', 'jerry_app', 'quark'),
'link_name': 'quark'
},
{ # quark/jerryscript
'src': jerry_path,
'link_name': os.path.join('quark', 'jerryscript')
}
]
for link in links:
src = os.path.join(jerry_path, link['src'])
link_name = os.path.join(project_path, link['link_name'])
if not os.path.islink(link_name):
os.symlink(src, link_name)
print("Created symlink '{link_name}' -> '{src}'".format(src=src, link_name=link_name))
def find_sources(root_dir, sub_dir):
"""
Find .c and .S files inside the @root_dir/@sub_dir directory.
Note: the returned paths will be relative to the @root_dir directory.
"""
src_dir = os.path.join(root_dir, sub_dir)
matches = []
for root, dirnames, filenames in os.walk(src_dir):
for filename in fnmatch.filter(filenames, '*.[c|S]'):
file_path = os.path.join(root, filename)
relative_path = os.path.relpath(file_path, root_dir)
matches.append(relative_path)
return matches
def build_jerry_data(jerry_path):
"""
Build up a dictionary which contains the following items:
- sources: list of JerryScript sources which should be built.
- dirs: list of JerryScript dirs used.
- cflags: CFLAGS for the build.
"""
jerry_sources = []
jerry_dirs = set()
for sub_dir in ['jerry-core', 'jerry-math', os.path.join('targets', 'curie_bsp', 'source')]:
for file in find_sources(os.path.normpath(jerry_path), sub_dir):
path = os.path.join('jerryscript', file)
jerry_sources.append(path)
jerry_dirs.add(os.path.split(path)[0])
jerry_cflags = [
'-DJERRY_GLOBAL_HEAP_SIZE=10',
'-DJERRY_NDEBUG',
'-DJERRY_DISABLE_HEAVY_DEBUG',
'-DJERRY_BUILTIN_NUMBER=0',
'-DJERRY_BUILTIN_STRING=0',
'-DJERRY_BUILTIN_BOOLEAN=0',
#'-DJERRY_BUILTIN_ERRORS=0',
'-DJERRY_BUILTIN_ARRAY=0',
'-DJERRY_BUILTIN_MATH=0',
'-DJERRY_BUILTIN_JSON=0',
'-DJERRY_BUILTIN_DATE=0',
'-DJERRY_BUILTIN_REGEXP=0',
'-DJERRY_BUILTIN_ANNEXB=0',
'-DJERRY_ESNEXT=0',
'-DJERRY_LCACHE=0',
'-DJERRY_PROPRETY_HASHMAP=0',
]
return {
'sources': jerry_sources,
'dirs': jerry_dirs,
'cflags': jerry_cflags,
}
def write_file(path, content):
""" Writes @content into the file at specified by the @path. """
norm_path = os.path.normpath(path)
with open(norm_path, "w+") as f:
f.write(content)
print("Wrote file '{0}'".format(norm_path))
def build_obj_y(source_list):
"""
Build obj-y additions from the @source_list.
Note: the input sources should have their file extensions.
"""
return '\n'.join(['obj-y += {0}.o'.format(os.path.splitext(fname)[0]) for fname in source_list])
def build_cflags_y(cflags_list):
"""
Build cflags-y additions from the @cflags_list.
Note: the input sources should have their file extensions.
"""
return '\n'.join(['cflags-y += {0}'.format(cflag) for cflag in cflags_list])
def build_mkdir(dir_list):
""" Build mkdir calls for each dir in the @dir_list. """
return '\n'.join(['\t$(AT)mkdir -p {0}'.format(os.path.join('$(OUT_SRC)', path)) for path in dir_list])
def create_root_kbuild(project_path):
""" Creates @project_path/Kbuild.mk file. """
root_kbuild_path = os.path.join(project_path, 'Kbuild.mk')
root_kbuild_content = '''
obj-$(CONFIG_QUARK_SE_ARC) += arc/
obj-$(CONFIG_QUARK_SE_QUARK) += quark/
'''
write_file(root_kbuild_path, root_kbuild_content)
def create_root_makefile(project_path):
""" Creates @project_path/Makefile file. """
root_makefile_path = os.path.join(project_path, 'Makefile')
root_makefile_content = '''
THIS_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))
T := $(abspath $(THIS_DIR)/../..)
PROJECT := {project_name}
BOARD := curie_101
ifeq ($(filter curie_101, $(BOARD)),)
$(error The curie jerry sample application can only run on the curie_101 Board)
endif
BUILDVARIANT ?= debug
quark_DEFCONFIG = $(PROJECT_PATH)/quark/defconfig
arc_DEFCONFIG = $(PROJECT_PATH)/arc/defconfig
# Optional: set the default version
VERSION_MAJOR := 1
VERSION_MINOR := 0
VERSION_PATCH := 0
include $(T)/build/project.mk
'''.format(project_name=project_name)
write_file(root_makefile_path, root_makefile_content)
def create_arc_kbuild(project_path):
""" Creates @project_path/arc/Kbuild.mk file. """
arc_path = os.path.join(project_path, 'arc')
arc_kbuild_path = os.path.join(arc_path, 'Kbuild.mk')
arc_sources = find_sources(arc_path, '.')
arc_kbuild_content = build_obj_y(arc_sources)
write_file(arc_kbuild_path, arc_kbuild_content)
def create_quark_kbuild(project_path, jerry_path):
""" Creates @project_path/quark/Kbuild.mk file. """
quark_kbuild_path = os.path.join(project_path, 'quark', 'Kbuild.mk')
# Extract a few JerryScript related data
jerry_data = build_jerry_data(jerry_path)
jerry_objects = build_obj_y(jerry_data['sources'])
jerry_defines = jerry_data['cflags']
jerry_build_dirs = build_mkdir(jerry_data['dirs'])
quark_include_paths = [
'include',
'jerryscript',
os.path.join('jerryscript', 'jerry-math', 'include'),
os.path.join('jerryscript', 'targets' ,'curie_bsp', 'include')
] + list(jerry_data['dirs'])
quark_includes = [
'-Wno-error',
] + ['-I%s' % os.path.join(project_path, 'quark', path) for path in quark_include_paths]
quark_cflags = build_cflags_y(jerry_defines + quark_includes)
quark_kbuild_content = '''
{cflags}
obj-y += main.o
{objects}
build_dirs:
{dirs}
$(OUT_SRC): build_dirs
'''.format(objects=jerry_objects, cflags=quark_cflags, dirs=jerry_build_dirs)
write_file(quark_kbuild_path, quark_kbuild_content)
def main(curie_path, project_name, jerry_path):
project_path = os.path.join(curie_path, 'wearable_device_sw', 'projects', project_name)
build_soft_links(project_path, jerry_path)
create_root_kbuild(project_path)
create_root_makefile(project_path)
create_arc_kbuild(project_path)
create_quark_kbuild(project_path, jerry_path)
if __name__ == '__main__':
import sys
if len(sys.argv) != 2:
print('Usage:')
print('{script_name} [full or relative path of Curie_BSP]'.format(script_name=sys.argv[0]))
sys.exit(1)
project_name = 'curie_bsp_jerry'
file_dir = os.path.dirname(os.path.abspath(__file__))
jerry_path = os.path.join(file_dir, "..", "..")
curie_path = os.path.join(os.getcwd(), sys.argv[1])
main(curie_path, project_name, jerry_path)
@@ -0,0 +1,72 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <infra/time.h>
#include <misc/printk.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "jerryscript-port.h"
/**
* Provide log message implementation for the engine.
* Curie BSP implementation
*/
void
jerry_port_log (jerry_log_level_t level, /**< log level */
const char *format, /**< format string */
...) /**< parameters */
{
if (level <= JERRY_LOG_LEVEL_ERROR)
{
char buf[256];
int length = 0;
va_list args;
va_start (args, format);
length = vsnprintf (buf, 256, format, args);
buf[length] = '\0';
printk ("%s", buf);
va_end (args);
}
} /* jerry_port_log */
/**
* Curie BSP implementation of jerry_port_fatal.
*/
void jerry_port_fatal (jerry_fatal_code_t code)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Jerry Fatal Error!\n");
while (true);
} /* jerry_port_fatal */
/**
* Curie BSP implementation of jerry_port_get_local_time_zone_adjustment.
*/
double jerry_port_get_local_time_zone_adjustment (double unix_ms, bool is_utc)
{
//EMPTY implementation
return 0;
} /* jerry_port_get_local_time_zone_adjustment */
/**
* Curie BSP implementation of jerry_port_get_current_time.
*/
double jerry_port_get_current_time (void)
{
uint32_t uptime_ms = get_uptime_ms ();
uint32_t epoch_time = uptime_to_epoch (uptime_ms);
return ((double) epoch_time) * 1000.0;
} /* jerry_port_get_current_time */
@@ -0,0 +1,77 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
.macro func _name
.global \_name
.type \_name, %function
\_name:
.endm
.macro endfunc _name
.size \_name, .-\_name
.endm
/**
* setjmp (jmp_buf env)
*
* See also:
* longjmp
*
* @return 0 - if returns from direct call,
* nonzero - if returns after longjmp.
*/
func setjmp
mov %eax,(%eax);
mov %ebx,0x4(%eax);
mov %ecx,0x8(%eax);
mov %edx,0xc(%eax);
mov %esi,0x10(%eax);
mov %edi,0x14(%eax);
mov %ebp,0x18(%eax);
mov %esp,0x1c(%eax);
push %edx;
mov 0x4(%esp),%edx;
mov %edx,0x20(%eax);
pop %edx;
xor %eax,%eax;
ret
endfunc setjmp
/**
* longjmp (jmp_buf env, int val)
*
* Note:
* if val is not 0, then it would be returned from setjmp,
* otherwise - 0 would be returned.
*
* See also:
* setjmp
*/
func longjmp
test %edx, %edx;
jne . + 0x3;
inc %edx;
mov 0x4(%eax),%ebx;
mov 0x8(%eax),%ecx;
mov 0x10(%eax),%esi;
mov 0x14(%eax),%edi;
mov 0x18(%eax),%ebp;
mov 0x1c(%eax),%esp;
push %edx;
mov 0x20(%eax),%edx;
mov %edx,0x4(%esp);
mov 0xc(%eax),%edx;
pop %eax;
ret
endfunc longjmp
@@ -0,0 +1,16 @@
# assumes there is a component with this the following
# - set the JERRY_DIR wherever the jerryscript source code (the include files) is
# - a "lib" directory with the 2 libraries below
set(JERRY_DIR ${PROJECT_DIR}/../../jerryscript/)
idf_component_register(
SRC_DIRS ${JERRY_DIR}/targets/esp-idf
INCLUDE_DIRS ${JERRY_DIR}/jerry-core/include ${JERRY_DIR}/jerry-ext/include
)
add_prebuilt_library(libjerry-core lib/libjerry-core.a REQUIRES newlib PRIV_REQUIRES ${COMPONENT_NAME})
add_prebuilt_library(libjerry-ext lib/libjerry-ext.a PRIV_REQUIRES ${COMPONENT_NAME})
target_link_libraries(${COMPONENT_LIB} INTERFACE libjerry-core)
target_link_libraries(${COMPONENT_LIB} INTERFACE libjerry-ext)
@@ -0,0 +1,28 @@
This is a port for espressif's esp-idf (esp32). The MATH, LTO and STRIP options should be disabled, so to build under the IDF toolchain, just run the following command
```
python tools\build.py --toolchain=cmake/toolchain-esp32.cmake --cmake-param "-GUnix Makefiles" --jerry-cmdline=OFF --jerry-port-default=OFF --lto=OFF --strip=OFF
```
NB: the MATH, STRIP and LTO might be disabled by platform as well. I strongly suggest limiting heap memorry with '--mem-heap=128' but that really depends on the SRAM avaiulable on your esp32.
Then copy the artefacts 'build/lib/\*.a' in an esp-idf component named 'jerryscript' (eg) and use a 'CMakeLists.txt' like this one
```
# assumes there is a component with this the following
# - set the JERRY_DIR wherever the jerryscript source code (the include files) is
# - a "lib" directory with the 2 libraries below
set(JERRY_DIR ${PROJECT_DIR}/../../jerryscript/)
idf_component_register(
SRC_DIRS ${JERRY_DIR}/targets/esp-idf
INCLUDE_DIRS ${JERRY_DIR}/jerry-core/include ${JERRY_DIR}/jerry-ext/include
)
add_prebuilt_library(libjerry-core lib/libjerry-core.a REQUIRES newlib PRIV_REQUIRES ${COMPONENT_NAME})
add_prebuilt_library(libjerry-ext lib/libjerry-ext.a PRIV_REQUIRES ${COMPONENT_NAME})
target_link_libraries(${COMPONENT_LIB} INTERFACE libjerry-core)
target_link_libraries(${COMPONENT_LIB} INTERFACE libjerry-ext)
```
@@ -0,0 +1,67 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <sys/time.h>
#include "jerryscript-port.h"
/**
* Default implementation of jerry_port_get_local_time_zone_adjustment. Uses the 'tm_gmtoff' field
* of 'struct tm' (a GNU extension) filled by 'localtime_r' if available on the
* system, does nothing otherwise.
*
* @return offset between UTC and local time at the given unix timestamp, if
* available. Otherwise, returns 0, assuming UTC time.
*/
double jerry_port_get_local_time_zone_adjustment (double unix_ms, /**< ms since unix epoch */
bool is_utc) /**< is the time above in UTC? */
{
struct tm tm;
char buf[8];
time_t now = (time_t) (unix_ms / 1000);
localtime_r (&now, &tm);
if (!is_utc)
{
strftime(buf, 8, "%z", &tm);
now -= -atof(buf) * 3600 * 1000 / 100;
localtime_r (&now, &tm);
}
strftime(buf, 8, "%z", &tm);
return -atof(buf) * 3600 * 1000 / 100;
} /* jerry_port_get_local_time_zone_adjustment */
/**
* Default implementation of jerry_port_get_current_time. Uses 'gettimeofday' if
* available on the system, does nothing otherwise.
*
* @return milliseconds since Unix epoch - if 'gettimeofday' is available and
* executed successfully,
* 0 - otherwise.
*/
double jerry_port_get_current_time (void)
{
struct timeval tv;
if (gettimeofday (&tv, NULL) == 0)
{
return ((double) tv.tv_sec) * 1000.0 + ((double) tv.tv_usec) / 1000.0;
}
return 0.0;
} /* jerry_port_get_current_time */
@@ -0,0 +1,28 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "jerryscript-port.h"
/**
* Default implementation of jerry_port_sleep. Uses 'nanosleep' or 'usleep' if
* available on the system, does nothing otherwise.
*/
void jerry_port_sleep (uint32_t sleep_time) /**< milliseconds to sleep */
{
vTaskDelay( sleep_time / portTICK_PERIOD_MS);
} /* jerry_port_sleep */
@@ -0,0 +1,43 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-port.h"
/**
* Pointer to the current context.
* Note that it is a global variable, and is not a thread safe implementation.
* But I don't see how jerryscript can make that thread-safe, only the appication can
*/
static jerry_context_t *current_context_p = NULL;
/**
* Set the current_context_p as the passed pointer.
*/
void
jerry_port_default_set_current_context (jerry_context_t *context_p) /**< points to the created context */
{
current_context_p = context_p;
} /* jerry_port_default_set_current_context */
/**
* Get the current context.
*
* @return the pointer to the current context
*/
jerry_context_t *
jerry_port_get_current_context (void)
{
return current_context_p;
} /* jerry_port_get_current_context */
@@ -0,0 +1,34 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "jerryscript-port.h"
static const char TAG[] = "JS";
/**
* Default implementation of jerry_port_fatal. Calls 'abort' if exit code is
* non-zero, 'exit' otherwise.
*/
void jerry_port_fatal (jerry_fatal_code_t code) /**< cause of error */
{
ESP_LOGE(TAG, "Fatal error %d", code);
vTaskSuspend(NULL);
abort();
} /* jerry_port_fatal */
@@ -0,0 +1,124 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "esp_log.h"
#include "jerryscript-port.h"
#include "jerryscript-debugger.h"
static const char TAG[] = "JS";
static esp_log_level_t crosslog(jerry_log_level_t level)
{
switch(level)
{
case JERRY_LOG_LEVEL_ERROR: return ESP_LOG_ERROR;
case JERRY_LOG_LEVEL_WARNING: return ESP_LOG_WARN;
case JERRY_LOG_LEVEL_DEBUG: return ESP_LOG_DEBUG;
case JERRY_LOG_LEVEL_TRACE: return ESP_LOG_VERBOSE;
}
return ESP_LOG_NONE;
}
/**
* Actual log level
*/
static jerry_log_level_t jerry_port_default_log_level = JERRY_LOG_LEVEL_ERROR;
/**
* Get the log level
*
* @return current log level
*/
jerry_log_level_t
jerry_port_default_get_log_level (void)
{
return jerry_port_default_log_level;
} /* jerry_port_default_get_log_level */
/**
* Set the log level
*/
void
jerry_port_default_set_log_level (jerry_log_level_t level) /**< log level */
{
jerry_port_default_log_level = level;
} /* jerry_port_default_set_log_level */
/**
* Default implementation of jerry_port_log. Prints log message to the standard
* error with 'vfprintf' if message log level is less than or equal to the
* current log level.
*
* If debugger support is enabled, printing happens first to an in-memory buffer,
* which is then sent both to the standard error and to the debugger client.
*/
void
jerry_port_log (jerry_log_level_t level, /**< message log level */
const char *format, /**< format string */
...) /**< parameters */
{
if (level <= jerry_port_default_log_level)
{
va_list args;
va_start (args, format);
#if defined (JERRY_DEBUGGER) && (JERRY_DEBUGGER == 1)
int length = vsnprintf (NULL, 0, format, args);
va_end (args);
va_start (args, format);
JERRY_VLA (char, buffer, length + 1);
vsnprintf (buffer, (size_t) length + 1, format, args);
esp_log_write(crosslog(level), TAG, buffer);
jerry_debugger_send_log (level, (jerry_char_t *) buffer, (jerry_size_t) length);
#else /* If jerry-debugger isn't defined, libc is turned on */
esp_log_writev(crosslog(level), TAG, format, args);
#endif /* defined (JERRY_DEBUGGER) && (JERRY_DEBUGGER == 1) */
va_end (args);
}
} /* jerry_port_log */
#if defined (JERRY_DEBUGGER) && (JERRY_DEBUGGER == 1)
#define DEBUG_BUFFER_SIZE (256)
static char debug_buffer[DEBUG_BUFFER_SIZE];
static int debug_buffer_index = 0;
#endif /* defined (JERRY_DEBUGGER) && (JERRY_DEBUGGER == 1) */
/**
* Default implementation of jerry_port_print_char. Uses 'putchar' to
* print a single character to standard output.
*/
void
jerry_port_print_char (char c) /**< the character to print */
{
putchar(c);
#if defined (JERRY_DEBUGGER) && (JERRY_DEBUGGER == 1)
debug_buffer[debug_buffer_index++] = c;
if ((debug_buffer_index == DEBUG_BUFFER_SIZE) || (c == '\n'))
{
jerry_debugger_send_output ((jerry_char_t *) debug_buffer, (jerry_size_t) debug_buffer_index);
debug_buffer_index = 0;
}
#endif /* defined (JERRY_DEBUGGER) && (JERRY_DEBUGGER == 1) */
} /* jerry_port_print_char */
@@ -0,0 +1,113 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <limits.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "jerryscript-port.h"
/**
* Opens file with the given path and reads its source.
* @return the source of the file
*/
uint8_t *
jerry_port_read_source (const char *file_name_p, /**< file name */
size_t *out_size_p) /**< [out] read bytes */
{
FILE *file_p = fopen (file_name_p, "rb");
if (file_p == NULL)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: Failed to open file: %s\n", file_name_p);
return NULL;
}
struct stat info = { };
fstat(fileno(file_p), &info);
uint8_t *buffer_p = (uint8_t *) malloc (info.st_size);
if (buffer_p == NULL)
{
fclose (file_p);
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: Failed to allocate memory for file: %s\n", file_name_p);
return NULL;
}
size_t bytes_read = fread (buffer_p, 1u, info.st_size, file_p);
if (bytes_read != info.st_size)
{
fclose (file_p);
free (buffer_p);
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: Failed to read file: %s\n", file_name_p);
return NULL;
}
fclose (file_p);
*out_size_p = bytes_read;
return buffer_p;
} /* jerry_port_read_source */
/**
* Release the previously opened file's content.
*/
void
jerry_port_release_source (uint8_t *buffer_p) /**< buffer to free */
{
free (buffer_p);
} /* jerry_port_release_source */
/**
* Normalize a file path
*
* @return length of the path written to the output buffer
*/
size_t
jerry_port_normalize_path (const char *in_path_p, /**< input file path */
char *out_buf_p, /**< output buffer */
size_t out_buf_size, /**< size of output buffer */
char *base_file_p) /**< base file path */
{
size_t ret = strlen(base_file_p) + strlen(in_path_p) + 1;
if (ret < out_buf_size) {
strcpy (out_buf_p, base_file_p);
strcat (out_buf_p, "/");
strcat (out_buf_p, in_path_p);
return ret;
}
return 0;
} /* jerry_port_normalize_path */
/**
* Get the module object of a native module.
*
* @return Undefined, if 'name' is not a native module
* jerry_value_t containing the module object, otherwise
*/
jerry_value_t
jerry_port_get_native_module (jerry_value_t name) /**< module specifier */
{
(void) name;
return jerry_create_undefined ();
} /* jerry_port_get_native_module */
@@ -0,0 +1,45 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-port.h"
/**
* Track unhandled promise rejections.
*
* Note:
* This port function is called by jerry-core when JERRY_BUILTIN_PROMISE
* is enabled.
*
* @param promise rejected promise
* @param operation HostPromiseRejectionTracker operation
*/
void
jerry_port_track_promise_rejection (const jerry_value_t promise,
const jerry_promise_rejection_operation_t operation)
{
(void) operation; /* unused */
jerry_value_t reason = jerry_get_promise_result (promise);
jerry_value_t reason_to_string = jerry_value_to_string (reason);
jerry_size_t req_sz = jerry_get_utf8_string_size (reason_to_string);
jerry_char_t str_buf_p[req_sz + 1];
jerry_string_to_utf8_char_buffer (reason_to_string, str_buf_p, req_sz);
str_buf_p[req_sz] = '\0';
jerry_release_value (reason_to_string);
jerry_release_value (reason);
jerry_port_log (JERRY_LOG_LEVEL_WARNING, "Uncaught (in promise) %s\n", str_buf_p);
} /* jerry_port_track_promise_rejection */
@@ -0,0 +1,56 @@
Copyright 2015 Samsung Electronics Co., Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================================================
ESPRSSIF MIT License
Copyright (c) 2015 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266 only, in which case,
it is free of charge, to any person obtaining a copy of this software and associated
documentation files (the ¡°Software¡±), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED ¡°AS IS¡±, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
ÀÖöÎ MIT Ðí¿ÉÖ¤
°æÈ¨ (c) 2015 <ÀÖöÎÐÅÏ¢¿Æ¼¼£¨ÉϺ££©ÓÐÏÞ¹«Ë¾>
¸ÃÐí¿ÉÖ¤ÊÚȨ½öÏÞÓÚÀÖöÎÐÅÏ¢¿Æ¼¼ ESP8266 ²úÆ·µÄÓ¦Óÿª·¢¡£ÔÚ´ËÇé¿öÏ£¬¸ÃÐí¿ÉÖ¤Ãâ·ÑÊÚȨÈκλñµÃ¸Ã
Èí¼þ¼°ÆäÏà¹ØÎĵµ£¨Í³³ÆÎª¡°Èí¼þ¡±£©µÄÈËÎÞÏÞÖÆµØ¾­Óª¸ÃÈí¼þ£¬°üÀ¨ÎÞÏÞÖÆµÄʹÓᢸ´ÖÆ¡¢Ð޸ġ¢ºÏ²¢¡¢
³ö°æ·¢ÐС¢É¢²¼¡¢ÔÙÊÚȨ¡¢¼°··ÊÛÈí¼þ¼°Èí¼þ¸±±¾µÄȨÀû¡£±»ÊÚȨÈËÔÚÏíÊÜÕâЩȨÀûµÄͬʱ£¬Ðè·þ´ÓÏÂÃæ
µÄÌõ¼þ£º
ÔÚÈí¼þºÍÈí¼þµÄËùÓи±±¾Öж¼±ØÐë°üº¬ÒÔÉϵİæÈ¨ÉùÃ÷ºÍÊÚȨÉùÃ÷¡£
¸ÃÈí¼þ°´±¾À´µÄÑù×ÓÌṩ£¬Ã»ÓÐÈκÎÃ÷È·»ò°µº¬µÄµ£±££¬°üÀ¨µ«²»½öÏÞÓÚ¹ØÓÚÊÔÏúÐÔ¡¢ÊʺÏÄ³Ò»ÌØ¶¨ÓÃ;
ºÍ·ÇÇÖȨµÄ±£Ö¤¡£×÷ÕߺͰæÈ¨³ÖÓÐÈËÔÚÈκÎÇé¿öϾù²»¾ÍÓÉÈí¼þ»òÈí¼þʹÓÃÒýÆðµÄÒÔºÏͬÐÎʽ¡¢ÃñÊÂÇÖȨ
»òÆäËü·½Ê½Ìá³öµÄÈκÎË÷Åâ¡¢Ë𺦻òÆäËüÔðÈθºÔð¡£
@@ -0,0 +1,162 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#############################################################
# Required variables for each makefile
# Discard this section from all parent makefiles
# Expected variables (with automatic defaults):
# CSRCS (all "C" files in the dir)
# SUBDIRS (all subdirs with a Makefile)
# GEN_LIBS - list of libs to be generated ()
# GEN_IMAGES - list of object file images to be generated ()
# GEN_BINS - list of binaries to be generated ()
# COMPONENTS_xxx - a list of libs/objs in the form
# subdir/lib to be extracted and rolled up into
# a generated lib/image xxx.a ()
#
# Tabsize : 8
#
TARGET = eagle
FLAVOR = release
#FLAVOR = debug
#EXTRA_CCFLAGS += -u
ifndef PDIR # {
GEN_IMAGES= eagle.app.v6.out
GEN_BINS= eagle.app.v6.bin
SPECIAL_MKTARGETS=$(APP_MKTARGETS)
SUBDIRS= user
endif # } PDIR
# path to the JERRYSCRIPT directory
JERRYDIR ?= $(CURDIR)/../../..
LDDIR = $(SDK_PATH)/ld
#############################################################
# JerryScript requires a modified linker script with specified alignments
# so we use it instead of the original one from SDK.
JERRY_LD_FILE = $(CURDIR)/ld/eagle.app.v6.ld
CCFLAGS += -Os -std=c99
#CCFLAGS += -O0
TARGET_LDFLAGS = \
-nostdlib \
-Wl,-EL \
--longcalls \
--text-section-literals
ifeq ($(FLAVOR),debug)
TARGET_LDFLAGS += -O0 -g
endif
ifeq ($(FLAVOR),release)
TARGET_LDFLAGS += -Os
endif
COMPONENTS_eagle.app.v6 = \
user/libuser.a
LINKFLAGS_eagle.app.v6 = \
-L$(SDK_PATH)/lib \
-Wl,--gc-sections \
-Wl,-Map,output.map \
-nostdlib \
-T$(JERRY_LD_FILE) \
-Wl,--no-check-sections \
-u call_user_start \
-Wl,-static \
-Wl,--start-group \
-lcirom \
-lcrypto \
-lespconn \
-lespnow \
-lfreertos \
-lgcc \
-lhal \
-ljson \
-llwip \
-ldriver \
-lmain \
-lmirom \
-lnet80211 \
-lnopoll \
-lphy \
-lpp \
-lpwm \
-lsmartconfig \
-lspiffs \
-lssl \
-lwpa \
-lwps \
-L./libs \
-ljerry-core \
-ljerry-math \
$(DEP_LIBS_eagle.app.v6) \
-Wl,--end-group
DEPENDS_eagle.app.v6 = \
$(JERRY_LD_FILE) \
$(LDDIR)/eagle.rom.addr.v6.ld \
./include/jerry-targetjs.h \
./libs/libjerry-core.a \
./libs/libjerry-math.a
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
# Generally values applying to a tree are captured in the
# makefile at its root level - these are then overridden
# for a subtree within the makefile rooted therein
#
#UNIVERSAL_TARGET_DEFINES = \
# Other potential configuration flags include:
# -DTXRX_TXBUF_DEBUG
# -DTXRX_RXBUF_DEBUG
# -DWLAN_CONFIG_CCX
CONFIGURATION_DEFINES = -DICACHE_FLASH
DEFINES += \
$(UNIVERSAL_TARGET_DEFINES) \
$(CONFIGURATION_DEFINES)
DDEFINES += \
$(UNIVERSAL_TARGET_DEFINES) \
$(CONFIGURATION_DEFINES)
#############################################################
# Recursion Magic - Don't touch this!!
#
# Each subtree potentially has an include directory
# corresponding to the common APIs applicable to modules
# rooted at that subtree. Accordingly, the INCLUDE PATH
# of a module can only contain the include directories up
# its parent path, and not its siblings
#
# Required for each makefile to inherit from the parent
#
INCLUDES := -I $(JERRYDIR)/jerry-core/include
INCLUDES := $(INCLUDES) -I $(PDIR)include -I $(PDIR)source
sinclude $(SDK_PATH)/Makefile
.PHONY: FORCE
FORCE:
@@ -0,0 +1,88 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
CURDIR = `pwd`
ESP_LIB = $(SDK_PATH)/lib
BUILD_DIR = build/obj-esp8266
COPYTARGET = targets/esp8266/libs
USBDEVICE ?= /dev/ttyUSB0
JERRYHEAP ?= 20
ESPTOOL ?= $(ESPTOOL_PATH)/esptool.py
# compile flags
ESP_CFLAGS := -D__TARGET_ESP8266 -D__attr_always_inline___=
MFORCE32 = $(shell xtensa-lx106-elf-gcc --help=target | grep mforce-l32)
ifneq ($(MFORCE32),)
# Your compiler supports the -mforce-l32 flag which means that
# constants can be placed in ROM to free additional RAM
ESP_CFLAGS += -DJERRY_ATTR_CONST_DATA="__attribute__((aligned(4))) __attribute__((section(\".irom.text\")))"
ESP_CFLAGS += -mforce-l32
endif
ESP_CFLAGS += -Wl,-EL -fno-inline-functions
ESP_CFLAGS += -ffunction-sections -fdata-sections
ESP_CFLAGS += -mlongcalls -mtext-section-literals -mno-serialize-volatile
.PHONY: jerry js2c mkbin check-env flash clean
all: check-env jerry js2c mkbin
jerry:
mkdir -p $(BUILD_DIR)
mkdir -p $(COPYTARGET)
cmake -B$(BUILD_DIR) -H./ \
-DCMAKE_SYSTEM_NAME=MCU \
-DCMAKE_SYSTEM_PROCESSOR=xtensia-lx106 \
-DCMAKE_C_COMPILER=xtensa-lx106-elf-gcc \
-DCMAKE_C_COMPILER_WORKS=TRUE \
-DENABLE_LTO=OFF \
-DENABLE_AMALGAM=ON \
-DJERRY_MATH=ON \
-DJERRY_CMDLINE=OFF \
-DJERRY_PROFILE="es5.1" \
-DEXTERNAL_COMPILE_FLAGS="$(ESP_CFLAGS)" \
-DJERRY_GLOBAL_HEAP_SIZE=$(JERRYHEAP)
make -C$(BUILD_DIR) jerry-core jerry-math
cp $(BUILD_DIR)/lib/libjerry-core.a $(COPYTARGET)/
cp $(BUILD_DIR)/lib/libjerry-math.a $(COPYTARGET)/
js2c:
tools/js2c.py --dest targets/esp8266/include --js-source targets/esp8266/js
mkbin:
make -Ctargets/esp8266 clean
make -Ctargets/esp8266 BOOT=new APP=0 SPI_SPEED=40 SPI_MODE=DIO SPI_SIZE_MAP=4
check-env:
ifndef SDK_PATH
$(error SDK_PATH is undefined for ESP8266)
endif
ifndef BIN_PATH
$(error BIN_PATH is undefined for ESP8266)
endif
flash:
$(ESPTOOL) --port $(USBDEVICE) write_flash \
0x00000 $(BIN_PATH)/eagle.flash.bin \
0x20000 $(BIN_PATH)/eagle.irom0text.bin \
0x3FC000 $(SDK_PATH)/bin/esp_init_data_default.bin
erase_flash:
$(ESPTOOL) --port $(USBDEVICE) erase_flash
clean:
rm -rf $(BUILD_DIR)
@@ -0,0 +1,46 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Default target for running the build test outside the Travis CI environment.
all:
$(MAKE) install
$(MAKE) script
## Targets for installing build dependencies of the ESP8266 JerryScript target.
# Install tools via apt.
install-apt-get-deps:
sudo apt-get install -q -y wget
# Fetch and build crosstool-NG with support for Xtensa.
install-xtensa-kx106-gcc:
wget https://dl.espressif.com/dl/xtensa-lx106-elf-linux64-1.22.0-88-gde0bdc1-4.8.5.tar.gz -O ../xtensa-lx106-elf-linux64-1.22.0-88-gde0bdc1-4.8.5.tar.gz --no-check-certificate
cd .. && tar xvfz xtensa-lx106-elf-linux64-1.22.0-88-gde0bdc1-4.8.5.tar.gz
# Fetch Espressif SDK and Xtensa libraries.
install-espressif-sdk:
git clone https://github.com/espressif/ESP8266_RTOS_SDK.git ../ESP8266_RTOS_SDK -b v2.1.0
# Perform all the necessary (JerryScript-independent) installation steps.
install-noapt: install-xtensa-kx106-gcc install-espressif-sdk
install: install-apt-get-deps install-noapt
## Targets for building ESP8266 with JerryScript.
# Build the firmware (ESP8266 with JerryScript).
script:
PATH=$(CURDIR)/../xtensa-lx106-elf/bin:$$PATH $(MAKE) -f ./targets/esp8266/Makefile.esp8266 BIN_PATH=build/obj-esp8266 SDK_PATH=$(CURDIR)/../ESP8266_RTOS_SDK
@@ -0,0 +1,120 @@
#### Preparation
##### Accessories
You need,
* 3.3V power supply. You can use bread board power (+5V, +3.3V). I used LM317 like this;
* Use [LM317](http://www.ti.com/lit/ds/symlink/lm317.pdf)
* R1 = 330 Ohm, R2 = 545 Ohm (1K + 1.2K in parallel)
* 5V 2A adaptor
* USB to RS-232 Serial + RS-232 Serial to Digital or USB-to-RS232 TTL converter
#### Tools
The rest of this document will assume that you download all necessary tools into
a common directory structure. For the sake of simplicity, `$HOME/Espressif` will
be used as the root of this structure. Feel free to deviate from this but then
adapt all the paths accordingly.
```
mkdir $HOME/Espressif
```
##### Toolchain
Download the [toolchain](https://github.com/espressif/ESP8266_RTOS_SDK/tree/v3.0.1#get-toolchain)
pre-built for your development platform to `$HOME/Espressif` and untar it. E.g.,
on Linux/x86-64:
```
cd $HOME/Espressif
tar xvfz xtensa-lx106-elf-linux64-1.22.0-88-gde0bdc1-4.8.5.tar.gz
```
##### Espressif SDK: use Espressif official
```
cd $HOME/Esprissif
git clone https://github.com/espressif/ESP8266_RTOS_SDK.git -b v2.1.0
```
This version is tested and works properly.
##### ESP image tool
```
cd $HOME/Espressif
wget -O esptool_0.0.2-1_i386.deb https://github.com/esp8266/esp8266-wiki/raw/master/deb/esptool_0.0.2-1_i386.deb
sudo dpkg -i esptool_0.0.2-1_i386.deb
```
##### ESP upload tool
```
cd $HOME/Espressif
git clone https://github.com/themadinventor/esptool
```
##### Set environment variables
Set environment variables, might also go in your `.profile`:
```
export PATH=$HOME/Espressif/xtensa-lx106-elf/bin:$PATH
export SDK_PATH=$HOME/Espressif/ESP8266_RTOS_SDK
export ESPTOOL_PATH=$HOME/Espressif/esptool
export BIN_PATH=(to output folder path)
```
#### Test writing with Blinky example
##### Get the source
found one example that works with SDK V1.2 (which is based on FreeRTOS, as of writing)
* https://github.com/mattcallow/esp8266-sdk/tree/master/rtos_apps/01blinky
##### Compile
Read `2A-ESP8266__IOT_SDK_User_Manual_EN` document in
[this](http://bbs.espressif.com/viewtopic.php?f=51&t=1024) link.
It's configured 2048KB flash
```
BOOT=new APP=1 SPI_SPEED=80 SPI_MODE=QIO SPI_SIZE_MAP=5 make
BOOT=new APP=2 SPI_SPEED=80 SPI_MODE=QIO SPI_SIZE_MAP=5 make
```
or old way... this works not sure this is ok.
```
make BOOT=new APP=0 SPI_SPEED=80 SPI_MODE=QIO SPI_SIZE_MAP=2
```
##### Flashing
* power off ESP8266 board
* connect GPIO0 to GND, connect GPIO2 to VCC
* power on
* write
```
sudo $HOME/Espressif/esptool/esptool.py \
--port /dev/ttyUSB0 write_flash \
0x00000 $SDK_PATH/bin/"boot_v1.7.bin" \
0x01000 $BIN_PATH/upgrade/user1.2048.new.5.bin \
0x101000 $BIN_PATH/upgrade/user2.2048.new.5.bin \
0x3FE000 $SDK_PATH/bin/blank.bin \
0x3FC000 $SDK_PATH/bin/esp_init_data_default.bin
```
_change `/dev/ttyUSB1` to whatever you have._
or the old way...this works not sure this is ok.
```
cd $BIN_PATH
sudo $HOME/Espressif/esptool/esptool.py \
--port /dev/ttyUSB0 write_flash \
0x00000 eagle.flash.bin 0x40000 eagle.irom0text.bin
```
* power off
* disconnect GPIO0 so that it is floating
* connect GPIO2 with serial of 470 Ohm + LED and to GND
* power On
@@ -0,0 +1,35 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __JERRY_EXTAPI_H__
#define __JERRY_EXTAPI_H__
#define JERRY_STANDALONE_EXIT_CODE_OK (0)
#define JERRY_STANDALONE_EXIT_CODE_FAIL (1)
#ifdef __cplusplus
extern "C" {
#endif
void js_register_functions (void);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,36 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __JERRY_RUN_H__
#define __JERRY_RUN_H__
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void js_entry (void);
int js_eval (const char *source_p, const size_t source_size);
int js_loop (uint32_t ticknow);
void js_exit (void);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,24 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __USER_CONFIG_H__
#define __USER_CONFIG_H__
/* number of stack items, x4 for bytes */
#define JERRY_STACK_SIZE 2000
#endif
@@ -0,0 +1,15 @@
var check = 1;
function blink() {
var inp = gpio_get(0);
var blk = (check > 8) ? 1 - inp : inp;
gpio_set(2, blk);
check = check >= 10 ? 1 : check+1;
}
// GPIO 0 as input
// GPIO 2 as output
gpio_dir(0, 0);
gpio_dir(2, 1);
print("blink js OK");
@@ -0,0 +1,5 @@
function sysloop(ticknow) {
blink();
};
print("Random generated number: ", Math.random());
print("main js OK");
@@ -0,0 +1,32 @@
/* eagle.flash.bin @ 0x00000 */
/* eagle.irom0text.bin @ 0x20000 */
/* Flash Map, support 512KB/1MB/2MB/4MB SPI Flash */
/* |......|..............................|..........................|.....|....| */
/* ^ ^ ^ ^ ^ */
/* |_flash.bin start(0x00000) |_irom0text.bin start(0x20000) | */
/* |_flash.bin end |_irom0text.bin end */
/* |_system param area(0x7b000) */
/* NOTICE: */
/* 1. You can change irom0 org, but MUST make sure irom0text.bin start not overlap flash.bin end. */
/* 2. You can change irom0 len, but MUST make sure irom0text.bin end not overlap system param area. */
/* 3. Space between flash.bin end and irom0text.bin start can be used as user param area. */
/* 4. Space between irom0text.bin end and system param area can be used as user param area. */
/* 5. Make sure irom0text.bin end < 0x100000 */
/* 6. system param area: */
/* 1>. 512KB--->0x07b000 */
/* 2>. 1MB----->0x0fb000 */
/* 3>. 2MB----->0x1fb000 */
/* 4>. 4MB----->0x3fb000 */
/* 7. Don't change any other seg. */
MEMORY
{
dport0_0_seg : org = 0x3FF00000, len = 0x10
dram0_0_seg : org = 0x3FFE8000, len = 0x18000
iram1_0_seg : org = 0x40100000, len = 0x8000
irom0_0_seg : org = 0x40220000, len = 0x7C000
}
INCLUDE ../ld/eagle.app.v6.common.ld
@@ -0,0 +1,88 @@
### About
Files in this folder (targets/esp8266) are copied from
`examples/project_template` of `esp_iot_rtos_sdk` and modified for JerryScript.
You can view online from
[this](https://github.com/espressif/esp_iot_rtos_sdk/tree/master/examples/project_template) page.
### How to build JerryScript for ESP8266
#### 1. SDK
Follow [this](./docs/ESP-PREREQUISITES.md) page to setup build environment
#### 2. Building JerryScript
```
# assume you are in jerryscript folder
make -f ./targets/esp8266/Makefile.esp8266
```
Output files should be placed at $BIN_PATH
#### 3. Flashing for ESP8266 12E
Follow
[this](http://www.kloppenborg.net/images/blog/esp8266/esp8266-esp12e-specs.pdf) page to get details about this board.
```
make -f ./targets/esp8266/Makefile.esp8266 flash
```
Default USB device is `/dev/ttyUSB0`. If you have different one, give with `USBDEVICE`, like;
```
USBDEVICE=/dev/ttyUSB1 make -f ./targets/esp8266/Makefile.esp8266 flash
```
### 4. Running
* power off
* connect GPIO2 with serial of 470 Ohm + LED and to GND
* power On
LED should blink on and off every second
#### 5. Cleaning
To clean the build result:
```
make -f ./targets/esp8266/Makefile.esp8266 clean
```
To clean the board's flash memory:
```
make -f ./targets/esp8266/Makefile.esp8266 erase_flash
```
### 6. Optimizing initial RAM usage (ESP8266 specific)
The existing open source gcc compiler with Xtensa support stores const(ants) in
the same limited RAM where our code needs to run.
It is possible to force the compiler to store a constant into ROM and also read it from there thus saving RAM.
The only requirement is to add `JERRY_ATTR_CONST_DATA` attribute to your constant.
For example:
```C
static const lit_magic_size_t lit_magic_string_sizes[] =
```
can be modified to
```C
static const lit_magic_size_t lit_magic_string_sizes[] JERRY_ATTR_CONST_DATA =
```
That is already done to some constants in jerry-core. E.g.:
- vm_decode_table
- ecma_property_hashmap_steps
- lit_magic_string_sizes
- unicode_letter_interv_sps
- unicode_letter_interv_len
- unicode_non_letter_ident_
- unicode_letter_chars
@@ -0,0 +1,44 @@
#############################################################
# Required variables for each makefile
# Discard this section from all parent makefiles
# Expected variables (with automatic defaults):
# CSRCS (all "C" files in the dir)
# SUBDIRS (all subdirs with a Makefile)
# GEN_LIBS - list of libs to be generated ()
# GEN_IMAGES - list of images to be generated ()
# COMPONENTS_xxx - a list of libs/objs in the form
# subdir/lib to be extracted and rolled up into
# a generated lib/image xxx.a ()
#
ifndef PDIR
GEN_LIBS = libuser.a
endif
#############################################################
# Configuration i.e. compile options etc.
# Target specific stuff (defines etc.) goes in here!
# Generally values applying to a tree are captured in the
# makefile at its root level - these are then overridden
# for a subtree within the makefile rooted therein
#
#DEFINES +=
#############################################################
# Recursion Magic - Don't touch this!!
#
# Each subtree potentially has an include directory
# corresponding to the common APIs applicable to modules
# rooted at that subtree. Accordingly, the INCLUDE PATH
# of a module can only contain the include directories up
# its parent path, and not its siblings
#
# Required for each makefile to inherit from the parent
#
INCLUDES := $(INCLUDES) -I $(PDIR)include
INCLUDES += -I ./
PDIR := ../$(PDIR)
sinclude $(PDIR)Makefile
@@ -0,0 +1,188 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include "c_types.h"
#include "gpio.h"
#include "jerryscript.h"
#include "jerry_extapi.h"
#define __UNUSED__ __attribute__((unused))
#define DELCARE_HANDLER(NAME) \
static jerry_value_t \
NAME ## _handler (const jerry_value_t function_obj_val __UNUSED__, \
const jerry_value_t this_val __UNUSED__, \
const jerry_value_t args_p[], \
const jerry_length_t args_cnt)
#define REGISTER_HANDLER(NAME) \
register_native_function ( # NAME, NAME ## _handler)
DELCARE_HANDLER(assert) {
if (args_cnt == 1
&& jerry_value_is_boolean (args_p[0])
&& jerry_get_boolean_value (args_p[0]))
{
printf (">> Jerry assert true\r\n");
return jerry_create_boolean (true);
}
printf ("Script assertion failed\n");
exit (JERRY_STANDALONE_EXIT_CODE_FAIL);
return jerry_create_boolean (false);
} /* assert */
DELCARE_HANDLER(print) {
if (args_cnt)
{
for (jerry_length_t cc = 0; cc < args_cnt; cc++)
{
if (jerry_value_is_string (args_p[cc]))
{
jerry_size_t size = jerry_get_utf8_string_size (args_p[0]);
char *buffer;
buffer = (char *) malloc(size + 1);
if(!buffer)
{
// not enough memory for this string.
printf("[<too-long-string>]");
continue;
}
jerry_string_to_utf8_char_buffer (args_p[cc],
(jerry_char_t *) buffer,
size);
*(buffer + size) = 0;
printf("%s ", buffer);
free (buffer);
}
else if (jerry_value_is_number (args_p[cc]))
{
double number = jerry_get_number_value (args_p[cc]);
if ((int) number == number)
{
printf ("%d", (int) number);
}
else
{
char buff[50];
sprintf(buff, "%.10f", number);
printf("%s", buff);
}
}
}
printf ("\r\n");
}
return jerry_create_boolean (true);
} /* print */
DELCARE_HANDLER(gpio_dir) {
if (args_cnt < 2)
{
return jerry_create_boolean (false);
}
int port = (int) jerry_get_number_value (args_p[0]);
int value = (int) jerry_get_number_value (args_p[1]);
if (value)
{
GPIO_AS_OUTPUT(1 << port);
}
else
{
GPIO_AS_INPUT(1 << port);
}
return jerry_create_boolean (true);
} /* gpio_dir */
DELCARE_HANDLER(gpio_set) {
if (args_cnt < 2)
{
return jerry_create_boolean (false);
}
int port = (int) jerry_get_number_value (args_p[0]);
int value = (int) jerry_get_number_value (args_p[1]);
GPIO_OUTPUT_SET(port, value);
return jerry_create_boolean (true);
} /* gpio_set */
DELCARE_HANDLER(gpio_get) {
if (args_cnt < 1)
{
return jerry_create_boolean (false);
}
int port = (int) jerry_get_number_value (args_p[0]);
int value = GPIO_INPUT_GET(port) ? 1 : 0;
return jerry_create_number ((double) value);
} /* gpio_get */
static bool
register_native_function (const char* name,
jerry_external_handler_t handler)
{
jerry_value_t global_obj_val = jerry_get_global_object ();
jerry_value_t reg_func_val = jerry_create_external_function (handler);
bool bok = true;
if (!(jerry_value_is_function (reg_func_val)
&& jerry_value_is_constructor (reg_func_val)))
{
printf ("!!! create_external_function failed !!!\r\n");
jerry_release_value (reg_func_val);
jerry_release_value (global_obj_val);
return false;
}
jerry_value_t prop_name_val = jerry_create_string ((const jerry_char_t *) name);
jerry_value_t res = jerry_set_property (global_obj_val, prop_name_val, reg_func_val);
jerry_release_value (reg_func_val);
jerry_release_value (global_obj_val);
jerry_release_value (prop_name_val);
if (jerry_value_is_error (res))
{
printf ("!!! register_native_function failed: [%s]\r\n", name);
jerry_release_value (res);
return false;
}
jerry_release_value (res);
return true;
} /* register_native_function */
void js_register_functions (void)
{
REGISTER_HANDLER(assert);
REGISTER_HANDLER(print);
REGISTER_HANDLER(gpio_dir);
REGISTER_HANDLER(gpio_set);
REGISTER_HANDLER(gpio_get);
} /* js_register_functions */
@@ -0,0 +1,73 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdarg.h>
#include <sys/time.h>
#include "esp_common.h"
#include "jerryscript-port.h"
/**
* Provide log message implementation for the engine.
*/
void
jerry_port_log (jerry_log_level_t level, /**< log level */
const char *format, /**< format string */
...) /**< parameters */
{
(void) level; /* ignore log level */
va_list args;
va_start (args, format);
vfprintf (stderr, format, args);
va_end (args);
} /* jerry_port_log */
/**
* Provide fatal message implementation for the engine.
*/
void
jerry_port_fatal (jerry_fatal_code_t code)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Jerry Fatal Error!\n");
while (true);
} /* jerry_port_fatal */
/**
* Implementation of jerry_port_get_current_time.
*
* @return current timer's counter value in milliseconds
*/
double
jerry_port_get_current_time (void)
{
uint32_t rtc_time = system_rtc_clock_cali_proc();
return (double) rtc_time;
} /* jerry_port_get_current_time */
/**
* Dummy function to get the time zone adjustment.
*
* @return 0
*/
double
jerry_port_get_local_time_zone_adjustment (double unix_ms, bool is_utc)
{
/* We live in UTC. */
return 0;
} /* jerry_port_get_local_time_zone_adjustment */
@@ -0,0 +1,100 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include "jerry_extapi.h"
#include "jerry_run.h"
#include "jerryscript.h"
#include "jerryscript-port.h"
static const char* fn_sys_loop_name = "sysloop";
void js_entry ()
{
union { double d; unsigned u; } now = { .d = jerry_port_get_current_time () };
srand (now.u);
jerry_init (JERRY_INIT_EMPTY);
js_register_functions ();
}
int js_eval (const char *source_p, const size_t source_size)
{
jerry_value_t res = jerry_eval ((jerry_char_t *) source_p,
source_size,
JERRY_PARSE_NO_OPTS);
if (jerry_value_is_error (res)) {
jerry_release_value (res);
return -1;
}
jerry_release_value (res);
return 0;
}
int js_loop (uint32_t ticknow)
{
jerry_value_t global_obj_val = jerry_get_global_object ();
jerry_value_t prop_name_val = jerry_create_string ((const jerry_char_t *) fn_sys_loop_name);
jerry_value_t sysloop_func = jerry_get_property (global_obj_val, prop_name_val);
jerry_release_value (prop_name_val);
if (jerry_value_is_error (sysloop_func)) {
printf ("Error: '%s' not defined!!!\r\n", fn_sys_loop_name);
jerry_release_value (sysloop_func);
jerry_release_value (global_obj_val);
return -1;
}
if (!jerry_value_is_function (sysloop_func)) {
printf ("Error: '%s' is not a function!!!\r\n", fn_sys_loop_name);
jerry_release_value (sysloop_func);
jerry_release_value (global_obj_val);
return -2;
}
jerry_value_t val_args[] = { jerry_create_number (ticknow) };
uint16_t val_argv = sizeof (val_args) / sizeof (jerry_value_t);
jerry_value_t res = jerry_call_function (sysloop_func,
global_obj_val,
val_args,
val_argv);
for (uint16_t i = 0; i < val_argv; i++) {
jerry_release_value (val_args[i]);
}
jerry_release_value (sysloop_func);
jerry_release_value (global_obj_val);
if (jerry_value_is_error (res)) {
jerry_release_value (res);
return -3;
}
jerry_release_value (res);
return 0;
}
void js_exit (void)
{
jerry_cleanup ();
}
@@ -0,0 +1,147 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/******************************************************************************
* Copyright 2013-2014 Espressif Systems (Wuxi)
*
* FileName: user_main.c
*
* Description: entry file of user application
*
* Modification history:
* 2014/12/1, v1.0 create this file.
*******************************************************************************/
#include "esp_common.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "uart.h"
#include "user_config.h"
#include "jerry_run.h"
#include "jerry-targetjs.h"
static void show_free_mem(int idx) {
size_t res = xPortGetFreeHeapSize();
printf("dbg free memory(%d): %d\r\n", idx, res);
}
static int jerry_task_init(void) {
DECLARE_JS_CODES;
js_entry();
/* run rest of the js files first */
show_free_mem(2);
for (int src = 1; js_codes[src].source; src++) {
int retcode = js_eval(js_codes[src].source, js_codes[src].length);
if (retcode != 0) {
printf("js_eval failed code(%d) [%s]\r\n", retcode, js_codes[src].name);
return -1;
}
}
/* run main.js */
int retcode = js_eval(js_codes[0].source, js_codes[0].length);
if (retcode != 0) {
printf("js_eval failed code(%d) [%s]\r\n", retcode, js_codes[0].name);
return -2;
}
show_free_mem(3);
return 0;
}
static void jerry_task(void *pvParameters) {
if (jerry_task_init() == 0) {
const portTickType xDelay = 100 / portTICK_RATE_MS;
uint32_t ticknow = 0;
for (;;) {
vTaskDelay(xDelay);
js_loop(ticknow);
if (!ticknow) {
show_free_mem(4);
}
ticknow++;
}
}
js_exit();
}
/*
* This is entry point for user code
*/
void ICACHE_FLASH_ATTR user_init(void)
{
UART_SetBaudrate(UART0, BIT_RATE_115200);
show_free_mem(0);
wifi_softap_dhcps_stop();
show_free_mem(1);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0); // GPIO 0
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); // GPIO 2
xTaskCreate(jerry_task, "jerry", JERRY_STACK_SIZE, NULL, 2, NULL);
}
/*
* FunctionName : user_rf_cal_sector_set
* Description : SDK just reserved 4 sectors, used for rf init data and Parameters.
* We add this function to force users to set rf cal sector, since
* we don't know which sector is free in user's application.
* sector map for last several sectors : ABCCC
* A : rf cal
* B : rf init data
* C : sdk parameters
* Parameters : none
* Returns : rf cal sector
*/
uint32 user_rf_cal_sector_set(void)
{
flash_size_map size_map = system_get_flash_size_map();
uint32 rf_cal_sec = 0;
switch (size_map) {
case FLASH_SIZE_4M_MAP_256_256:
rf_cal_sec = 128 - 5;
break;
case FLASH_SIZE_8M_MAP_512_512:
rf_cal_sec = 256 - 5;
break;
case FLASH_SIZE_16M_MAP_512_512:
case FLASH_SIZE_16M_MAP_1024_1024:
rf_cal_sec = 512 - 5;
break;
case FLASH_SIZE_32M_MAP_512_512:
case FLASH_SIZE_32M_MAP_1024_1024:
rf_cal_sec = 1024 - 5;
break;
case FLASH_SIZE_64M_MAP_1024_1024:
rf_cal_sec = 2048 - 5;
break;
case FLASH_SIZE_128M_MAP_1024_1024:
rf_cal_sec = 4096 - 5;
break;
default:
rf_cal_sec = 0;
break;
}
return rf_cal_sec;
}
@@ -0,0 +1,9 @@
mbed-os
mbed-events
.build
.mbed
.temp/
mbed_settings.py
js/pins.js
source/pins.cpp
source/jerry-targetjs.h
@@ -0,0 +1,94 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# USAGE:
# specify the board using the command line:
# make BOARD=[mbed board name]
BOARD=$(subst [mbed] ,,$(shell mbed target))
HEAPSIZE=16
DEBUG?=0
NO_JS?=0
MBED_VERBOSE?=0
MBED_CLI_FLAGS=-j0 --source . --source ../../
EXTRA_SRC=
ifneq ($(EXTRA_SRC),)
EXTRA_SRC_MOD=--source $(subst :, --source ,$(EXTRA_SRC))
MBED_CLI_FLAGS += $(EXTRA_SRC_MOD)
endif
EXTERN_BUILD_DIR=
ifneq ($(EXTERN_BUILD_DIR),)
MBED_CLI_FLAGS += --build $(EXTERN_BUILD_DIR)
endif
ifeq ($(DEBUG), 1)
MBED_CLI_FLAGS += --profile ./mbed-os/tools/profiles/debug.json
endif
ifeq ($(MBED_VERBOSE), 1)
MBED_CLI_FLAGS += -v
else ifeq ($(MBED_VERBOSE), 2)
MBED_CLI_FLAGS += -vv
endif
MBED_CLI_FLAGS += -D "JERRY_GLOBAL_HEAP_SIZE=$(HEAPSIZE)"
MBED_CLI_FLAGS += -t GCC_ARM
.PHONY: all js2c getlibs rebuild library
all: source/jerry-targetjs.h source/pins.cpp .mbed ../../.mbedignore
mbed target $(BOARD)
mbed compile $(MBED_CLI_FLAGS)
library: .mbed ../../.mbedignore
# delete encoded js code if it exists
rm -f source/jerry-targetjs.h
mbed target $(BOARD)
mbed compile $(MBED_CLI_FLAGS) --library
clean:
rm -rf ./BUILD/$(BOARD)
js2c: js/main.js js/flash_leds.js
python ../../tools/js2c.py --ignore pins.js
source/pins.cpp:
python tools/generate_pins.py ${BOARD}
ifeq ($(NO_JS),0)
source/jerry-targetjs.h: js2c
else
source/jerry-targetjs.h: ;
endif
getlibs: .mbed
.mbed:
echo 'ROOT=.' > .mbed
mbed config root .
mbed toolchain GCC_ARM
mbed target $(BOARD)
mbed deploy
../../.mbedignore:
ifeq ($(OS),Windows_NT)
copy template-mbedignore.txt ..\..\.mbedignore
else
cp ./template-mbedignore.txt ../../.mbedignore
endif
@@ -0,0 +1,40 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Default target for running the build test outside the Travis CI environment.
all:
$(MAKE) install
$(MAKE) script
## Targets for installing build dependencies of the Mbed OS 5 JerryScript target.
# Deploy Mbed and install Mbed Python dependencies.
install:
pip install mbed-cli
cd targets/mbedos5 && mbed deploy
pip install idna==2.5 # FIXME: workaround
pip install -r targets/mbedos5/mbed-os/requirements.txt
pip install -r targets/mbedos5/tools/requirements.txt
## Targets for building Mbed OS 5 with JerryScript.
# Build the firmware (Mbed OS 5 with JerryScript).
script:
# HACK: `EXTRA_SRC[_MOD]` are abused to pass `--library` to `mbed compile` in the `all` make target that builds an app
# HACK: this is needed because the Mbed OS 5 target code does not contain any `main` function, so the `all` make target does not link
# HACK: but the `library` make target does not build either because the launcher sources require `jerry-targetjs.h` that are explicitly not generated for libraries
$(MAKE) -C targets/mbedos5 BOARD=K64F EXTRA_SRC=dummy EXTRA_SRC_MOD=--library
@@ -0,0 +1,74 @@
# JerryScript with mbed OS 5
TL;DR? jump straight to [quickstart](#quick-start)
## Introduction
This directory contains the necessary code to build JerryScript for devices
capable of running mbed OS 5. It has been tested with the following boards
so far:
- [Nordic Semiconductor NRF52 Development Kit](https://developer.mbed.org/platforms/Nordic-nRF52-DK/)
- [NXP Freedom K64F](https://developer.mbed.org/platforms/FRDM-K64F/)
- [STM NUCLEO F401RE](https://developer.mbed.org/platforms/ST-Nucleo-F401RE/)
- [Silicon Labs EFM32 Giant Gecko](https://developer.mbed.org/platforms/EFM32-Giant-Gecko/)
## Features
### Peripheral Drivers
Peripheral Drivers are intended as a 1-to-1 mapping to mbed C++ APIs, with a few
differences (due to differences between JavaScript and C++ like lack of operator
overloading).
- [DigitalOut](https://docs.mbed.com/docs/mbed-os-api-reference/en/5.1/APIs/io/DigitalOut/)
- [InterruptIn](https://docs.mbed.com/docs/mbed-os-api-reference/en/5.1/APIs/io/InterruptIn/)
- [I2C](https://docs.mbed.com/docs/mbed-os-api-reference/en/5.1/APIs/interfaces/digital/I2C/)
- setInterval and setTimeout using [mbed-event](https://github.com/ARMmbed/mbed-events)
## Dependencies
### mbed CLI
mbed CLI is used as the build tool for mbed OS 5. You can find out how to install
it in the [official documentation](https://docs.mbed.com/docs/mbed-os-handbook/en/5.1/dev_tools/cli/#installing-mbed-cli).
### arm-none-eabi-gcc
arm-none-eabi-gcc is the only currently tested compiler for jerryscript on mbed,
and instructions for building can be found as part of the mbed-cli installation
instructions above.
### make
make is used to automate the process of fetching dependencies, and making sure that
mbed-cli is called with the correct arguments.
### nodejs
npm is used to install the dependencies in the local node_modules folder.
### gulp
gulp is used to automate tasks, like cloning repositories or generate source files.
If you create an own project, for more info see [mbed-js-gulp](https://github.com/ARMmbed/mbed-js-gulp).
### (optional) jshint
jshint is used to statically check your JavaScript code, as part of the build process.
This ensures that pins you are using in your code are available on your chosen target
platform.
## Quick Start
Once you have all of your dependencies installed, you can build the example project as follows:
```bash
git clone https://github.com/ARMmbed/mbed-js-example
cd mbed-js-example
npm install
gulp --target=YOUR_TARGET_NAME
```
The produced file (in build/out/YOUR_TARGET_NAME) can then be uploaded to your board, and will
run when you press reset.
@@ -0,0 +1,22 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_ANALOGIN_H
#define _JERRYSCRIPT_MBED_DRIVERS_ANALOGIN_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_CLASS_CONSTRUCTOR(AnalogIn);
#endif // _JERRYSCRIPT_MBED_DRIVERS_ANALOGIN_H
@@ -0,0 +1,22 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_DIGITALOUT_H
#define _JERRYSCRIPT_MBED_DRIVERS_DIGITALOUT_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_CLASS_CONSTRUCTOR(DigitalOut);
#endif // _JERRYSCRIPT_MBED_DRIVERS_DIGITALOUT_H
@@ -0,0 +1,22 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_I2C_H
#define _JERRYSCRIPT_MBED_DRIVERS_I2C_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_CLASS_CONSTRUCTOR(I2C);
#endif // _JERRYSCRIPT_MBED_DRIVERS_I2C_H
@@ -0,0 +1,22 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_INTERRUPTIN_H
#define _JERRYSCRIPT_MBED_DRIVERS_INTERRUPTIN_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_CLASS_CONSTRUCTOR(InterruptIn);
#endif // _JERRYSCRIPT_MBED_DRIVERS_INTERRUPTIN_H
@@ -0,0 +1,22 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_PWMOUT_H
#define _JERRYSCRIPT_MBED_DRIVERS_PWMOUT_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_CLASS_CONSTRUCTOR(PwmOut);
#endif // _JERRYSCRIPT_MBED_DRIVERS_PWMOUT_H
@@ -0,0 +1,42 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_LIB_DRIVERS_H
#define _JERRYSCRIPT_MBED_DRIVERS_LIB_DRIVERS_H
#include "jerryscript-ext/handler.h"
#include "jerryscript-mbed-drivers/InterruptIn-js.h"
#include "jerryscript-mbed-drivers/DigitalOut-js.h"
#include "jerryscript-mbed-drivers/setInterval-js.h"
#include "jerryscript-mbed-drivers/setTimeout-js.h"
#include "jerryscript-mbed-drivers/I2C-js.h"
#include "jerryscript-mbed-drivers/AnalogIn-js.h"
#include "jerryscript-mbed-drivers/PwmOut-js.h"
DECLARE_JS_WRAPPER_REGISTRATION (base) {
REGISTER_GLOBAL_FUNCTION_WITH_HANDLER(assert, jerryx_handler_assert);
REGISTER_GLOBAL_FUNCTION_WITH_HANDLER(gc, jerryx_handler_gc);
REGISTER_GLOBAL_FUNCTION_WITH_HANDLER(print, jerryx_handler_print);
REGISTER_GLOBAL_FUNCTION(setInterval);
REGISTER_GLOBAL_FUNCTION(setTimeout);
REGISTER_GLOBAL_FUNCTION(clearInterval);
REGISTER_GLOBAL_FUNCTION(clearTimeout);
REGISTER_CLASS_CONSTRUCTOR(DigitalOut);
REGISTER_CLASS_CONSTRUCTOR(I2C);
REGISTER_CLASS_CONSTRUCTOR(InterruptIn);
REGISTER_CLASS_CONSTRUCTOR(AnalogIn);
REGISTER_CLASS_CONSTRUCTOR(PwmOut);
}
#endif // _JERRYSCRIPT_MBED_DRIVERS_LIB_DRIVERS_H
@@ -0,0 +1,23 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_SET_INTERVAL_H
#define _JERRYSCRIPT_MBED_DRIVERS_SET_INTERVAL_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_GLOBAL_FUNCTION(setInterval);
DECLARE_GLOBAL_FUNCTION(clearInterval);
#endif // _JERRYSCRIPT_MBED_DRIVERS_SET_INTERVAL_H
@@ -0,0 +1,23 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_DRIVERS_SET_TIMEOUT_H
#define _JERRYSCRIPT_MBED_DRIVERS_SET_TIMEOUT_H
#include "jerryscript-mbed-library-registry/wrap_tools.h"
DECLARE_GLOBAL_FUNCTION(setTimeout);
DECLARE_GLOBAL_FUNCTION(clearTimeout);
#endif // _JERRYSCRIPT_MBED_DRIVERS_SET_TIMEOUT_H
@@ -0,0 +1,112 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-library-registry/wrap_tools.h"
#include "mbed.h"
/**
* AnalogIn#destructor
*
* Called if/when the AnalogIn is GC'ed.
*/
void NAME_FOR_CLASS_NATIVE_DESTRUCTOR(AnalogIn)(void* void_ptr) {
delete static_cast<AnalogIn*>(void_ptr);
}
/**
* Type infomation of the native AnalogIn pointer
*
* Set AnalogIn#destructor as the free callback.
*/
static const jerry_object_native_info_t native_obj_type_info = {
.free_cb = NAME_FOR_CLASS_NATIVE_DESTRUCTOR(AnalogIn)
};
/**
* AnalogIn#read (native JavaScript method)
*
* Read the input voltage, represented as a float in the range [0.0, 1.0]
*
* @returns A floating-point value representing the current input voltage, measured as a percentage
*/
DECLARE_CLASS_FUNCTION(AnalogIn, read) {
CHECK_ARGUMENT_COUNT(AnalogIn, read, (args_count == 0));
// Extract native AnalogIn pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native AnalogIn pointer");
}
AnalogIn* native_ptr = static_cast<AnalogIn*>(void_ptr);
float result = native_ptr->read();
return jerry_create_number(result);
}
/**
* AnalogIn#read_u16 (native JavaScript method)
*
* Read the input voltage, represented as an unsigned short in the range [0x0, 0xFFFF]
*
* @returns 16-bit unsigned short representing the current input voltage, normalised to a 16-bit value
*/
DECLARE_CLASS_FUNCTION(AnalogIn, read_u16) {
CHECK_ARGUMENT_COUNT(AnalogIn, read_u16, (args_count == 0));
// Extract native AnalogIn pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native AnalogIn pointer");
}
AnalogIn* native_ptr = static_cast<AnalogIn*>(void_ptr);
uint16_t result = native_ptr->read_u16();
return jerry_create_number(result);
}
/**
* AnalogIn (native JavaScript constructor)
*
* @param pin_name mbed pin to connect the AnalogIn to.
* @returns a JavaScript object representing a AnalogIn.
*/
DECLARE_CLASS_CONSTRUCTOR(AnalogIn) {
CHECK_ARGUMENT_COUNT(AnalogIn, __constructor, args_count == 1);
CHECK_ARGUMENT_TYPE_ALWAYS(AnalogIn, __constructor, 0, number);
PinName pin_name = PinName(jerry_get_number_value(args[0]));
// create native object
AnalogIn* native_ptr = new AnalogIn(pin_name);
// create the jerryscript object
jerry_value_t js_object = jerry_create_object();
jerry_set_object_native_pointer(js_object, native_ptr, &native_obj_type_info);
// attach methods
ATTACH_CLASS_FUNCTION(js_object, AnalogIn, read);
ATTACH_CLASS_FUNCTION(js_object, AnalogIn, read_u16);
return js_object;
}
@@ -0,0 +1,155 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-library-registry/wrap_tools.h"
#include "mbed.h"
/**
* DigitalOut#destructor
*
* Called if/when the DigitalOut is GC'ed.
*/
void NAME_FOR_CLASS_NATIVE_DESTRUCTOR(DigitalOut)(void* void_ptr) {
delete static_cast<DigitalOut*>(void_ptr);
}
/**
* Type infomation of the native DigitalOut pointer
*
* Set DigitalOut#destructor as the free callback.
*/
static const jerry_object_native_info_t native_obj_type_info = {
.free_cb = NAME_FOR_CLASS_NATIVE_DESTRUCTOR(DigitalOut)
};
/**
* DigitalOut#write (native JavaScript method)
*
* Writes a binary value to a DigitalOut.
*
* @param value 1 or 0, specifying whether the output pin is high or low,
* respectively
* @returns undefined, or an error if invalid arguments are provided.
*/
DECLARE_CLASS_FUNCTION(DigitalOut, write) {
CHECK_ARGUMENT_COUNT(DigitalOut, write, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(DigitalOut, write, 0, number);
// Extract native DigitalOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native DigitalOut pointer");
}
DigitalOut* native_ptr = static_cast<DigitalOut*>(void_ptr);
int arg0 = jerry_get_number_value(args[0]);
native_ptr->write(arg0);
return jerry_create_undefined();
}
/**
* DigitalOut#read (native JavaScript method)
*
* Reads the current status of a DigitalOut
*
* @returns 1 if the pin is currently high, or 0 if the pin is currently low.
*/
DECLARE_CLASS_FUNCTION(DigitalOut, read) {
CHECK_ARGUMENT_COUNT(DigitalOut, read, (args_count == 0));
// Extract native DigitalOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native DigitalOut pointer");
}
DigitalOut* native_ptr = static_cast<DigitalOut*>(void_ptr);
int result = native_ptr->read();
return jerry_create_number(result);
}
/**
* DigitalOut#is_connected (native JavaScript method)
*
* @returns 0 if the DigitalOut is set to NC, or 1 if it is connected to an
* actual pin
*/
DECLARE_CLASS_FUNCTION(DigitalOut, is_connected) {
CHECK_ARGUMENT_COUNT(DigitalOut, is_connected, (args_count == 0));
// Extract native DigitalOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native DigitalOut pointer");
}
DigitalOut* native_ptr = static_cast<DigitalOut*>(void_ptr);
int result = native_ptr->is_connected();
return jerry_create_number(result);
}
/**
* DigitalOut (native JavaScript constructor)
*
* @param pin_name mbed pin to connect the DigitalOut to.
* @param value (optional) Initial value of the DigitalOut.
* @returns a JavaScript object representing a DigitalOut.
*/
DECLARE_CLASS_CONSTRUCTOR(DigitalOut) {
CHECK_ARGUMENT_COUNT(DigitalOut, __constructor, (args_count == 1 || args_count == 2));
CHECK_ARGUMENT_TYPE_ALWAYS(DigitalOut, __constructor, 0, number);
CHECK_ARGUMENT_TYPE_ON_CONDITION(DigitalOut, __constructor, 1, number, (args_count == 2));
DigitalOut* native_ptr;
// Call correct overload of DigitalOut::DigitalOut depending on the
// arguments passed.
PinName pin_name = PinName(jerry_get_number_value(args[0]));
switch (args_count) {
case 1:
native_ptr = new DigitalOut(pin_name);
break;
case 2:
int value = static_cast<int>(jerry_get_number_value(args[1]));
native_ptr = new DigitalOut(pin_name, value);
break;
}
// create the jerryscript object
jerry_value_t js_object = jerry_create_object();
jerry_set_object_native_pointer(js_object, native_ptr, &native_obj_type_info);
// attach methods
ATTACH_CLASS_FUNCTION(js_object, DigitalOut, write);
ATTACH_CLASS_FUNCTION(js_object, DigitalOut, read);
ATTACH_CLASS_FUNCTION(js_object, DigitalOut, is_connected);
return js_object;
}
@@ -0,0 +1,315 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-drivers/I2C-js.h"
#include "jerryscript-mbed-library-registry/wrap_tools.h"
#include "mbed.h"
/**
* I2C#destructor
*
* Called if/when the I2C object is GC'ed.
*/
void NAME_FOR_CLASS_NATIVE_DESTRUCTOR(I2C) (void *void_ptr) {
delete static_cast<I2C*>(void_ptr);
}
/**
* Type infomation of the native I2C pointer
*
* Set I2C#destructor as the free callback.
*/
static const jerry_object_native_info_t native_obj_type_info = {
.free_cb = NAME_FOR_CLASS_NATIVE_DESTRUCTOR(I2C)
};
/**
* I2C#frequency (native JavaScript method)
*
* Set the frequency of the I2C bus.
*
* @param frequency New I2C Frequency
*/
DECLARE_CLASS_FUNCTION(I2C, frequency) {
CHECK_ARGUMENT_COUNT(I2C, frequency, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, frequency, 0, number);
// Unwrap native I2C object
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
int hz = jerry_get_number_value(args[0]);
native_ptr->frequency(hz);
return jerry_create_undefined();
}
/**
* I2C#read (native JavaScript method)
*
* Read data from the I2C bus.
*
* @overload I2C#read(int)
* Read a single byte from the I2C bus
*
* @param ack indicates if the byte is to be acknowledged (1 => acknowledge)
*
* @returns array: Data read from the I2C bus
*
* @overload I2C#read(int, array, int)
* Read a series of bytes from the I2C bus
*
* @param address I2C address to read from
* @param data Array to read into
* @param length Length of data to read
*
* @returns array: Data read from the I2C bus
*/
DECLARE_CLASS_FUNCTION(I2C, read) {
CHECK_ARGUMENT_COUNT(I2C, read, (args_count == 1 || args_count == 3 || args_count == 4));
if (args_count == 1) {
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, read, 0, number);
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
int data = jerry_get_number_value(args[0]);
int result = native_ptr->read(data);
return jerry_create_number(result);
} else {
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, read, 0, number);
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, read, 1, array);
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, read, 2, number);
CHECK_ARGUMENT_TYPE_ON_CONDITION(I2C, read, 3, boolean, (args_count == 4));
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
const uint32_t data_len = jerry_get_array_length(args[1]);
int address = jerry_get_number_value(args[0]);
int length = jerry_get_number_value(args[2]);
char *data = new char[data_len];
bool repeated = false;
if (args_count == 4) {
repeated = jerry_get_boolean_value(args[3]);
}
int result = native_ptr->read(address, data, length, repeated);
jerry_value_t out_array = jerry_create_array(data_len);
for (uint32_t i = 0; i < data_len; i++) {
jerry_value_t val = jerry_create_number(double(data[i]));
jerry_release_value(jerry_set_property_by_index(out_array, i, val));
jerry_release_value(val);
}
delete[] data;
if (result == 0) {
// ACK
return out_array;
} else {
// NACK
const char *error_msg = "NACK received from I2C bus";
jerry_release_value(out_array);
return jerry_create_error(JERRY_ERROR_COMMON, reinterpret_cast<const jerry_char_t *>(error_msg));
}
}
}
/**
* I2C#write (native JavaScript method)
*
* @overload I2C#write(int)
* Write a single byte to the I2C bus
*
* @param data Data byte to write to the I2C bus
*
* @returns 1 on success, 0 on failure
*
* @overload I2C#write(int, array, int, bool)
* Write an array of data to a certain address on the I2C bus
*
* @param address 8-bit I2C slave address
* @param data Array of bytes to send
* @param length Length of data to write
* @param repeated (optional) If true, do not send stop at end.
*
* @returns 0 on success, non-0 on failure
*/
DECLARE_CLASS_FUNCTION(I2C, write) {
CHECK_ARGUMENT_COUNT(I2C, write, (args_count == 1 || args_count == 3 || args_count == 4));
if (args_count == 1) {
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, write, 0, number);
// Extract native I2C object
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
// Unwrap arguments
int data = jerry_get_number_value(args[0]);
int result = native_ptr->write(data);
return jerry_create_number(result);
} else {
// 3 or 4
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, write, 0, number);
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, write, 1, array);
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, write, 2, number);
CHECK_ARGUMENT_TYPE_ON_CONDITION(I2C, write, 3, boolean, (args_count == 4));
// Extract native I2C object
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
// Unwrap arguments
int address = jerry_get_number_value(args[0]);
const uint32_t data_len = jerry_get_array_length(args[1]);
int length = jerry_get_number_value(args[2]);
bool repeated = args_count == 4 && jerry_get_boolean_value(args[3]);
// Construct data byte array
char *data = new char[data_len];
for (uint32_t i = 0; i < data_len; i++) {
data[i] = jerry_get_number_value(jerry_get_property_by_index(args[1], i));
}
int result = native_ptr->write(address, data, length, repeated);
// free dynamically allocated resources
delete[] data;
return jerry_create_number(result);
}
}
/**
* I2C#start (native JavaScript method)
*
* Creates a start condition on the I2C bus.
*/
DECLARE_CLASS_FUNCTION(I2C, start) {
CHECK_ARGUMENT_COUNT(I2C, start, (args_count == 0));
// Extract native I2C object
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
native_ptr->start();
return jerry_create_undefined();
}
/**
* I2C#stop (native JavaScript method)
*
* Creates a stop condition on the I2C bus.
*/
DECLARE_CLASS_FUNCTION(I2C, stop) {
CHECK_ARGUMENT_COUNT(I2C, stop, (args_count == 0));
// Extract native I2C object
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native I2C pointer");
}
I2C *native_ptr = static_cast<I2C*>(void_ptr);
native_ptr->stop();
return jerry_create_undefined();
}
/**
* I2C (native JavaScript constructor)
*
* @param sda mbed pin for I2C data
* @param scl mbed pin for I2C clock
* @returns a JavaScript object representing the I2C bus.
*/
DECLARE_CLASS_CONSTRUCTOR(I2C) {
CHECK_ARGUMENT_COUNT(I2C, __constructor, (args_count == 2));
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, __constructor, 0, number);
CHECK_ARGUMENT_TYPE_ALWAYS(I2C, __constructor, 1, number);
int sda = jerry_get_number_value(args[0]);
int scl = jerry_get_number_value(args[1]);
I2C *native_ptr = new I2C((PinName)sda, (PinName)scl);
jerry_value_t js_object = jerry_create_object();
jerry_set_object_native_pointer(js_object, native_ptr, &native_obj_type_info);
ATTACH_CLASS_FUNCTION(js_object, I2C, frequency);
ATTACH_CLASS_FUNCTION(js_object, I2C, read);
ATTACH_CLASS_FUNCTION(js_object, I2C, write);
ATTACH_CLASS_FUNCTION(js_object, I2C, start);
ATTACH_CLASS_FUNCTION(js_object, I2C, stop);
return js_object;
}
@@ -0,0 +1,268 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-event-loop/EventLoop.h"
#include "jerryscript-mbed-library-registry/wrap_tools.h"
#include "mbed.h"
/**
* InterruptIn#destructor
*
* Called if/when the InterruptIn object is GC'ed.
*/
void NAME_FOR_CLASS_NATIVE_DESTRUCTOR(InterruptIn) (void *void_ptr) {
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
native_ptr->rise(0);
native_ptr->fall(0);
delete native_ptr;
}
/**
* Type infomation of the native InterruptIn pointer
*
* Set InterruptIn#destructor as the free callback.
*/
static const jerry_object_native_info_t native_obj_type_info = {
.free_cb = NAME_FOR_CLASS_NATIVE_DESTRUCTOR(InterruptIn)
};
/**
* InterruptIn#rise (native JavaScript method)
*
* Register a rise callback for an InterruptIn
*
* @param cb Callback function, or null to detach previously attached callback.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, rise) {
CHECK_ARGUMENT_COUNT(InterruptIn, rise, (args_count == 1));
// Detach the rise callback when InterruptIn::rise(null) is called
if (jerry_value_is_null(args[0])) {
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_rise");
jerry_value_t cb_func = jerry_get_property(this_obj, property_name);
jerry_release_value(property_name);
// Only drop the callback if it exists
if (jerry_value_is_function(cb_func)) {
// Ensure that the EventLoop frees memory used by the callback.
mbed::js::EventLoop::getInstance().dropCallback(cb_func);
}
jerry_release_value(cb_func);
native_ptr->rise(0);
return jerry_create_undefined();
}
// Assuming we actually have a callback now...
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, rise, 0, function);
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
jerry_value_t f = args[0];
// Pass the function to EventLoop.
mbed::Callback<void()> cb = mbed::js::EventLoop::getInstance().wrapFunction(f);
native_ptr->rise(cb);
// Keep track of our callback internally.
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_rise");
jerry_release_value(jerry_set_property(this_obj, property_name, f));
jerry_release_value(property_name);
return jerry_create_undefined();
}
/**
* InterruptIn#fall (native JavaScript method)
*
* Register a fall callback for an InterruptIn
*
* @param cb Callback function, or null to detach previously attached callback.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, fall) {
CHECK_ARGUMENT_COUNT(InterruptIn, fall, (args_count == 1));
// Detach the fall callback when InterruptIn::fall(null) is called
if (jerry_value_is_null(args[0])) {
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_fall");
jerry_value_t cb_func = jerry_get_property(this_obj, property_name);
jerry_release_value(property_name);
// Only drop the callback if it exists
if (jerry_value_is_function(cb_func)) {
// Ensure that the EventLoop frees memory used by the callback.
mbed::js::EventLoop::getInstance().dropCallback(cb_func);
}
jerry_release_value(cb_func);
native_ptr->fall(0);
return jerry_create_undefined();
}
// Assuming we actually have a callback now...
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, fall, 0, function);
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
jerry_value_t f = args[0];
// Pass the function to EventLoop.
mbed::Callback<void()> cb = mbed::js::EventLoop::getInstance().wrapFunction(f);
native_ptr->fall(cb);
// Keep track of our callback internally.
jerry_value_t property_name = jerry_create_string((const jerry_char_t*)"cb_fall");
jerry_release_value(jerry_set_property(this_obj, property_name, f));
jerry_release_value(property_name);
return jerry_create_undefined();
}
/**
* InterruptIn#mode (native JavaScript method)
*
* Set the mode of the InterruptIn pin.
*
* @param mode PullUp, PullDown, PullNone
*/
DECLARE_CLASS_FUNCTION(InterruptIn, mode) {
CHECK_ARGUMENT_COUNT(InterruptIn, mode, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, mode, 0, number);
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
int pull = jerry_get_number_value(args[0]);
native_ptr->mode((PinMode)pull);
return jerry_create_undefined();
}
/**
* InterruptIn#disable_irq (native JavaScript method)
*
* Disable IRQ. See InterruptIn.h in mbed-os sources for more details.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, disable_irq) {
CHECK_ARGUMENT_COUNT(InterruptIn, disable_irq, (args_count == 0));
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
native_ptr->disable_irq();
return jerry_create_undefined();
}
/**
* InterruptIn#enable_irq (native JavaScript method)
*
* Enable IRQ. See InterruptIn.h in mbed-os sources for more details.
*/
DECLARE_CLASS_FUNCTION(InterruptIn, enable_irq) {
CHECK_ARGUMENT_COUNT(InterruptIn, enable_irq, (args_count == 0));
void *void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native InterruptIn pointer");
}
InterruptIn *native_ptr = static_cast<InterruptIn*>(void_ptr);
native_ptr->enable_irq();
return jerry_create_undefined();
}
/**
* InterruptIn (native JavaScript constructor)
*
* @param pin PinName
*
* @returns JavaScript object wrapping InterruptIn native object
*/
DECLARE_CLASS_CONSTRUCTOR(InterruptIn) {
CHECK_ARGUMENT_COUNT(InterruptIn, __constructor, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(InterruptIn, __constructor, 0, number);
int pin = jerry_get_number_value(args[0]);
InterruptIn *native_ptr = new InterruptIn((PinName)pin);
jerry_value_t js_object = jerry_create_object();
jerry_set_object_native_pointer(js_object, native_ptr, &native_obj_type_info);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, rise);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, fall);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, mode);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, enable_irq);
ATTACH_CLASS_FUNCTION(js_object, InterruptIn, disable_irq);
return js_object;
}
@@ -0,0 +1,291 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-library-registry/wrap_tools.h"
#include "mbed.h"
/**
* PwmOut#destructor
*
* Called if/when the PwmOut is GC'ed.
*/
void NAME_FOR_CLASS_NATIVE_DESTRUCTOR(PwmOut)(void* void_ptr) {
delete static_cast<PwmOut*>(void_ptr);
}
/**
* Type infomation of the native PwmOut pointer
*
* Set PwmOut#destructor as the free callback.
*/
static const jerry_object_native_info_t native_obj_type_info = {
.free_cb = NAME_FOR_CLASS_NATIVE_DESTRUCTOR(PwmOut)
};
/**
* PwmOut#write (native JavaScript method)
*
* Set the ouput duty-cycle, specified as a percentage (float)
*
* @param value A floating-point value representing the output duty-cycle,
* specified as a percentage. The value should lie between
* 0.0 (representing on 0%) and 1.0 (representing on 100%).
* Values outside this range will be saturated to 0.0f or 1.0f
* @returns undefined
*/
DECLARE_CLASS_FUNCTION(PwmOut, write) {
CHECK_ARGUMENT_COUNT(PwmOut, write, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, write, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->write(static_cast<float>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut#read (native JavaScript method)
*
* Return the current output duty-cycle setting, measured as a percentage (float)
*
* @returns
* A floating-point value representing the current duty-cycle being output on the pin,
* measured as a percentage. The returned value will lie between
* 0.0 (representing on 0%) and 1.0 (representing on 100%).
*
* @note
* This value may not match exactly the value set by a previous <write>.
*/
DECLARE_CLASS_FUNCTION(PwmOut, read) {
CHECK_ARGUMENT_COUNT(PwmOut, read, (args_count == 0));
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
float result = native_ptr->read();
return jerry_create_number(result);
}
/**
* PwmOut#period (native JavaScript method)
*
* Set the PWM period, specified in seconds (float), keeping the duty cycle the same.
*
* @note
* The resolution is currently in microseconds; periods smaller than this
* will be set to zero.
*/
DECLARE_CLASS_FUNCTION(PwmOut, period) {
CHECK_ARGUMENT_COUNT(PwmOut, period, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, period, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->period(static_cast<float>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut#period_ms (native JavaScript method)
*
* Set the PWM period, specified in milli-seconds (int), keeping the duty cycle the same.
*/
DECLARE_CLASS_FUNCTION(PwmOut, period_ms) {
CHECK_ARGUMENT_COUNT(PwmOut, period_ms, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, period_ms, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->period_ms(static_cast<int>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut#period_us (native JavaScript method)
*
* Set the PWM period, specified in micro-seconds (int), keeping the duty cycle the same.
*/
DECLARE_CLASS_FUNCTION(PwmOut, period_us) {
CHECK_ARGUMENT_COUNT(PwmOut, period_us, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, period_us, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->period_us(static_cast<int>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut#pulsewidth (native JavaScript method)
*
* Set the PWM pulsewidth, specified in seconds (float), keeping the period the same.
*/
DECLARE_CLASS_FUNCTION(PwmOut, pulsewidth) {
CHECK_ARGUMENT_COUNT(PwmOut, pulsewidth, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, pulsewidth, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->pulsewidth(static_cast<float>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut#pulsewidth_ms (native JavaScript method)
*
* Set the PWM pulsewidth, specified in milli-seconds (int), keeping the period the same.
*/
DECLARE_CLASS_FUNCTION(PwmOut, pulsewidth_ms) {
CHECK_ARGUMENT_COUNT(PwmOut, pulsewidth_ms, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, pulsewidth_ms, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->pulsewidth_ms(static_cast<int>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut#pulsewidth_us (native JavaScript method)
*
* Set the PWM pulsewidth, specified in micro-seconds (int), keeping the period the same.
*/
DECLARE_CLASS_FUNCTION(PwmOut, pulsewidth_us) {
CHECK_ARGUMENT_COUNT(PwmOut, pulsewidth_us, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, pulsewidth_us, 0, number);
// Extract native PwmOut pointer
void* void_ptr;
bool has_ptr = jerry_get_object_native_pointer(this_obj, &void_ptr, &native_obj_type_info);
if (!has_ptr) {
return jerry_create_error(JERRY_ERROR_TYPE,
(const jerry_char_t *) "Failed to get native PwmOut pointer");
}
PwmOut* native_ptr = static_cast<PwmOut*>(void_ptr);
double arg0 = jerry_get_number_value(args[0]);
native_ptr->pulsewidth_us(static_cast<int>(arg0));
return jerry_create_undefined();
}
/**
* PwmOut (native JavaScript constructor)
*
* @param pin_name mbed pin to connect the PwmOut to.
* @returns a JavaScript object representing a PwmOut.
*/
DECLARE_CLASS_CONSTRUCTOR(PwmOut) {
CHECK_ARGUMENT_COUNT(PwmOut, __constructor, args_count == 1);
CHECK_ARGUMENT_TYPE_ALWAYS(PwmOut, __constructor, 0, number);
PinName pin_name = PinName(jerry_get_number_value(args[0]));
// Create the native object
PwmOut* native_ptr = new PwmOut(pin_name);
// create the jerryscript object
jerry_value_t js_object = jerry_create_object();
jerry_set_object_native_pointer(js_object, native_ptr, &native_obj_type_info);
// attach methods
ATTACH_CLASS_FUNCTION(js_object, PwmOut, write);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, read);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, period);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, period_ms);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, period_us);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, pulsewidth);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, pulsewidth_ms);
ATTACH_CLASS_FUNCTION(js_object, PwmOut, pulsewidth_us);
return js_object;
}
@@ -0,0 +1,73 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-drivers/setInterval-js.h"
#include "jerryscript-mbed-event-loop/EventLoop.h"
/**
* setInterval (native JavaScript function)
*
* Call a JavaScript function at fixed intervals.
*
* @param function Function to call
* @param interval Time between function calls, in ms.
*/
DECLARE_GLOBAL_FUNCTION(setInterval) {
CHECK_ARGUMENT_COUNT(global, setInterval, (args_count == 2));
CHECK_ARGUMENT_TYPE_ALWAYS(global, setInterval, 0, function);
CHECK_ARGUMENT_TYPE_ALWAYS(global, setInterval, 1, number);
int interval = int(jerry_get_number_value(args[1]));
int id = mbed::js::EventLoop::getInstance().getQueue().call_every(interval, jerry_call_function, args[0], jerry_create_null(), (jerry_value_t*)NULL, 0);
jerry_value_t result = jerry_set_property_by_index(function_obj_p, id, args[0]);
if (jerry_value_is_error(result)) {
jerry_release_value(result);
mbed::js::EventLoop::getInstance().getQueue().cancel(id);
return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *) "Failed to run setInterval");
}
jerry_release_value(result);
return jerry_create_number(id);
}
/**
* clearInterval (native JavaScript function)
*
* Cancel an event that was previously scheduled via setInterval.
*
* @param id ID of the timeout event, returned by setInterval.
*/
DECLARE_GLOBAL_FUNCTION(clearInterval) {
CHECK_ARGUMENT_COUNT(global, clearInterval, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(global, clearInterval, 0, number);
int id = int(jerry_get_number_value(args[0]));
mbed::js::EventLoop::getInstance().getQueue().cancel(id);
jerry_value_t global_obj = jerry_get_global_object();
jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)"setInterval");
jerry_value_t func_obj = jerry_get_property(global_obj, prop_name);
jerry_release_value(prop_name);
jerry_delete_property_by_index(func_obj, id);
jerry_release_value(func_obj);
jerry_release_value(global_obj);
return jerry_create_undefined();
}
@@ -0,0 +1,73 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-drivers/setTimeout-js.h"
#include "jerryscript-mbed-event-loop/EventLoop.h"
/**
* setTimeout (native JavaScript function)
*
* Call a JavaScript function once, after a fixed time period.
*
* @param function Function to call
* @param wait_time Time before function is called, in ms.
*/
DECLARE_GLOBAL_FUNCTION(setTimeout) {
CHECK_ARGUMENT_COUNT(global, setTimeout, (args_count == 2));
CHECK_ARGUMENT_TYPE_ALWAYS(global, setTimeout, 0, function);
CHECK_ARGUMENT_TYPE_ALWAYS(global, setTimeout, 1, number);
int interval = int(jerry_get_number_value(args[1]));
int id = mbed::js::EventLoop::getInstance().getQueue().call_in(interval, jerry_call_function, args[0], jerry_create_null(), (jerry_value_t*)NULL, 0);
jerry_value_t result = jerry_set_property_by_index(function_obj_p, id, args[0]);
if (jerry_value_is_error(result)) {
jerry_release_value(result);
mbed::js::EventLoop::getInstance().getQueue().cancel(id);
return jerry_create_error(JERRY_ERROR_TYPE, (const jerry_char_t *) "Failed to run setTimeout");
}
jerry_release_value(result);
return jerry_create_number(id);
}
/**
* clearTimeout (native JavaScript function)
*
* Cancel an event that was previously scheduled via setTimeout.
*
* @param id ID of the timeout event, returned by setTimeout.
*/
DECLARE_GLOBAL_FUNCTION(clearTimeout) {
CHECK_ARGUMENT_COUNT(global, clearTimeout, (args_count == 1));
CHECK_ARGUMENT_TYPE_ALWAYS(global, clearTimeout, 0, number);
int id = int(jerry_get_number_value(args[0]));
mbed::js::EventLoop::getInstance().getQueue().cancel(id);
jerry_value_t global_obj = jerry_get_global_object();
jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)"setTimeout");
jerry_value_t func_obj = jerry_get_property(global_obj, prop_name);
jerry_release_value(prop_name);
jerry_delete_property_by_index(func_obj, id);
jerry_release_value(func_obj);
jerry_release_value(global_obj);
return jerry_create_undefined();
}
@@ -0,0 +1,114 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_EVENT_LOOP_BOUND_CALLBACK_H
#define _JERRYSCRIPT_MBED_EVENT_LOOP_BOUND_CALLBACK_H
#include "Callback.h"
namespace mbed {
namespace js {
template<typename T>
class BoundCallback;
template<typename R, typename A0>
class BoundCallback<R(A0)> {
public:
BoundCallback(Callback<R(A0)> cb, A0 a0) : a0(a0), cb(cb) { }
void call() {
cb(a0);
}
operator Callback<void()>() {
Callback<void()> cb(this, &BoundCallback::call);
return cb;
}
private:
A0 a0;
Callback<R(A0)> cb;
};
template<typename R, typename A0, typename A1>
class BoundCallback<R(A0, A1)> {
public:
BoundCallback(Callback<R(A0, A1)> cb, A0 a0, A1 a1) : a0(a0), a1(a1), cb(cb) { }
void call() {
cb(a0, a1);
}
operator Callback<void()>() {
Callback<void()> cb(this, &BoundCallback::call);
return cb;
}
private:
A0 a0;
A0 a1;
Callback<R(A0, A1)> cb;
};
template<typename R, typename A0, typename A1, typename A2>
class BoundCallback<R(A0, A1, A2)> {
public:
BoundCallback(Callback<R(A0, A1, A2)> cb, A0 a0, A1 a1, A2 a2) : a0(a0), a1(a1), a2(a2), cb(cb) { }
void call() {
cb(a0, a1, a2);
}
operator Callback<void()>() {
Callback<void()> cb(this, &BoundCallback::call);
return cb;
}
private:
A0 a0;
A1 a1;
A2 a2;
Callback<R(A0, A1, A2)> cb;
};
template<typename R, typename A0, typename A1, typename A2, typename A3>
class BoundCallback<R(A0, A1, A2, A3)> {
public:
BoundCallback(Callback<R(A0, A1, A2, A3)> cb, A0 a0, A1 a1, A2 a2, A3 a3) : a0(a0), a1(a1), a2(a2), a3(a3), cb(cb) { }
void call() {
cb(a0, a1, a2, a3);
}
operator Callback<void()>() {
Callback<void()> cb(this, &BoundCallback::call);
return cb;
}
private:
A0 a0;
A1 a1;
A2 a2;
A3 a3;
Callback<R(A0, A1, A2, A3)> cb;
};
} // namespace js
} // namespace mbed
#endif // _JERRYSCRIPT_MBED_EVENT_LOOP_BOUND_CALLBACK_H
@@ -0,0 +1,99 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_EVENT_LOOP_EVENT_LOOP_H
#define _JERRYSCRIPT_MBED_EVENT_LOOP_EVENT_LOOP_H
#include <vector>
#include "jerry-core/include/jerryscript.h"
#include "Callback.h"
#include "mbed_assert.h"
#include "events/EventQueue.h"
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-event-loop/BoundCallback.h"
extern "C" void exit(int return_code);
namespace mbed {
namespace js {
static const uint32_t EVENT_INTERVAL_MS = 1;
class EventLoop {
private:
static EventLoop instance;
public:
static EventLoop& getInstance() {
return instance;
}
void go() {
while (true) {
queue.dispatch();
}
}
Callback<void()> wrapFunction(jerry_value_t f) {
MBED_ASSERT(jerry_value_is_function(f));
// we need to return a callback that'll schedule this
Callback<void(uint32_t)> cb_raw(this, &EventLoop::callback);
BoundCallback<void(uint32_t)> *cb = new BoundCallback<void(uint32_t)>(cb_raw, f);
bound_callbacks.push_back(std::make_pair(f, cb));
return *cb;
}
void dropCallback(jerry_value_t f) {
for (std::vector<std::pair<jerry_value_t, BoundCallback<void(uint32_t)>*> >::iterator it = bound_callbacks.begin(); it != bound_callbacks.end(); it++) {
std::pair<jerry_value_t, BoundCallback<void(uint32_t)>*> element = *it;
if (element.first == f) {
delete element.second;
break;
}
}
}
void callback(jerry_value_t f) {
queue.call(jerry_call_function, f, jerry_create_null(), (const jerry_value_t*)NULL, 0);
}
void nativeCallback(Callback<void()> cb) {
queue.call(cb);
}
events::EventQueue& getQueue() {
return queue;
}
private:
EventLoop() {}
std::vector<std::pair<jerry_value_t, BoundCallback<void(uint32_t)>*> > bound_callbacks;
events::EventQueue queue;
};
void event_loop();
} // namespace js
} // namespace mbed
#endif // _JERRYSCRIPT_MBED_EVENT_LOOP_EVENT_LOOP_H
@@ -0,0 +1,27 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-event-loop/EventLoop.h"
namespace mbed {
namespace js {
EventLoop EventLoop::instance;
void event_loop() {
EventLoop::getInstance().go();
}
} // namespace js
} // namespace mbed
@@ -0,0 +1,21 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_LAUNCHER_LAUNCHER_H
#define _JERRYSCRIPT_MBED_LAUNCHER_LAUNCHER_H
void jsmbed_js_launch(void);
void jsmbed_js_exit(void);
#endif // _JERRYSCRIPT_MBED_LAUNCHER_LAUNCHER_H
@@ -0,0 +1,22 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_LAUNCHER_SETUP_H
#define _JERRYSCRIPT_MBED_LAUNCHER_SETUP_H
#include "jerry-core/include/jerryscript.h"
void jsmbed_js_load_magic_strings(void);
#endif // _JERRYSCRIPT_MBED_LAUNCHER_SETUP_H
@@ -0,0 +1,95 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed.h"
#include "rtos.h"
#include "jerry-core/include/jerryscript.h"
#include "jerry-core/include/jerryscript-port.h"
#include "jerryscript-mbed-event-loop/EventLoop.h"
#include "jerryscript-mbed-util/js_source.h"
#include "jerryscript-mbed-library-registry/registry.h"
#include "jerryscript-mbed-launcher/launcher.h"
#include "jerryscript-mbed-launcher/setup.h"
#include "jerry-targetjs.h"
DECLARE_JS_CODES;
/**
* load_javascript
*
* Parse and run javascript files specified in jerry-targetjs.h
*/
static int load_javascript() {
for (int src = 0; js_codes[src].source; src++) {
LOG_PRINT("running js file %s\r\n", js_codes[src].name);
const jerry_char_t* code = reinterpret_cast<const jerry_char_t*>(js_codes[src].source);
const size_t length = js_codes[src].length;
jerry_value_t parsed_code = jerry_parse(NULL, 0, code, length, JERRY_PARSE_NO_OPTS);
if (jerry_value_is_error(parsed_code)) {
LOG_PRINT_ALWAYS("jerry_parse failed [%s]\r\n", js_codes[src].name);
jerry_release_value(parsed_code);
jsmbed_js_exit();
return -1;
}
jerry_value_t returned_value = jerry_run(parsed_code);
jerry_release_value(parsed_code);
if (jerry_value_is_error(returned_value)) {
LOG_PRINT_ALWAYS("jerry_run failed [%s]\r\n", js_codes[src].name);
jerry_release_value(returned_value);
jsmbed_js_exit();
return -1;
}
jerry_release_value(returned_value);
}
return 0;
}
int jsmbed_js_init() {
union { double d; unsigned u; } now = { .d = jerry_port_get_current_time () };
srand (now.u);
jerry_init_flag_t flags = JERRY_INIT_EMPTY;
jerry_init(flags);
jsmbed_js_load_magic_strings();
mbed::js::LibraryRegistry::getInstance().register_all();
return 0;
}
void jsmbed_js_exit() {
jerry_cleanup();
}
void jsmbed_js_launch() {
jsmbed_js_init();
puts(" JerryScript in mbed\r\n");
puts(" build date: " __DATE__ " \r\n");
if (load_javascript() == 0) {
mbed::js::event_loop();
}
}
@@ -0,0 +1,49 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include "jerryscript-mbed-launcher/setup.h"
#include "jerryscript-mbed-util/logging.h"
extern uint32_t jsmbed_js_magic_string_count;
extern uint32_t jsmbed_js_magic_string_values[];
extern const jerry_char_t *jsmbed_js_magic_strings[];
extern const jerry_length_t jsmbed_js_magic_string_lengths[];
void jsmbed_js_load_magic_strings() {
if (jsmbed_js_magic_string_count == 0) {
return;
}
jerry_register_magic_strings(jsmbed_js_magic_strings,
jsmbed_js_magic_string_count,
jsmbed_js_magic_string_lengths);
jerry_value_t global = jerry_get_global_object();
for (unsigned int idx = 0; idx < jsmbed_js_magic_string_count; idx++) {
jerry_value_t constant_value = jerry_create_number(jsmbed_js_magic_string_values[idx]);
jerry_value_t magic_string = jerry_create_string(jsmbed_js_magic_strings[idx]);
jerry_release_value(jerry_set_property(global, magic_string, constant_value));
jerry_release_value(constant_value);
jerry_release_value(magic_string);
}
jerry_release_value(global);
}
@@ -0,0 +1,57 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_LIBRARY_REGISTRY_REGISTRY_H
#define _JERRYSCRIPT_MBED_LIBRARY_REGISTRY_REGISTRY_H
#include <vector>
#include "stdint.h"
#define JERRY_USE_MBED_LIBRARY(NAME) \
mbed::js::LibraryRegistry::getInstance().add(jsmbed_wrap_registry_entry__ ## NAME)
namespace mbed {
namespace js {
typedef void (*library_registration_function_t)(void);
class LibraryRegistry {
private:
static LibraryRegistry instance;
public:
static LibraryRegistry& getInstance() {
return instance;
}
void add(library_registration_function_t lib_func) {
funcs.push_back(lib_func);
}
void register_all() {
for (std::size_t i = 0; i < funcs.size(); i++) {
funcs[i]();
}
}
private:
LibraryRegistry() {}
std::vector<library_registration_function_t> funcs;
};
} // namespace js
} // namespace mbed
#endif // _JERRYSCRIPT_MBED_LIBRARY_REGISTRY_REGISTRY_H
@@ -0,0 +1,17 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "jerryscript-mbed-library-registry/registry.h"
mbed::js::LibraryRegistry mbed::js::LibraryRegistry::instance;
@@ -0,0 +1,77 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <stdio.h>
#include "jerryscript-mbed-library-registry/wrap_tools.h"
bool jsmbed_wrap_register_global_function(const char* name, jerry_external_handler_t handler) {
jerry_value_t global_object_val = jerry_get_global_object();
jerry_value_t reg_function = jerry_create_external_function(handler);
bool is_ok = true;
if (!(jerry_value_is_function(reg_function)
&& jerry_value_is_constructor(reg_function))) {
is_ok = false;
LOG_PRINT_ALWAYS("Error: jerry_create_external_function failed!\r\n");
jerry_release_value(global_object_val);
jerry_release_value(reg_function);
return is_ok;
}
if (jerry_value_is_error(reg_function)) {
is_ok = false;
LOG_PRINT_ALWAYS("Error: jerry_create_external_function has error flag! \r\n");
jerry_release_value(global_object_val);
jerry_release_value(reg_function);
return is_ok;
}
jerry_value_t jerry_name = jerry_create_string((jerry_char_t *) name);
jerry_value_t set_result = jerry_set_property(global_object_val, jerry_name, reg_function);
if (jerry_value_is_error(set_result)) {
is_ok = false;
LOG_PRINT_ALWAYS("Error: jerry_create_external_function failed: [%s]\r\n", name);
}
jerry_release_value(jerry_name);
jerry_release_value(global_object_val);
jerry_release_value(reg_function);
jerry_release_value(set_result);
return is_ok;
}
bool jsmbed_wrap_register_class_constructor(const char* name, jerry_external_handler_t handler) {
// Register class constructor as a global function
return jsmbed_wrap_register_global_function(name, handler);
}
bool jsmbed_wrap_register_class_function(jerry_value_t this_obj, const char* name, jerry_external_handler_t handler) {
jerry_value_t property_name = jerry_create_string(reinterpret_cast<const jerry_char_t *>(name));
jerry_value_t handler_obj = jerry_create_external_function(handler);
jerry_release_value(jerry_set_property(this_obj, property_name, handler_obj));
jerry_release_value(handler_obj);
jerry_release_value(property_name);
// TODO: check for errors, and return false in the case of errors
return true;
}
@@ -0,0 +1,43 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_LIBRARY_REGISTRY_WRAP_TOOLS_H
#define _JERRYSCRIPT_MBED_LIBRARY_REGISTRY_WRAP_TOOLS_H
#include <stdlib.h>
#include "jerry-core/include/jerryscript.h"
#include "jerryscript-mbed-util/logging.h"
#include "jerryscript-mbed-util/wrappers.h"
//
// Functions used by the wrapper registration API.
//
bool
jsmbed_wrap_register_global_function (const char* name,
jerry_external_handler_t handler);
bool
jsmbed_wrap_register_class_constructor (const char* name,
jerry_external_handler_t handler);
bool
jsmbed_wrap_register_class_function (jerry_value_t this_obj_p,
const char* name,
jerry_external_handler_t handler);
#endif // _JERRYSCRIPT_MBED_LIBRARY_REGISTRY_WRAP_TOOLS_H
@@ -0,0 +1,24 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_UTIL_JS_SOURCE_H
#define _JERRYSCRIPT_MBED_UTIL_JS_SOURCE_H
struct jsmbed_js_source_t {
const char* name;
const char* source;
const int length;
};
#endif // _JERRYSCRIPT_MBED_UTIL_JS_SOURCE_H
@@ -0,0 +1,28 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_UTIL_LOGGING_H
#define _JERRYSCRIPT_MBED_UTIL_LOGGING_H
#include "mbed.h"
#ifdef DEBUG_WRAPPER
#define LOG_PRINT(...) printf(__VA_ARGS__)
#else
#define LOG_PRINT(...) while(0) { }
#endif
#define LOG_PRINT_ALWAYS(...) printf(__VA_ARGS__)
#endif // _JERRYSCRIPT_MBED_UTIL_LOGGING_H
@@ -0,0 +1,96 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _JERRYSCRIPT_MBED_UTIL_WRAPPERS_H
#define _JERRYSCRIPT_MBED_UTIL_WRAPPERS_H
/*
* Used in header/source files for wrappers, to declare the signature of the
* registration function.
*/
#define DECLARE_JS_WRAPPER_REGISTRATION(NAME) \
void jsmbed_wrap_registry_entry__ ## NAME (void)
//
// 2. Wrapper function declaration/use macros
//
// Global functions
#define DECLARE_GLOBAL_FUNCTION(NAME) \
jerry_value_t \
NAME_FOR_GLOBAL_FUNCTION(NAME) (const jerry_value_t function_obj_p, \
const jerry_value_t this_obj, \
const jerry_value_t args[], \
const jerry_length_t args_count)
#define REGISTER_GLOBAL_FUNCTION(NAME) \
jsmbed_wrap_register_global_function ( # NAME, NAME_FOR_GLOBAL_FUNCTION(NAME) )
#define REGISTER_GLOBAL_FUNCTION_WITH_HANDLER(NAME, HANDLER) \
jsmbed_wrap_register_global_function ( # NAME, HANDLER )
// Class constructors
#define DECLARE_CLASS_CONSTRUCTOR(CLASS) \
jerry_value_t \
NAME_FOR_CLASS_CONSTRUCTOR(CLASS) (const jerry_value_t function_obj, \
const jerry_value_t this_obj, \
const jerry_value_t args[], \
const jerry_length_t args_count)
#define REGISTER_CLASS_CONSTRUCTOR(CLASS) \
jsmbed_wrap_register_class_constructor ( # CLASS, NAME_FOR_CLASS_CONSTRUCTOR(CLASS) )
// Class functions
#define DECLARE_CLASS_FUNCTION(CLASS, NAME) \
jerry_value_t \
NAME_FOR_CLASS_FUNCTION(CLASS, NAME) (const jerry_value_t function_obj, \
const jerry_value_t this_obj, \
const jerry_value_t args[], \
const jerry_length_t args_count)
#define ATTACH_CLASS_FUNCTION(OBJECT, CLASS, NAME) \
jsmbed_wrap_register_class_function (OBJECT, # NAME, NAME_FOR_CLASS_FUNCTION(CLASS, NAME) )
//
// 3. Argument checking macros
//
#define CHECK_ARGUMENT_COUNT(CLASS, NAME, EXPR) \
if (!(EXPR)) { \
const char* error_msg = "ERROR: wrong argument count for " # CLASS "." # NAME ", expected " # EXPR "."; \
return jerry_create_error(JERRY_ERROR_TYPE, reinterpret_cast<const jerry_char_t*>(error_msg)); \
}
#define CHECK_ARGUMENT_TYPE_ALWAYS(CLASS, NAME, INDEX, TYPE) \
if (!jerry_value_is_ ## TYPE (args[INDEX])) { \
const char* error_msg = "ERROR: wrong argument type for " # CLASS "." # NAME ", expected argument " # INDEX " to be a " # TYPE ".\n"; \
return jerry_create_error(JERRY_ERROR_TYPE, reinterpret_cast<const jerry_char_t*>(error_msg)); \
}
#define CHECK_ARGUMENT_TYPE_ON_CONDITION(CLASS, NAME, INDEX, TYPE, EXPR) \
if ((EXPR)) { \
if (!jerry_value_is_ ## TYPE (args[INDEX])) { \
const char* error_msg = "ERROR: wrong argument type for " # CLASS "." # NAME ", expected argument " # INDEX " to be a " # TYPE ".\n"; \
return jerry_create_error(JERRY_ERROR_TYPE, reinterpret_cast<const jerry_char_t*>(error_msg)); \
} \
}
#define NAME_FOR_GLOBAL_FUNCTION(NAME) __gen_jsmbed_global_func_ ## NAME
#define NAME_FOR_CLASS_CONSTRUCTOR(CLASS) __gen_jsmbed_class_constructor_ ## CLASS
#define NAME_FOR_CLASS_FUNCTION(CLASS, NAME) __gen_jsmbed_func_c_ ## CLASS ## _f_ ## NAME
#define NAME_FOR_CLASS_NATIVE_CONSTRUCTOR(CLASS, TYPELIST) __gen_native_jsmbed_ ## CLASS ## __Special_create_ ## TYPELIST
#define NAME_FOR_CLASS_NATIVE_DESTRUCTOR(CLASS) __gen_native_jsmbed_ ## CLASS ## __Special_destroy
#define NAME_FOR_CLASS_NATIVE_FUNCTION(CLASS, NAME) __gen_native_jsmbed_ ## CLASS ## _ ## NAME
#endif // _JERRYSCRIPT_MBED_UTIL_WRAPPERS_H
@@ -0,0 +1,76 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var led = 0;
// Setting the pin to 0 turns the LED on
var led_off = 1;
var led_on = 0;
var digital_outs = [];
var leds = [LED1, LED2, LED3, LED4];
function connect_pins() {
print("Creating new DigitalOuts");
digital_outs = [];
for (var i = 0; i < 4; i++) {
digital_outs.push(DigitalOut(leds[i], led_off));
if (digital_outs[i].is_connected()) {
print("LED " + i + " is connected.");
}
else {
print("LED " + i + " is not connected.");
}
}
}
connect_pins();
function blink() {
digital_outs[0].write(led_off);
digital_outs[1].write(led_off);
digital_outs[2].write(led_off);
digital_outs[3].write(led_off);
digital_outs[led].write(led_on);
print("Finished with LED " + led);
led = (led + 1) % 4;
}
// BUTTON2 on NRF52
// USER_BUTTON on NUCLEO
// SW2 on the K64F
// BTN0 on EFM32GG
var button;
/* global BUTTON2, SW2, USER_BUTTON, BTN0 */
if (typeof BUTTON2 !== 'undefined') {
button = InterruptIn(BUTTON2);
} else if (typeof SW2 !== 'undefined') {
button = InterruptIn(SW2);
} else if (typeof USER_BUTTON !== 'undefined') {
button = InterruptIn(USER_BUTTON);
} else if (typeof BTN0 !== 'undefined') {
button = InterruptIn(BTN0);
} else {
print("no button specified");
}
button.fall(function() {
print("YOU PUSHED THE BUTTON!");
});
print("flash_leds.js has finished executing.");
@@ -0,0 +1,20 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
setInterval(function() {
blink();
}, 1000);
print("main.js has finished executing.");
@@ -0,0 +1 @@
https://github.com/ARMmbed/mbed-os/#e4b81f67f939a0c0b11c147ce74aa367271e1279
@@ -0,0 +1,7 @@
{
"target_overrides": {
"NRF52_DK": {
"target.uart_hwfc": 0
}
}
}
@@ -0,0 +1,92 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _BSD_SOURCE
#include <stdarg.h>
#include <stdlib.h>
#include <sys/time.h>
#include "jerry-core/include/jerryscript-port.h"
#include "us_ticker_api.h"
#ifndef JSMBED_OVERRIDE_JERRY_PORT_LOG
/**
* Provide log message implementation for the engine.
*/
void
jerry_port_log (jerry_log_level_t level, /**< log level */
const char *format, /**< format string */
...) /**< parameters */
{
(void) level; /* ignore log level */
va_list args;
va_start (args, format);
vfprintf (stderr, format, args);
va_end (args);
if (strlen (format) == 1 && format[0] == 0x0a) /* line feed (\n) */
{
printf ("\r"); /* add CR for proper display in serial monitors */
}
} /* jerry_port_log */
#endif /* JSMBED_OVERRIDE_JERRY_PORT_LOG */
/**
* Implementation of jerry_port_get_local_time_zone_adjustment.
*
* @return 0, as we live in UTC.
*/
double
jerry_port_get_local_time_zone_adjustment (double unix_ms, bool is_utc)
{
return 0;
} /* jerry_port_get_local_time_zone_adjustment */
/**
* Implementation of jerry_port_get_current_time.
*
* @return current timer's counter value in milliseconds
*/
double
jerry_port_get_current_time (void)
{
static uint64_t last_tick = 0;
static time_t last_time = 0;
static uint32_t skew = 0;
uint64_t curr_tick = us_ticker_read (); /* The value is in microseconds. */
time_t curr_time = time(NULL); /* The value is in seconds. */
double result = curr_time * 1000;
/* The us_ticker_read () has an overflow for each UINT_MAX microseconds
* (~71 mins). For each overflow event the ticker-based clock is about 33
* milliseconds fast. Without a timer thread the milliseconds part of the
* time can be corrected if the difference of two get_current_time calls
* are within the mentioned 71 mins. Above that interval we can assume
* that the milliseconds part of the time is negligibe.
*/
if (curr_time - last_time > (time_t) (((uint32_t) - 1) / 1000000)) {
skew = 0;
} else if (last_tick > curr_tick) {
skew = (skew + 33) % 1000;
}
result += (curr_tick / 1000 - skew) % 1000;
last_tick = curr_tick;
last_time = curr_time;
return result;
} /* jerry_port_get_current_time */
@@ -0,0 +1,10 @@
cmake/*
docs/*
jerry-main/*
jerry-math/*
jerry-port/default/default-date.c
jerry-port/default/default-io.c
targets/*
tests/*
third-party/*
tools/*
@@ -0,0 +1,31 @@
#!/bin/bash
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# If we're checking only for global variable definitions of pins, then
# file ordering doesn't matter. This is because:
#
# var a = b;
# var b = 7;
#
# will be accepted by jshint, just 'a' will evaluate to 'undefined'.
# Awkward, but at least it means we can have pins.js included at any
# point in the clump of files and it won't give us false positives.
cat js/*.js | jshint -c tools/jshint.conf - | grep "not defined"
if [ "$?" == 0 ]; then
exit 1
fi
exit 0
@@ -0,0 +1,17 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is intentionally blank, and is used as a dummy cmsis.h file
* when preprocessing generate_pins.py.
*/
@@ -0,0 +1,221 @@
#!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Generate pins.cpp for a specified target, using target definitions from the
mbed OS source tree.
It's expecting to be run from the targets/mbedos5 directory.
"""
from __future__ import print_function
import argparse
import ast
import sys
import os
from pycparserext.ext_c_parser import GnuCParser
from pycparser import parse_file, c_ast
# import mbed tools
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'mbed-os'))
from tools.targets import Target
LICENSE = '''/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the \"License\");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an \"AS IS\" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is generated by generate_pins.py. Please do not modify.
*/
'''
def find_file(root_dir, directories, name):
"""
Find the first instance of file with name 'name' in the directory tree
starting with 'root_dir'.
Filter out directories that are not in directories, or do not start with
TARGET_.
Since this looks in (essentially )the same directories as the compiler would
when compiling mbed OS, we should only find one PinNames.h.
"""
for root, dirs, files in os.walk(root_dir, topdown=True):
# modify dirs in place
dirs[:] = [directory for directory in dirs if directory in directories or not directory.startswith('TARGET_')]
if name in files:
return os.path.join(root, name)
def enumerate_includes(root_dir, directories):
"""
Walk through the directory tree, starting at root_dir, and enumerate all
valid include directories.
"""
for root, dirs, _ in os.walk(root_dir, topdown=True):
# modify dirs in place
dirs[:] = [dir_label for dir_label in dirs
if dir_label in directories
or (not dir_label.startswith('TARGET_')
and not dir_label.startswith('TOOLCHAIN_'))]
yield root
class TypeDeclVisitor(c_ast.NodeVisitor):
"""
A TypeDecl visitor class that walks the ast and calls a visitor function for every node found.
"""
def __init__(self, filter_names=None):
self.names = filter_names or []
def visit(self, node):
value = None
if node.__class__.__name__ == "TypeDecl":
value = self.visit_typedecl(node)
if value is None:
for _, child_node in node.children():
value = value or self.visit(child_node)
return value
def visit_typedecl(self, node):
"""
Visit a node.
"""
if node.declname in self.names:
return [pin.name for pin in node.type.values.enumerators]
def enumerate_pins(c_source_file, include_dirs, definitions):
"""
Enumerate pins specified in PinNames.h, by looking for a PinName enum
typedef somewhere in the file.
"""
definitions += ['__attribute(x)__=', '__extension__(x)=', 'register=', '__IO=', 'uint32_t=unsigned int']
gcc_args = ['-E', '-fmerge-all-constants']
gcc_args += ['-I' + directory for directory in include_dirs]
gcc_args += ['-D' + definition for definition in definitions]
parsed_ast = parse_file(c_source_file,
use_cpp=True,
cpp_path='arm-none-eabi-gcc',
cpp_args=gcc_args,
parser=GnuCParser())
# now, walk the AST
visitor = TypeDeclVisitor(['PinName'])
return visitor.visit(parsed_ast)
def write_pins_to_file(pins, pins_file, out_cpp_file):
"""
Write the generated pins for a specified mbed board into the output C++ file.
"""
include = '\n#include "../{}"'.format(pins_file)
count = '''
unsigned int jsmbed_js_magic_string_count = {};
'''.format(len(pins))
lengths = ',\n '.join(str(len(pin)) for pin in pins)
lenghts_source = '''
unsigned int jsmbed_js_magic_string_lengths[] = {
%s
};
''' % lengths
magic_values = ',\n '.join(pins)
magic_source = '''
int jsmbed_js_magic_string_values[] = {
%s
};
''' % magic_values
magic_strings = ',\n '.join('"' + pin + '"' for pin in pins)
magic_string_source = '''
const char * jsmbed_js_magic_strings[] = {
%s
};
''' % magic_strings
out_cpp_file.write(LICENSE + include + count + lenghts_source + magic_source + magic_string_source)
def main():
"""
Perform the main function of this program
"""
if not os.path.exists('./mbed-os'):
print("Fatal: mbed-os directory does not exist.")
print("Try running 'make getlibs'")
sys.exit(1)
description = """
Generate pins.cpp for a specified mbed board, using target definitions from the
mbed OS source tree.
"""
parser = argparse.ArgumentParser(description=description)
parser.add_argument('board', help='mbed board name')
parser.add_argument('-c',
help='Output C++ file (default: %(default)s)',
default='source/pins.cpp',
type=argparse.FileType('w'))
args = parser.parse_args()
board_name = args.board.upper()
target = Target.get_target(board_name)
directory_labels = ['TARGET_' + label for label in target.labels] + target.macros
targets_dir = os.path.join('.', 'mbed-os', 'targets')
pins_file = find_file(targets_dir, directory_labels, 'PinNames.h')
includes = enumerate_includes(targets_dir, directory_labels)
defines = list(directory_labels)
# enumerate pins from PinNames.h
pins = enumerate_pins(pins_file, ['./tools'] + list(includes), defines)
# first sort alphabetically, then by length.
pins = sorted(pins, key=lambda x: (len(x), x.lower()))
write_pins_to_file(pins, pins_file, args.c)
if __name__ == "__main__":
main()
@@ -0,0 +1,4 @@
{
"undef": true,
"predef": ["print", "BLEDevice", "BLEService", "BLECharacteristic", "DigitalOut", "I2C", "setInterval", "setTimeout", "InterruptIn", "LWIPInterface", "SimpleMbedClient", "M2MBase"]
}
@@ -0,0 +1,2 @@
pycparserext
simpleeval
@@ -0,0 +1,7 @@
# Files generated / copied by the NuttX build
.built
.depend
Make.dep
*.c.obj
*.o
*.a
@@ -0,0 +1,30 @@
#
# For a description of the syntax of this configuration file,
# see the file kconfig-language.txt in the NuttX tools repository.
#
config JERRYSCRIPT
bool "Jerryscript"
default n
---help---
Enable Jerryscript ECMAScript 5.1 interpreter
if JERRYSCRIPT
config JERRYSCRIPT_PROGNAME
string "Program name"
default "jerry"
depends on BUILD_KERNEL
---help---
This is the name of the program that will be
use when the NSH ELF program is installed.
config JERRYSCRIPT_PRIORITY
int "Jerryscript task priority"
default 100
config JERRYSCRIPT_STACKSIZE
int "Jerryscript stack size"
default 16384
endif # JERRYSCRIPT
@@ -0,0 +1,17 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
ifeq ($(CONFIG_JERRYSCRIPT),y)
CONFIGURED_APPS += interpreters/jerryscript
endif
@@ -0,0 +1,62 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-include $(TOPDIR)/Make.defs
# Jerryscript built-in application information.
CONFIG_JERRYSCRIPT_PRIORITY ?= SCHED_PRIORITY_DEFAULT
CONFIG_JERRYSCRIPT_PROGNAME ?= jerry$(EXEEXT)
CONFIG_JERRYSCRIPT_STACKSIZE ?= 16384
PROGNAME = $(CONFIG_JERRYSCRIPT_PROGNAME)
PRIORITY = $(CONFIG_JERRYSCRIPT_PRIORITY)
STACKSIZE = $(CONFIG_JERRYSCRIPT_STACKSIZE)
# Path to the JerryScript project. If not specified, it is supposed
# that JerryScript is located next to the nuttx-apps folder.
JERRYSCRIPT_ROOT_DIR ?= ../../../jerryscript
CFLAGS += -std=c99
CFLAGS += -I$(JERRYSCRIPT_ROOT_DIR)/jerry-core/include
CFLAGS += -I$(JERRYSCRIPT_ROOT_DIR)/jerry-ext/include
CFLAGS += -I$(JERRYSCRIPT_ROOT_DIR)/jerry-math/include
# These libs should be copied from the JerryScript project.
LIBS = libjerry-core.a libjerry-ext.a libjerry-math.a
APPNAME = jerry
ASRCS = setjmp.S
CSRCS = jerry_port.c
MAINSRC = jerry_main.c
.PHONY: copylibs
copylibs:
cp $(JERRYSCRIPT_ROOT_DIR)/build/lib/lib*.a .
$(LIBS): copylibs
$(firstword $(AR)) x $@
.PHONY: updateobjs
updateobjs:
$(eval OBJS += $(shell find . -name "*.obj"))
.PHONY: cleanlibs
cleanlibs: updateobjs
rm -f $(OBJS)
clean:: cleanlibs
.built: $(LIBS) updateobjs
include $(APPDIR)/Application.mk
@@ -0,0 +1,70 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Default target for running the build test outside the Travis CI environment.
all:
$(MAKE) install
$(MAKE) script
## Targets for installing build dependencies of the NuttX JerryScript target.
# Install cross-compiler and tools via apt.
install-apt-get-deps:
sudo apt-get install -q -y gcc-arm-none-eabi gperf
# Fetch and build kconfig-frontends (kconfig-conf) from nuttx/tools.
LOCAL_INSTALL:=$(CURDIR)/../local/
install-kconfig:
git clone https://bitbucket.org/nuttx/tools.git ../tools
mkdir -p $(LOCAL_INSTALL)
# FIXME: 'autoreconf --force --install' is a workaround after
# https://bitbucket.org/nuttx/tools/commits/164450f982b404fdc2b3233db51dc3eaa1f08b7f
cd ../tools/kconfig-frontends && autoreconf --force --install && ./configure --disable-mconf --disable-nconf --disable-gconf --disable-qconf --disable-shared --enable-static --prefix=$(LOCAL_INSTALL)
$(MAKE) -C ../tools/kconfig-frontends
$(MAKE) -C ../tools/kconfig-frontends install
# Fetch nuttx/{apps,nuttx} repositories.
install-clone-nuttx:
git clone https://github.com/apache/incubator-nuttx-apps.git ../apps -b releases/9.0
git clone https://github.com/apache/incubator-nuttx.git ../nuttx -b releases/9.0
# Perform all the necessary (JerryScript-independent) installation steps.
install-noapt: install-kconfig install-clone-nuttx
install: install-apt-get-deps install-noapt
## Targets for building NuttX with JerryScript.
# Build JerryScript.
script-build-jerryscript:
tools/build.py --clean --toolchain cmake/toolchain_mcu_stm32f4.cmake --profile=es.next --jerry-cmdline OFF --lto OFF --jerry-math ON --amalgam ON --jerry-port-default OFF --mem-heap 70 --compile-flag='--sysroot=../nuttx'
# Link in the NuttX JerryScript target directory under the NuttX apps tree.
script-add-jerryscript-app:
ln -s ../../jerryscript/targets/nuttx-stm32f4 ../apps/interpreters/jerryscript
# Configure USB shell.
script-configure-usbnsh:
cd ../nuttx/tools && PATH=$(LOCAL_INSTALL)/bin:$$PATH ./configure.sh stm32f4discovery/usbnsh
# Configure and build the firmware (NuttX with JerryScript).
script: script-build-jerryscript script-add-jerryscript-app script-configure-usbnsh
echo 'CONFIG_HOST_LINUX=y' >> ../nuttx/.config
echo 'CONFIG_ARCH_FPU=y' >> ../nuttx/.config
echo 'CONFIG_JERRYSCRIPT=y'>> ../nuttx/.config
PATH=$(LOCAL_INSTALL)/bin:$$PATH $(MAKE) -C ../nuttx olddefconfig
PATH=$(LOCAL_INSTALL)/bin:$$PATH $(MAKE) -C ../nuttx
@@ -0,0 +1,186 @@
### About
This folder contains files to run JerryScript on
[STM32F4-Discovery board](http://www.st.com/content/st_com/en/products/evaluation-tools/product-evaluation-tools/mcu-eval-tools/stm32-mcu-eval-tools/stm32-mcu-discovery-kits/stm32f4discovery.html) with [NuttX](http://nuttx.org/)
### How to build
#### 1. Setup the build environment for STM32F4-Discovery board
Clone the necessary projects into a `jerry-nuttx` directory. The last tested working version of NuttX is 9.0.
```sh
# Create a base folder for all the projects.
mkdir jerry-nuttx && cd jerry-nuttx
git clone https://github.com/jerryscript-project/jerryscript.git
git clone https://bitbucket.org/nuttx/nuttx.git -b releases/9.0
git clone https://bitbucket.org/nuttx/apps.git -b releases/9.0
git clone https://github.com/texane/stlink.git -b v1.5.1-patch
```
The following directory structure is created after these commands:
```
jerry-nuttx
+ apps
+ jerryscript
| + targets
| + nuttx-stm32f4
+ nuttx
+ stlink
```
#### 2. Build JerryScript for NuttX
Build JerryScript as a static library using the NuttX folder as sysroot. The created static libraries will be used later by NuttX.
```sh
# Assuming you are in jerry-nuttx folder.
jerryscript/tools/build.py \
--clean \
--lto=OFF \
--jerry-cmdline=OFF \
--jerry-math=ON \
--amalgam=ON \
--mem-heap=70 \
--profile=es.next \
--compile-flag="--sysroot=${PWD}/nuttx" \
--toolchain=${PWD}/jerryscript/cmake/toolchain_mcu_stm32f4.cmake
```
#### 3. Copy JerryScript's application files to NuttX
After creating the static libs (see previous step), it is needed to move the JerryScript application files to the NuttX's interpreter path.
```sh
# Assuming you are in jerry-nuttx folder.
mkdir -p apps/interpreters/jerryscript
cp jerryscript/targets/nuttx-stm32f4/* apps/interpreters/jerryscript/
# Or more simply:
# ln -s jerryscript/targets/nuttx-stm32f4 apps/interpreters/jerryscript
```
#### 4. Configure NuttX
NuttX requires configuration first. The configuration creates a `.config` file in the root folder of NuttX that has all the necessary options for the build.
```sh
# Assuming you are in jerry-nuttx folder.
cd nuttx/tools
# Configure NuttX to use USB console shell.
./configure.sh stm32f4discovery/usbnsh
```
By default, JerryScript is not enabled, so it is needed to modify the configuration file.
##### 4.1 Enable JerryScript without user interaction
```sh
# Assuming you are in jerry-nuttx folder.
sed --in-place "s/CONFIG_HOST_WINDOWS/# CONFIG_HOST_WINDOWS/g" nuttx/.config
sed --in-place "s/CONFIG_WINDOWS_CYGWIN/# CONFIG_WINDOWS_CYGWIN/g" nuttx/.config
sed --in-place "s/CONFIG_TOOLCHAIN_WINDOWS/# CONFIG_TOOLCHAIN_WINDOWS/g" nuttx/.config
cat >> nuttx/.config << EOL
CONFIG_HOST_LINUX=y
CONFIG_ARCH_FPU=y
CONFIG_JERRYSCRIPT=y
CONFIG_JERRYSCRIPT_PRIORITY=100
CONFIG_JERRYSCRIPT_STACKSIZE=16384
EOL
```
##### 4.2 Enable JerryScript using kconfig-frontend
`kconfig-frontend` could be useful if there are another options that should be enabled or disabled in NuttX.
###### 4.2.1 Install kconfig-frontend
```sh
# Assuming you are in jerry-nuttx folder.
git clone https://bitbucket.org/nuttx/tools.git nuttx-tools
cd nuttx-tools/kconfig-frontends
./configure \
--disable-nconf \
--disable-gconf \
--disable-qconf \
--disable-shared \
--enable-static \
--prefix=${PWD}/install
make
sudo make install
# Add the install folder to PATH
PATH=$PATH:${PWD}/install/bin
```
###### 4.2.2 Enable JerryScript
```sh
# Assuming you are in jerry-nuttx folder.
# Might be required to run `make menuconfig` twice.
make -C nuttx menuconfig
```
* Change `Build Setup -> Build Host Platform` to Linux
* Enable `System Type -> FPU support`
* Enable JerryScript `Application Configuration -> Interpreters -> JerryScript`
#### 5. Build NuttX
```sh
# Assuming you are in jerry-nuttx folder.
make -C nuttx
```
#### 6. Flash the device
Connect Mini-USB for power supply and connect Micro-USB for `NSH` console.
```sh
# Assuming you are in jerry-nuttx folder.
make -C stlink release
sudo stlink/build/Release/st-flash write nuttx/nuttx.bin 0x8000000
```
### Running JerryScript
You can use `minicom` for terminal program, or any other you may like, but set
baud rate to `115200`.
```sh
sudo minicom --device=/dev/ttyACM0 --baud=115200
```
You may have to press `RESET` on the board and press `Enter` keys on the console
several times to make `nsh` prompt to appear.
If the prompt shows like this,
```
NuttShell (NSH)
nsh>
nsh>
nsh>
```
please set `Add Carriage Ret` option by `CTRL-A` > `Z` > `U` at the console,
if you're using `minicom`.
Run `jerry` with javascript file(s)
```
NuttShell (NSH)
nsh> jerry full_path/any.js
```
Without argument it prints:
```
nsh> jerry
No input files, running a hello world demo:
Hello world 5 times from JerryScript
```
@@ -0,0 +1,465 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "jerryscript.h"
#include "jerryscript-ext/debugger.h"
#include "jerryscript-ext/handler.h"
#include "jerryscript-port.h"
#include "setjmp.h"
/**
* Maximum command line arguments number.
*/
#define JERRY_MAX_COMMAND_LINE_ARGS (16)
/**
* Standalone Jerry exit codes.
*/
#define JERRY_STANDALONE_EXIT_CODE_OK (0)
#define JERRY_STANDALONE_EXIT_CODE_FAIL (1)
/**
* Context size of the SYNTAX_ERROR
*/
#define SYNTAX_ERROR_CONTEXT_SIZE 2
void set_log_level (jerry_log_level_t level);
/**
* Print usage and available options
*/
static void
print_help (char *name)
{
printf ("Usage: %s [OPTION]... [FILE]...\n"
"\n"
"Options:\n"
" --log-level [0-3]\n"
" --mem-stats\n"
" --mem-stats-separate\n"
" --show-opcodes\n"
" --start-debug-server\n"
" --debug-server-port [port]\n"
"\n",
name);
} /* print_help */
/**
* Read source code into buffer.
*
* Returned value must be freed with jmem_heap_free_block if it's not NULL.
* @return NULL, if read or allocation has failed
* pointer to the allocated memory block, otherwise
*/
static const uint8_t *
read_file (const char *file_name, /**< source code */
size_t *out_size_p) /**< [out] number of bytes successfully read from source */
{
FILE *file = fopen (file_name, "r");
if (file == NULL)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: cannot open file: %s\n", file_name);
return NULL;
}
int fseek_status = fseek (file, 0, SEEK_END);
if (fseek_status != 0)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Failed to seek (error: %d)\n", fseek_status);
fclose (file);
return NULL;
}
long script_len = ftell (file);
if (script_len < 0)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Failed to get the file size(error %ld)\n", script_len);
fclose (file);
return NULL;
}
rewind (file);
uint8_t *buffer = (uint8_t *) malloc (script_len);
if (buffer == NULL)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Out of memory error\n");
fclose (file);
return NULL;
}
size_t bytes_read = fread (buffer, 1u, script_len, file);
if (!bytes_read || bytes_read != script_len)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: failed to read file: %s\n", file_name);
free ((void*) buffer);
fclose (file);
return NULL;
}
fclose (file);
*out_size_p = bytes_read;
return (const uint8_t *) buffer;
} /* read_file */
/**
* Convert string into unsigned integer
*
* @return converted number
*/
static uint32_t
str_to_uint (const char *num_str_p, /**< string to convert */
char **out_p) /**< [out] end of the number */
{
assert (jerry_is_feature_enabled (JERRY_FEATURE_ERROR_MESSAGES));
uint32_t result = 0;
while (*num_str_p >= '0' && *num_str_p <= '9')
{
result *= 10;
result += (uint32_t) (*num_str_p - '0');
num_str_p++;
}
if (out_p != NULL)
{
*out_p = num_str_p;
}
return result;
} /* str_to_uint */
/**
* Print error value
*/
static void
print_unhandled_exception (jerry_value_t error_value) /**< error value */
{
assert (jerry_value_is_error (error_value));
error_value = jerry_get_value_from_error (error_value, false);
jerry_value_t err_str_val = jerry_value_to_string (error_value);
jerry_size_t err_str_size = jerry_get_utf8_string_size (err_str_val);
jerry_char_t err_str_buf[256];
jerry_release_value (error_value);
if (err_str_size >= 256)
{
const char msg[] = "[Error message too long]";
err_str_size = sizeof (msg) / sizeof (char) - 1;
memcpy (err_str_buf, msg, err_str_size);
}
else
{
jerry_size_t sz = jerry_string_to_utf8_char_buffer (err_str_val, err_str_buf, err_str_size);
assert (sz == err_str_size);
err_str_buf[err_str_size] = 0;
if (jerry_is_feature_enabled (JERRY_FEATURE_ERROR_MESSAGES)
&& jerry_get_error_type (error_value) == JERRY_ERROR_SYNTAX)
{
jerry_char_t *string_end_p = err_str_buf + sz;
uint32_t err_line = 0;
uint32_t err_col = 0;
char *path_str_p = NULL;
char *path_str_end_p = NULL;
/* 1. parse column and line information */
for (jerry_char_t *current_p = err_str_buf; current_p < string_end_p; current_p++)
{
if (*current_p == '[')
{
current_p++;
if (*current_p == '<')
{
break;
}
path_str_p = (char *) current_p;
while (current_p < string_end_p && *current_p != ':')
{
current_p++;
}
path_str_end_p = (char *) current_p++;
err_line = str_to_uint ((char *) current_p, (char **) &current_p);
current_p++;
err_col = str_to_uint ((char *) current_p, NULL);
break;
}
} /* for */
if (err_line != 0 && err_col != 0)
{
uint32_t curr_line = 1;
bool is_printing_context = false;
uint32_t pos = 0;
/* Temporarily modify the error message, so we can use the path. */
*path_str_end_p = '\0';
size_t source_size;
const jerry_char_t *source_p = read_file (path_str_p, &source_size);
/* Revert the error message. */
*path_str_end_p = ':';
/* 2. seek and print */
while (source_p[pos] != '\0')
{
if (source_p[pos] == '\n')
{
curr_line++;
}
if (err_line < SYNTAX_ERROR_CONTEXT_SIZE
|| (err_line >= curr_line
&& (err_line - curr_line) <= SYNTAX_ERROR_CONTEXT_SIZE))
{
/* context must be printed */
is_printing_context = true;
}
if (curr_line > err_line)
{
break;
}
if (is_printing_context)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "%c", source_p[pos]);
}
pos++;
}
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "\n");
while (--err_col)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "~");
}
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "^\n");
}
}
}
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Script Error: %s\n", err_str_buf);
jerry_release_value (err_str_val);
} /* print_unhandled_exception */
/**
* Register a JavaScript function in the global object.
*/
static void
register_js_function (const char *name_p, /**< name of the function */
jerry_external_handler_t handler_p) /**< function callback */
{
jerry_value_t result_val = jerryx_handler_register_global ((const jerry_char_t *) name_p, handler_p);
if (jerry_value_is_error (result_val))
{
jerry_port_log (JERRY_LOG_LEVEL_WARNING, "Warning: failed to register '%s' method.", name_p);
}
jerry_release_value (result_val);
} /* register_js_function */
/**
* Main program.
*
* @return 0 if success, error code otherwise
*/
#ifdef CONFIG_BUILD_KERNEL
int main (int argc, FAR char *argv[])
#else
int jerry_main (int argc, char *argv[])
#endif
{
if (argc > JERRY_MAX_COMMAND_LINE_ARGS)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR,
"Too many command line arguments. Current maximum is %d\n",
JERRY_MAX_COMMAND_LINE_ARGS);
return JERRY_STANDALONE_EXIT_CODE_FAIL;
}
const char *file_names[JERRY_MAX_COMMAND_LINE_ARGS];
int i;
int files_counter = 0;
bool start_debug_server = false;
uint16_t debug_port = 5001;
jerry_init_flag_t flags = JERRY_INIT_EMPTY;
for (i = 1; i < argc; i++)
{
if (!strcmp ("-h", argv[i]) || !strcmp ("--help", argv[i]))
{
print_help (argv[0]);
return JERRY_STANDALONE_EXIT_CODE_OK;
}
else if (!strcmp ("--mem-stats", argv[i]))
{
flags |= JERRY_INIT_MEM_STATS;
set_log_level (JERRY_LOG_LEVEL_DEBUG);
}
else if (!strcmp ("--mem-stats-separate", argv[i]))
{
flags |= JERRY_INIT_MEM_STATS_SEPARATE;
set_log_level (JERRY_LOG_LEVEL_DEBUG);
}
else if (!strcmp ("--show-opcodes", argv[i]))
{
flags |= JERRY_INIT_SHOW_OPCODES | JERRY_INIT_SHOW_REGEXP_OPCODES;
set_log_level (JERRY_LOG_LEVEL_DEBUG);
}
else if (!strcmp ("--log-level", argv[i]))
{
if (++i < argc && strlen (argv[i]) == 1 && argv[i][0] >='0' && argv[i][0] <= '3')
{
set_log_level (argv[i][0] - '0');
}
else
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: wrong format or invalid argument\n");
return JERRY_STANDALONE_EXIT_CODE_FAIL;
}
}
else if (!strcmp ("--start-debug-server", argv[i]))
{
start_debug_server = true;
}
else if (!strcmp ("--debug-server-port", argv[i]))
{
if (++i < argc)
{
debug_port = str_to_uint (argv[i], NULL);
}
else
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: wrong format or invalid argument\n");
return JERRY_STANDALONE_EXIT_CODE_FAIL;
}
}
else
{
file_names[files_counter++] = argv[i];
}
}
jerry_init (flags);
if (start_debug_server)
{
jerryx_debugger_after_connect (jerryx_debugger_tcp_create (debug_port)
&& jerryx_debugger_ws_create ());
}
register_js_function ("assert", jerryx_handler_assert);
register_js_function ("gc", jerryx_handler_gc);
register_js_function ("print", jerryx_handler_print);
jerry_value_t ret_value = jerry_create_undefined ();
if (files_counter == 0)
{
printf ("No input files, running a hello world demo:\n");
const jerry_char_t script[] = "var str = 'Hello World'; print(str + ' from JerryScript')";
ret_value = jerry_parse (NULL, 0, script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
if (!jerry_value_is_error (ret_value))
{
ret_value = jerry_run (ret_value);
}
}
else
{
for (i = 0; i < files_counter; i++)
{
size_t source_size;
const jerry_char_t *source_p = read_file (file_names[i], &source_size);
if (source_p == NULL)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Source file load error\n");
return JERRY_STANDALONE_EXIT_CODE_FAIL;
}
ret_value = jerry_parse ((jerry_char_t *) file_names[i],
strlen (file_names[i]),
source_p,
source_size,
JERRY_PARSE_NO_OPTS);
free ((void*) source_p);
if (!jerry_value_is_error (ret_value))
{
jerry_value_t func_val = ret_value;
ret_value = jerry_run (func_val);
jerry_release_value (func_val);
}
if (jerry_value_is_error (ret_value))
{
print_unhandled_exception (ret_value);
break;
}
jerry_release_value (ret_value);
ret_value = jerry_create_undefined ();
}
}
int ret_code = JERRY_STANDALONE_EXIT_CODE_OK;
if (jerry_value_is_error (ret_value))
{
ret_code = JERRY_STANDALONE_EXIT_CODE_FAIL;
}
jerry_release_value (ret_value);
ret_value = jerry_run_all_enqueued_jobs ();
if (jerry_value_is_error (ret_value))
{
ret_code = JERRY_STANDALONE_EXIT_CODE_FAIL;
}
jerry_release_value (ret_value);
jerry_cleanup ();
return ret_code;
} /* main */
@@ -0,0 +1,258 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "jerryscript.h"
#include "jerryscript-port.h"
/**
* JerryScript log level
*/
static jerry_log_level_t jerry_log_level = JERRY_LOG_LEVEL_ERROR;
/**
* Sets log level.
*/
void set_log_level (jerry_log_level_t level)
{
jerry_log_level = level;
} /* set_log_level */
/**
* Aborts the program.
*/
void jerry_port_fatal (jerry_fatal_code_t code)
{
exit (1);
} /* jerry_port_fatal */
/**
* Provide log message implementation for the engine.
*/
void
jerry_port_log (jerry_log_level_t level, /**< log level */
const char *format, /**< format string */
...) /**< parameters */
{
if (level <= jerry_log_level)
{
va_list args;
va_start (args, format);
vfprintf (stderr, format, args);
va_end (args);
}
} /* jerry_port_log */
/**
* Determines the size of the given file.
* @return size of the file
*/
static size_t
jerry_port_get_file_size (FILE *file_p) /**< opened file */
{
fseek (file_p, 0, SEEK_END);
long size = ftell (file_p);
fseek (file_p, 0, SEEK_SET);
return (size_t) size;
} /* jerry_port_get_file_size */
/**
* Opens file with the given path and reads its source.
* @return the source of the file
*/
uint8_t *
jerry_port_read_source (const char *file_name_p, /**< file name */
size_t *out_size_p) /**< [out] read bytes */
{
FILE *file_p = fopen (file_name_p, "rb");
if (file_p == NULL)
{
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: failed to open file: %s\n", file_name_p);
return NULL;
}
size_t file_size = jerry_port_get_file_size (file_p);
uint8_t *buffer_p = (uint8_t *) malloc (file_size);
if (buffer_p == NULL)
{
fclose (file_p);
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: failed to allocate memory for module");
return NULL;
}
size_t bytes_read = fread (buffer_p, 1u, file_size, file_p);
if (!bytes_read)
{
fclose (file_p);
free (buffer_p);
jerry_port_log (JERRY_LOG_LEVEL_ERROR, "Error: failed to read file: %s\n", file_name_p);
return NULL;
}
fclose (file_p);
*out_size_p = bytes_read;
return buffer_p;
} /* jerry_port_read_source */
/**
* Release the previously opened file's content.
*/
void
jerry_port_release_source (uint8_t *buffer_p) /**< buffer to free */
{
free (buffer_p);
} /* jerry_port_release_source */
/**
* Normalize a file path
*
* @return length of the path written to the output buffer
*/
size_t
jerry_port_normalize_path (const char *in_path_p, /**< input file path */
char *out_buf_p, /**< output buffer */
size_t out_buf_size, /**< size of output buffer */
char *base_file_p) /**< base file path */
{
(void) base_file_p;
size_t len = strlen (in_path_p);
if (len + 1 > out_buf_size)
{
return 0;
}
/* Return the original string. */
strcpy (out_buf_p, in_path_p);
return len;
} /* jerry_port_normalize_path */
/**
* Get the module object of a native module.
*
* @return undefined
*/
jerry_value_t
jerry_port_get_native_module (jerry_value_t name) /**< module specifier */
{
(void) name;
return jerry_create_undefined ();
} /* jerry_port_get_native_module */
/**
* Dummy function to get the time zone adjustment.
*
* @return 0
*/
double
jerry_port_get_local_time_zone_adjustment (double unix_ms, bool is_utc)
{
/* We live in UTC. */
return 0;
} /* jerry_port_get_local_time_zone_adjustment */
/**
* Dummy function to get the current time.
*
* @return 0
*/
double
jerry_port_get_current_time (void)
{
return 0;
} /* jerry_port_get_current_time */
/**
* Provide the implementation of jerry_port_print_char.
* Uses 'printf' to print a single character to standard output.
*/
void
jerry_port_print_char (char c) /**< the character to print */
{
printf ("%c", c);
} /* jerry_port_print_char */
/**
* Provide implementation of jerry_port_sleep.
*/
void jerry_port_sleep (uint32_t sleep_time) /**< milliseconds to sleep */
{
usleep ((useconds_t) sleep_time * 1000);
} /* jerry_port_sleep */
/**
* Pointer to the current context.
*/
static jerry_context_t *current_context_p = NULL;
/**
* Set the current_context_p as the passed pointer.
*/
void
jerry_port_default_set_current_context (jerry_context_t *context_p) /**< points to the created context */
{
current_context_p = context_p;
} /* jerry_port_default_set_current_context */
/**
* Get the current context.
*
* @return the pointer to the current context
*/
jerry_context_t *
jerry_port_get_current_context (void)
{
return current_context_p;
} /* jerry_port_get_current_context */
/**
* Track unhandled promise rejections.
*
* Note:
* This port function is called by jerry-core when JERRY_BUILTIN_PROMISE
* is enabled.
*
* @param promise rejected promise
* @param operation HostPromiseRejectionTracker operation
*/
void
jerry_port_track_promise_rejection (const jerry_value_t promise,
const jerry_promise_rejection_operation_t operation)
{
(void) operation; /* unused */
jerry_value_t reason = jerry_get_promise_result (promise);
jerry_value_t reason_to_string = jerry_value_to_string (reason);
jerry_size_t req_sz = jerry_get_utf8_string_size (reason_to_string);
jerry_char_t str_buf_p[req_sz + 1];
jerry_string_to_utf8_char_buffer (reason_to_string, str_buf_p, req_sz);
str_buf_p[req_sz] = '\0';
jerry_release_value (reason_to_string);
jerry_release_value (reason);
jerry_port_log (JERRY_LOG_LEVEL_WARNING, "Uncaught (in promise) %s\n", str_buf_p);
} /* jerry_port_track_promise_rejection */
@@ -0,0 +1,65 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
.syntax unified
.macro func _name
.global \_name
.type \_name, %function
\_name:
.endm
.macro endfunc _name
.size \_name, .-\_name
.endm
/**
* setjmp (jmp_buf env)
*
* See also:
* longjmp
*
* @return 0 - if returns from direct call,
* nonzero - if returns after longjmp.
*/
func setjmp
stmia r0!, {r4 - r11, lr}
str sp, [r0], #4
vstm r0, {s16 - s31}
mov r0, #0
bx lr
endfunc setjmp
/**
* longjmp (jmp_buf env, int val)
*
* Note:
* if val is not 0, then it would be returned from setjmp,
* otherwise - 0 would be returned.
*
* See also:
* setjmp
*/
func longjmp
ldmia r0!, {r4 - r11, lr}
ldr sp, [r0]
add r0, r0, #4
vldm r0, {s16 - s31}
mov r0, r1
cmp r0, #0
bne 1f
mov r0, #1
1:
bx lr
endfunc longjmp
@@ -0,0 +1,25 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SETJMP_H
#define SETJMP_H
#include <stdint.h>
typedef uint64_t jmp_buf[14];
int setjmp (jmp_buf env);
void longjmp (jmp_buf env, int val);
#endif /* !SETJMP_H */
@@ -0,0 +1,96 @@
# JerryScript for OpenWrt build guide
This document describes the steps required to compile the JerryScript
for OpenWrt. For target device the TP-Link WR1043ND v1.x router is
used. Please be advised, that if you have a different one minor
modifications to this document could be required.
IMPORTANT!
As the TP-Link WR1043ND is a mips based device and mips is a big-endian
architecture a JerryScipt snapshot which was built on an little-endian
system will not work correctly. Thus it is advised that the
snapshot functionally should be used with caution, that is
DO NOT run snapshots generated on little-endian system(s) on
a big-endian system.
## OpenWrt notes
In 2018 ~January the OpenWrt and LEDE project merged into one
and thus the old OpenWrt parts are now usable only from
an archived repository: https://github.com/openwrt/archive
## OpenWrt toolchain setup
To build the JerryScript for OpenWrt a toolchain is required for
the target router/device. The toolchain setup in this document was
tested on an Ubuntu 16.04.3 LTS Linux.
Steps required for toolchain creation:
### 0. Install OpenWrt build requirements
```sh
$ sudo apt-get install git-core build-essential libssl-dev libncurses5-dev unzip gawk zlib1g-dev subversion mercurial
```
### 1. Clone OpenWrt (Chaos Calmer version)
```sh
$ git clone https://github.com/openwrt/archive openwrt -b chaos_calmer
$ cd openwrt
```
### 2. Run Menuconfig and configure the OpenWrt
```sh
$ make menuconfig
```
Options which should be set:
* Set "Target System" to "Atheros AR7xxx/AR9xxx".
* Set "Target Profile" to "TP-LINK TL-WR1043N/ND".
Save the configuration (as .config) and exit from the menuconfig.
### 3. Configure the environment variables
```sh
$ export BUILDROOT=$(pwd) # where the openwrt root dir is
$ export STAGING_DIR=${BUILDROOT}/staging_dir/ # required by the compiler
$ export PATH=$PATH:${STAGING_DIR}/host/bin:${STAGING_DIR}/toolchain-mips_34kc_gcc-4.8-linaro_uClibc-0.9.33.2/bin/
```
The name `toolchain-mips_34kc_gcc-4.8-linaro_uClibc-0.9.33.2` is created based on the menuconfig.
This changes depending on the target device!
### 4. Build the OpenWrt
```sh
$ make
```
### 5. Check if the compiler was built
```sh
$ mips-openwrt-linux-gcc --version # running this should print out the version information
```
At this point we have the required compiler for OpenWrt.
## Build JerryScript for OpenWrt
### 0. Check environment
Please check if the `STAGING_DIR` is configured correctly and that the toolchain binary is on the `PATH`.
### 1. Run the build with the OpenWrt toolchain file
```
$ ./tools/build.py --toolchain cmake/toolchain_openwrt_mips.cmake \
--lto OFF
```
### 2. Copy the binary
After a successful build the `build/bin/jerry` binary file can be copied to the target device.
On how to copy a binary file to an OpenWrt target device please see the OpenWrt manual(s).
@@ -0,0 +1,63 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
PARTICLE_FIRMWARE := $(CURDIR)/../particle/firmware
JERRYDIR ?= $(CURDIR)
JERRYHEAP ?= 16
BUILD_DIR ?= $(JERRYDIR)/build/particle
EXT_CFLAGS += -mlittle-endian -mthumb -mcpu=cortex-m4
EXT_CFLAGS += -Wno-error=format=
.PHONY: jerrycore jerry-main flash clean
PARTICLE_BUILD_CONFIG = \
INCLUDE_DIRS=$(JERRYDIR)/jerry-core/include \
LIBS=jerry-core \
PLATFORM=photon \
LIB_DIRS=$(BUILD_DIR)/lib \
APPDIR=$(JERRYDIR)/targets/particle/source \
TARGET_FILE=jerry_main \
TARGET_DIR=$(BUILD_DIR) \
LDFLAGS=--specs=nano.specs
all: jerrycore jerry-main
jerrycore:
mkdir -p $(BUILD_DIR)
cmake -B$(BUILD_DIR) -H./ \
-DCMAKE_SYSTEM_NAME=MCU \
-DCMAKE_SYSTEM_PROCESSOR=armv7l \
-DCMAKE_C_COMPILER=arm-none-eabi-gcc \
-DCMAKE_C_COMPILER_WORKS=TRUE \
-DENABLE_LTO=ON \
-DJERRY_CMDLINE=OFF \
-DJERRY_PROFILE=minimal \
-DENABLE_STRIP=OFF \
-DEXTERNAL_COMPILE_FLAGS="$(EXT_CFLAGS)" \
-DJERRY_GLOBAL_HEAP_SIZE=$(JERRYHEAP)
make -C$(BUILD_DIR) jerry-core
jerry-main: jerrycore
$(PARTICLE_BUILD_CONFIG) make -C$(PARTICLE_FIRMWARE) -f $(PARTICLE_FIRMWARE)/makefile
flash:
$(PARTICLE_BUILD_CONFIG) make -C$(PARTICLE_FIRMWARE)/main -f $(PARTICLE_FIRMWARE)/main/makefile program-dfu
clean:
$(PARTICLE_BUILD_CONFIG) make -C$(PARTICLE_FIRMWARE) -f $(PARTICLE_FIRMWARE)/makefile clean
rm -rf $(BUILD_DIR)
@@ -0,0 +1,91 @@
### About
This folder contains files to run JerryScript beside Particle Device Firmware on Photon board.
It runs a mini example, blinking an LED which is the "Hello World" example of the microcontroller universe.
### How to build
#### 1. Preface / Directory structure
Assume `root` as the path to the projects to build.
The folder tree related would look like this.
```
root
+ jerryscript
| + targets
| + particle
+ particle
| + firmware
```
#### 2, Update/Install the Particle Firmware
For detailed descriptions please visit the official website of the firmware: https://www.particle.io/
You can checkout the firmware with the following command:
```
# assume you are in root folder
git clone https://github.com/spark/firmware.git particle/firmware
````
The Photons latest firmware release is hosted in the latest branch of the firmware repo.
```
# assume you are in root folder
cd particle/firmware
git checkout latest
```
Before you type any commands, put your Photon in DFU mode: hold down both the SETUP and RESET buttons. Then release RESET, but hold SETUP until you see the RGB blink yellow. That means the Photon is in DFU mode. To verify that the Photon is in DFU mode and dfu-util is installed properly, try the dfu-util -l command. You should see the device, and the important parts there are the hex values inside the braces the USB VID and PID, which should be 2b04 and d006 for the Photon.
To build and flash the firmware: switch to the modules directory then call make with a few parameters to build and upload the firmware:
```
cd modules
make PLATFORM=photon clean all program-dfu
```
#### 3. Build JerryScript
```
# assume you are in root folder
cd jerryscript
make -f ./targets/particle/Makefile.particle
```
This will create a binary file in the `/build/particle/` folder:
```
jerry_main.bin
```
Thats the binary what well be flashing with dfu-util.
#### 4. Flashing
Make sure you put your Photon in DFU mode.
Alternatively, you can make your life a bit easier by using the make command to invoke dfu-util:
```
make -f targets/particle/Makefile.particle flash
```
You can also use this dfu-util command directly to upload your BIN file to the Photons application memory:
```
dfu-util -d 2b04:d006 -a 0 -i 0 -s 0x80A0000:leave -D build/particle/jerry_main.bin
```
#### 5. Cleaning
To clean the build result:
```
make -f targets/particle/Makefile.particle clean
```
### Running the example
The example program will blinks the D7 led periodically after the flash.
@@ -0,0 +1,146 @@
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "application.h"
#include "jerryscript.h"
SYSTEM_MODE (MANUAL);
/**
* Set led value
*/
static jerry_value_t
set_led (const jerry_value_t func_value, /**< function object */
const jerry_value_t this_value, /**< this arg */
const jerry_value_t *args_p, /**< function arguments */
const jerry_length_t args_cnt) /**< number of function arguments */
{
if (args_cnt != 2)
{
Serial.println ("Wrong arguments count in 'test.setLed' function.");
return jerry_create_boolean (false);
}
int ledPin = jerry_get_number_value (args_p[0]);
bool value = jerry_get_boolean_value (args_p[1]);
pinMode (ledPin, OUTPUT);
digitalWrite (ledPin, value);
return jerry_create_boolean (true);
} /* set_led */
/**
* Delay function
*/
static jerry_value_t
js_delay (const jerry_value_t func_value, /**< function object */
const jerry_value_t this_value, /**< this arg */
const jerry_value_t *args_p, /**< function arguments */
const jerry_length_t args_cnt) /**< number of function arguments */
{
if (args_cnt != 1)
{
Serial.println ("Wrong arguments count in 'test.delay' function.");
return jerry_create_boolean (false);
}
int millisec = jerry_get_number_value (args_p[0]);
delay (millisec);
return jerry_create_boolean (true);
} /* js_delay */
/*
* Init available js functions
*/
static void
init_jerry ()
{
jerry_init (JERRY_INIT_EMPTY);
/* Create an empty JS object */
jerry_value_t object = jerry_create_object ();
jerry_value_t func_obj;
jerry_value_t prop_name;
func_obj = jerry_create_external_function (set_led);
prop_name = jerry_create_string ((const jerry_char_t *) "setLed");
jerry_release_value (jerry_set_property (object, prop_name, func_obj));
jerry_release_value (prop_name);
jerry_release_value (func_obj);
func_obj = jerry_create_external_function (js_delay);
prop_name = jerry_create_string ((const jerry_char_t *) "delay");
jerry_release_value (jerry_set_property (object, prop_name, func_obj));
jerry_release_value (prop_name);
jerry_release_value (func_obj);
/* Wrap the JS object (not empty anymore) into a jerry api value */
jerry_value_t global_object = jerry_get_global_object ();
/* Add the JS object to the global context */
prop_name = jerry_create_string ((const jerry_char_t *) "test");
jerry_release_value (jerry_set_property (global_object, prop_name, object));
jerry_release_value (prop_name);
jerry_release_value (object);
jerry_release_value (global_object);
} /* init_jerry */
/**
* Jerryscript simple test
*/
static void
test_jerry ()
{
const jerry_char_t script[] = " \
test.setLed(7, true); \
test.delay(250); \
test.setLed(7, false); \
test.delay(250); \
";
jerry_value_t eval_ret = jerry_eval (script, sizeof (script) - 1, JERRY_PARSE_NO_OPTS);
/* Free JavaScript value, returned by eval */
jerry_release_value (eval_ret);
} /* test_jerry */
/**
* Setup code for particle firmware
*/
void
setup ()
{
Serial.begin (9600);
delay (2000);
Serial.println ("Beginning Listening mode test!");
} /* setup */
/**
* Loop code for particle firmware
*/
void
loop ()
{
init_jerry ();
/* Turn on and off the D7 LED */
test_jerry ();
jerry_cleanup ();
} /* loop */
@@ -0,0 +1,48 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# application name
APPLICATION = riot_jerry
# default BOARD enviroment
BOARD ?= stm32f4discovery
# LLVM/Clang-based toolchain
TOOLCHAIN ?= llvm
# path to the RIOT base directory
RIOTBASE ?= $(CURDIR)/../RIOT
# path to the JERRYSCRIPT directory
JERRYDIR ?= $(CURDIR)
# path to the application directory
APPDIR ?= $(JERRYDIR)/targets/riot-stm32f4/source
# path to the binary directory
BINDIR ?= $(JERRYDIR)/targets/riot-stm32f4/bin/
# Change this to 0 show compiler invocation lines by default:
QUIET ?= 1
INCLUDES += -I$(JERRYDIR)/jerry-core/include -I$(JERRYDIR)/jerry-ext/include
# Add the shell and some shell commands
USEMODULE += shell
USEMODULE += shell_commands
# Add the jerry libs
USEMODULE += libjerry-core libjerry-port-default libjerry-ext
include $(RIOTBASE)/Makefile.include
@@ -0,0 +1,69 @@
# Copyright JS Foundation and other contributors, http://js.foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Build and output directories
BUILD_DIR ?= build/riotstm32f4
COPYTARGET ?= targets/riot-stm32f4/bin
# JerryScript configuration
JERRYHEAP ?= 16
# To be defined on the command line of make if Clang is available via a
# different name (e.g., clang-N.M)
CC ?= clang
# Cross-compilation settings for Clang
EXT_CFLAGS := -target arm-none-eabi
EXT_CFLAGS += -mlittle-endian -mthumb -mcpu=cortex-m4
EXT_CFLAGS += -isystem /usr/arm-none-eabi/include
EXT_CFLAGS += $(addprefix -isystem $(lastword $(sort $(wildcard /usr/lib/gcc/arm-none-eabi/*/))), include include-fixed)
EXT_CFLAGS += -nostdinc
# For ABI compatibility with RIOT-OS
EXT_CFLAGS += -fshort-enums
.PHONY: libjerry riot-jerry flash clean
all: libjerry riot-jerry
libjerry:
mkdir -p $(BUILD_DIR)
cmake -B$(BUILD_DIR) -H./ \
-DCMAKE_SYSTEM_NAME=RIOT \
-DCMAKE_SYSTEM_PROCESSOR=armv7l \
-DCMAKE_C_COMPILER=$(CC) \
-DCMAKE_C_COMPILER_WORKS=TRUE \
-DENABLE_LTO=OFF \
-DJERRY_CMDLINE=OFF \
-DJERRY_PROFILE="es5.1" \
-DEXTERNAL_COMPILE_FLAGS="$(EXT_CFLAGS)" \
-DJERRY_GLOBAL_HEAP_SIZE=$(JERRYHEAP)
make -C$(BUILD_DIR) jerry-core jerry-port-default jerry-ext
mkdir -p $(COPYTARGET)
cp $(BUILD_DIR)/lib/libjerry-core.a $(COPYTARGET)
cp $(BUILD_DIR)/lib/libjerry-port-default.a $(COPYTARGET)
cp $(BUILD_DIR)/lib/libjerry-ext.a $(COPYTARGET)
riot-jerry: libjerry
make -f ./targets/riot-stm32f4/Makefile
flash: libjerry
make -f ./targets/riot-stm32f4/Makefile flash
clean:
rm -rf $(COPYTARGET)
rm -rf $(BUILD_DIR)
make -f ./targets/riot-stm32f4/Makefile clean

Some files were not shown because too many files have changed in this diff Show More