--- /dev/null
--- /dev/null
++# This file is generated by below command,
++# $ clang-format-3.8 -style=google -dump-config > .clang-format
++# then modified according to IoT.js style guide.
++---
++Language: Cpp
++# BasedOnStyle: Google
++AccessModifierOffset: -1
++AlignAfterOpenBracket: Align
++AlignConsecutiveAssignments: false
++AlignConsecutiveDeclarations: false
++AlignEscapedNewlinesLeft: true
++AlignOperands: true
++AlignTrailingComments: true
++AllowAllParametersOfDeclarationOnNextLine: true
++AllowShortBlocksOnASingleLine: false
++AllowShortCaseLabelsOnASingleLine: false
++AllowShortFunctionsOnASingleLine: None
++AllowShortIfStatementsOnASingleLine: false
++AllowShortLoopsOnASingleLine: false
++AlwaysBreakAfterDefinitionReturnType: None
++AlwaysBreakAfterReturnType: None
++AlwaysBreakBeforeMultilineStrings: true
++AlwaysBreakTemplateDeclarations: true
++BinPackArguments: true
++BinPackParameters: true
++BraceWrapping:
++ AfterClass: false
++ AfterControlStatement: false
++ AfterEnum: false
++ AfterFunction: false
++ AfterNamespace: false
++ AfterObjCDeclaration: false
++ AfterStruct: false
++ AfterUnion: false
++ BeforeCatch: false
++ BeforeElse: false
++ IndentBraces: false
++BreakBeforeBinaryOperators: None
++BreakBeforeBraces: Attach
++BreakBeforeTernaryOperators: true
++BreakConstructorInitializersBeforeComma: false
++ColumnLimit: 80
++CommentPragmas: '^ IWYU pragma:'
++ConstructorInitializerAllOnOneLineOrOnePerLine: true
++ConstructorInitializerIndentWidth: 4
++ContinuationIndentWidth: 4
++Cpp11BracedListStyle: false
++DerivePointerAlignment: true
++DisableFormat: false
++ExperimentalAutoDetectBinPacking: false
++ForEachMacros: [ ]
++IncludeCategories:
++ - Regex: '^"(iotjs_def)'
++ Priority: -1
++ - Regex: '^.iotjs'
++ Priority: 1
++ - Regex: '^.jerry'
++ Priority: 2
++ - Regex: '^.uv'
++ Priority: 2
++ - Regex: '^.http'
++ Priority: 2
++ - Regex: '^(<)'
++ Priority: 3
++IndentCaseLabels: true
++IndentWidth: 2
++IndentWrappedFunctionNames: false
++KeepEmptyLinesAtTheStartOfBlocks: false
++MacroBlockBegin: ''
++MacroBlockEnd: ''
++MaxEmptyLinesToKeep: 2
++NamespaceIndentation: None
++ObjCBlockIndentWidth: 2
++ObjCSpaceAfterProperty: false
++ObjCSpaceBeforeProtocolList: false
++PenaltyBreakBeforeFirstCallParameter: 500
++PenaltyBreakComment: 300
++PenaltyBreakFirstLessLess: 120
++PenaltyBreakString: 1000
++PenaltyExcessCharacter: 1000000
++PenaltyReturnTypeOnItsOwnLine: 200
++PointerAlignment: Left
++ReflowComments: true
++SortIncludes: true
++SpaceAfterCStyleCast: false
++SpaceBeforeAssignmentOperators: true
++SpaceBeforeParens: ControlStatements
++SpaceInEmptyParentheses: false
++SpacesBeforeTrailingComments: 1
++SpacesInAngles: false
++SpacesInContainerLiterals: true
++SpacesInCStyleCastParentheses: false
++SpacesInParentheses: false
++SpacesInSquareBrackets: false
++Standard: Auto
++TabWidth: 8
++UseTab: Never
++...
++
--- /dev/null
+ [general]
+ upstream_branch = ${upstreamversion}
+ upstream_tag = ${upstreamversion}
++packaging_dir = config/tizen/packaging
--- /dev/null
--- /dev/null
++# Produced files
++
++/build
++/build/*
++/src/iotjs_js.h
++/src/iotjs_js.c
++/src/iotjs_string_ext.inl.h
++/test/tmp/*
++
++# IDE related files
++nbproject
++**.sublime-project
++**.sublime-workspace
++.idea
++
++# Random Trash
++*.swp
++*.swo
++*~
++core
++vgcore.*
++**.orig
++**.directory
++**.patch
++.tags*
++cscope.*
++*.pyc
++
++# ctags and ID database
++tags
++ID
++TAGS
++
++# config files
++*.config
++!build.config
--- /dev/null
- [submodule "iotjs"]
- path = iotjs
- url = https://github.com/Samsung/iotjs.git
++[submodule "deps/jerry"]
++ path = deps/jerry
++ url = https://github.com/jerryscript-project/jerryscript.git
++[submodule "deps/http-parser"]
++ path = deps/http-parser
++ url = https://github.com/Samsung/http-parser.git
++[submodule "deps/libtuv"]
++ path = deps/libtuv
++ url = https://github.com/Samsung/libtuv.git
--- /dev/null
--- /dev/null
++language: c
++
++os: linux
++dist: trusty
++sudo: required
++
++before_install:
++ - if [[ "$INSTALL_ARM_DEPS" == "yes" ]]; then tools/apt-get-install-arm.sh; fi
++ - if [[ "$INSTALL_NUTTX_DEPS" == "yes" ]]; then tools/apt-get-install-nuttx.sh; fi
++ - if [[ "$INSTALL_TIZEN_DEPS" == "yes" ]]; then . tools/apt-get-install-tizen.sh; fi
++ - if [[ "$INSTALL_TRAVIS_I686_DEPS" == "yes" ]]; then tools/apt-get-install-travis-i686.sh; fi
++ - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then tools/apt-get-install-deps.sh; fi
++ - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then tools/brew-install-deps.sh; fi
++
++install:
++
++script: "tools/precommit.py $OPTS"
++
++env:
++ global:
++ - secure: "lUGzoKK/Yn4/OmpqLQALrIgfY9mQWE51deUawPrCO87UQ2GknfQ4BvwY3UT5QY0XnztPBP1+vRQ2qxbiAU7VWicp280sXDnh0FeuZD14FcE9l0FczraL12reoLu+gY5HWFfbkZncmcBsZkxDEYxhkM14FJU8fxyqGQW2ypJNz+gUGP+8r40Re5J3WjcddCQNe5IG8U+M9B4YeDHhN2QspLdN5pkgn56XtdGa3+qbecO2NpjJG5ltM9j1tTuo/Dg22DxrIFVfeFSFKUj4nfMrgPo5LevRsC/lfaBSCsj751eqrxRcQRh2hkpiIJ7mEBs2LL1EH9O6Mbj+eRh8BvIYqTB85VPNFc43sLWk14apcSVBrxJE5j3kP9sAsOD9Y5JynnkeuxYyISrkywwoX2uxsmCzIfGbwsv5VLToQzrqWlGYrHOAmVXNi8561dLfsWwxxFUjdqkZr1Kgc8UfnBEcBUtSiKCHS86/YUUbBJGkEkjDUS0GiqhFY4bXLQCR7EX4qDX3m6p7Mnh4NVUolpnSmyeYE/MjmqQ+7PJsPLL3EcIYmJ7dtW3mZ3yE2NyaFD0Pym9+TiuCCXRtrNVK1M3Kya64KNv+HbhjT/fTCgXLSeyDmJOKVAqugRlDo3b1KGR1LI0AfegzSA6mEC4e9JLjYiSnHPMUahzgLt8oU0hNFRY="
++ matrix:
++ - OPTS="--test=host-linux"
++ - OPTS="--test=rpi2" INSTALL_ARM_DEPS=yes
++ - OPTS="--test=nuttx" INSTALL_NUTTX_DEPS=yes
++ - OPTS="--test=artik10" INSTALL_TIZEN_DEPS=yes
++ - OPTS="--test=misc"
++
++matrix:
++ include:
++ - os: osx
++ env: OPTS="--test=host-darwin"
++ - os: linux
++ before_install:
++ - tools/apt-get-install-deps.sh
++ - echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca-
++ addons:
++ coverity_scan:
++ project:
++ name: "Samsung/iotjs"
++ description: "Platform for Internet of Things with JavaScript"
++ notification_email: duddlf.choi@samsung.com
++ build_command: "tools/precommit.py --test=coverity"
++ branch_pattern: master
++ env: OPTS="--test=coverity"
++ - compiler: gcc-4.9
++ addons:
++ apt:
++ sources:
++ - ubuntu-toolchain-r-test
++ packages:
++ - gcc-4.9
++ - gcc-4.9-multilib
++ env: OPTS="--test=host-linux --buildtype=debug --buildoptions=--target-arch=i686,--compile-flag=-fsanitize=address,--compile-flag=-fno-omit-frame-pointer,--compile-flag=-fno-common,--compile-flag=-O2,--jerry-cmake-param=-DJERRY_LIBC=OFF,--jerry-cmake-param=-DFEATURE_SYSTEM_ALLOCATOR=ON,--no-snapshot,--no-check-valgrind" INSTALL_TRAVIS_I686_DEPS=yes ASAN_OPTIONS=detect_stack_use_after_return=1:check_initialization_order=true:strict_init_order=true
++ - compiler: gcc-4.9
++ addons:
++ apt:
++ sources:
++ - ubuntu-toolchain-r-test
++ packages:
++ - gcc-4.9
++ - gcc-4.9-multilib
++ env: OPTS="--test=host-linux --buildtype=debug --buildoptions=--target-arch=i686,--compile-flag=-fsanitize=undefined,--compile-flag=-fno-omit-frame-pointer,--compile-flag=-fno-common,--jerry-cmake-param=-DJERRY_LIBC=OFF,--jerry-cmake-param=-DFEATURE_SYSTEM_ALLOCATOR=ON,--no-snapshot,--no-check-valgrind" INSTALL_TRAVIS_I686_DEPS=yes UBSAN_OPTIONS=print_stacktrace=1
++ fast_finish: true
--- /dev/null
+ # IoT.js: Platform for Internet of Things with JavaScript
+ [](https://gitter.im/Samsung/iotjs?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+ [](LICENSE)
+ [](https://travis-ci.org/Samsung/iotjs)
+ [](https://scan.coverity.com/projects/samsung-iotjs)
+ [](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2FSamsung%2Fiotjs?ref=badge_shield)
+
+ You can find project details on our [project page](http://samsung.github.io/iotjs/) and [wiki](https://github.com/Samsung/iotjs/wiki).
+
++Memory usage and Binary footprint are measured at [here](https://samsung.github.io/iotjs-test-results) with real target daily.
++
++The following table shows the latest results on the devices:
++
++| STM32F4-Discovery | [](https://samsung.github.io/iotjs-test-results/) |
++| :---: | :---: |
++| **Raspberry Pi 2** | [](https://samsung.github.io/iotjs-test-results/) |
++
+ IRC channel: #iotjs on [freenode](https://freenode.net)
+ Mailing list: iotjs-dev@groups.io, you can subscribe [here](https://groups.io/g/iotjs-dev) and access the mailing list archive [here](https://groups.io/g/iotjs-dev/topics).
+
+ ## Quick Start
+ ### Getting the sources
+
+ ```bash
+ git clone https://github.com/Samsung/iotjs.git
+ cd iotjs
+ ```
+
+ ### How to Build
+
+ ```bash
+ tools/build.py
+ ```
+
+ ### How to Test
+
+ ```bash
+ build/x86_64-linux/debug/bin/iotjs tools/check_test.js
+ ```
+
+
+ For Additional information see [Getting Started](docs/help/Getting-Started.md).
+
+ ## Documentation
+ - [Getting Started](docs/help/Getting-Started.md)
+ - [API Reference](docs/api/IoT.js-API-reference.md)
+
+ ## License
+ IoT.js is Open Source software under the [Apache 2.0 license](https://www.apache.org/licenses/LICENSE-2.0). Complete license and copyright information can be found within the code.
+
+ [](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2FSamsung%2Fiotjs?ref=badge_large)
+
+ > Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+
+ > 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 Node.js contributors. All rights reserved.
+
+ > Permission is hereby granted, 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.
+
+ > This license applies to parts of '*.js' files in '/src/js', implementing node.js
+ compatible API, originating from the https://github.com/nodejs/node repository:
--- /dev/null
-#if(NOT "${CMAKE_C_COMPILER}" STREQUAL "")
-# find_program(COMPILER_PATH ${CMAKE_C_COMPILER})
-# if(COMPILER_PATH STREQUAL "")
-# message(WARNING "Command ${CMAKE_C_COMPILER} not found")
-# unset(CMAKE_C_COMPILER)
-# endif()
-# unset(COMPILER_PATH)
-#endif()
+ # Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
+ #
+ # 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(CMakeForceCompiler)
+
+ set(CMAKE_SYSTEM_NAME Linux)
+ set(CMAKE_SYSTEM_PROCESSOR armv7l)
+
+ # Only set the compiler if not provided already
-#if("${CMAKE_C_COMPILER}" STREQUAL "")
-# set(CMAKE_C_COMPILER arm-linux-gnueabi-gcc)
-#endif()
++if(NOT "${CMAKE_C_COMPILER}" STREQUAL "")
++ find_program(COMPILER_PATH ${CMAKE_C_COMPILER})
++ if(COMPILER_PATH STREQUAL "")
++ message(WARNING "Command ${CMAKE_C_COMPILER} not found")
++ unset(CMAKE_C_COMPILER)
++ endif()
++ unset(COMPILER_PATH)
++endif()
+
++if("${CMAKE_C_COMPILER}" STREQUAL "")
++ set(CMAKE_C_COMPILER arm-linux-gnueabi-gcc)
++endif()
--- /dev/null
--- /dev/null
++#!/bin/bash
++
++# Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++#
++# 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.
++
++cd ..
++
++echo "******************************************************************"
++echo "* Tizen GBS build *"
++echo "* *"
++echo "* Please input user, passwd of http://Tizen.org on '~/.gbs.conf' *"
++echo "* For more information, please read Guide Docs. folder *"
++echo "* ~/.gbs.conf sample is at 'config/tizen/sample.gbs.conf'. *"
++echo "* *"
++echo "******************************************************************"
++read -p "[Warning] This working folder will be copied to ../iotjs_tizen_gbs \
++Are you sure to continue? (y/n) " -n 1 -r
++
++echo ""
++if [[ $REPLY =~ ^[Yy]$ ]]
++then
++ echo copy from $OLDPWD to ../iotjs_tizen_gbs
++ cp -ra $OLDPWD iotjs_tizen_gbs
++ cd iotjs_tizen_gbs
++ echo -e "\n(1) Now, cloning submodules. "
++ git submodule init
++ echo -e "\n(2) Update submodules... "
++ git submodule update
++ echo -e "\n(3) Remove compiler specified lines on CMake"
++ rm ./cmake/config/arm-tizen.cmake
++ echo "include(CMakeForceCompiler)
++
++ set(CMAKE_SYSTEM_NAME Linux)
++ set(CMAKE_SYSTEM_PROCESSOR armv7l)"\
++ >> ./cmake/config/arm-tizen.cmake
++
++ rm ./deps/libtuv/cmake/config/config_arm-tizen.cmake
++ echo "include(CMakeForceCompiler)
++
++ set(CMAKE_SYSTEM_NAME Linux)
++ set(CMAKE_SYSTEM_PROCESSOR arm)"\
++ >> ./deps/libtuv/cmake/config/config_arm-tizen.cmake
++
++ rm ./deps/jerry/cmake/toolchain_linux_armv7l-el.cmake
++ echo "set(CMAKE_SYSTEM_NAME Linux)
++ set(CMAKE_SYSTEM_PROCESSOR armv7l-el)
++ set(FLAGS_COMMON_ARCH -mlittle-endian -mthumb)" \
++ >> ./deps/jerry/cmake/toolchain_linux_armv7l-el.cmake
++
++ echo -e "\n(4) 3 files have been modified."
++
++ find ./ -name '.git' | xargs rm -rf
++ # Initialize Git repositoryã…£
++ if [ ! -d .git ]
++ then
++ git init ./
++ git checkout -b tizen_gbs
++ git add ./
++ git commit -m "Initial commit"
++ fi
++
++ echo -e "\n(5) Calling core gbs build command"
++ gbscommand="gbs build -A armv7l --include-all --clean"
++ echo $gbscommand
++ if eval $gbscommand
++ then
++ echo "========================================================"
++ echo "1. GBS Build is successful."
++ echo "2. Please move to new working folder ../iotjs_tizen_gbs "
++ echo " cd ../iotjs_tizen_gbs"
++ echo "3. From now, you can build with this command on new directory"
++ echo " gbs build -A armv7l --include"
++ echo "4. Your new branch 'tizen_gbs' is added."
++ echo "5. 'iotjs origin' repository is added."
++ git remote add origin https://github.com/samsung/iotjs
++ echo "(You cant fetch origin repository with this command)"
++ echo " git fetch --all"
++ echo "========================================================"
++ # git remote add origin
++ # https://review.tizen.org/git/platform/upstream/iotjs
++ git branch -a
++ git status
++ else
++ echo "GBS Build failed!"
++ exit 1
++ fi
++fi
--- /dev/null
--- /dev/null
++<manifest>
++ <request>
++ <domain name="_"/>
++ </request>
++</manifest>
--- /dev/null
--- /dev/null
++prefix=@prefix@
++exec_prefix=@exec_prefix@
++libdir=@libdir@
++includedir=@includedir@
++
++Name: iotjs
++Description: Platform for Internet of Things with JavaScript
++Version: 1.0.0
++Libs:
++Cflags: -I${includedir}
--- /dev/null
--- /dev/null
++Name: iotjs
++Version: 1.0.0
++Release: 0
++Summary: Platform for Internet of Things with JavaScript
++Group: Network & Connectivity
++License: Apache-2.0
++URL: https://www.iotjs.net/
++Source: %{name}-%{version}.tar.gz
++Source1: %{name}.pc.in
++Source1001: %{name}.manifest
++
++BuildRequires: python
++BuildRequires: cmake
++BuildRequires: glibc-static
++BuildRequires: aul
++BuildRequires: pkgconfig(appcore-agent)
++BuildRequires: pkgconfig(capi-appfw-service-application)
++BuildRequires: pkgconfig(capi-appfw-app-common)
++BuildRequires: pkgconfig(capi-appfw-package-manager)
++BuildRequires: pkgconfig(capi-appfw-application)
++BuildRequires: pkgconfig(dlog)
++#for https
++BuildRequires: openssl-devel
++BuildRequires: libcurl-devel
++
++Requires(postun): /sbin/ldconfig
++Requires(post): /sbin/ldconfig
++
++%description
++Platform for Internet of Things with JavaScript
++
++# default is RELEASE mode.
++# If DEBUG mode is needed, please use tizen_build_devel_mode
++%define RELEASE False
++# For Example
++%if %{RELEASE} == "True"
++%define build_mode release
++%else
++%define build_mode debug
++%endif
++
++# Default values to be eventually overiden BEFORE or as gbs params:
++%{!?RELEASE: %define RELEASE 0}
++
++%package service
++Summary: Development files for %{name}
++Group: Network & Connectivity/Service
++Requires: %{name} = %{version}-%{release}
++
++%description service
++The %{name}-service package contains service iotjs files for
++developing applications that use %{name}.
++
++%package devel
++Summary: Header files for %{name}
++Group: Network & Connectivity/Service
++Requires: %{name} = %{version}-%{release}
++
++%description devel
++Development libraries for %{name}
++
++%prep
++%setup -q -c
++chmod g-w %_sourcedir/*
++cat LICENSE
++cp %{SOURCE1001} .
++
++%build
++./tools/build.py --clean --buildtype=%{build_mode} --target-arch=arm \
++ --target-os=tizen --target-board=artik10 \
++ --no-init-submodule --no-parallel-build --no-check-test
++
++%install
++mkdir -p %{buildroot}%{_bindir}
++mkdir -p %{buildroot}%{_includedir}/iotjs
++mkdir -p %{buildroot}%{_libdir}/iotjs
++mkdir -p %{buildroot}%{_libdir}/pkgconfig
++
++
++cp ./build/arm-tizen/%{build_mode}/bin/iotjs %{buildroot}%{_bindir}/
++cp ./build/arm-tizen/%{build_mode}/lib/* %{buildroot}%{_libdir}/iotjs/
++
++cp ./include/*.h %{buildroot}%{_includedir}
++cp ./src/*.h %{buildroot}%{_includedir}
++cp ./config/tizen/packaging/%{name}.pc.in %{buildroot}/%{_libdir}/pkgconfig/%{name}.pc
++
++%post -p /sbin/ldconfig
++%postun -p /sbin/ldconfig
++
++
++%files
++%manifest config/tizen/packaging/%{name}.manifest
++%defattr(-,root,root,-)
++%license LICENSE
++%{_bindir}/*
++
++%files devel
++%defattr(-,root,root,-)
++%{_libdir}/iotjs/*.a
++%{_libdir}/pkgconfig/%{name}.pc
++%{_includedir}/*
--- /dev/null
--- /dev/null
++[general]
++profile = profile.tizen_unified
++
++[profile.tizen_unified]
++obs = obs.spin
++repos = repo.public_4.0_base_arm, repo.tizen_unified
++
++[profile.tizen_artik10]
++obs = obs.spin
++repos = repo.public_3.0_base_arm, repo.public_3_arm
++
++[obs.spin]
++url = http://168.219.209.58:81
++
++[obs.tizen]
++url = https://api.tizen.org
++user = obs_viewer
++passwdx = QlpoOTFBWSZTWRP5nYMAAB6fgCAAeUA9mr+QBvzF4CAAVGAZDTRoDI0YBlCKeptQBoA0aGZIAottAkltEPOK7BAFXE9mTUzocPMzQRkPoPpNwEZx3rRQhxkXmGHS6wCjHskyVCP4u5IpwoSAn8zsGA==
++
++[repo.public_3_arm]
++url = http://download.tizen.org/releases/milestone/tizen/3.0.m2/common_artik/tizen-common-artik_20170111.3/repos/arm-wayland/packages/
++user =
++passwdx =
++
++[repo.tizen_unified]
++url=http://download.tizen.org/snapshots/tizen/unified/latest/repos/standard/packages/
++user=
++passwdx=
++
++[repo.base_arm]
++url=http://download.tizen.org/snapshots/tizen/base/latest/repos/arm/
++user=
++passwdx=
++
++
++[repo.public_3.0_base_arm]
++url = http://download.tizen.org/snapshots/tizen/base/latest/repos/arm/packages/armv7l/
++user =
++passwdx =
++
++[repo.public_4.0_base_arm]
++url = http://download.tizen.org/snapshots/tizen/base/latest/repos/arm/packages/
++user =
++passwdx =
++
--- /dev/null
-EXTRA_LIBPATHS += -L$(IOTJS_LIB_DIR)
+ ###########################################################################
+ #
+ # Copyright 2016 Samsung Electronics All Rights Reserved.
+ #
+ # 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.
+ #
+ ###########################################################################
+ ############################################################################
+ # apps/examples/iotjs/Makefile
+ #
+ # Copyright (C) 2008, 2010-2013 Gregory Nutt. All rights reserved.
+ # Author: Gregory Nutt <gnutt@nuttx.org>
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions
+ # are met:
+ #
+ # 1. Redistributions of source code must retain the above copyright
+ # notice, this list of conditions and the following disclaimer.
+ # 2. Redistributions in binary form must reproduce the above copyright
+ # notice, this list of conditions and the following disclaimer in
+ # the documentation and/or other materials provided with the
+ # distribution.
+ # 3. Neither the name NuttX nor the names of its contributors may be
+ # used to endorse or promote products derived from this software
+ # without specific prior written permission.
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ # OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ # POSSIBILITY OF SUCH DAMAGE.
+ #
+ ############################################################################
+
-
+ EXTRA_LIBS += libhttpparser.a libiotjs.a libjerrycore.a libtuv.a libjerry-libm.a
-CSRCS =
+ LINKLIBS=$(EXTRA_LIBS)
+
+ -include $(TOPDIR)/.config
+ -include $(TOPDIR)/Make.defs
+ include $(APPDIR)/Make.defs
+
++ifeq ($(IOTJS_ROOT_DIR),)
++ IOTJS_ROOT_DIR = ../../iotjs
++endif
++
++ifeq ($(IOTJS_LIB_DIR),)
++ifeq ($(CONFIG_DEBUG),y)
++ IOTJS_LIB_DIR = ../../$(IOTJS_ROOT_DIR)/build/arm-tizenrt/debug/lib
++else
++ IOTJS_LIB_DIR = ../../$(IOTJS_ROOT_DIR)/build/arm-tizenrt/release/lib
++endif
++
++endif
++EXTRA_LIBPATHS += -L$(IOTJS_LIB_DIR)
++
++
++IOTJS_ABSOLUTE_ROOT_DIR := $(shell cd $(TOPDIR) && cd $(IOTJS_ROOT_DIR) && pwd)
+
+ # IoT.js application
+ CONFIG_IOTJS_PRIORITY ?= SCHED_PRIORITY_DEFAULT
+ CONFIG_IOTJS_STACKSIZE ?= 16384
+ IOTJS_LIB_DIR ?= n
+
+ APPNAME = iotjs
++CFLAGS += -I$(IOTJS_ABSOLUTE_ROOT_DIR)/deps/jerry/jerry-core/include
++CFLAGS += -I$(IOTJS_ABSOLUTE_ROOT_DIR)/deps/jerry/jerry-ext/include
+ PRIORITY = $(CONFIG_IOTJS_PRIORITY)
+ STACKSIZE = $(CONFIG_IOTJS_STACKSIZE)
+ HEAPSIZE = $(CONFIG_IOTJS_HEAPSIZE)
+
+ ASRCS =
++CSRCS = jerry_port.c
+ MAINSRC = iotjs_main.c
+
+ AOBJS = $(ASRCS:.S=$(OBJEXT))
+ COBJS = $(CSRCS:.c=$(OBJEXT))
+ MAINOBJ = $(MAINSRC:.c=$(OBJEXT))
+
+ SRCS = $(ASRCS) $(CSRCS) $(MAINSRC)
+ OBJS = $(AOBJS) $(COBJS)
+
+ ifeq ($(R),1)
+ BUILD_TYPE = release
+ else
+ BUILD_TYPE = debug
+ endif
+
+ ifneq ($(CONFIG_BUILD_KERNEL),y)
+ OBJS += $(MAINOBJ)
+ endif
+
+ ifeq ($(CONFIG_WINDOWS_NATIVE),y)
+ BIN = ..\..\libapps$(LIBEXT)
+ else
+ ifeq ($(WINTOOL),y)
+ BIN = ..\\..\\libapps$(LIBEXT)
+ else
+ BIN = ../../libapps$(LIBEXT)
+ endif
+ endif
+
+ ifeq ($(WINTOOL),y)
+ INSTALL_DIR = "${shell cygpath -w $(BIN_DIR)}"
+ else
+ INSTALL_DIR = $(BIN_DIR)
+ endif
+
+ CONFIG_IOTJS_PROGNAME ?= iotjs$(EXEEXT)
+ PROGNAME = $(CONFIG_IOTJS_PROGNAME)
+
+ ROOTDEPPATH = --dep-path .
+
+ # Common build
+
+ VPATH =
+
+ all: .built
+ .PHONY: clean depend distclean check_iotjs
+
+ $(AOBJS): %$(OBJEXT): %.S
+ $(call ASSEMBLE, $<, $@)
+
+ $(COBJS) $(MAINOBJ): %$(OBJEXT): %.c
+ $(call COMPILE, $<, $@)
+
+ .built: $(OBJS) check_iotjs
+ $(call ARCHIVE, $(BIN), $(OBJS))
+ @touch .built
+
+ ifeq ($(CONFIG_BUILD_KERNEL),y)
+ $(BIN_DIR)$(DELIM)$(PROGNAME): $(OBJS) $(MAINOBJ) check_iotjs
+ $(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) -o $(INSTALL_DIR)$(DELIM)$(PROGNAME) $(ARCHCRT0OBJ) $(MAINOBJ) $(LDLIBS)
+ $(Q) $(NM) -u $(INSTALL_DIR)$(DELIM)$(PROGNAME)
+
+ install: $(BIN_DIR)$(DELIM)$(PROGNAME)
+
+ else
+ install:
+
+ endif
+
+ check_iotjs:
+ ifeq ($(IOTJS_LIB_DIR),n)
+ @echo "ERROR: IOTJS_LIB_DIR not set! Aborting..."
+ @exit 1
+ endif
+ @echo IOTJS_LIB_DIR set!
+ @echo "$(LDLIBPATH), $(IOTJS_LIB_DIR) $(TOPDIR)"
+ @cp $(IOTJS_LIB_DIR)/lib* $(TOPDIR)/../build/output/libraries/
+ @cp $(IOTJS_LIB_DIR)/../deps/jerry/lib/libjerry-libm.a $(TOPDIR)/../build/output/libraries/
+
+ context:
+
+ .depend: Makefile $(SRCS)
+ @$(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep
+ @touch $@
+
+ depend: .depend
+
+ clean:
+ $(call DELFILE, .built)
+ $(call CLEAN)
+
+ distclean: clean
+ $(call DELFILE, Make.dep)
+ $(call DELFILE, .depend)
+
+ -include Make.dep
+ .PHONY: preconfig
+ preconfig:
--- /dev/null
-int iotjs_entry(int argc, char *argv[]);
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 (C) 2013 Gregory Nutt. All rights reserved.
+ * Author: Gregory Nutt <gnutt@nuttx.org>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name NuttX nor the names of its contributors may be
+ * used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ ****************************************************************************/
+
+ /****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+ #include <apps/shell/tash.h>
+ #include <tinyara/arch.h>
+ #include <tinyara/config.h>
+
+ #include <setjmp.h>
+ #include <stdio.h>
+
+ #define USE_IOTJS_THREAD 1
+
+ /**
+ * Compiler built-in setjmp function.
+ *
+ * @return 0 when called the first time
+ * 1 when returns from a longjmp call
+ */
+
+ int setjmp(jmp_buf buf) {
+ return __builtin_setjmp(buf);
+ } /* setjmp */
+
+ /**
+ * Compiler built-in longjmp function.
+ *
+ * Note:
+ * ignores value argument
+ */
+
+ void longjmp(jmp_buf buf, int value) {
+ /* Must be called with 1. */
+ __builtin_longjmp(buf, 1);
+ } /* longjmp */
+
- return iotjs(argc, argv);
-}
-
-int iotjs_register_cmd() {
- tash_cmd_install("iotjs", iotjs, TASH_EXECMD_SYNC);
- return 0;
++int iotjs_entry(int argc, char **argv);
+ int tuv_cleanup(void);
+
+
+ #if USE_IOTJS_THREAD
+ struct iotjs_thread_arg {
+ int argc;
+ char **argv;
+ };
+
+ pthread_addr_t iotjs_thread(void *thread_arg) {
+ struct iotjs_thread_arg *arg = thread_arg;
+ int ret = 0;
+
+ ret = iotjs_entry(arg->argc, arg->argv);
+ tuv_cleanup();
+
+ sleep(1);
+ printf("iotjs thread end\n");
+ return NULL;
+ }
+
+ int iotjs(int argc, char *argv[]) {
+ pthread_attr_t attr;
+ int status;
+ struct sched_param sparam;
+ pthread_t tid;
+ struct iotjs_thread_arg arg;
+
+ status = pthread_attr_init(&attr);
+ if (status != 0) {
+ printf("fail to initialize iotjs thread\n");
+ return -1;
+ }
+
+ sparam.sched_priority = CONFIG_IOTJS_PRIORITY;
+ status = pthread_attr_setschedparam(&attr, &sparam);
+ status = pthread_attr_setschedpolicy(&attr, SCHED_RR);
+ status = pthread_attr_setstacksize(&attr, CONFIG_IOTJS_STACKSIZE);
+
+ arg.argc = argc;
+ arg.argv = argv;
+
+ status = pthread_create(&tid, &attr, iotjs_thread, &arg);
+ if (status < 0) {
+ printf("fail to start iotjs thread\n");
+ return -1;
+ }
+ pthread_setname_np(tid, "iotjs_thread");
+ pthread_join(tid, NULL);
+
+ return 0;
+ }
+
+ #else
+
+ static int iotjs(int argc, char *argv[]) {
+ int ret = 0;
+ ret = iotjs_entry(argc, argv);
+ tuv_cleanup();
+ return ret;
+ }
+
+ #endif
+
++int iotjs_register_cmds(void) {
++ tash_cmd_install("iotjs", iotjs, TASH_EXECMD_SYNC);
++ return 0;
++}
++
+ #ifdef CONFIG_BUILD_KERNEL
+ int main(int argc, FAR char *argv[])
+ #else
+ int iotjs_main(int argc, char *argv[])
+ #endif
+ {
++ return iotjs_register_cmds();
+ }
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 <stdlib.h>
++#include <string.h>
++
++#include "jerryscript-ext/handler.h"
++#include "jerryscript-port.h"
++#include "jerryscript.h"
++
++/**
++ * 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 */
++ /* Drain log messages since IoT.js has not support log levels yet. */
++} /* jerry_port_log */
++
++/**
++ * Dummy function to get the time zone.
++ *
++ * @return true
++ */
++bool jerry_port_get_time_zone(jerry_time_zone_t *tz_p) {
++ /* We live in UTC. */
++ tz_p->offset = 0;
++ tz_p->daylight_saving_time = 0;
++
++ return true;
++} /* jerry_port_get_time_zone */
++
++/**
++ * 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 jerryx_port_handler_print_char.
++ * Uses 'printf' to print a single character to standard output.
++ */
++void jerryx_port_handler_print_char(char c) { /**< the character to print */
++ printf("%c", c);
++} /* jerryx_port_handler_print_char */
--- /dev/null
--- /dev/null
++###########################################################################
++#
++# Copyright 2017-present Samsung Electronics All Rights Reserved.
++#
++# 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.
++#
++###########################################################################
++############################################################################
++# configs/artik053/iotivity/Make.defs
++#
++# Copyright (C) 2011, 2012-2013 Gregory Nutt. All rights reserved.
++# Author: Gregory Nutt <gnutt@nuttx.org>
++#
++# Redistribution and use in source and binary forms, with or without
++# modification, are permitted provided that the following conditions
++# are met:
++#
++# 1. Redistributions of source code must retain the above copyright
++# notice, this list of conditions and the following disclaimer.
++# 2. Redistributions in binary form must reproduce the above copyright
++# notice, this list of conditions and the following disclaimer in
++# the documentation and/or other materials provided with the
++# distribution.
++# 3. Neither the name NuttX nor the names of its contributors may be
++# used to endorse or promote products derived from this software
++# without specific prior written permission.
++#
++# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
++# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
++# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
++# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
++# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
++# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
++# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
++# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
++# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
++# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
++# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
++# POSSIBILITY OF SUCH DAMAGE.
++#
++############################################################################
++
++include ${TOPDIR}/.config
++include ${TOPDIR}/tools/Config.mk
++include ${TOPDIR}/arch/arm/src/armv7-r/Toolchain.defs
++
++LDSCRIPT = flash.ld
++
++ifeq ($(CONFIG_UCLIBCXX_HAVE_LIBSUPCXX),y)
++LIBSUPXX = ${shell $(CC) --print-file-name=libsupc++.a}
++EXTRA_LIBPATHS = -L "${shell dirname "$(LIBSUPXX)"}"
++EXTRA_LIBS = -lsupc++
++endif
++
++EXTRA_LIBS += -lhttpparser -liotjs -ljerry-core -ltuv -ljerry-libm
++
++ifeq ($(WINTOOL),y)
++ # Windows-native toolchains
++ DIRLINK = $(TOPDIR)/tools/copydir.sh
++ DIRUNLINK = $(TOPDIR)/tools/unlink.sh
++ MKDEP = $(TOPDIR)/tools/mkwindeps.sh
++ ARCHINCLUDES = -I. -isystem "${shell cygpath -w $(TOPDIR)/include}"
++ ARCHXXINCLUDES = -I. -isystem "${shell cygpath -w $(TOPDIR)/include}" -isystem "${shell cygpath -w $(TOPDIR)/include/cxx}" -isystem "${shell cygpath -w $(TOPDIR)/include/uClibc++}"
++ ARCHSCRIPT = -T "${shell cygpath -w $(TOPDIR)/configs/$(CONFIG_ARCH_BOARD)/scripts/$(LDSCRIPT)}"
++else
++ # Linux/Cygwin-native toolchain
++ MKDEP = $(TOPDIR)/tools/mkdeps$(HOSTEXEEXT)
++ ARCHINCLUDES = -I. -isystem $(TOPDIR)/include -isystem $(TOPDIR)/../framework/include
++ ARCHXXINCLUDES = -I. -isystem $(TOPDIR)/include -isystem $(TOPDIR)/include/cxx -isystem $(TOPDIR)/include/uClibc++
++ ARCHSCRIPT = -T$(TOPDIR)/../build/configs/$(CONFIG_ARCH_BOARD)/scripts/$(LDSCRIPT)
++
++endif
++
++CC = $(CROSSDEV)gcc
++CXX = $(CROSSDEV)g++
++CPP = $(CROSSDEV)gcc -E
++LD = $(CROSSDEV)ld
++AR = $(CROSSDEV)ar rcs
++NM = $(CROSSDEV)nm
++OBJCOPY = $(CROSSDEV)objcopy
++OBJDUMP = $(CROSSDEV)objdump
++
++ARCHCCVERSION = ${shell $(CC) -v 2>&1 | sed -n '/^gcc version/p' | sed -e 's/^gcc version \([0-9\.]\)/\1/g' -e 's/[-\ ].*//g' -e '1q'}
++ARCHCCMAJOR = ${shell echo $(ARCHCCVERSION) | cut -d'.' -f1}
++ARCHCCMINOR = ${shell echo $(ARCHCCVERSION) | cut -d'.' -f2}
++
++ifeq ($(CONFIG_DEBUG_SYMBOLS),y)
++ ARCHOPTIMIZATION = -g
++endif
++
++ifneq ($(CONFIG_DEBUG_NOOPT),y)
++ ARCHOPTIMIZATION += $(MAXOPTIMIZATION) -fno-strict-aliasing -fno-strength-reduce -fomit-frame-pointer
++endif
++
++ifeq ($(CONFIG_FRAME_POINTER),y)
++ ARCHOPTIMIZATION += -fno-omit-frame-pointer -mapcs -mno-sched-prolog
++endif
++
++ARCHCFLAGS = -fno-builtin -mcpu=cortex-r4 -mfpu=vfpv3
++ARCHCXXFLAGS = -fno-builtin -fexceptions -mcpu=cortex-r4 -mfpu=vfpv3
++ifeq ($(QUICKBUILD),y)
++ARCHWARNINGS = -Wall -Werror -Wstrict-prototypes -Wshadow -Wundef -Wno-implicit-function-declaration -Wno-unused-function -Wno-unused-but-set-variable
++ARCHWARNINGSXX = -Wall -Werror -Wshadow -Wundef
++else
++ARCHWARNINGS = -Wall -Werror -Wstrict-prototypes -Wshadow -Wundef -Wno-implicit-function-declaration -Wno-unused-function -Wno-unused-but-set-variable
++ARCHWARNINGSXX = -Wall -Werror -Wshadow -Wundef
++# only version 4.9 supports color diagnostics
++ifeq "$(ARCHMAJOR)" "4"
++ifeq "$(ARCHMINOR)" "9"
++ ARCHWARNINGS += -fdiagnostics-color=auto
++ ARCHWARNINGSCC += -fdiagnostics-color=auto
++endif
++endif
++
++endif
++ARCHDEFINES =
++ARCHPICFLAGS = -fpic -msingle-pic-base -mpic-register=r10
++
++CFLAGS = $(ARCHCFLAGS) $(ARCHWARNINGS) $(ARCHOPTIMIZATION) $(ARCHCPUFLAGS) $(ARCHINCLUDES) $(ARCHDEFINES) $(EXTRADEFINES) -pipe -ffunction-sections -fdata-sections
++CPICFLAGS = $(ARCHPICFLAGS) $(CFLAGS)
++CXXFLAGS = $(ARCHCXXFLAGS) $(ARCHWARNINGSXX) $(ARCHOPTIMIZATION) $(ARCHCPUFLAGS) $(ARCHXXINCLUDES) $(ARCHDEFINES) $(EXTRADEFINES) -pipe
++CXXPICFLAGS = $(ARCHPICFLAGS) $(CXXFLAGS)
++CPPFLAGS = $(ARCHINCLUDES) $(ARCHDEFINES) $(EXTRADEFINES)
++AFLAGS = $(CFLAGS) -D__ASSEMBLY__
++MAXOPTIMIZATION = -O0
++
++
++NXFLATLDFLAGS1 = -r -d -warn-common
++NXFLATLDFLAGS2 = $(NXFLATLDFLAGS1) -T$(TOPDIR)/binfmt/libnxflat/gnu-nxflat-pcrel.ld -no-check-sections
++LDNXFLATFLAGS = -e main -s 2048
++
++ASMEXT = .S
++OBJEXT = .o
++LIBEXT = .a
++EXEEXT =
++
++ifneq ($(CROSSDEV),arm-nuttx-elf-)
++ LDFLAGS += -nostartfiles -nodefaultlibs
++endif
++ifeq ($(CONFIG_DEBUG_SYMBOLS),y)
++ LDFLAGS += -g
++endif
++
++LDFLAGS += --gc-sections
++
++HOSTCC = gcc
++HOSTINCLUDES = -I.
++HOSTCFLAGS = -Wall -Wstrict-prototypes -Wshadow -Wundef -g -pipe
++HOSTLDFLAGS =
++
++define DOWNLOAD
++ @$(TOPDIR)/../build/configs/artik053/artik053_download.sh $(1)
++endef
++
--- /dev/null
--- /dev/null
++#
++# Automatically generated file; DO NOT EDIT.
++# TinyAra Configuration
++#
++
++#
++# Build Setup
++#
++# CONFIG_EXPERIMENTAL is not set
++# CONFIG_DEFAULT_SMALL is not set
++CONFIG_HOST_LINUX=y
++# CONFIG_HOST_OSX is not set
++# CONFIG_HOST_WINDOWS is not set
++# CONFIG_HOST_OTHER is not set
++# CONFIG_WINDOWS_NATIVE is not set
++
++#
++# Build Configuration
++#
++CONFIG_APPS_DIR="../apps"
++CONFIG_FRAMEWORK_DIR="../framework"
++CONFIG_TOOLS_DIR="../tools"
++CONFIG_BUILD_FLAT=y
++# CONFIG_BUILD_PROTECTED is not set
++# CONFIG_BUILD_2PASS is not set
++
++#
++# Binary Output Formats
++#
++# CONFIG_INTELHEX_BINARY is not set
++# CONFIG_MOTOROLA_SREC is not set
++CONFIG_RAW_BINARY=y
++CONFIG_SAMSUNG_NS2=y
++# CONFIG_UBOOT_UIMAGE is not set
++# CONFIG_DOWNLOAD_IMAGE is not set
++# CONFIG_SMARTFS_IMAGE is not set
++
++#
++# Customize Header Files
++#
++# CONFIG_ARCH_STDINT_H is not set
++# CONFIG_ARCH_STDBOOL_H is not set
++# CONFIG_ARCH_MATH_H is not set
++# CONFIG_ARCH_FLOAT_H is not set
++# CONFIG_ARCH_STDARG_H is not set
++
++#
++# Debug Options
++#
++CONFIG_DEBUG=y
++CONFIG_DEBUG_ERROR=y
++# CONFIG_DEBUG_WARN is not set
++CONFIG_DEBUG_VERBOSE=y
++
++#
++# Subsystem Debug Options
++#
++# CONFIG_DEBUG_FS is not set
++# CONFIG_DEBUG_LIB is not set
++# CONFIG_DEBUG_MM is not set
++CONFIG_DEBUG_NET=y
++# CONFIG_DEBUG_NET_ERROR is not set
++# CONFIG_DEBUG_NET_INFO is not set
++# CONFIG_DEBUG_SCHED is not set
++CONFIG_DEBUG_WLAN=y
++
++#
++# SLSI WLAN FW Debug Options
++#
++# CONFIG_SCSC_ENABLE_FWFAULT_LOG is not set
++
++#
++# SLSI WLAN Driver Debug Options
++#
++CONFIG_DEBUG_WLAN_DRIVER_ERROR=y
++# CONFIG_DEBUG_WLAN_DRIVER_DEBUG is not set
++# CONFIG_DEBUG_WLAN_DRIVER_MORE is not set
++# CONFIG_DEBUG_WLAN_DRIVER_VERBOSE is not set
++
++#
++# SLSI WPA Supplicant Debug Options
++#
++CONFIG_DEBUG_WLAN_SUPPLICANT_ERROR=y
++# CONFIG_DEBUG_WLAN_SUPPLICANT_DEBUG is not set
++# CONFIG_DEBUG_WLAN_SUPPLICANT_MORE is not set
++# CONFIG_DEBUG_WLAN_SUPPLICANT_VERBOSE is not set
++
++#
++# SLSI Wi-Fi API Debug Options
++#
++CONFIG_DEBUG_WLAN_API_ERROR=y
++# CONFIG_DEBUG_WLAN_API_DEBUG is not set
++# CONFIG_DEBUG_WLAN_API_VERBOSE is not set
++
++#
++# OS Function Debug Options
++#
++# CONFIG_ARCH_HAVE_HEAPCHECK is not set
++CONFIG_DEBUG_MM_HEAPINFO=y
++# CONFIG_DEBUG_IRQ is not set
++
++#
++# Driver Debug Options
++#
++# CONFIG_DEBUG_PWM is not set
++# CONFIG_DEBUG_RTC is not set
++# CONFIG_DEBUG_SPI is not set
++# CONFIG_DEBUG_WATCHDOG is not set
++# CONFIG_DEBUG_TTRACE is not set
++
++#
++# Stack Debug Options
++#
++CONFIG_ARCH_HAVE_STACKCHECK=y
++CONFIG_STACK_COLORATION=y
++
++#
++# Build Debug Options
++#
++CONFIG_DEBUG_SYMBOLS=y
++# CONFIG_FRAME_POINTER is not set
++CONFIG_ARCH_HAVE_CUSTOMOPT=y
++# CONFIG_DEBUG_NOOPT is not set
++# CONFIG_DEBUG_CUSTOMOPT is not set
++CONFIG_DEBUG_FULLOPT=y
++
++#
++# Chip Selection
++#
++CONFIG_ARCH_ARM=y
++CONFIG_ARCH="arm"
++
++#
++# ARM Options
++#
++CONFIG_ARCH_CHIP_S5J=y
++# CONFIG_ARCH_CORTEXM3 is not set
++# CONFIG_ARCH_CORTEXM4 is not set
++CONFIG_ARCH_CORTEXR4=y
++CONFIG_ARCH_FAMILY="armv7-r"
++CONFIG_ARCH_CHIP="s5j"
++# CONFIG_ARCH_HAVE_FPU is not set
++CONFIG_ARMV7M_MPU=y
++CONFIG_ARMV7M_MPU_NREGIONS=12
++
++#
++# Exception stack options
++#
++CONFIG_ARCH_HAVE_DABORTSTACK=y
++CONFIG_ARCH_DABORTSTACK=0
++
++#
++# ARMv7-R Configuration Options
++#
++CONFIG_ARMV7R_HAVE_GICv2=y
++CONFIG_ARMV7R_MEMINIT=y
++CONFIG_ARMV7R_ICACHE=y
++CONFIG_ARMV7R_DCACHE=y
++# CONFIG_ARMV7R_DCACHE_WRITETHROUGH is not set
++# CONFIG_ARMV7R_HAVE_L2CC is not set
++# CONFIG_ARMV7R_HAVE_L2CC_PL310 is not set
++# CONFIG_ARMV7R_TOOLCHAIN_BUILDROOT is not set
++# CONFIG_ARMV7R_TOOLCHAIN_CODESOURCERYL is not set
++CONFIG_ARMV7R_TOOLCHAIN_GNU_EABIL=y
++# CONFIG_ARMV7R_TOOLCHAIN_GNU_OABI is not set
++# CONFIG_ARMV7R_HAVE_DECODEFIQ is not set
++# CONFIG_BOOT_RESULT is not set
++
++#
++# S5J Configuration Options
++#
++CONFIG_ARCH_CHIP_S5JT200=y
++CONFIG_S5J_S5JT200=y
++
++#
++# S5J Peripheral Support
++#
++CONFIG_S5J_HAVE_ADC=y
++CONFIG_S5J_HAVE_I2C=y
++CONFIG_S5J_HAVE_MCT=y
++CONFIG_S5J_HAVE_PWM0=y
++CONFIG_S5J_HAVE_PWM1=y
++CONFIG_S5J_HAVE_PWM2=y
++CONFIG_S5J_HAVE_PWM3=y
++CONFIG_S5J_HAVE_PWM4=y
++CONFIG_S5J_HAVE_PWM5=y
++CONFIG_S5J_HAVE_PWR=y
++CONFIG_S5J_HAVE_RTC=y
++CONFIG_S5J_HAVE_SFLASH=y
++CONFIG_S5J_HAVE_SPI=y
++CONFIG_S5J_HAVE_SSS=y
++CONFIG_S5J_HAVE_UART0=y
++CONFIG_S5J_HAVE_UART1=y
++CONFIG_S5J_HAVE_UART2=y
++CONFIG_S5J_HAVE_UART3=y
++CONFIG_S5J_HAVE_UART4=y
++CONFIG_S5J_HAVE_WATCHDOG=y
++CONFIG_S5J_ADC=y
++CONFIG_S5J_I2C=y
++# CONFIG_S5J_MCT is not set
++# CONFIG_S5J_TIMER0 is not set
++# CONFIG_S5J_TIMER1 is not set
++# CONFIG_S5J_TIMER2 is not set
++# CONFIG_S5J_TIMER3 is not set
++# CONFIG_S5J_UART_FLOWCONTROL is not set
++CONFIG_S5J_UART0=y
++CONFIG_S5J_UART1=y
++CONFIG_S5J_UART2=y
++# CONFIG_S5J_UART2_FLOWCONTROL is not set
++CONFIG_S5J_UART3=y
++# CONFIG_S5J_UART3_FLOWCONTROL is not set
++CONFIG_S5J_UART4=y
++CONFIG_S5J_PWM=y
++CONFIG_S5J_PWM0=y
++CONFIG_S5J_PWM1=y
++CONFIG_S5J_PWM2=y
++CONFIG_S5J_PWM3=y
++CONFIG_S5J_PWM4=y
++CONFIG_S5J_PWM5=y
++CONFIG_S5J_SSS=y
++CONFIG_S5J_SPI=y
++# CONFIG_S5J_WATCHDOG is not set
++CONFIG_S5J_SFLASH=y
++CONFIG_S5J_PWR=y
++
++#
++# PMU Configuration
++#
++CONFIG_S5J_PWR_DSTOP=y
++# CONFIG_S5J_PWR_SLEEP is not set
++
++#
++# Architecture Options
++#
++# CONFIG_ARCH_NOINTC is not set
++# CONFIG_ARCH_VECNOTIRQ is not set
++# CONFIG_ARCH_DMA is not set
++# CONFIG_ARCH_HAVE_IRQPRIO is not set
++# CONFIG_ARCH_L2CACHE is not set
++# CONFIG_ARCH_HAVE_COHERENT_DCACHE is not set
++# CONFIG_ARCH_HAVE_ADDRENV is not set
++# CONFIG_ARCH_NEED_ADDRENV_MAPPING is not set
++CONFIG_ARCH_HAVE_VFORK=y
++# CONFIG_ARCH_HAVE_MMU is not set
++CONFIG_ARCH_HAVE_MPU=y
++# CONFIG_ARCH_NAND_HWECC is not set
++# CONFIG_ARCH_HAVE_EXTCLK is not set
++# CONFIG_ARCH_HAVE_POWEROFF is not set
++CONFIG_ARCH_HAVE_RESET=y
++CONFIG_ARCH_USE_MPU=y
++CONFIG_ARCH_STACKDUMP=y
++# CONFIG_ENDIAN_BIG is not set
++# CONFIG_ARCH_IDLE_CUSTOM is not set
++CONFIG_ARCH_CUSTOM_PMINIT=y
++# CONFIG_ARCH_HAVE_RAMFUNCS is not set
++# CONFIG_ARCH_HAVE_RAMVECTORS is not set
++
++#
++# Board Settings
++#
++CONFIG_BOARD_LOOPSPERMSEC=29100
++# CONFIG_ARCH_CALIBRATION is not set
++
++#
++# Interrupt options
++#
++CONFIG_ARCH_HAVE_INTERRUPTSTACK=y
++CONFIG_ARCH_INTERRUPTSTACK=0
++# CONFIG_ARCH_HAVE_HIPRI_INTERRUPT is not set
++
++#
++# Boot options
++#
++# CONFIG_BOOT_RUNFROMEXTSRAM is not set
++CONFIG_BOOT_RUNFROMFLASH=y
++# CONFIG_BOOT_RUNFROMISRAM is not set
++# CONFIG_BOOT_RUNFROMSDRAM is not set
++# CONFIG_BOOT_COPYTORAM is not set
++
++#
++# Boot Memory Configuration
++#
++CONFIG_RAM_START=0x02023800
++CONFIG_RAM_SIZE=804864
++# CONFIG_ARCH_HAVE_SDRAM is not set
++
++#
++# Board Selection
++#
++CONFIG_ARCH_BOARD_ARTIK053=y
++# CONFIG_ARCH_BOARD_SIDK_S5JT200 is not set
++CONFIG_ARCH_BOARD="artik053"
++
++#
++# Common Board Options
++#
++# CONFIG_BOARD_CRASHDUMP is not set
++CONFIG_LIB_BOARDCTL=y
++CONFIG_BOARDCTL_RESET=y
++# CONFIG_BOARDCTL_UNIQUEID is not set
++# CONFIG_BOARD_COREDUMP_FLASH is not set
++# CONFIG_BOARD_FOTA_SUPPORT is not set
++# CONFIG_BOARD_RAMDUMP_FLASH is not set
++# CONFIG_BOARD_RAMDUMP_UART is not set
++
++#
++# Board-Specific Options
++#
++CONFIG_ARTIK053_BOOT_FAILURE_DETECTION=y
++CONFIG_ARTIK053_BOOT_COUNTS_ADDR=0x80090810
++CONFIG_ARTIK053_FLASH_CAPACITY=8388608
++CONFIG_ARTIK053_FLASH_PAGE_SIZE=4096
++CONFIG_ARTIK053_FLASH_PART=y
++CONFIG_ARTIK053_FLASH_MINOR=0
++CONFIG_ARTIK053_FLASH_PART_LIST="16,48,192,32,512,2400,1536,1536,1000,400,8,512,"
++CONFIG_ARTIK053_FLASH_PART_TYPE="none,ftl,none,none,none,none,none,ftl,smartfs,romfs,config,none,"
++CONFIG_ARTIK053_FLASH_PART_NAME="bl1,sssro,bl2,sssfw,wlanfw,os,factory,ota,user,rom,nvram,sssrw,"
++CONFIG_ARTIK053_AUTOMOUNT=y
++CONFIG_ARTIK053_AUTOMOUNT_USERFS=y
++CONFIG_ARTIK053_AUTOMOUNT_USERFS_DEVNAME="/dev/smart0p8"
++CONFIG_ARTIK053_AUTOMOUNT_USERFS_MOUNTPOINT="/mnt"
++
++#
++# RTOS Features
++#
++CONFIG_DISABLE_OS_API=y
++# CONFIG_DISABLE_POSIX_TIMERS is not set
++# CONFIG_DISABLE_PTHREAD is not set
++# CONFIG_DISABLE_SIGNALS is not set
++# CONFIG_DISABLE_MQUEUE is not set
++# CONFIG_DISABLE_ENVIRON is not set
++
++#
++# Clocks and Timers
++#
++CONFIG_ARCH_HAVE_TICKLESS=y
++# CONFIG_SCHED_TICKLESS is not set
++CONFIG_USEC_PER_TICK=9979
++CONFIG_SYSTEM_TIME64=y
++CONFIG_CLOCK_MONOTONIC=y
++# CONFIG_JULIAN_TIME is not set
++CONFIG_MAX_WDOGPARMS=4
++CONFIG_PREALLOC_WDOGS=32
++CONFIG_WDOG_INTRESERVE=4
++CONFIG_PREALLOC_TIMERS=8
++
++#
++# Tasks and Scheduling
++#
++CONFIG_INIT_ENTRYPOINT=y
++CONFIG_RR_INTERVAL=100
++CONFIG_TASK_NAME_SIZE=31
++CONFIG_MAX_TASKS=32
++CONFIG_SCHED_HAVE_PARENT=y
++# CONFIG_SCHED_CHILD_STATUS is not set
++CONFIG_SCHED_WAITPID=y
++
++#
++# Pthread Options
++#
++CONFIG_PTHREAD_MUTEX_TYPES=y
++# CONFIG_PTHREAD_MUTEX_ROBUST is not set
++CONFIG_PTHREAD_MUTEX_UNSAFE=y
++# CONFIG_PTHREAD_MUTEX_BOTH is not set
++CONFIG_NPTHREAD_KEYS=4
++# CONFIG_PTHREAD_CLEANUP is not set
++# CONFIG_CANCELLATION_POINTS is not set
++
++#
++# Performance Monitoring
++#
++# CONFIG_SCHED_CPULOAD is not set
++# CONFIG_SCHED_INSTRUMENTATION is not set
++
++#
++# Latency optimization
++#
++# CONFIG_SCHED_YIELD_OPTIMIZATION is not set
++
++#
++# Files and I/O
++#
++CONFIG_DEV_CONSOLE=y
++# CONFIG_FDCLONE_DISABLE is not set
++# CONFIG_FDCLONE_STDIO is not set
++# CONFIG_SDCLONE_DISABLE is not set
++CONFIG_NFILE_DESCRIPTORS=16
++CONFIG_NFILE_STREAMS=16
++CONFIG_NAME_MAX=32
++CONFIG_PRIORITY_INHERITANCE=y
++CONFIG_SEM_PREALLOCHOLDERS=16
++CONFIG_SEM_NNESTPRIO=16
++
++#
++# RTOS hooks
++#
++CONFIG_BOARD_INITIALIZE=y
++# CONFIG_BOARD_INITTHREAD is not set
++# CONFIG_SCHED_STARTHOOK is not set
++CONFIG_SCHED_ATEXIT=y
++CONFIG_SCHED_ONEXIT=y
++CONFIG_SCHED_ONEXIT_MAX=1
++
++#
++# Signal Numbers
++#
++CONFIG_SIG_SIGUSR1=1
++CONFIG_SIG_SIGUSR2=2
++CONFIG_SIG_SIGALARM=3
++CONFIG_SIG_SIGCHLD=4
++CONFIG_SIG_SIGCONDTIMEDOUT=16
++CONFIG_SIG_SIGWORK=17
++
++#
++# POSIX Message Queue Options
++#
++CONFIG_PREALLOC_MQ_MSGS=4
++CONFIG_MQ_MAXMSGSIZE=600
++
++#
++# Work Queue Support
++#
++CONFIG_SCHED_WORKQUEUE=y
++CONFIG_SCHED_WORKQUEUE_SORTING=y
++CONFIG_SCHED_HPWORK=y
++CONFIG_SCHED_HPWORKPRIORITY=224
++CONFIG_SCHED_HPWORKPERIOD=50000
++CONFIG_SCHED_HPWORKSTACKSIZE=2048
++CONFIG_SCHED_LPWORK=y
++CONFIG_SCHED_LPNTHREADS=1
++CONFIG_SCHED_LPWORKPRIORITY=176
++CONFIG_SCHED_LPWORKPRIOMAX=176
++CONFIG_SCHED_LPWORKPERIOD=50000
++CONFIG_SCHED_LPWORKSTACKSIZE=2048
++
++#
++# Stack size information
++#
++CONFIG_IDLETHREAD_STACKSIZE=1024
++CONFIG_USERMAIN_STACKSIZE=2048
++CONFIG_PREAPP_STACKSIZE=2048
++# CONFIG_MPU_STACKGAURD is not set
++CONFIG_PTHREAD_STACK_MIN=256
++CONFIG_PTHREAD_STACK_DEFAULT=2048
++
++#
++# System Call
++#
++# CONFIG_LIB_SYSCALL is not set
++
++#
++# Device Drivers
++#
++# CONFIG_DISABLE_POLL is not set
++CONFIG_DEV_NULL=y
++CONFIG_DEV_ZERO=y
++
++#
++# Buffering
++#
++# CONFIG_DRVR_WRITEBUFFER is not set
++# CONFIG_DRVR_READAHEAD is not set
++# CONFIG_CAN is not set
++# CONFIG_ARCH_HAVE_PWM_PULSECOUNT is not set
++# CONFIG_ARCH_HAVE_PWM_MULTICHAN is not set
++CONFIG_PWM=y
++# CONFIG_ARCH_HAVE_I2CRESET is not set
++CONFIG_I2C=y
++CONFIG_I2C_SLAVE=y
++CONFIG_I2C_USERIO=y
++CONFIG_I2C_TRANSFER=y
++CONFIG_I2C_POLLED=y
++# CONFIG_I2C_TRACE is not set
++# CONFIG_I2C_WRITEREAD is not set
++CONFIG_SPI=y
++# CONFIG_SPI_OWNBUS is not set
++# CONFIG_SPI_EXCHANGE is not set
++# CONFIG_SPI_CMDDATA is not set
++# CONFIG_SPI_BITBANG is not set
++CONFIG_GPIO=y
++CONFIG_I2S=y
++# CONFIG_BCH is not set
++CONFIG_RTC=y
++CONFIG_RTC_DATETIME=y
++# CONFIG_RTC_ALARM is not set
++CONFIG_RTC_DRIVER=y
++# CONFIG_RTC_IOCTL is not set
++CONFIG_WATCHDOG=y
++CONFIG_WATCHDOG_DEVPATH="/dev/watchdog0"
++# CONFIG_TIMER is not set
++CONFIG_ANALOG=y
++CONFIG_ADC=y
++CONFIG_ADC_FIFOSIZE=8
++# CONFIG_DAC is not set
++# CONFIG_AUDIO_DEVICES is not set
++# CONFIG_LCD is not set
++CONFIG_NETDEVICES=y
++
++#
++# General Ethernet MAC Driver Options
++#
++CONFIG_NETDEV_TELNET=y
++CONFIG_NETDEV_MULTINIC=y
++# CONFIG_NET_DUMPPACKET is not set
++
++#
++# External Ethernet MAC Device Support
++#
++# CONFIG_NET_DM90x0 is not set
++# CONFIG_ENC28J60 is not set
++# CONFIG_ENCX24J600 is not set
++# CONFIG_NET_E1000 is not set
++# CONFIG_NET_SLIP is not set
++# CONFIG_NET_VNET is not set
++# CONFIG_PIPES is not set
++CONFIG_POWER=y
++# CONFIG_BATTERY_CHARGER is not set
++# CONFIG_BATTERY_GAUGE is not set
++# CONFIG_SERCOMM_CONSOLE is not set
++CONFIG_SERIAL=y
++# CONFIG_DEV_LOWCONSOLE is not set
++# CONFIG_16550_UART is not set
++# CONFIG_ARCH_HAVE_UART is not set
++CONFIG_ARCH_HAVE_UART0=y
++CONFIG_ARCH_HAVE_UART1=y
++CONFIG_ARCH_HAVE_UART2=y
++CONFIG_ARCH_HAVE_UART3=y
++CONFIG_ARCH_HAVE_UART4=y
++# CONFIG_ARCH_HAVE_UART5 is not set
++# CONFIG_ARCH_HAVE_UART6 is not set
++# CONFIG_ARCH_HAVE_UART7 is not set
++# CONFIG_ARCH_HAVE_UART8 is not set
++# CONFIG_ARCH_HAVE_SCI0 is not set
++# CONFIG_ARCH_HAVE_SCI1 is not set
++# CONFIG_ARCH_HAVE_USART0 is not set
++# CONFIG_ARCH_HAVE_USART1 is not set
++# CONFIG_ARCH_HAVE_USART2 is not set
++# CONFIG_ARCH_HAVE_USART3 is not set
++# CONFIG_ARCH_HAVE_USART4 is not set
++# CONFIG_ARCH_HAVE_USART5 is not set
++# CONFIG_ARCH_HAVE_USART6 is not set
++# CONFIG_ARCH_HAVE_USART7 is not set
++# CONFIG_ARCH_HAVE_USART8 is not set
++# CONFIG_ARCH_HAVE_OTHER_UART is not set
++
++#
++# USART Configuration
++#
++CONFIG_MCU_SERIAL=y
++CONFIG_STANDARD_SERIAL=y
++CONFIG_SERIAL_NPOLLWAITERS=2
++# CONFIG_SERIAL_IFLOWCONTROL is not set
++# CONFIG_SERIAL_OFLOWCONTROL is not set
++# CONFIG_SERIAL_TIOCSERGSTRUCT is not set
++CONFIG_ARCH_HAVE_SERIAL_TERMIOS=y
++CONFIG_SERIAL_TERMIOS=y
++# CONFIG_UART0_SERIAL_CONSOLE is not set
++# CONFIG_UART1_SERIAL_CONSOLE is not set
++# CONFIG_UART2_SERIAL_CONSOLE is not set
++# CONFIG_UART3_SERIAL_CONSOLE is not set
++CONFIG_UART4_SERIAL_CONSOLE=y
++# CONFIG_OTHER_SERIAL_CONSOLE is not set
++# CONFIG_NO_SERIAL_CONSOLE is not set
++
++#
++# UART0 Configuration
++#
++CONFIG_UART0_RXBUFSIZE=64
++CONFIG_UART0_TXBUFSIZE=64
++CONFIG_UART0_BAUD=115200
++CONFIG_UART0_BITS=8
++CONFIG_UART0_PARITY=0
++CONFIG_UART0_2STOP=0
++# CONFIG_UART0_IFLOWCONTROL is not set
++# CONFIG_UART0_OFLOWCONTROL is not set
++
++#
++# UART1 Configuration
++#
++CONFIG_UART1_RXBUFSIZE=256
++CONFIG_UART1_TXBUFSIZE=256
++CONFIG_UART1_BAUD=115200
++CONFIG_UART1_BITS=8
++CONFIG_UART1_PARITY=0
++CONFIG_UART1_2STOP=0
++# CONFIG_UART1_IFLOWCONTROL is not set
++# CONFIG_UART1_OFLOWCONTROL is not set
++
++#
++# UART2 Configuration
++#
++CONFIG_UART2_RXBUFSIZE=256
++CONFIG_UART2_TXBUFSIZE=256
++CONFIG_UART2_BAUD=115200
++CONFIG_UART2_BITS=8
++CONFIG_UART2_PARITY=0
++CONFIG_UART2_2STOP=0
++# CONFIG_UART2_IFLOWCONTROL is not set
++# CONFIG_UART2_OFLOWCONTROL is not set
++
++#
++# UART3 Configuration
++#
++CONFIG_UART3_RXBUFSIZE=256
++CONFIG_UART3_TXBUFSIZE=256
++CONFIG_UART3_BAUD=115200
++CONFIG_UART3_BITS=8
++CONFIG_UART3_PARITY=0
++CONFIG_UART3_2STOP=0
++# CONFIG_UART3_IFLOWCONTROL is not set
++# CONFIG_UART3_OFLOWCONTROL is not set
++
++#
++# UART4 Configuration
++#
++CONFIG_UART4_RXBUFSIZE=256
++CONFIG_UART4_TXBUFSIZE=256
++CONFIG_UART4_BAUD=115200
++CONFIG_UART4_BITS=8
++CONFIG_UART4_PARITY=0
++CONFIG_UART4_2STOP=0
++# CONFIG_UART4_IFLOWCONTROL is not set
++# CONFIG_UART4_OFLOWCONTROL is not set
++# CONFIG_USBDEV is not set
++# CONFIG_FOTA_DRIVER is not set
++
++#
++# System Logging
++#
++# CONFIG_RAMLOG is not set
++# CONFIG_SYSLOG_CONSOLE is not set
++
++#
++# T-trace
++#
++# CONFIG_TTRACE is not set
++
++#
++# Wireless Device Options
++#
++CONFIG_DRIVERS_WIRELESS=y
++CONFIG_SCSC_WLAN=y
++# CONFIG_SLSI_RX_PERFORMANCE_TEST is not set
++CONFIG_SCSC_TX_FLOW_CONTROL=y
++CONFIG_SCSC_ENABLE_PORT_CONTROL=y
++# CONFIG_SCSC_WLAN_STA_ONLY is not set
++# CONFIG_SCSC_WLAN_BLOCK_IPV6 is not set
++# CONFIG_SCSC_WLAN_UDP_FLOWCONTROL is not set
++# CONFIG_SCSC_WLAN_AUTO_RECOVERY is not set
++CONFIG_SCSC_WLAN_POWER_SAVE=y
++CONFIG_SCSC_WLAN_MAX_INTERFACES=1
++CONFIG_SCSC_CORE=y
++CONFIG_SCSC_PLATFORM=y
++# CONFIG_SCSC_WLANLITE is not set
++# CONFIG_SCSC_DISABLE_WLAN_RESET is not set
++
++#
++# Networking Support
++#
++CONFIG_ARCH_HAVE_NET=y
++# CONFIG_ARCH_HAVE_PHY is not set
++CONFIG_NET=y
++CONFIG_NET_LWIP=y
++
++#
++# LwIP options
++#
++CONFIG_NET_IPv4=y
++CONFIG_NET_IP_DEFAULT_TTL=255
++# CONFIG_NET_IP_FORWARD is not set
++CONFIG_NET_IP_OPTIONS_ALLOWED=y
++CONFIG_NET_IP_FRAG=y
++CONFIG_NET_IP_REASSEMBLY=y
++CONFIG_NET_IPV4_REASS_MAX_PBUFS=20
++CONFIG_NET_IPV4_REASS_MAXAGE=5
++
++#
++# Socket support
++#
++CONFIG_NET_SOCKET=y
++CONFIG_NSOCKET_DESCRIPTORS=8
++CONFIG_NET_TCP_KEEPALIVE=y
++CONFIG_NET_RAW=y
++# CONFIG_NET_SOCKET_OPTION_BROADCAST is not set
++# CONFIG_NET_RANDOMIZE_INITIAL_LOCAL_PORTS is not set
++# CONFIG_NET_SO_SNDTIMEO is not set
++CONFIG_NET_SO_RCVTIMEO=y
++# CONFIG_NET_SO_RCVBUF is not set
++CONFIG_NET_SO_REUSE=y
++# CONFIG_NET_SO_REUSE_RXTOALL is not set
++CONFIG_NET_ARP=y
++CONFIG_NET_ARP_TABLESIZE=10
++CONFIG_NET_ARP_QUEUEING=y
++CONFIG_NET_ETHARP_TRUST_IP_MAC=y
++CONFIG_NET_ETH_PAD_SIZE=0
++# CONFIG_NET_ARP_STATIC_ENTRIES is not set
++CONFIG_NET_UDP=y
++# CONFIG_NET_NETBUF_RECVINFO is not set
++CONFIG_NET_UDP_TTL=255
++# CONFIG_NET_UDPLITE is not set
++CONFIG_NET_TCP=y
++CONFIG_NET_TCP_TTL=255
++CONFIG_NET_TCP_WND=58400
++CONFIG_NET_TCP_MAXRTX=12
++CONFIG_NET_TCP_SYNMAXRTX=6
++CONFIG_NET_TCP_QUEUE_OOSEQ=y
++CONFIG_NET_TCP_MSS=1460
++CONFIG_NET_TCP_CALCULATE_EFF_SEND_MSS=y
++CONFIG_NET_TCP_SND_BUF=29200
++CONFIG_NET_TCP_SND_QUEUELEN=80
++# CONFIG_NET_TCP_LISTEN_BACKLOG is not set
++CONFIG_NET_TCP_OVERSIZE=536
++# CONFIG_NET_TCP_TIMESTAMPS is not set
++CONFIG_NET_TCP_WND_UPDATE_THREASHOLD=536
++CONFIG_NET_ICMP=y
++CONFIG_NET_ICMP_TTL=255
++# CONFIG_NET_BROADCAST_PING is not set
++# CONFIG_NET_MULTICAST_PING is not set
++CONFIG_NET_LWIP_IGMP=y
++CONFIG_NET_LWIP_MEMP_NUM_IGMP_GROUP=8
++
++#
++# LWIP Mailbox Configurations
++#
++CONFIG_NET_TCPIP_MBOX_SIZE=64
++CONFIG_NET_DEFAULT_ACCEPTMBOX_SIZE=64
++CONFIG_NET_DEFAULT_RAW_RECVMBOX_SIZE=64
++CONFIG_NET_DEFAULT_TCP_RECVMBOX_SIZE=54
++CONFIG_NET_DEFAULT_UDP_RECVMBOX_SIZE=64
++
++#
++# Memory Configurations
++#
++CONFIG_NET_MEM_ALIGNMENT=4
++# CONFIG_NET_ALLOW_MEM_FREE_FROM_OTHER_CONTEXT is not set
++# CONFIG_NET_MEM_LIBC_MALLOC is not set
++CONFIG_NET_MEMP_MEM_MALLOC=y
++# CONFIG_NET_MEM_USE_POOLS is not set
++CONFIG_NET_MEM_SIZE=153600
++
++#
++# LWIP Task Configurations
++#
++# CONFIG_NET_TCPIP_CORE_LOCKING is not set
++# CONFIG_NET_TCPIP_CORE_LOCKING_INPUT is not set
++CONFIG_NET_TCPIP_THREAD_NAME="LWIP_TCP/IP"
++CONFIG_NET_TCPIP_THREAD_PRIO=110
++CONFIG_NET_TCPIP_THREAD_STACKSIZE=4096
++CONFIG_NET_COMPAT_MUTEX=y
++CONFIG_NET_SYS_LIGHTWEIGHT_PROT=y
++CONFIG_NET_DEFAULT_THREAD_NAME="lwIP"
++CONFIG_NET_DEFAULT_THREAD_PRIO=1
++CONFIG_NET_DEFAULT_THREAD_STACKSIZE=0
++
++#
++# Debug Options for Network
++#
++# CONFIG_NET_LWIP_DEBUG is not set
++
++#
++# Enable Statistics
++#
++CONFIG_NET_STATS=y
++CONFIG_NET_STATS_DISPLAY=y
++CONFIG_NET_LINK_STATS=y
++CONFIG_NET_ETHARP_STATS=y
++CONFIG_NET_IP_STATS=y
++# CONFIG_NET_IPFRAG_STATS is not set
++# CONFIG_NET_ICMP_STATS is not set
++CONFIG_NET_UDP_STATS=y
++CONFIG_NET_TCP_STATS=y
++CONFIG_NET_MEM_STATS=y
++CONFIG_NET_SYS_STATS=y
++# CONFIG_NET_LWIP_VLAN is not set
++CONFIG_NET_LWIP_LOOPBACK_INTERFACE=y
++# CONFIG_NET_LWIP_SLIP_INTERFACE is not set
++# CONFIG_NET_LWIP_PPP_SUPPORT is not set
++# CONFIG_NET_LWIP_SNMP is not set
++CONFIG_NET_SECURITY_TLS=y
++# CONFIG_TLS_WITH_SSS is not set
++
++#
++# Driver buffer configuration
++#
++CONFIG_NET_MULTIBUFFER=y
++CONFIG_NET_ETH_MTU=1500
++CONFIG_NET_GUARDSIZE=2
++
++#
++# Data link support
++#
++# CONFIG_NET_MULTILINK is not set
++CONFIG_NET_ETHERNET=y
++
++#
++# Network Device Operations
++#
++# CONFIG_NETDEV_PHY_IOCTL is not set
++
++#
++# Routing Table Configuration
++#
++# CONFIG_NET_ROUTE is not set
++
++#
++# File Systems
++#
++
++#
++# File system configuration
++#
++# CONFIG_DISABLE_MOUNTPOINT is not set
++# CONFIG_FS_AUTOMOUNTER is not set
++# CONFIG_DISABLE_PSEUDOFS_OPERATIONS is not set
++CONFIG_FS_READABLE=y
++CONFIG_FS_WRITABLE=y
++# CONFIG_FS_AIO is not set
++# CONFIG_FS_NAMED_SEMAPHORES is not set
++CONFIG_FS_MQUEUE_MPATH="/var/mqueue"
++CONFIG_FS_SMARTFS=y
++
++#
++# SMARTFS options
++#
++CONFIG_SMARTFS_ERASEDSTATE=0xff
++CONFIG_SMARTFS_MAXNAMLEN=32
++# CONFIG_SMARTFS_MULTI_ROOT_DIRS is not set
++CONFIG_SMARTFS_ALIGNED_ACCESS=y
++# CONFIG_SMARTFS_BAD_SECTOR is not set
++# CONFIG_SMARTFS_DYNAMIC_HEADER is not set
++# CONFIG_SMARTFS_JOURNALING is not set
++# CONFIG_SMARTFS_SECTOR_RECOVERY is not set
++CONFIG_FS_PROCFS=y
++
++#
++# Exclude individual procfs entries
++#
++# CONFIG_FS_PROCFS_EXCLUDE_PROCESS is not set
++# CONFIG_FS_PROCFS_EXCLUDE_UPTIME is not set
++# CONFIG_FS_PROCFS_EXCLUDE_VERSION is not set
++# CONFIG_FS_PROCFS_EXCLUDE_MTD is not set
++# CONFIG_FS_PROCFS_EXCLUDE_PARTITIONS is not set
++# CONFIG_FS_PROCFS_EXCLUDE_SMARTFS is not set
++# CONFIG_FS_PROCFS_EXCLUDE_POWER is not set
++CONFIG_FS_ROMFS=y
++
++#
++# Block Driver Configurations
++#
++CONFIG_RAMDISK=y
++
++#
++# MTD Configuration
++#
++CONFIG_MTD=y
++CONFIG_MTD_PARTITION=y
++CONFIG_MTD_PARTITION_NAMES=y
++CONFIG_MTD_PROGMEM=y
++CONFIG_MTD_FTL=y
++
++#
++# MTD_FTL Configurations
++#
++CONFIG_MTD_CONFIG=y
++
++#
++# MTD Configurations
++#
++# CONFIG_MTD_CONFIG_RAM_CONSOLIDATE is not set
++CONFIG_MTD_CONFIG_ERASEDVALUE=0xff
++# CONFIG_MTD_BYTE_WRITE is not set
++
++#
++# MTD Device Drivers
++#
++# CONFIG_MTD_M25P is not set
++# CONFIG_RAMMTD is not set
++CONFIG_MTD_SMART=y
++
++#
++# SMART Device options
++#
++CONFIG_MTD_SMART_SECTOR_SIZE=4096
++# CONFIG_MTD_SMART_WEAR_LEVEL is not set
++# CONFIG_MTD_SMART_ENABLE_CRC is not set
++# CONFIG_MTD_SMART_SECTOR_ERASE_DEBUG is not set
++# CONFIG_MTD_SMART_ALLOC_DEBUG is not set
++
++#
++# System Logging
++#
++# CONFIG_SYSLOG is not set
++# CONFIG_SYSLOG_TIMESTAMP is not set
++
++#
++# Arastorage
++#
++
++#
++# AraStorage database configuration
++#
++# CONFIG_ARASTORAGE is not set
++
++#
++# Memory Management
++#
++# CONFIG_DISABLE_REALLOC_NEIGHBOR_EXTENTION is not set
++# CONFIG_MM_SMALL is not set
++CONFIG_MM_REGIONS=1
++# CONFIG_ARCH_HAVE_HEAP2 is not set
++# CONFIG_GRAN is not set
++
++#
++# Power Management
++#
++CONFIG_PM=y
++# CONFIG_DEBUG_PM is not set
++# CONFIG_PM_TEST is not set
++CONFIG_PM_DEVNAME_LEN=32
++# CONFIG_PM_METRICS is not set
++CONFIG_PM_SLICEMS=100
++CONFIG_PM_NDOMAINS=1
++CONFIG_PM_MEMORY=2
++CONFIG_PM_COEFN=1
++CONFIG_PM_COEF1=1
++CONFIG_PM_COEF2=1
++CONFIG_PM_COEF3=1
++CONFIG_PM_COEF4=1
++CONFIG_PM_COEF5=1
++CONFIG_PM_IDLEENTER_THRESH=1
++CONFIG_PM_IDLEEXIT_THRESH=2
++CONFIG_PM_IDLEENTER_COUNT=30
++CONFIG_PM_STANDBYENTER_THRESH=1
++CONFIG_PM_STANDBYEXIT_THRESH=2
++CONFIG_PM_STANDBYENTER_COUNT=50
++CONFIG_PM_SLEEPENTER_THRESH=1
++CONFIG_PM_SLEEPEXIT_THRESH=2
++CONFIG_PM_SLEEPENTER_COUNT=70
++
++#
++# Logger Module
++#
++CONFIG_LOGM=y
++# CONFIG_PRINTF2LOGM is not set
++CONFIG_SYSLOG2LOGM=y
++# CONFIG_LOGM_TIMESTAMP is not set
++CONFIG_LOGM_BUFFER_SIZE=10240
++CONFIG_LOGM_PRINT_INTERVAL=1000
++CONFIG_LOGM_TASK_PRIORITY=110
++CONFIG_LOGM_TASK_STACKSIZE=2048
++# CONFIG_LOGM_TEST is not set
++
++#
++# Library Routines
++#
++
++#
++# Standard C Library Options
++#
++CONFIG_STDIO_BUFFER_SIZE=64
++CONFIG_STDIO_LINEBUFFER=y
++CONFIG_NUNGET_CHARS=2
++CONFIG_LIB_HOMEDIR="/"
++CONFIG_LIBM=y
++# CONFIG_NOPRINTF_FIELDWIDTH is not set
++CONFIG_LIBC_FLOATINGPOINT=y
++CONFIG_LIBC_IOCTL_VARIADIC=y
++CONFIG_LIB_RAND_ORDER=1
++# CONFIG_EOL_IS_CR is not set
++# CONFIG_EOL_IS_LF is not set
++# CONFIG_EOL_IS_BOTH_CRLF is not set
++CONFIG_EOL_IS_EITHER_CRLF=y
++CONFIG_POSIX_SPAWN_PROXY_STACKSIZE=1024
++CONFIG_TASK_SPAWN_DEFAULT_STACKSIZE=2048
++CONFIG_LIBC_STRERROR=y
++# CONFIG_LIBC_STRERROR_SHORT is not set
++# CONFIG_LIBC_PERROR_STDOUT is not set
++CONFIG_LIBC_TMPDIR="/tmp"
++CONFIG_LIBC_MAX_TMPFILE=32
++CONFIG_ARCH_LOWPUTC=y
++# CONFIG_LIBC_LOCALTIME is not set
++# CONFIG_TIME_EXTENDED is not set
++CONFIG_LIB_SENDFILE_BUFSIZE=512
++# CONFIG_ARCH_ROMGETC is not set
++CONFIG_ARCH_OPTIMIZED_FUNCTIONS=y
++# CONFIG_ARCH_MEMCPY is not set
++CONFIG_MEMCPY_VIK=y
++# CONFIG_MEMCPY_PRE_INC_PTRS is not set
++CONFIG_MEMCPY_INDEXED_COPY=y
++# CONFIG_MEMCPY_64BIT is not set
++# CONFIG_ARCH_MEMCMP is not set
++# CONFIG_ARCH_MEMMOVE is not set
++# CONFIG_ARCH_MEMSET is not set
++# CONFIG_MEMSET_OPTSPEED is not set
++# CONFIG_ARCH_STRCHR is not set
++# CONFIG_ARCH_STRCMP is not set
++# CONFIG_ARCH_STRCPY is not set
++# CONFIG_ARCH_STRNCPY is not set
++# CONFIG_ARCH_STRLEN is not set
++# CONFIG_ARCH_STRNLEN is not set
++# CONFIG_ARCH_BZERO is not set
++CONFIG_LIBC_NETDB=y
++# CONFIG_NETDB_HOSTFILE is not set
++CONFIG_NETDB_DNSCLIENT=y
++CONFIG_NETDB_DNSCLIENT_ENTRIES=8
++CONFIG_NETDB_DNSCLIENT_NAMESIZE=32
++CONFIG_NETDB_DNSCLIENT_LIFESEC=3600
++CONFIG_NETDB_DNSCLIENT_MAXRESPONSE=512
++# CONFIG_NETDB_RESOLVCONF is not set
++CONFIG_NETDB_DNSSERVER_BY_DHCP=y
++# CONFIG_NETDB_DNSSERVER_IPv4 is not set
++
++#
++# Non-standard Library Support
++#
++
++#
++# Basic CXX Support
++#
++# CONFIG_C99_BOOL8 is not set
++# CONFIG_HAVE_CXX is not set
++
++#
++# External Functions
++#
++CONFIG_DM=y
++# CONFIG_LWM2M_WAKAAMA is not set
++CONFIG_DM_WIFI=y
++CONFIG_DM_AP_SSID="TizenRT1"
++CONFIG_DM_AP_PASS="tizenrt_tdc2017"
++CONFIG_DM_AP_SECURITY="wpa2_aes"
++
++#
++# IOTIVITY Config Parameters
++#
++# CONFIG_ENABLE_IOTIVITY is not set
++# CONFIG_LIBTUV is not set
++# CONFIG_AWS_SDK is not set
++
++#
++# Application Configuration
++#
++# CONFIG_ENTRY_MANUAL is not set
++
++#
++# Application entry point list
++#
++# CONFIG_ENTRY_HELLO is not set
++# CONFIG_ENTRY_IPERF is not set
++# CONFIG_ENTRY_WIFI_TEST is not set
++CONFIG_ENTRY_IOTJS=y
++CONFIG_USER_ENTRYPOINT="iotjs_main"
++CONFIG_BUILTIN_APPS=y
++
++#
++# Examples
++#
++# CONFIG_EXAMPLES_ARTIK_DEMO is not set
++# CONFIG_EXAMPLES_AWS is not set
++# CONFIG_EXAMPLES_DNSCLIENT_TEST is not set
++# CONFIG_EXAMPLES_DTLS_CLIENT is not set
++# CONFIG_EXAMPLES_DTLS_SERVER is not set
++# CONFIG_EXAMPLES_EEPROM_TEST is not set
++# CONFIG_EXAMPLES_FOTA_SAMPLE is not set
++CONFIG_EXAMPLES_HELLO=y
++# CONFIG_EXAMPLES_HELLO_TASH is not set
++# CONFIG_EXAMPLES_HELLOXX is not set
++# CONFIG_EXAMPLES_IOTBUS_TEST is not set
++CONFIG_EXAMPLES_IPERF=y
++# CONFIG_EXAMPLES_KERNEL_SAMPLE is not set
++# CONFIG_EXAMPLES_LIBTUV is not set
++# CONFIG_EXAMPLES_MTDPART is not set
++# CONFIG_EXAMPLES_NETTEST is not set
++# CONFIG_EXAMPLES_PROC_TEST is not set
++# CONFIG_EXAMPLES_SELECT_TEST is not set
++# CONFIG_EXAMPLES_SENSORBOARD is not set
++CONFIG_EXAMPLES_SLSIWIFI=y
++CONFIG_EXAMPLES_SLSIWIFI_PRIORITY=50
++CONFIG_EXAMPLES_SLSIWIFI_STACKSIZE=2048
++# CONFIG_EXAMPLES_SMART is not set
++# CONFIG_EXAMPLES_SMART_TEST is not set
++# CONFIG_EXAMPLES_SYSIO_TEST is not set
++# CONFIG_EXAMPLES_TESTCASE is not set
++# CONFIG_EXAMPLES_TLS_CLIENT is not set
++# CONFIG_EXAMPLES_TLS_SELFTEST is not set
++# CONFIG_EXAMPLES_TLS_SERVER is not set
++# CONFIG_EXAMPLES_WAKAAMA_CLIENT is not set
++CONFIG_EXAMPLES_WIFI_TEST=y
++# CONFIG_EXAMPLES_WORKQUEUE is not set
++
++#
++# Network Utilities
++#
++# CONFIG_NETUTILS_CODECS is not set
++CONFIG_NETUTILS_DHCPC=y
++CONFIG_NETUTILS_DHCPD=y
++CONFIG_NETUTILS_DHCPD_IGNOREBROADCAST=y
++CONFIG_NETUTILS_DHCPD_INTERFACE="wl1"
++CONFIG_NETUTILS_DHCPD_LEASETIME=864000
++CONFIG_NETUTILS_DHCPD_MINLEASETIME=86400
++CONFIG_NETUTILS_DHCPD_MAXLEASETIME=2592000
++CONFIG_NETUTILS_DHCPD_MAXLEASES=6
++CONFIG_NETUTILS_DHCPD_STARTIP=0xc0a82f02
++CONFIG_NETUTILS_DHCPD_ROUTERIP=0xc0a82f01
++CONFIG_NETUTILS_DHCPD_NETMASK=0xffffff00
++CONFIG_NETUTILS_DHCPD_DNSIP=0x08080808
++CONFIG_NETUTILS_DHCPD_OFFERTIME=3600
++CONFIG_NETUTILS_DHCPD_DECLINETIME=3600
++# CONFIG_NETUTILS_ERCOAP is not set
++# CONFIG_NETUTILS_FTPC is not set
++CONFIG_NETUTILS_FTPD=y
++CONFIG_NETUTILS_JSON=y
++# CONFIG_NETUTILS_MDNS is not set
++# CONFIG_NETUTILS_MQTT is not set
++CONFIG_NETUTILS_NETLIB=y
++# CONFIG_NETUTILS_NTPCLIENT is not set
++# CONFIG_NETUTILS_SMTP is not set
++# CONFIG_NETUTILS_TELNETD is not set
++# CONFIG_NETUTILS_TFTPC is not set
++# CONFIG_NETUTILS_WEBCLIENT is not set
++# CONFIG_NETUTILS_WEBSERVER is not set
++# CONFIG_NETUTILS_WEBSOCKET is not set
++CONFIG_NETUTILS_WIFI=y
++CONFIG_SLSI_WIFI_DEFAULT_WLAN_COUNTRY_CODE="00"
++CONFIG_SLSI_WIFI_DEFAULT_WLAN_TX_POWER=30
++# CONFIG_SLSI_WIFI_FILESYSTEM_SUPPORT is not set
++# CONFIG_NETUTILS_XMLRPC is not set
++
++#
++# Platform-specific Support
++#
++# CONFIG_PLATFORM_CONFIGDATA is not set
++
++#
++# Shell
++#
++CONFIG_TASH=y
++CONFIG_TASH_MAX_COMMANDS=132
++# CONFIG_DEBUG_TASH is not set
++CONFIG_TASH_TELNET_INTERFACE=y
++CONFIG_TASH_CMDTASK_STACKSIZE=4096
++CONFIG_TASH_CMDTASK_PRIORITY=100
++
++#
++# System Libraries and Add-Ons
++#
++# CONFIG_SYSTEM_CLE is not set
++# CONFIG_SYSTEM_CUTERM is not set
++# CONFIG_SYSTEM_FOTA_HAL is not set
++# CONFIG_SYSTEM_I2CTOOL is not set
++# CONFIG_SYSTEM_INIFILE is not set
++# CONFIG_SYSTEM_INSTALL is not set
++CONFIG_SYSTEM_IOTJS=y
++CONFIG_IOTJS_PRIORITY=100
++CONFIG_IOTJS_STACKSIZE=65536
++# CONFIG_SYSTEM_NETDB is not set
++# CONFIG_SYSTEM_POWEROFF is not set
++CONFIG_SYSTEM_RAMTEST=y
++# CONFIG_SYSTEM_RAMTRON is not set
++CONFIG_SYSTEM_READLINE=y
++CONFIG_READLINE_ECHO=y
++CONFIG_SYSTEM_INFORMATION=y
++CONFIG_KERNEL_CMDS=y
++CONFIG_FS_CMDS=y
++CONFIG_FSCMD_BUFFER_LEN=64
++CONFIG_NET_CMDS=y
++CONFIG_ENABLE_DATE=y
++CONFIG_ENABLE_ENV_GET=y
++CONFIG_ENABLE_ENV_SET=y
++CONFIG_ENABLE_ENV_UNSET=y
++CONFIG_ENABLE_FREE=y
++CONFIG_ENABLE_HEAPINFO=y
++CONFIG_ENABLE_KILL=y
++CONFIG_ENABLE_KILLALL=y
++CONFIG_ENABLE_PS=y
++CONFIG_ENABLE_STACKMONITOR=y
++CONFIG_STACKMONITOR_PRIORITY=100
++CONFIG_STACKMONITOR_INTERVAL=5
++CONFIG_ENABLE_UPTIME=y
++CONFIG_SYSTEM_VI=y
++CONFIG_SYSTEM_VI_COLS=64
++CONFIG_SYSTEM_VI_ROWS=16
++CONFIG_SYSTEM_VI_DEBUGLEVEL=0
++
++#
++# wpa_supplicant
++#
++CONFIG_WPA_SUPPLICANT=y
++CONFIG_WPA_SUPPLICANT_PRIORITY=100
++CONFIG_WPA_SUPPLICANT_STACKSIZE=16384
++CONFIG_WPA_SUPPLICANT_ENTRYPOINT="wpa_supplicant_main"
++CONFIG_CTRL_IFACE=y
++CONFIG_CTRL_IFACE_FIFO=y
++CONFIG_WPA_CTRL_FIFO_DEV_REQ="/dev/wpa_ctrl_req"
++CONFIG_WPA_CTRL_FIFO_DEV_CFM="/dev/wpa_ctrl_cfm"
++CONFIG_WPA_CTRL_FIFO_DEV_GLOBAL_REQ="/dev/wpa_ctrl_global_req"
++CONFIG_WPA_CTRL_FIFO_DEV_GLOBAL_CFM="/dev/wpa_ctrl_global_cfm"
++CONFIG_WPA_MONITOR_FIFO_DEV="/dev/wpa_monitor"
++CONFIG_WPA_CTRL_FIFO_MK_MODE=666
++CONFIG_ELOOP_POLL=y
++# CONFIG_WPA_SUPPLICANT_CMD is not set
--- /dev/null
--- /dev/null
++To contribute to the IoT.js Project (such as reporting bugs and submitting patches):
++* Follow the [Development Process](devs/Development-Process.md) and [GitHub contributor guidelines](https://guides.github.com/activities/contributing-to-open-source/).
++* Add the [IoT.js DCO](devs/IoT.js-Developer's-Certificate-of-Origin-1.0.md) signoff to each commit message during development.
++* Add the [License](License.md) if you introduce any new source code or script files
--- /dev/null
--- /dev/null
++### Supported platforms
++Current supported platforms are **Linux and NuttX**
++
++OSX 10.10 as development host
++
++* [Build for x86 / Linux](build/Build-for-x86-Linux.md): Ubuntu 14.04 is used as a base platform.
++* [Build for Stm32f4 / NuttX](build/Build-for-STM32F4-NuttX.md)
++* [Build for Raspberry Pi 2 / Linux](build/Build-for-RPi2-Linux.md)
++
++#### H/W boards
++* Current supporting
++ * STM32F4-Discovery + BB
++ * Raspberry Pi 2
++* Plan to support
++ * Samsung Artik 053
++ * Samsung Artik 10
++ * (and your contributions including above plans)
++
++We will support the correct behavior of APIs for above environments. However, since IoT.js is targeting various kind IoT devices and platforms, single implementation cannot be the best practice for every environments. Therefore embedders should be in charge of optimization for their own environments. For more details on optimization, see the [Optimization Tips](devs/Optimization-Tips.md) page.
++
++
++### Build script
++There is a script to help you build IoT.js called "[build.py](https://github.com/Samsung/iotjs/blob/master/tools/build.py)" in source repository.
++
--- /dev/null
-* If you would like to try IoT.js, please check [Getting Started](help/Getting-Started.md).
-* If you would like to jump into IoT.js, please follow [Development Process](help/Development-Process.md) of IoT.js.
-
-### IoT.js
-- Project Overview
+ Welcome to the IoT.js!
+
-<br>
+ > IoT.js is a framework for "Internet of Things" built on
+ > lightweight JavaScript interpreter ['JerryScript'](https://github.com/jerryscript-project/jerryscript)
+ > and libtuv for event driven(non-blocking I/O model) similar to node.js.
+
++### IoT.js Wiki
++
++**About**
+ - [License](License.md)
-### [Getting Started](help/Getting-Started.md) - Developer guide
-### [Getting Involved](help/Getting-involved.md)
-### Roadmap(TBD)
++- [Governance](contributing/Governance.md)
++
++**[Getting Started](Getting-Started.md)**
++- [x86 / Linux](build/Build-for-x86-Linux.md)
++- [Raspberry Pi 2 / Linux](build/Build-for-RPi2-Linux.md)
++- [Stm32f4 / NuttX](build/Build-for-STM32F4-NuttX.md)
+
++**[Developer Guide](Developer's-Guide.md)**
++- [Development Process](devs/Development-Process.md)
++- [Certificate of Origin](devs/IoT.js-Developer's-Certificate-of-Origin-1.0.md)
++- [Test Guidelines](devs/Test-Guidelines.md)
++- [Coding Style Guidelines](devs/Coding-Style-Guidelines.md)
++- [API Document Guidelines](devs/API-Document-Guidelines.md)
++- [Developer Tutorial](devs/Developer-Tutorial.md)
++- [Advanced Development](devs/Advanced-Development.md)
++- [IoT.js API Reference](api/IoT.js-API-reference.md)
+
++**Contributing**
++- [Patch Submission Process](contributing/Patch-Submission-Process.md)
++- [Community Guideline](contributing/Community-Guidelines.md)
++- [Assigned People](contributing/Assigned-People.md)
--- /dev/null
-var buf1 = Buffer(10);
+ ### Platform Support
+
+ The following shows Buffer module APIs available for each platform.
+
+ | | Linux<br/>(Ubuntu) | Raspbian<br/>(Raspberry Pi) | NuttX<br/>(STM32F4-Discovery) |
+ | :---: | :---: | :---: | :---: |
+ | buf.compare | O | O | O |
+ | buf.copy | O | O | O |
+ | buf.equals | O | O | O |
+ | buf.fill | O | O | O |
+ | buf.slice | O | O | O |
+ | buf.toString | O | O | O |
+ | buf.write | O | O | O |
+ | buf.writeUInt8 | O | O | O |
+ | buf.writeUInt16LE | O | O | O |
+ | buf.writeUInt32LE | O | O | O |
+ | buf.readInt8 | O | O | O |
+ | buf.readUInt8 | O | O | O |
+ | buf.readUInt16LE | O | O | O |
+
+
+ # Buffer
+
+ Buffer class is a global type with various constructors and accessors.
+
+ IoT.js provides Buffer to manipulate binary data. Currently buffer has
+ a pure ES5 compatible implementation, but this might be reworked to use
+ UInt8Array in the future.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ // Creates a zero-filled Buffer of length 10.
-var buf2 = Buffer([1, 2, 3]);
++var buf1 = new Buffer(10);
+
+ // Creates a Buffer containing [0x1, 0x2, 0x3].
-var buf3 = Buffer('tést');
++var buf2 = new Buffer([1, 2, 3]);
+
+ // Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74].
-var buffer = new Buffer(String.fromCharCode(65))
++var buf3 = new Buffer('tést');
+ ```
+
++## Class: Buffer
+
+ ### new Buffer(size)
+ * `size` {integer} Size of the new buffer.
+
+ Creates a new buffer of `size` bytes and initialize its data to zero.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer(5);
+ ```
+
+ ### new Buffer(buffer)
+ * `buffer` {Buffer} Source buffer.
+
+ Creates a copy of an existing buffer. The buffer data is not shared
+ between the two buffers.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer1 = new Buffer(5);
+ var buffer2 = new Buffer(buffer1);
+ ```
+
+
+ ### new Buffer(str[, encoding])
+ * `str` {string} Source string.
+ * `encoding` {string} Encoding format.
+
+ Creates a new buffer which contains the CESU-8 representation of
+ the `str` string argument. If `encoding` optional argument is
+ present its value must be `hex`. When this encoding is specified
+ the `str` argument must be a sequence of hexadecimal digit pairs,
+ and these pairs are converted to bytes.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
-var buffer = new Buffer(String.fromCharCode(128))
++var buffer = new Buffer(String.fromCharCode(65));
+
+ // prints: 1
+ console.log(buffer);
+
-var buffer = new Buffer(String.fromCharCode(2048))
++var buffer = new Buffer(String.fromCharCode(128));
+
+ // prints: 2
+ console.log(buffer);
+
-var buffer = new Buffer('4142', 'hex')
++var buffer = new Buffer(String.fromCharCode(2048));
+
+ // prints: 3
+ console.log(buffer);
+
-var buffer = new Buffer([65, 256 + 65, 65 - 256, 65.1])
++var buffer = new Buffer('4142', 'hex');
+
+ // prints: AB
+ console.log(buffer);
+ ```
+
+
+ ### new Buffer(array)
+ * `array` {Array} Array of numbers.
+
+ Creates a new Buffer from an array of numbers. The
+ numbers are converted to integers first and their modulo
+ 256 remainder is used for constructing the buffer.
+
+ **Example**
+
+ ```js
-var buffer = new Buffer([0xc8, 0x80])
++var buffer = new Buffer([65, 256 + 65, 65 - 256, 65.1]);
+
+ // prints: AAAA
+ console.log(buffer);
+ ```
+
+
+ ### Buffer.byteLength(str, encoding)
+
+ * `str` {string} Source string.
+ * `encoding` {string} String encoding.
+ * Returns: {integer} Byte length of source string.
+
+ Returns the byte length of a buffer representing the value
+ of the string argument encoded with encoding. The effect is
+ the same as:
+
+ ```js
+ return new Buffer(str, encoding).length;
+ ```
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ // prints: 1
+ console.log(Buffer.byteLength(String.fromCharCode(65)));
+
+ // prints: 2
+ console.log(Buffer.byteLength(String.fromCharCode(128)));
+
+ // prints: 3
+ console.log(Buffer.byteLength(String.fromCharCode(2048)));
+
+ // prints: 2
+ console.log(Buffer.byteLength('4142', 'hex'));
+ ```
+
+
+ ### Buffer.concat(list)
+ * `list` {Array} An array of `Buffer` objects.
+ * Returns: {Buffer} Concatenated buffer.
+
+ Returns the concatenation of the `Buffer` objects
+ provided in the `list` array.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = Buffer.concat([ new Buffer('He'),
+ new Buffer('llo'),
+ new Buffer(' wo'),
+ new Buffer('rld') ])
+
+ // prints: Hello world
+ console.log(buffer);
+ ```
+
+
+ ### Buffer.isBuffer(obj)
+ * `obj` {Object}
+ * Returns: {boolean}
+
+ Returns `true` if `obj` is an instance of `Buffer`. Returns
+ `false` otherwise.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ // prints: true
+ console.log(Buffer.isBuffer(new Buffer(1)));
+
+ // prints: false
+ console.log(Buffer.isBuffer('str'));
+ ```
+
+
+ ### buf.length
+ * {integer}
+
+ Returns the capacity of the buffer in bytes. Note: when
+ the buffer is converted to another type (e.g. String) the
+ length of the converted value might be different from
+ this value.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
++var buffer = new Buffer([0xc8, 0x80]);
+
+ // prints: 2
+ console.log(buffer.length);
+
+ var str = buffer.toString();
+
+ // prints: 1
+ console.log(str.length);
+ ```
+
+
+ ### buf.compare(otherBuffer)
+ * `otherBuffer` {Buffer} The right-hand side of the comparison.
+ * Returns: {integer}
+
+ This function performs a lexicographic comparison between
+ two buffers.
+
+ It returns with `0` if the two buffers are the same. Otherwise
+ it returns with `-1` if the first different byte is lower for
+ `buf`, and `1` if the byte is higher. If the length of the two
+ buffers are different, the comparison is performed until the
+ lower length is reached. If all bytes are the same the function
+ returns with `-1` if `buf.length` is less than `otherBuffer.length`
+ and `1` otherwise.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer1 = new Buffer('AB');
+ var buffer2 = new Buffer('A');
+ var buffer3 = new Buffer('B');
+
+ // prints: 0
+ console.log(buffer1.compare(buffer1));
+
+ // prints: 1
+ console.log(buffer1.compare(buffer2));
+
+ // prints: -1
+ console.log(buffer1.compare(buffer3));
+ ```
+
+
+ ### buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])
+ * `targetBuffer` {Buffer} The buffer to be modified.
+ * `targetStart` {Integer} **Default:** `0`
+ * `sourceStart` {integer} **Default:** `0`
+ * `sourceEnd` {integer} **Default:** `buf.length`
+ * Returns: {integer} The number of bytes copied.
+
+ Copy a sequence of bytes from `buf` buffer to `targetBuffer` buffer.
+ The source byte range is specified by `sourceStart` and `sourceEnd`
+ and the destination byte offset is specified by `targetStart`. Only
+ the `targetBuffer` is modified.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer1 = new Buffer('Hello XY world!');
+ var buffer2 = new Buffer('<JS>');
+
+ buffer2.copy(buffer1, 6, 1, 3);
+
+ // prints: Hello JS world!
+ console.log(buffer1);
+ ```
+
+
+ ### buf.equals(otherBuffer)
+ * `otherBuffer` {Buffer} The right-hand side of the comparison.
+ * Returns: {boolean}
+
+ Returns `true` if `this` and `otherBuffer` have exactly the
+ same bytes. Returns `false` otherwise. The effect is the same as:
+
+ ```js
+ return buf.compare(otherBuffer) == 0;
+ ```
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer1 = new Buffer('AB');
+ var buffer2 = new Buffer('4142', 'hex');
+ var buffer3 = new Buffer('A');
+
+ // prints: true
+ console.log(buffer1.equals(buffer2));
+
+ // prints: false
+ console.log(buffer1.equals(buffer3));
+ ```
+
+
+ ### buf.fill(value)
+ * `value` {integer} All bytes are set to this value.
+ * Returns: {Buffer} The original buffer.
+
+ Set all bytes of the buffer to value. The value is converted to
+ integer first and its modulo 256 remainder is used for updating
+ the buffer. Returns with `buf`.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('Hello');
+
+ buffer.fill(65);
+
+ // prints: AAAAA
+ console.log(buffer);
+
+ buffer.fill(66 - 256);
+
+ // prints: BBBBB
+ console.log(buffer);
+ ```
+
+
+ ### buf.slice([start[, end]])
+ * `start` {integer} **Default:** `0`
+ * `end` {integer} **Default:** `buf.length`
+ * Returns: {Buffer} A newly created buffer.
+
+ This function returns with a newly created buffer which
+ contains the bytes of the `buf` buffer between `start`
+ and `end`.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('This is JavaScript!!!');
+
+ // prints: JavaScript
+ console.log(buffer.slice(8, 18));
+ ```
+
+
+ ### buf.toString([start[, end]])
+ * `start` {integer} **Default:** `0`
+ * `end` {integer} **Default:** `buffer.length`
+ * Returns: {string}
+
+ Returns a string created from the bytes stored in the buffer.
+ By passing `start` and `end` the conversion can be limited
+ to a subset of the `buf` buffer. If a single `hex` string is
+ passed to the function, the whole buffer is converted to
+ hexadecimal data.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('DEFG');
+
+ // prints: EF
+ console.log(buffer.toString(1, 3));
+
+ // prints: 44454647
+ console.log(buffer.toString('hex'));
+ ```
+
+
+ ### buf.write(string[, offset[, length]])
+ * `string` {string} Data to be written into buffer.
+ * `offset` {integer} Start position of writing. **Default:** `0`
+ * `length` {integer} How many bytes to write. **Default:** `buffer.length - offset`.
+ * Returns: {integer} Total number of bytes written.
+
+ Writes `string` into the `buf` buffer. The start position of the
+ writing can be specified by `offset` and the maximum number of
+ updated bytes can be limited by `length`. Returns total number
+ of bytes written to the buffer.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('......');
+ buffer.write('AB');
+ buffer.write('XY', 3);
+
+ // prints: AB.XY.
+ console.log(buffer);
+
+ var buffer = new Buffer('......');
+ buffer.write('ABCDEF', 1, 3);
+
+ // prints: .ABC..
+ console.log(buffer);
+ ```
+
+
+ ### buf.writeUInt8(value, offset[, noAssert])
+ * `value` {integer} Number to be written into the buffer.
+ * `offset` {integer} Start position of the writing.
+ * `noAssert` {boolean} Skip argument validation. **Default:** `false`
+ * Returns: {number} Offset plus the number of bytes written.
+
+ Writes `value` into the buffer starting from `offset` position.
+ The `value` must be a valid 8-bit unsigned integer.
+
+ If `noAssert` is set and the value is outside of the expected range
+ or the offset is higher than the size of the buffer the operation
+ is undefined.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('....');
+
+ // prints: 3
+ console.log(buffer.writeUInt8(65, 2));
+
+ // prints: ..A.
+ console.log(buffer);
+ ```
+
+
+ ### buf.writeUInt16LE(value, offset[, noAssert])
+ * `value` {integer} Number to be written into the buffer.
+ * `offset` {integer} Start position of the writing.
+ * `noAssert` {boolean} Skip argument validation. **Default:** `false`
+ * Returns: {integer} Offset plus the number of bytes written.
+
+ Writes `value` into the buffer starting from `offset` position
+ with little endian format. The `value` must be a valid 16-bit
+ unsigned integer.
+
+ If `noAssert` is set and the value is outside of the expected range
+ or the offset is higher than the size of the buffer the operation
+ is undefined.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('......');
+
+ // prints: 3
+ console.log(buffer.writeUInt16LE(0x4142, 1));
+
+ // prints .BA...
+ console.log(buffer);
+ ```
+
+
+ ### buf.writeUInt32LE(value, offset[, noAssert])
+ * `value` {integer} Number to be written into the buffer.
+ * `offset` {integer} Start position of the writing.
+ * `noAssert` {boolean} Skip argument validation. **Default:** `false`
+ * Returns: {integer} Offset plus the number of bytes written.
+
+ Writes `value` into the buffer starting from `offset` position
+ with little endian format. The `value` must be a valid 32-bit
+ unsigned integer.
+
+ If `noAssert` is set and the value is outside of the expected range
+ or the offset is higher than the size of the buffer the operation
+ is undefined.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('......');
+
+ // prints: 5
+ console.log(buffer.writeUInt32LE(0x41424344, 1));
+
+ // prints: .DCBA.
+ console.log(buffer);
+ ```
+
+
+ ### buf.readInt8(offset[, noAssert])
+ * `offset` {number} Start position of buffer for reading.
+ * `noAssert` {boolean} Skip offset validation. **Default:** `false`
+ * Returns: {number}
+
+ Reads a signed 8-bit integer from `buf` buffer starting from
+ `offset` position.
+
+ If `noAssert` is set and the offset is higher than the size of
+ the buffer the result is undefined.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('ABCDEF');
+
+ // prints: 42
+ console.log(buffer.readUInt8(1).toString(16));
+ ```
+
+
+ ### buf.readUInt8(offset[, noAssert])
+ * `offset` {integer} Start position of the reading.
+ * `noAssert` {boolean} Skip argument validation. **Default:** `false`
+ * Returns: {number}
+
+ Reads an unsigned 8-bit integer from `buf` buffer starting from
+ `offset` position.
+
+ If `noAssert` is set and the offset is higher than the size of
+ the buffer the result is undefined.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('ABCDEF');
+
+ // prints: 42
+ console.log(buffer.readUInt8(1).toString(16));
+ ```
+
+
+ ### buf.readUInt16LE(offset[, noAssert])
+ * `offset` {number} Start position of buffer for reading.
+ * `noAssert` {boolean} Skip offset validation. **Default:** `false`
+ * Returns: {number}
+
+ Reads an unsigned 16-bit integer from `buf` buffer starting from
+ `offset` position with little endian format.
+
+ If `noAssert` is set and the offset is higher than the size of
+ the buffer the result is undefined.
+
+ **Example**
+
+ ```js
+ var Buffer = require('buffer');
+
+ var buffer = new Buffer('ABCDEF');
+
+ // prints: 4342
+ console.log(buffer.readUInt16LE(1).toString(16));
+ ```
--- /dev/null
+ ### Platform Support
+
+ The following shows process module APIs available for each platform.
+
+ | | Linux<br/>(Ubuntu) | Raspbian<br/>(Raspberry Pi) | NuttX<br/>(STM32F4-Discovery) |
+ | :---: | :---: | :---: | :---: |
+ | process.nextTick | O | O | O |
+ | process.exit | O | O | O |
+ | process.cwd | O | O | O |
+ | process.chdir | O | O | O |
+
+ ※ On NuttX, you should pass absolute path to `process.chdir`.
+
+ # Process
+
+ The `process` object is a global that provides information about, and control over, the current IoT.js process.
+ As a global, it is always available to IoT.js applications without using `require()`.
+
+ ### process.arch
+ * {string}
+
+ The `arch` property returns the processor architecture identifier that the IoT.js process is currently running on.
+ For instance `'arm'`, `'ia32'`, `'x64'`, or `'unknown'`.
+
+ ### process.argv
+ * {Array}
+
+ The `argv` property returns an array containing the command line arguments passed when the IoT.js
+ process was launched. The first element is the path to the IoT.js program.
+ The second element is the path of the JavaScript file currently being executed.
+ The remaining elements will be any additional arguments passed via command line.
+
+ **Example**
+
+ To print out all command line arguments the following example could be used:
+
+ ```js
+ process.argv.forEach(function(val, idx) {
+ console.log('index: ' + idx + ' value: ' + val);
+ });
+ ```
+
+ ### process.env
+ * {Object}
+
+ The `env` property returns an object containing a few environment variables.
+ The following environment elements can be accessed:
+ * `HOME`
+ * `IOTJS_PATH` which is set to `/mnt/sdcard` on NuttX by default.
+ * `env` contains `'experimental'` if the IoT.js was build with experimental support.
+
+ **Example**
+
+ ```js
+ console.log('HOME: ' + process.env.HOME);
+ // prints: HOME: /home/user
+ ```
+
+ ### process.exitCode
+ * {integer} **Default:** `0`
+
+ The `exitCode` property can be used to specify the exit code of the IoT.js process.
+ This will be used when the process exits gracefully, or exited via `process.exit()` without specifying an exit code.
+
+ Specifying an exit code for the `process.exit()` call will override any previous setting of `process.exitCode`.
+
+ ### process.iotjs
+ * {Object}
+
+ The `iotjs` property holds IoT.js related information in an object.
+ The following keys can be accessed via this property:
+ * `board` specifies the device type on which the IoT.js is running currently. For instance `'STM32F4DIS'`, `'RP2'`, or `'unknown'`.
+
+ **Example**
+
+ ```js
+ console.log(process.iotjs.board);
+ // on Raspberry 2 it prints: RP2
+ ```
+
+ ### process.platform
+ * {string}
+
+ The `platform` returns the identification of the operating system the IoT.js process
+ is currently running on. For instance `'linux'`, `'darwin'`, `'nuttx'`, `'tizenrt'`, or `'unknown'`.
+
+
+ ### process.chdir(path)
+ * `path` {string} The path to change working directory to.
+
+ The `chdir` method changes the current working directory of the IoT.js process or
+ throws an exception if the operation fails (for instance the `path` specified does not exist).
+
+ **Example**
+
+ ```js
+ try {
+ process.chdir('/invalid/path');
+ } catch(err) {
+ console.log('invalid path');
+ }
+ // prints: invalid path
+ ```
+
+ ### process.cwd()
+ * Returns: {string}
+
+ The `cwd()` call returns the current working directory of the IoT.js process.
+
+ **Example**
+
+ ```js
+ console.log('Current dir: ' + process.cwd());
+ ```
+
+ ### process.exit([code])
+ * `code` {integer} The exit code. **Default:** `0`
+
+ The `exit()` method instructs the IoT.js to terminate the process synchronously with an exit status of `code`.
+ If `code` is not specified, exit uses the `process.exitCode` value which defaults to `0`.
+ IoT.js will not exit till all `'exit'` event listeners are called.
+
+ The `process.exit()` method call will force the process to exit as quickly as possible,
+ ignoring if there is any asynchronous operations still pending.
+
+ In most situations, it is not necessary to explcitly call `process.exit()`. The IoT.js will exit on its own
+ if there is no additional work pending in the event loop. The `process.exitCode` property can be set
+ to exit code when the process exits gracefully.
+
+ If it is necessary to terminate the IoT.js process due to an error condition, throwing an
+ uncaught error and allowing the process to terminate accordingly is advised instead of calling `process.exit()`.
+
+ **Example**
+
+ To exit with a failure code:
+
+ ```js
+ process.exit(1);
+ ```
+ The shell that executed the IoT.js should see the returned exit code as `1`.
+
+ To set the exit code on graceful exit:
+
+ ```js
+ doSomeWork()
+ process.exitCode = 1;
+ ```
+
+ ### process.nextTick(callback)
+ * `callback` {Function}
+
+ The `nextTick` method adds the `callback` method to the "next tick queue".
+ Once the current turn of the event loop is completed, all callbacks currently in the next tick queue will be called.
+
+ This is not a simple alias to `setTimeout` call. It runs before any additional I/O events.
+
+ **Example**
+ ```js
+ console.log('step 1');
+ process.nextTick(function() {
+ console.log('step 2');
+ });
+ console.log('step 3');
+ // prints:
+ // step 1
+ // step 3
+ // step 2
+ ```
+
++### process.version
++* {string}
++
++The `version` property returns the version numbering of the currently running IoT.js process as a string.
++
++**Example**
++```js
++console.log(process.version);
++// prints: (in case of version 1.0.0)
++// 1.0.0
++```
++
+ ### Event: 'exit'
+ * `callback` {Function}
+ * `code` {integer} exitCode
+
+ The `'exit'` event is emitted when the IoT.js process is about to exit.
+ This can happen two ways:
+ * The `process.exit()` method was called explicitly;
+ * The IoT.js event loop does not have any additional work to perform.
+
+ There is no way to prevent the exiting, and once all `'exit'` listeners have finished
+ running the process will terminate.
+
+ The listener callback function is invoked with the exit code specified either by the
+ `process.exitCode` property, or the `exitCode` argument passed to the `process.exit()` method.
+
+ Listener functions *must* only perform *synchronous* operations. The IoT.js process will exit
+ immediately after calling the `'exit'` event listeners causing any additional work still queued
+ to be abandoned.
+
+ **Example**
+
+ ```js
+ process.on('exit', function(code) {
+ console.log('exited with: ' + code);
+ });
+ ```
+
+ ### Event: 'uncaughtException'
+ * `callback` {Function}
+ * `err` {Error} error object uncaught by catch handler
+
+ The `'uncaughtException'` event is emitted when an uncaught JavaScript exception bubbles all the
+ way back to the event loop. By default, IoT.js handles such exceptions by printing it to `stderr` and exiting.
+ Adding a handler for the `'uncaughtException'` event overrides the default behavior.
+
+ The listener function is called with the `Error` object passed as the only argument.
+
+ **Warning: Using the `'uncaughtException'` event correctly**
+
+ This event is a crude mechanism for exception handling intended to be used only as a last resort.
+ The event should not be used as an eqivalent to 'On Error Resume Next'. Unhandled exceptions inherently mean
+ that a program is in an unknown state. Thus attempting to resume the application code without properly
+ recovering from the exception can cause unforeseen/unpredictable issues.
+
+ Only one exception thrown within the event handler will be caught and will immediately terminate the application.
+
+ The correct use of the event is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc)
+ before shutting down the process. **It is not safe to resume normal operation after this event**.
+
+ To restart a crashed application in a more reliable way, whether uncaughtException is emitted or not,
+ an external monitoring application should be employed in a separate process to detect application failures and
+ recover or restart as needed.
+
+ **Example**
+
+ ```js
+ process.on('uncaughtException', function(err) {
+ console.log('Something went wrong: ' + err);
+ });
+
+ nonExistentFunctionCall();
+ console.log('This will not be printed.');
+ ```
--- /dev/null
-| spi.open | O | O | X |
-| spibus.transfer | O | O | X |
-| spibus.transferSync | O | O | X |
-| spibus.close | O | O | X |
-| spibus.closeSync | O | O | X |
+ ### Platform Support
+
+ The following shows spi module APIs available for each platform.
+
+ | | Linux<br/>(Ubuntu) | Raspbian<br/>(Raspberry Pi) | NuttX<br/>(STM32F4-Discovery) |
+ | :---: | :---: | :---: | :---: |
- * `device` {string} The specified path for `spidev`.
++| spi.open | O | O | O |
++| spibus.transfer | O | O | O |
++| spibus.transferSync | O | O | O |
++| spibus.close | O | O | O |
++| spibus.closeSync | O | O | O |
+
+
+ ## Class: SPI
+
+ SPI (Serial Peripheral Interface) is a communication protocol which defines a way to communicate between devices.
+
++On NuttX, you have to know the number of pins that is defined on the target board module. For more information, please see the list below.
++ * [STM32F4-discovery](../targets/nuttx/stm32f4dis/IoT.js-API-Stm32f4dis.md)
++
+ ### new SPI()
+
+ Returns a new SPI object which can open SPI bus.
+
+ ### SPI.MODE
+ The clock polarity and the clock phase can be specified as `0` or `1` to form four unique modes to provide flexibility in communication between devices. The `SPI.MODE` will specify which one to use (the combinations of the polarity and phase).
+
+ * `0` Clock Polarity(0), Clock Phase(0), Clock Edge(1)
+ * `1` Clock Polarity(0), Clock Phase(1), Clock Edge(0)
+ * `2` Clock Polarity(1), Clock Phase(0), Clock Edge(1)
+ * `3` Clock Polarity(1), Clock Phase(1), Clock Edge(0)
+
+
+ ### SPI.CHIPSELECT
+ * `NONE`
+ * `HIGH`
+
+ The chip select is an access-enable switch. When the chip select pin is in the `HIGH` state, the device responds to changes on its input pins.
+
+ ### SPI.BITORDER
+ * `MSB` The most significant bit.
+ * `LSB` The least significant bit.
+
+ Sets the order of the bits shifted out of and into the SPI bus, either MSB (most-significant bit first) or LSB (least-significant bit first).
+
+ ### spi.open(configuration[, callback])
+ * `configuration` {Object}
++ * `device` {string} The specified path for `spidev`. (only on Linux)
++ * `bus` {number} The specified bus number. (only on NuttX)
+ * `mode` {SPI.MODE} The combinations of the polarity and phase. **Default:** `SPI.MODE[0]`.
+ * `chipSelect` {SPI.CHIPSELECT} Chip select state. **Default:** `SPI.CHIPSELECT.NONE`.
+ * `maxSpeed` {number} Maximum transfer speed. **Default:** `500000`.
+ * `bitsPerWord` {number} Bits per word to send (should be 8 or 9). **Default:** `8`.
+ * `bitOrder` {SPI.BITORDER} Order of the bits shifted out of and into the SPI bus. Default: `SPI.BITORDER.MSB`.
+ * `loopback` {boolean} Using loopback. **Default:** `false`.
+ * `callback` {Function}.
+ * `err` {Error|null}.
+ * Returns: {SPIBus}.
+
+ Opens an SPI device with the specified configuration.
+
+ **Example**
+
+ ```js
+
+ var Spi = require('spi');
+ var spi = new Spi();
+ var spi0 = spi.open({
+ device: '/dev/spidev0.0'
+ }, function(err) {
+ if (err) {
+ throw err;
+ }
+ });
+
+ ```
+
+ ## Class: SPIBus
+
+ The SPIBus is commonly used for communication.
+
+ ### spibus.transfer(txBuffer, rxBuffer[, callback])
+ * `txBuffer` {Array|Buffer}.
+ * `rxBuffer` {Array|Buffer}.
+ * `callback` {Function}.
+ * `err` {Error|null}.
+
+ Writes and reads data from the SPI device asynchronously.
+ The `txBuffer` and `rxBuffer` must have equal length.
+
+ **Example**
+
+ ```js
+
+ var tx = new Buffer('Hello IoTjs');
+ var rx = new Buffer(tx.length);
+ spi0.transfer(tx, rx, function(err) {
+ if (err) {
+ throw err;
+ }
+
+ var value = '';
+ for (var i = 0; i < tx.length; i++) {
+ value += String.fromCharCode(rx[i]);
+ }
+ console.log(value);
+ });
+
+ ```
+
+ ### spibus.transferSync(txBuffer, rxBuffer)
+ * `txBuffer` {Array|Buffer}.
+ * `rxBuffer` {Array|Buffer}.
+
+ Writes and reads data from the SPI device synchronously.
+ The `txBuffer` and `rxBuffer` must have equal length.
+
+ **Example**
+
+ ```js
+
+ var tx = new Buffer('Hello IoTjs');
+ var rx = new Buffer(tx.length);
+ spi0.transferSync(tx, rx);
+ var value = '';
+ for (var i = 0; i < tx.length; i++) {
+ value += String.fromCharCode(rx[i]);
+ }
+ console.log(value);
+
+ ```
+
+ ### spibus.close([callback])
+ * `callback` {Function}.
+ * `err` {Error|null}.
+
+ Closes the SPI device asynchronously.
+
+ The `callback` function will be called after the SPI device is closed.
+
+ **Example**
+ ```js
+
+ spi0.close(function(err) {
+ if (err) {
+ throw err;
+ }
+ console.log('spi bus is closed');
+ });
+
+ ```
+
+ ### spibus.closeSync()
+
+ Closes the SPI device synchronously.
+
+ **Example**
+ ```js
+
+ spi.closeSync();
+
+ console.log('spi bus is closed');
+
+ ```
--- /dev/null
-The command will generate runnable IoT.js binary in "./build/<arch-os>/debug/iotjs/iotjs".
+ ## Overview
+
+ build.py help you build IoT.js.
+
+ It locates in "./tools" directory of source tree.
+
+ It automatically creates a directory where build object and outputs will be generated,
+ checks configurations, tidiness of source code, licenses, and more.
+ Also it downloads, updates and builds submodules.
+ And finally generate IoT.js binary.
+
+
+ ## How to use
+
+ You can build IoT.js with default setting for your host machine with;
+ ```
+ ./tools/build.py
+ ```
++The command will generate runnable IoT.js binary in "./build/<arch-os>/debug/bin/iotjs".
+
+ You can also build release binary with;
+ ```
+ ./tools/build.py --buildtype=release
+ ```
+
+ ## Parameters Candidates
+ **NOTE: some parameters are not supported by current version of build.py**
+
+ --
+ #### `--buildtype`
+ * `release` | `debug`
+
+ Specify whether build output will be for 'debug' or 'release'.
+
+ ```
+ ./tools/build.py --buildtype=release
+ ```
+
+ --
+ #### `--builddir`
+
+ Specify a directory where build outputs will be generated.
+
+ If given path is not exist, build.py will create it.
+
+ ```
+ ./tools/build.py --builddir=./build
+ ```
+
+ --
+ #### `--clean`
+ With given this option, build.py will clear all the build directory before start new build.
+
+ ```
+ ./tools/build.py --clean
+ ```
+
+ --
+ #### `--buildlib`
+ With given this option, build.py will generate IoT.js output as a library.
+
+ ```
+ ./tools/build.py ---buildlib
+ ```
+
+ --
+ #### `--target-arch`
+ * `arm` | `x86` | `i686` | `x86_64` | `x64`
+
+ Specify target architecture.
+
+ ```
+ ./tools/build.py --target-arch=arm
+ ```
+ --
+ #### `--target-os`
+ * `linux` | `darwin` | `osx` | `nuttx`
+
+ Specify target OS.
+
+ ```
+ ./tools/build.py --target-os=nuttx --target-arch=arm
+ ```
+
+ --
+ #### `--target-board`
+ * `stm32f4dis` | empty
+
+ Specify target board.
+
+ ```
+ ./tools/build.py --target-os=nuttx --target-arch=arm --target-board=stm32f4dis
+ ```
+ --
+ #### `--cmake-param`
+ Specify CMake parameters for IoT.js.
+
+ "cmake" command for IoT.js will be executed with the given parameter applied.
+
+ If you have multiple parameters, supply it with multiple use of this option;
+
+ ```
+ ./tools/build.py --cmake-param="..." --cmake-param="..."
+ ```
+
+ --
+ #### `--compile-flag`
+ Specify C compiler flags for IoT.js.
+
+ If you have multiple compile flags, supply it with multiple use of this option;
+ ```
+ ./tools/build.py --compile-flag="..." --compile-flag="..."
+ ```
+
+ --
+ #### `--link-flag`
+ Specify linker flags for IoT.js.
+
+ If you have multiple link flags, supply it with multiple use of this option;
+ ```
+ ./tools/build.py --link-flag="..." --link-flag="..."
+ ```
+
+ --
+ #### `--external-include-dir`
+ Specify external include directory for IoT.js.
+
+ If you have multiple external include directoies, supply it with multiple use of this option;
+ ```
+ ./tools/build.py --external-include-dir="..." --external-include-dir="..."
+ ```
+
+ --
+ #### `--external-static-lib`
+ Specify external static library that will be liked with IoT.js statically.
+
+ If you have multiple such libraries, supply it with multiple use of this option;
+ ```
+ ./tools/build.py --external-static-lib="libxxx.a"
+ ```
+
+ --
+ #### `--jerry-cmake-param`
+ Specify CMake parameters for JerryScript.
+
+ "cmake" command for JerryScript will be executed with the given parameter applied.
+
+ If you have multiple parameters, supply it with multiple use of this option
+
+ --
+ #### `--jerry-compile-flag`
+ Specify C compiler flags for JerryScript.
+
+ If you have multiple cflags, supply it with multiple use of this option
+
+ ```
+ ./tools/build.py --jerry-compile-flag="-DCONFIG_ECMA_LCACHE_DISABLE"
+ ```
+
+ --
+ #### `--jerry-link-flag`
+ Specify linker flags for JerryScript.
+
+ If you have multiple ldflags, supply it with multiple use of this option
+
+ --
+ #### `--jerry-heaplimit`
+ Specify object heap limit for JerryScript engine.
+
+ ```
+ ./tools/build.py --jerry-heaplimit=80
+ ```
+
+ --
+ #### `--jerry-memstat`
+ Enable memstat of JerryScript engine.
+
+ ```
+ ./tools/build.py --jerry-memstat
+ ```
+
+ --
+ #### `--jerry-lto`
+ With given this option, JerryScript will be built with LTO.
+
+ ```
+ ./tools/build.py --jerry-lto
+ ```
+
+ --
+ #### `--no-init-submodule`
+ With given this option, submoduls will not initialized before start build.
+
+ ```
+ ./tools/build.py --no-init-submodule
+ ```
+
+ --
+ #### `--no-check-tidy`
+ With given this option, tidy checking will not performed.
+
+ ```
+ ./tools/build.py --no-check-tidy
+ ```
+
+ --
+ #### `--no-check-test`
+ With given this option, unit test checking will not performed.
+
+ ```
+ ./tools/build.py --no-check-test
+ ```
+
+ --
+ #### `--no-parallel-build`
+ With given this option, compilation process will not run in parallel. In other words, executes `make` without `-j` option.
+
+ ```
+ ./tools/build.py --no-parallel-build
+ ```
+
+ --
+ #### `--nuttx-home`
+ To build for nuttx os, nuttx home directory must be given.
+
+ ```
+ ./tools/build.py --target-os=nuttx --target-arch=arm --target-board=stm32f4dis --nuttx-home="..."
+ ```
+
+ --
+ #### `--config`
+ Specify build configuration file path.
+
+ ```
+ ./tools/build.py --config=build.arm.nuttx.stm32f4dis.config
+ ```
+
+ `build.default.config` file is in the source tree for default setting.
+
+ If this option is not specified, `build.config` file will be applied. If the file is not exist, it will be copied from `build.default.config`.
+
+ Parameters specified by the config file is applied, and then the parameters given by command line overwrite over the settings.
+
+ If you need to apply the same set of parameters for each build, making your own config file and trigger build.py with the config file would be more convenient.
--- /dev/null
--- /dev/null
++### About
++
++This directory contains files to run IoT.js on [TizenRT](https://github.com/Samsung/TizenRT).
++
++WARNING: **This document is not 100% accurate since Artik05x board with tooling is not available yet**
++
++### How to build
++
++#### 1. Set up the build environment for Artik05x board
++
++Clone IoT.js and TizenRT into iotjs-tizenrt directory
++
++```bash
++$ mkdir iotjs-tizenrt
++$ cd iotjs-tizenrt
++$ git clone https://github.com/Samsung/iotjs.git
++$ git clone https://github.com/Samsung/TizenRT.git tizenrt
++```
++The following directory structure is created after these commands
++
++```bash
++iotjs-tizenrt
++ + iotjs
++ | + config
++ | + tizenrt
++ | + artik05x
++ + tizenrt
++```
++
++#### 2. Add IoT.js as a builtin application for TizenRT
++
++```bash
++$ cd tizenrt/apps/system
++$ mkdir iotjs
++$ cp ../../../iotjs/config/tizenrt/artik05x/app/* ./iotjs/
++```
++
++**WARNING: Manual modification is required**
++
++**WARNING: Below two bullet points are subject to change**
++
++* change tizenrt/apps/system/Kconfig to include iotjs folder
++ ```
++ menu "IoT.js node.js like Javascript runtime"
++ source "$APPSDIR/system/iotjs/Kconfig"
++ endmenu
++ ```
++* Libraries required to link iotjs have to be supplied in some way
++ ```
++ EXTRA_LIBS = -lhttpparser -liotjs -ljerrycore -ltuv -ljerry-libm
++ ```
++
++
++#### 3. Configure TizenRT
++
++```bash
++$ cd tizenrt/os/tools
++$ ./configure.sh sidk_s5jt200/hello_with_tash
++
++$ cd ..
++# might require to run "make menuconfig" twice
++$ make menuconfig
++```
++
++#### 4. Build IoT.js for TizenRT
++
++```bash
++$ cd iotjs
++$ ./tools/build.py --target-arch=arm --target-os=tizenrt --target-board=artik05x --sysroot=../tizenrt/os
++
++```
++
++#### 5. Build TizenRT
++
++```bash
++$ cd tizenrt/os
++IOTJS_LIB_DIR=../iotjs/build/arm-tizenrt/debug/lib make
++```
++Binaries are available in `tizenrt/build/output/bin`
++
++#### 6. Flashing
++
++Yet to be announced on [TizenRT page](https://github.com/Samsung/TizenRT#board)
--- /dev/null
--- /dev/null
++
++### 1. Tizen on ARTIK10 cross-compile
++
++#### Prerequisites
++
++* ARTIK10 with Tizen (https://wiki.tizen.org/wiki/Tizen_On_ARTIK)
++* Tizen Studio with Native app development CLI tools.
++ This is required to get rootstrap for Tizen (set of native libraries).
++
++* arm-linux-gnueabi-gcc cross compiler (can be found in Tizen Studio / Native toolchain)
++ Otherwise, you can install it on your PC.
++```bash
++sudo apt-get install gcc-arm-linux-gnueabi g++-arm-linux-gnueabi
++```
++
++#### Building
++1. Make sure arm-linux-gnueabi-gcc is in path.
++2. Locate Tizen SDK. Default location is: ~/tizen-studio.
++3. In platforms/tizen-3.0/mobile there should be compatible rootstrap (eg. mobile-3.0-device)
++
++Compile:
++* Compile with rootstrap in case you use tizen 3.0 libraries.
++``` bash
++tools/build.py \
++ --target-arch=arm --target-os=tizen --target-board=artik10 \
++ --compile-flag="--sysroot=~/tizen-studio/platforms/tizen-3.0/mobile/rootstraps/mobile-3.0-device.core/"
++```
++
++#### Testing
++Transfer iotjs binary and test file to the device:
++``` bash
++sdb push ./build/arm-tizen/debug/bin/iotjs /home/owner/iotjs/
++sdb push ./test/run_pass/test_console.js /home/owner/iotjs/
++```
++
++Run the test:
++``` bash
++sdb shell
++$ cd /home/owner/iotjs
++$ ./iotjs test_console.js
++```
++
++
++### 2. Build with GBS
++
++#### Prerequisites
++* Tizen uses GBS to create RPM packages.
++ SDB tool is in Tizen Studio. To send a file, please, install tizen studio.
++ (https://developer.tizen.org/development/tizen-studio/download)
++* To run GBS, please create a GBS configuration file at '~/.gbs.conf'
++ (https://source.tizen.org/documentation/reference/git-build-system/configuration-file)
++ You can use this sample, /config/tizen/sample.gbs.conf for GBS build.
++``` bash
++sudo apt-get install gbs mic
++cp ./config/tizen/sample.gbs.conf ~/.gbs.conf
++```
++Please add your Tizen.org id and password on this conf file.
++
++#### Building
++* You can modify IoT.js build option on the spec file.
++ (config/tizen/packaging/iotjs.spec)
++* Run gbsbuild.sh at first.
++Compile:
++``` bash
++cp ./config/tizen/gbsbuild.sh ./
++./gbsbuild.sh
++```
++After finishing build, move to a new working directory at '../iotjs_tizen_gbs/'.
++Next time, build with this basic command.
++```bash
++gbs build -A armv7l --include-all
++```
++
++#### Install
++Transfer iotjs binary and test file to the device:
++``` bash
++sdb push ~/GBS-ROOT/local/repos/tizen_unified/armv7l/RPMS/iotjs-1.0.0-0.armv7l.rpm /tmp
++sdb push ./test/run_pass/test_console.js /home/owner/iotjs/
++sdb root on
++sdb shell
++(target)$ cd /tmp
++(only in headless Tizen 4.0 target)$ mount -o remount,rw
++(target)$ rpm -ivh --force iotjs-1.0.0.rpm
++```
++
++Run the test:
++``` bash
++sdb shell
++$ iotjs test_console.js
++```
--- /dev/null
--- /dev/null
++
++IoT.js supports two build types:
++
++1. Build on your desktop. We support Linux(Ubuntu) and macOS. - Cross compile
++2. Build on Raspberry Pi 2.
++
++### Setting Raspberry Pi
++
++IoT.js officially supports Raspbian. For more information, please visit [the official site](https://www.raspberrypi.org/downloads/raspbian/).
++
++#### Enable the I2C interface
++
++To use I2C module, the I2C interface must be enabled.
++
++From the command line type:
++```bash
++sudo raspi-config
++```
++This will launch raspi-config utility.
++ * Select "9 Advanced Options"
++ * Select "A6 I2C"
++
++The screen will ask you to enable I2C interface.
++ * Select "Yes"
++ * Select "Ok"
++ * Select "Finish" to return to the command line.
++
++Reboot your Raspberry Pi.
++
++#### Enable the PWM interface
++
++Raspberry Pi2 has two PWM outputs on the following pins.
++
++| PWM Number | GPIO PIN(FUNC) |
++| :---: | :---: |
++| PWM0 | GPIO12(4), GPIO18(2) |
++| PWM1 | GPIO13(4), GPIO19(2) |
++
++To use PWM module, you must add PWM overlays in `/boot/config.txt` file.
++
++For example, to get a single PWM on GPIO18, add overlays like below.
++```
++dtoverlay=pwm,pin=18,func=2
++```
++
++For example, to get multi PWM on GPIO18 and GPIO19, add overlays like below.
++```
++dtoverlay=pwm-2chan,pin=18,func=2,pin2=19,func2=2
++```
++
++For more information about overlays, refer to [README](https://github.com/raspberrypi/linux/blob/rpi-4.9.y/arch/arm/boot/dts/overlays/README).
++
++* Note that it is necessary to have root privileges in order to run PWM module.
++
++#### Enable the UART interface
++
++To use UART module, the UART interface must be enabled.
++
++In `/boot/config.txt` file, change the value of enable_uart from 0 to 1.
++```
++enable_uart=1
++```
++
++To disable the serial console, edit the file `/boot/cmdline.txt`.
++remove the word phase ```"console=serial0,115200"``` or ```"console=ttyAMA0,115200"```
++
++To enable the serial console, edit the file `/boot/cmdline.txt`.
++add the word phase ```"console=serial0,115200"``` or ```"console=ttyAMA0,115200"```
++
++Reboot your Raspberry Pi.
++
++* Note for Raspberry Pi 3 : You should use /dev/ttyS0 instead of /dev/ttyAMA0 in RPI3.
++
++### Build IoT.js on your desktop.
++
++#### Prerequisite
++##### Linux
++
++Install arm linux cross compiler.
++
++``` bash
++sudo apt-get install gcc-arm-linux-gnueabihf
++```
++
++##### macOS
++
++Install arm linux cross compiler via [this site](http://www.welzels.de/blog/en/arm-cross-compiling-with-mac-os-x/).
++
++The default location for arm linux compiler toolchain is **"/usr/local/linaro/arm-linux-gnueabihf-raspbian"**.
++
++Then you need to locate c_compiler.
++In **"./cmake/config/arm-linux.cmake"**,
++``` cmake
++SET(EXTERNAL_CMAKE_C_COMPILER
++ /usr/local/linaro/arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc)
++```
++In **"./deps/libtuv/cmake/config/config_arm-linux.cmake"**,
++``` cmake
++SET(CMAKE_C_COMPILER
++ /usr/local/linaro/arm-linux-gnueabihf-raspbian/bin/arm-linux-gnueabihf-gcc)
++```
++
++#### Build IoT.js (Cross compile)
++Give `target-arch`, `target-os` and `target-board` options to the script named 'build.py', then the script do the rest for you.
++
++``` bash
++./tools/build.py --buildtype=[release|debug] --target-arch=arm \
++ --target-os=linux --target-board=rpi2
++```
++
++#### Running in Raspberry Pi 2
++
++This script gives you `build/arm-linux/release/bin/iotjs` or `build/arm-linux/debug/bin/iotjs`.
++Copy this binary with your favorite tool or `scp` like below.
++
++``` bash
++scp build/arm-linux/release/bin/iotjs pi@(your RPi2 IP):/home/pi/.
++```
++
++Lastly, open a shell and run with your test program.
++
++``` bash
++ssh pi@(your RPi2 IP)
++./iotjs (your test program)
++```
++
++### Build IoT.js on Raspberry Pi 2
++
++#### Prerequisite
++Install cmake.
++```bash
++sudo apt-get update
++sudo apt-get install cmake
++```
++
++#### Build IoT.js
++Executing below command will build IoT.js and run our testsuite.
++
++``` bash
++./tools/build.py --target-board=rpi2
++```
--- /dev/null
--- /dev/null
++
++### Target board
++We work on STM32F4 board for NuttX and the detail of the reference board is well described at [STM32F4-discovery with BB](http://www.st.com/web/en/catalog/tools/FM116/SC959/SS1532/LN1199/PF255417).
++
++### Relation with STM board?
++We do not have any business relation with STM board. It is selected because it has enough RAM and Flash ROM, so that development can be more comfortable. And it has lots of pins to play with.
++
++When IoT.js is built up and optimized, it may work in devices having smaller resource.
++
++
++### 1. Prepare for prerequisite
++
++#### Linux
++
++```bash
++$ sudo apt-get install autoconf libtool gperf flex bison autoconf2.13
++$ sudo apt-get install cmake libncurses-dev libusb-1.0-0-dev
++$ sudo apt-get install libsgutils2-dev gcc-arm-none-eabi minicom
++```
++
++To use menuconfig in NuttX, you may need to install kconfig frontend.
++
++```bash
++$ git clone https://github.com/jameswalmsley/kconfig-frontends.git
++$ cd kconfig-frontends
++$ ./bootstrap
++$ ./configure --enable-mconf
++$ make
++$ sudo make install
++$ sudo ldconfig
++```
++
++#### macOS
++
++* Install Xcode from the app store and run once Xcode to install components.
++* Install Xcode command line tools.
++```bash
++$ xcode-select --install
++```
++* Install [Homebrew package manager](http://brew.sh/)
++* Install packages
++```bash
++$ brew tap PX4/homebrew-px4
++$ brew update
++$ brew install cmake bash-completion pkg-config kconfig-frontends
++$ brew install gcc-arm-none-eabi libusb minicom
++```
++
++
++### 2. Set up the build environment for STM32F4-Discovery board
++
++#### Supported Nuttx version
++|Repository|Tag Name|
++|----------|:------:|
++| nuttx | nuttx-7.19 |
++| app | nuttx-7.19 |
++
++We only guarantee that the specified version will work well. It is recommended to check out with the specified tag from a git repository.
++
++#### Clone repository
++
++Clone IoT.js and NuttX into iotjs-nuttx directory
++
++```bash
++$ mkdir iotjs-nuttx
++$ cd iotjs-nuttx
++$ git clone https://github.com/Samsung/iotjs.git
++$ git clone https://bitbucket.org/nuttx/nuttx.git --branch nuttx-7.19
++$ git clone https://bitbucket.org/nuttx/apps.git --branch nuttx-7.19
++$ git clone https://github.com/texane/stlink.git
++```
++
++Note that we only support the specified git tag from nuttx repository
++
++The following directory structure is created after these commands
++
++```bash
++iotjs-nuttx
++ + apps
++ + iotjs
++ | + config
++ | + nuttx
++ | + stm32f4dis
++ + nuttx
++ + stlink
++```
++
++
++### 3. Build NuttX (For the first time)
++
++To generate headers which are required to build IoT.js, for the first time, you need to build NuttX at least once. This time NuttX build will be failed. But don't worry at this time. After one execution, you don't need this sequence any more.
++
++#### Add IoT.js as a builtin application for NuttX
++
++```bash
++$ cd apps/system
++$ mkdir iotjs
++$ cp ../../iotjs/config/nuttx/stm32f4dis/app/* ./iotjs/
++```
++
++#### Configure NuttX
++
++```bash
++# assuming you are in iotjs-nuttx folder
++$ cd nuttx/tools
++
++# configure NuttX USB console shell
++$ ./configure.sh stm32f4discovery/usbnsh
++```
++
++Now you can configure nuttx like either of below. For convenience, we provide built-in configure file for you. (This configure file is equipped with modules specified as `always`. For `optional` modules, you might follow instructions below.)
++```bash
++$ cd ..
++$ cp ../iotjs/config/nuttx/stm32f4dis/.config.default .config
++```
++
++Or if you want to configure yourself, you can follow guide below.
++```bash
++$ cd ..
++# might require to run "make menuconfig" twice
++$ make menuconfig
++```
++
++Followings are the options to set:
++
++* Common
++ * Change `Build Setup -> Build Host Platform` from _Windows_ to [_Linux_|_OSX_]
++ * Enable `System Type -> FPU support`
++ * Enable `System Type -> STM32 Peripheral Support -> SDIO`
++ * Enable `RTOS Features -> Clocks and Timers -> Support CLOCK_MONOTONIC`
++ * Enable `RTOS Features -> Pthread Options -> Enable mutex types`
++ * Enable `RTOS Features -> Files and I/O -> Enable /dev/console`
++ * Enable `RTOS Features -> Work queue support -> High priority (kernel) worker thread`
++ * Disable `Device Drivers -> Disable driver poll interfaces`
++ * Enable `Device Drivers -> MMC/SD Driver Support`
++ * Enable `Device Drivers -> MMC/SD Driver Support -> MMC/SD SDIO transfer support`
++ * Enable `Networking Support -> Networking Support`
++ * Enable `Networking Support -> Socket Support -> Socket options`
++ * Enable `Networking Support -> Unix Domain Socket Support`
++ * Enable `Networking Support -> TCP/IP Networking`
++ * Enable `Networking Support -> TCP/IP Networking -> Enable TCP/IP write buffering`
++ * Enable `File Systems -> FAT file system`
++ * Enable `File Systems -> FAT file system -> FAT upper/lower names`
++ * Enable `File Systems -> FAT file system -> FAT long file names`
++ * Enable `Device Drivers -> Network Device/PHY Support -> Late driver initialization`
++ * Enable `Library Routines -> Standard Math library`
++ * Enable `Application Configuration -> System Libraries and NSH Add-ons -> IoT.js`
++ * Enable all children of `Application Configuration -> System Libraries and NSH Add-ons -> readline() Support` (for those who wants to use readline)
++
++* For `net` module
++ * Enable `System Type -> STM32 Peripheral Support -> Ethernet MAC`
++ * Disable `System Type -> STM32 Peripheral Support -> USART2`
++ * Enable `System Type -> STM32 Peripheral Support -> USART6`
++ * Set `System Type -> Ethernet MAC configuration -> PHY address` to `0`
++ * Set `System Type -> Ethernet MAC configuration -> PHY Status Register Address (decimal)` to `31`
++ * Enable `System Type -> Ethernet MAC configuration -> PHY Status Alternate Bit Layout`
++ * Set `System Type -> Ethernet MAC configuration -> PHY Mode Mask` to `0x001c`
++ * Set `System Type -> Ethernet MAC configuration -> 10MBase-T Half Duplex Value` to `0x0004`
++ * Set `System Type -> Ethernet MAC configuration -> 100Base-T Half Duplex Value` to `0x0008`
++ * Set `System Type -> Ethernet MAC configuration -> 10Base-T Full Duplex Value` to `0x0014`
++ * Set `System Type -> Ethernet MAC configuration -> 10MBase-T Full Duplex Value` to `0x0018`
++ * Set `System Type -> Ethernet MAC configuration -> RMII clock configuration` to `External RMII clock`
++ * Enable `Board Selection -> STM32F4DIS-BB base board`
++ * Set `Device Drivers -> Network Device/PHY Support -> Board PHY Selection` to `SMSC LAN8720 PHY`
++ * Enable `Networking Support -> Data link support -> Local loopback`
++ * Enable `Networking Support -> TCP/IP Networking -> TCP/IP backlog support`
++ * Enable `Networking Support -> ARP Configuration -> ARP send`
++
++* For `dgram`
++ * Enable `Networking Support > UDP Networking`
++
++* For `pwm` module
++ * Enable `System Type -> STM32 Peripheral Support -> TIM(N)`
++ * Enable `System Type -> Timer Configuration -> TIM(N) PWM`
++ * Set `System Type -> Timer Configuration -> TIM(N) PWM -> TIM(n) PWM Output Channel` to channel number you want
++ * Enable `Device Drivers -> PWM Driver Support`
++
++* For `adc` module
++ * Enable `System Type -> STM32 Peripheral Support -> ADC(N)`
++ * Enable `System Type -> STM32 Peripheral Support -> TIM(M)`
++ * Enable `System Type -> Timer Configuration -> TIM(M) ADC`
++ * Enable `Device Drivers -> Analog Device(ADC/DAC) Support`
++ * Enable `Device Drivers -> Analog Device(ADC/DAC) Support -> Analog-to-Digital Conversion`
++
++* For `uart` module
++ * Enable `System Type -> STM32 Peripheral Support -> U[S]ART(N)`
++
++* For `i2c` module
++ * Enable `System Type -> STM32 Peripheral Support -> I2C1`
++ * Enable `Device Drivers -> I2C Driver Support`
++
++* For `spi` module
++ * Enable `System Type -> STM32 Peripheral Support -> SPI1`
++ * Enable `Device Drivers -> SPI exchange`
++
++#### Build NuttX Context
++
++```bash
++# assuming you are in iotjs-nuttx folder
++$ cd nuttx/
++$ make context
++```
++
++
++### 4. Build IoT.js for NuttX
++
++These options are needed.
++```bash
++--target-arch=arm
++--target-os=nuttx
++--nuttx-home=/path/to/nuttx
++--target-board=stm32f4dis
++--jerry-heaplimit=[..]
++```
++
++For example,
++```bash
++$ ./tools/build.py \
++--target-arch=arm --target-os=nuttx --nuttx-home=../nuttx \
++--target-board=stm32f4dis --jerry-heaplimit=78
++```
++
++Library files will be generated like below when build is successful.
++
++```bash
++$ ls build/arm-nuttx/release/lib
++libhttpparser.a libiotjs.a libjerrycore.a libtuv.a
++```
++
++### 5. Build NuttX
++
++```bash
++# assuming you are in iotjs-nuttx folder
++$ cd nuttx/
++$ make IOTJS_ROOT_DIR=../iotjs
++```
++For release version, you can type R=1 make on the command shell.
++
++
++### 6. Flashing
++
++Connect Mini-USB for power supply and connect Micro-USB for `NSH` console.
++
++To configure `stlink` utility for flashing, follow the instructions [here](https://github.com/texane/stlink#build-from-sources).
++
++To install,
++```bash
++# assuming you are in stlink folder
++$ cd stlink
++$ make
++```
++
++To flash,
++```bash
++# assuming you are in nuttx folder
++$ sudo ../stlink/build/Release/st-flash write nuttx.bin 0x8000000
++```
++
++
++### 7. Run IoT.js
++
++#### USB Connection
++
++There are two USB Connections on the Target board. USB mini CN1 and USB micro CN5. Both USB ports need to be connected to your Host. CN1 is used for power and Flashing, but it will not appear as a device in Linux. CN5 is used for NSH and will appear as `/dev/ttyACM0(linux)` or `/dev/tty.usbmodem1(macOS)` when things work well.
++
++#### Use minicom
++
++```bash
++// linux
++$ minicom --device=/dev/ttyACM0
++// macOS
++$ minicom --device=/dev/tty.usbmodem1
++
++```
++You may need to enable _Add Carriage Return_ option.
++* Press <kbd>Ctrl-A</kbd> + <kbd>Z</kbd> + <kbd>U</kbd> for short in minicom screen. (For linux user)
++* Press <kbd>[Meta](http://osxdaily.com/2013/02/01/use-option-as-meta-key-in-mac-os-x-terminal/)</kbd> + <kbd>Z</kbd> for short in minicom screen. (For macOS user)
++
++Press _Enter_ key several times to trigger NuttShell to start.
++
++If micro SD is enabled, you can copy any script file to it and run with _nsh_, for example;
++```
++NuttShell (NSH)
++nsh> mount -t vfat /dev/mmcsd0 /mnt/sdcard
++nsh> iotjs /mnt/sdcard/path_to_file.js
++```
++
++If you see
++```
+++-----------------------------+
++| |
++| Cannot open /dev/ttyACM0! |
++| |
+++-----------------------------+
++```
++and it stays on the screen, something is wrong. Blue LED may blink if NuttX is in abnormal state. Press black(reset) button on the board and try again. If you still see this warning message, begin with original NuttX code and check your board, USB line and other softwares.
--- /dev/null
--- /dev/null
++### Overall steps to build for Linux
++1. Get the sources
++2. Build all at once
++3. Execute IoT.js
++4. Clean build directory
++
++***
++
++#### Build Host
++Ubuntu 14.04 is recommended. Other Unix like platforms can be used. If it doesn't seem to work properly on other platforms, please look into the [Issues](https://github.com/Samsung/iotjs/issues) page. Someone may have already tried. If you can't find any related one, please leave an issue for help.
++
++#### Directory structure
++
++This document assumes 'harmony' as the root directory. _JerryScript_, _libtuv_ and _libuv_ are included as sub-modules in `deps` directory.
++
++* harmony
++ * iotjs
++ * deps
++ * http-parser
++ * jerry
++ * libuv
++ * libtuv
++
++
++※ harmony? It's from the initial code name of our project. (_Sounds good, isn't it? :)_)
++
++#### Prerequisite
++
++You need to install some packages to build IoT.js, as follows;
++
++```
++sudo apt-get install gyp cmake build-essential valgrind
++```
++
++gcc compiler 4.8 or higher versions are required to compile. If you don't know how to do it, you can get some help from [how-to-install-gcc-4-8](http://askubuntu.com/questions/271388/how-to-install-gcc-4-8) or google.
++
++### 1. Get the sources
++
++Clone our repository to look around and test it. If it attracts you and you want to try something interested, please fork it.
++
++To get the source for this repository,
++```
++cd harmony
++git clone https://github.com/Samsung/iotjs.git
++cd iotjs
++```
++
++Sub-modules(_http-parser_, _JerryScript_, _libuv_ and _libtuv_) will be pulled. And matching hash will be checked out for your current IoT.js version when you run the build script.
++
++
++### 2. Build all at once
++
++IoT.js and required sub-modules are generated all at once in tools directory with build.py.
++
++```
++cd iotjs
++./tools/build.py
++```
++
++
++#### Set build options
++Some basic options are provided.
++
++Existing build options are listed as follows;
++```
++buildtype=debug|release (debug is default)
++builddir=build (build is default)
++clean
++buildlib (default is False)
++target-arch=x86|x86_64|x64|i686|arm (depends on your host platform)
++target-os=linux|nuttx|darwin|osx (linux is default)
++target-board
++cmake-param
++compile-flag
++link_flag
++external-include-dir
++external-static-lib
++external-shared-lib
++iotjs-include-module
++iotjs-exclude-module
++jerry-cmake-param
++jerry-compile-flag
++jerry-link-flag
++jerry-lto
++jerry-heap-section
++jerry-heaplimit (default is 81, may change)
++jerry-memstat (default is False)
++no-init-submodule (default is init)
++no-check-tidy (default is check)
++no-check-test (default is check)
++no-parallel-build
++no-snapshot
++nuttx-home= (no default value)
++```
++
++To give options, please use two dashes '--' before the option name as described in the following sections.
++
++Options that may need explanations.
++* builddir: compile intermediate and output files are generated here.
++* buildlib: generating _iotjs_ to a library if True(e.g. for NuttX). give __--buildlib__ to make it True.
++* jerry-heaplimit: JerryScript default heap size (as of today) is 256Kbytes. This option is to change the size for embedded systems, NuttX for now, and current default is 81KB. For linux, this has no effect. While building nuttx if you see an error `region sram overflowed by xxxx bytes`, you may have to decrease about that amount.
++* jerry-memstat: turn on the flag so that jerry dumps byte codes and literals and memory usage while parsing and execution.
++* no-check-tidy: no checks codes are tidy. we recommend to check tidy.
++* no-check-test: do not run all tests in test folder after build.
++* nuttx-home: it's NuttX platform specific, to tell where the NuttX configuration and header files are.
++
++If you want to know more details about options, please check the [Build Script](Build-Script.md) page.
++
++
++#### Include extended module
++There are two ways to include [extended module](../api/IoT.js-API-reference.md).
++
++The first way is to modify a property value of module in `build.config` file. You can move a module name from 'exclude' to 'include'.
++
++The second way is by using build options which is `--iotjs-include-module`.
++If you enter several modules, separate them with a comma.
++
++```
++./tools/build.py --iotjs-include-module=dgram,pin,gpio
++```
++
++
++#### Options example
++
++It's a good practice to build in separate directory, like 'build'. IoT.js generates all outputs into separate **'build'** directory. You can change this by --builddir option. Usually you won't need to use this option. Target and architecture name are used as a name for a directory inside 'build' directory.
++
++To build debug version, type the command like below. And you can find the binary in 'output' directory.
++```
++./tools/build.py --builddir=output
++```
++
++To build 32bit version in x86_64 with debug version as a library, type the command like below.
++```
++./tools/build.py --target-arch=i686 --buildlib
++```
++
++To build release version with different jerry revision, type the command like below. (Assume that you have already checked it out.)
++```
++./tools/build.py --buildtype=release --no-init-submodule
++```
++
++
++
++#### Build only IoT.js with given build option
++
++This section for explaining how to build only IoT.js when you did some modification. IoT.js uses [CMake](http://www.cmake.org/) for makefile generation. You can go inside the build folder and build with 'make' command. Go inside where your target platform name is, for example x86_64 linux,
++```
++cd build/x86_64-linux/release/iotjs
++make
++```
++
++#### What build script does
++
++1. It will clone sub-modules, this will be done only once when version hash has not changed.
++2. Checkout matching version for each sub-modules.
++3. Build sub-modules, you can see the outputs at build/(target-arch)-(target-os)/(buildtype)/libs folder.
++4. Build IoT.js
++
++
++### 3. Execute IoT.js
++
++Executable name is **'iotjs'** and resides in (target-arch)-(target-os)/(buildtype)/iotjs.
++To run greetings JavaScript in test folder, for example;
++
++```
++./build/x86_64-linux/debug/bin/iotjs ./test/run_pass/test_console.js
++```
++
++#### Set execution Options
++
++Some execution options are provided as follows;
++```
++memstat
++show-opcodes
++```
++
++To give options, please use two dashes '--' before the option name as described in following sections.
++
++For more details on options, please see below.
++* memstat: dump memory statistics. To get this, must build with __jerry-memstat__ option.
++* show-opcodes: print compiled byte-code.
++
++
++#### Options example
++
++To print memory statistics, follow the below steps;
++```
++./tools/build.py --jerry-memstat
++
++./build/x86_64-linux/debug/bin/iotjs --memstat ./test/run_pass/test_console.js
++```
++
++With given `show-opcodes` option, opcodes will be shown.
++```
++./build/x86_64-linux/debug/bin/iotjs --show-opcodes ./test/run_pass/test_console.js
++```
++
++### 4. Clean build directory
++
++Just remove the folder as follows;
++```
++rm -rf build
++rm -rf deps/libuv/out
++```
--- /dev/null
--- /dev/null
++#### Maintainers
++* akosthekiss (integration)
++* LaszloLango (integration)
++* zherczeg (Steering Committee)
++* yichoi (Steering Committee, Project main contact)
++
++#### Committers
++* chokobole
++* glistening
++* hs0225
++* daeyeon
++* bzsolt
++* galpeter
--- /dev/null
--- /dev/null
++All community members must abide by rules of common sense, civility and good neighborliness. Frank discussion is welcomed and encouraged with the goal of arriving at the best technical solution possible.
++Community participants must adhere to these simple rules:
++- Respect and acknowledge all contributions, suggestions and comments from the community.
++- Listen and be open to all opinions, which are subject to open discussion.
++- Help each other.
++- Assume people mean well.
++
++<br>
++
++### Community Consensus, Lazy Consensus and Slient Consent
++
++Community consensus about a Project issue means that the issue has been submitted to and discussed by Contributors, and that ALL discussing member agree about the issue.<p>
++Lazy consensus means that Contributors may proceed with work when they have reason to believe that other Contributors in the community will agree with the direction of their work, and do not need to stop or initiate unnecessary discussion about the work. Contributors should publish their work (that is, merge proposals to master branch) in a timely manner to allow others to possibly raise issues about the work. When the Contributor is not sure there will be consensus, they should raise a proposal to the community via appropriate public communication channels(**_currently Github issues is possible way to achieve this_**)<p>
++Silent Consent means that those who do not offer a reasoned alternative in course of the discussion implicitly agree with the proposal.
++
++<br>
++
++### Meritocracy
++
++Responsibilities in the project (including decision making) are given to those who exhibit both the technical skill and dedication to project via their ongoing valuable contributions. Decision making happens inside the community, with more weight given to those who are more familiar with the code.
--- /dev/null
--- /dev/null
++* [Project Roles](#project-roles)
++ - [Contributor](#contributor)
++ - [Committer](#committer)
++ - [Maintainer](#maintainer)
++ - [Selection of Committers and Maintainers](#selection-of-committers-and-maintainers)
++ - [Revocation of Committers/Maintainers status](#revocation-of-committersmaintainers-status)
++ - [Steering Committee](#steering-committee)
++* [Decision Making Process](#decision-making-process)
++
++## Project Roles
++
++The IoT.js project recognizes the following formal roles: Contributor, Committer, and Maintainer.
++
++* [Assigned people](Assigned-people.md)
++
++#### Contributor
++A _Contributor_ is a developer who wishes to contribute to the project, at any level. Contributors who show dedication and skill are rewarded with additional rights and responsibilities. Their opinions weigh more when decisions are made, in a fully meritocratic fashion.
++
++Contributors are granted the following rights and responsibilities:
++* Right to contribute code, documentation, translations, artwork, etc.
++* Right to report defects (bugs) and suggestions for enhancement.
++* Right to participate in the process of reviewing contributions by others.
++* Right to initiate and participate in discussions in any communication methods.
++* Right to approach any member of the community with matters they believe to be important.
++* Responsibility to abide by decisions, once made. They are welcome to provide new, relevant information to reopen decisions.
++* Responsibility for issues and bugs introduced by one’s own contributions.
++* Responsibility to respect the rules of the community.
++* Responsibility to provide constructive advice whenever participating in discussions and in the review of contributions.
++
++#### Committer
++A _Committer_ is a Contributor who is also responsible for the maintenance of IoT.js source code.
++
++Committers have the following rights and responsibilities, in addition to those listed for Contributors:
++* Right to set goals for the short and medium terms for the project being maintained, alongside the Maintainer.
++* Right to exceptionally make more invasive changes to the source code, when required.
++* Right to approve own contribution, after discussing with other Contributors.
++* Right and responsibility to participate in the feature development process.
++* Responsibility to ensure all contributions of the project have been reviewed within reasonable time.
++* Responsibility to ensure the quality of the code to expected levels.
++* Responsibility to monitor discussions in the community.
++* Responsibility to participate in the quality verification and release process, when those happen.
++
++#### Maintainer
++A _Maintainer_ is a Contributor who is also responsible for knowing, directing and anticipating the needs of a given IoT.js source code.
++
++Maintainers have the following rights and responsibilities, in addition to those listed for Contributors and Committers:
++* right to set the overall organization of the source code of the project
++* right to participate in the decision-making of the project, in conjunction with the Committers.
++* Responsibility to ensure all contributions of the project have been reviewed within reasonable time.
++ - In the reviewing, only Maintainers can give binding scores(refer to [Approval Path for PR(Pull Request)](#approval-path-for-prpull-request))
++
++#### Selection of Committers and Maintainers
++
++A candidate for the Committer role should be one of the Contributors who has submitted at least 10 non-trivial patches in project and has shown characteristics consistent with the requirements of the Committer role.
++A candidate for the Maintainer role should be one of the Committers.
++To be a candidate for the Committer or Maintainer, a Contributor can self-nominate with proper evidences.
++
++The selection process should be achieved by consensus of the Contributors active in. If consensus cannot be achieved, Maintainers will make the decision by voting.
++
++#### Revocation of Committers/Maintainers Status
++
++A Maintainer or a Committer who intentionally abused his review privilege may have it temporarily suspended on the request of other Committers or Maintainers. Committers and Maintainers not including the person under consideration should discuss on the revocation of the person. If consensus cannot be reached, Maintainers will make the decision by voting.
++
++#### Steering Committee
++
++_Steering Committee_ oversees and guides the progress of IoT.js project.
++
++The Steering Committee have the following responsibilities:
++
++* responsibility to oversee the health of the project community.
++* responsibility to oversee and facilitate the development of the IoT.js source code under the governance rules of the IoT.js Open Source project.
++* responsibility to guide and direct the development towards goals.
++* responsibility to sets the goals and roadmap for the project
++
++## Decision Making Process
++
++Decisions in the IoT.js project are made always at the lowest level possible that is applicable for the decision in question. Decision makers always need to keep in mind the rules of community and the IoT.js goals and roadmap.
++
++* Individual Contributors are making decisions every time they submit changes in the form of deciding what to implement and how to go about it.
++* Two or more Contributors also make decisions when participating in discussions in community, on bug or feature reports, in reviewing of commits. Their arguments in why a given decision should be made are part of the consensus that needs to be reached for the decision. At this level, the principle of meritocracy is important, as the opinion of those who have contributed more will be given more weight in the consensus-building.
++* If those Contributors cannot agree and reach consensus on a decision, then IoT.js provides for decisions to be made by Maintainers following their own decision-making process, avoiding stalemates.
--- /dev/null
--- /dev/null
++The following guidelines on the submission process are provided to help you be more effective when submitting code to the IoT.js project.
++
++When development is complete, a patch set should be submitted via Github pull requests. A review of the patch set will take place. When accepted, the patch set will be integrated into the master branch, verified, and tested. It is then the responsibility of the authoring developer to maintain the code throughout its lifecycle.
++
++Please submit all patches in public by opening a pull request. Patches sent privately to Maintainers and Committers will not be considered. Because the IoT.js Project is an Open Source project, be prepared for feedback and criticism-it happens to everyone-. If asked to rework your code, be persistent and resubmit after making changes.
++
++#### 1. Scope the patch
++
++Smaller patches are generally easier to understand and test, so please submit changes in the smallest increments possible, within reason. Smaller patches are less likely to have unintended consequences, and if they do, getting to root cause is much easier for you and the Maintainers and Committers. Additionally, smaller patches are much more likely to be accepted.
++
++#### 2. Sign your work with the [IoT.js DCO](IoT.js-Developer's-Certificate-of-Origin-1.0.md)
++
++The sign-off is a simple line at the end of the explanation for the patch, which certifies that you wrote it or otherwise have the right to pass it on as an Open Source patch. The sign-off is required for a patch to be accepted.
++
++#### 3. Open [a Github pull request](https://github.com/Samsung/iotjs/pulls)
++
++#### 4. What if my patch is rejected?
++
++It happens all the time, for many reasons, and not necessarily because the code is bad. Take the feedback, adapt your code, and try again. Remember, the ultimate goal is to preserve the quality of the code and maintain the focus of the Project through intensive review.
++
++Maintainers and Committers typically have to process a lot of submissions, and the time for any individual response is generally limited. If the reason for rejection is unclear, please ask for more information to the Maintainers and Committers.
++If you have a solid technical reason to disagree with feedback and you feel that reason has been overlooked, take the time to thoroughly explain it in your response.
++
++#### 5. Code review
++
++Code review can be performed by all the members of the Project (not just Maintainers and Committers). Members can review code changes and share their opinion by comments with the following principles:
++* Discuss code; never discuss the code's author.
++* Respect and acknowledge contributions, suggestions, and comments.
++* Listen and be open to all different opinions.
++* Help each other.
++
++Changes are submitted via pull requests and only the Maintainers and Committers should approve or reject the pull request.
++Changes should be reviewed in reasonable amount of time. Maintainers and Committers should leave changes open for some time (at least 1 full business day) so others can offer feedback. Review times increase with the complexity of the review.
++
++### Tips on GitHub Pull Requests
++* Fork the GitHub repository(https://guides.github.com/activities/forking/) and clone it locally.
++Connect your local repository to the original upstream repository by adding it as a remote.
++Pull in upstream changes often to stay up-to-date so that when you submit your pull request, merge conflicts will be less likely.
++* For more details, see [GitHub fork synching guidelines](https://help.github.com/articles/syncing-a-fork/).
++[Create a branch](https://guides.github.com/introduction/flow/) for your edits.
--- /dev/null
--- /dev/null
++## This is a sample API reference. Please use this as a guideline to write your module's API references.
++
++- If you have any questions about this guide, please let us know as an issue.
++- `Markdown Example` is added to help understanding, and you can ignore it when writing the actual document.
++- The document contents should be in order of `"Module"`, `"Module Function"`, `"Class"`, `"Constructor"`, `"Properties"`, `"Static Function"`, `"Prototype Functions"`, and `"Events"`. If the content does not exist, it can be omitted.
++- `Module Functions` are what you can directly invoke without an instance of a certain Class. E.g) net.connect.
++- In case of `experimental` module, it's required to explicitly indicate that the features are experimental. Please put the caution below to the beginning of the document.
++> :exclamation: This document describes an experimental feature and considerations. Please be aware that every experimental feature may change, be broken, or be removed in the future without any notice.
++
++***
++
++### Platform Support
++
++The following shows `{Your_module_name}` module APIs available for each platform.
++
++| | Linux<br/>(Ubuntu) | Raspbian<br/>(Raspberry Pi) | NuttX<br/>(STM32F4-Discovery) |
++| :---: | :---: | :---: | :---: |
++| {class_name}.{functionName1} | O | O | O |
++| {class_name}.{functionName2} | O | O | O |
++| {class_name}.{functionName3} | O | O | O |
++
++# {Your_module_name}
++
++- Write a brief description of this module here.
++- The first character of the title must start with an `Uppercase letter`.
++
++#### Markdown Example
++
++```
++# Timer
++
++The timer module exposes a global API for scheduling functions to be called at some future period of time.
++Because the timer functions are globals, there is no need to call require('timers') to use the API.
++```
++
++## {your_module_name}.{your_module_function_name}([{argument_name}])
++* `{argument_name}` {{Argument_type}} {more information} **Default:** `{defalut_value}`
++* Returns: {{return_type}} {more information}
++
++- Write a description of this function here.
++- The first character of Module in the title must start with a `lowercase letter`.
++- The other rules are the same as mentioned before.
++
++**Example**
++```
++ Write a sample usage for this API if needed.
++```
++
++#### Markdown Example
++```
++### net.connect(port[, host][, connectListener])
++* `port` {number} Port the client should connect to.
++* `host` {string} Host the client should connect to. **Default:** `localhost`.
++* `connectListener` {Function} Listener for the `'connect'` event.
++* Returns {net.Socket}.
++
++Creates a new `net.Socket` and automatically connects to the supplied `port` and `host`.
++If host is omitted, `localhost` will be assumed.
++The `connectListener` is automatically registered as a `'connect'` event listener.
++```
++
++## Class: {Your_class_name}
++
++- Write a brief description of this class here.
++- The first character of the title must start with an `Uppercase letter`.
++- While you are writing this description, if you need to write down module / class / function / event name, arguments, or type which you already mentioned, then enclose the keyword in single-quotation. This rule applies to other items as well.
++
++ E.g) The given `callback` is called every `delay` milliseconds. If it's not a function, a `TypeError` will be thrown.
++
++### new {Your_class_name}([{argument_name}])
++* `{argument_name}` {{Argument_type}} {more information} **Default:** `{defalut_value}`
++* Returns: {{return_type}} {more information}
++
++Notice that every argument name of API and defalut value are in a single-quote.
++
++**Example**
++```
++ Write a sample usage for this API if needed.
++```
++
++#### Markdown Example
++
++```
++# Class: Buffer
++
++Buffer class is a global type with various constructors and accessors.
++IoT.js provides Buffer to manipulate binary data. Currently buffer has a pure
++ES5 compatible implementation, but this might be reworked to use `UInt8Array` in the future.
++
++
++### new Buffer(size)
++* `size` {integer} Size of the new buffer.
++
++Creates a new buffer of `size` bytes and initialize its data to zero.
++
++```
++
++
++### {Your_class_name}.{your_static_function_name}([{argument_name}])
++* `{argument_name}` {{Argument_type}} {more information} **Default:** `{defalut_value}`
++* Returns: {{return_type}} {more information}
++
++- Write a description of this static function here.
++- The first character of Class in the title must start with an `Uppercase letter`.
++- The other rules are the same as mentioned before.
++
++**Example**
++```
++ Write a sample usage for this API if needed.
++```
++
++#### Markdown Example
++
++```
++### Buffer.byteLength(str, encoding)
++
++* `str` {string} Source string.
++* `encoding` {string} String encoding.
++* Returns: {integer} Byte length of source string.
++
++Returns the byte length of a buffer representing the value
++of the string argument encoded with encoding. The effect is
++the same as:
++
++```js
++return new Buffer(str, encoding).length;
++```
++
++
++### {your_class_name}.{property_name}
++* {{property_type}}
++
++- Write a description of this property here.
++- The first character of the title must start with a `lowercase letter`.
++
++**Example**
++```
++ Write a sample usage for this API if needed.
++```
++#### Markdown Example
++```
++### buf.length
++* {integer}
++
++Returns the capacity of the buffer in bytes. Note: when
++the buffer is converted to another type (e.g. `String`) the
++length of the converted value might be different from
++this value.
++
++**Example**
++
++```js
++var Buffer = require('buffer');
++
++var buffer = new Buffer([0xc8, 0x80])
++console.log(buffer.length); // prints 2
++
++var str = buffer.toString();
++console.log(str.length); // prints 1
++```
++
++
++### {your_class_name}.{your_prototype_function_name}([{argument_name}])
++* `{argument_name}` {{Argument_type}} {more information} **Default:** `{defalut_value}`
++* Returns: {{return_type}} {more information}
++
++- Write a description of this prototype function here.
++- The first character of Class in the title must start with a `lowercase letter`.
++- The other rules are the same as mentioned before.
++
++**Example**
++```
++ Write a sample usage for this API if needed.
++```
++
++#### Markdown Example
++
++```
++### emitter.on(event, listener)
++* `event` {string} The name of the event.
++* `listener` {Function} The callback function.
++ * `args` {any}.
++* Returns `emitter` {events.EventEmitter}.
++
++Adds the `listener` callback function to the end of the listener's list for the given `event`. No checks are made to see if the `listener` has already been added.
++In case of multiple calls the `listener` will be added and called multiple times.
++
++**Example**
++
++```js
++var EventEmitter = require('events').EventEmitter;
++var emitter = new EventEmitter();
++
++emitter.on('event', function() {
++ console.log('emit event');
++});
++
++emitter.emit('event');
++
++```
++
++
++### Event: '{your_events_name}'
++* `{callback_name}` {{callback_function_argument}}
++ * `{argument1}` {{argument2_type}} {more information}
++
++- Write a description of this here.
++- In case of Event, the name of Class that this event belongs to, is not prepended in the title.
++- The other rules are the same as mentioned before.
++
++#### Markdown Example
++
++```
++### Event: 'lookup'
++* `callback` {Function}
++ * `err` {Error}
++ * `address` {string}
++ * `family` {string|null}
++
++Emitted after resolving hostname.
++```
++
++ - Notice that the `err {Error}` above is started with `2 spaces` indentation since it's given to `callback` as parameters, not `lookup` event.
--- /dev/null
--- /dev/null
++ - [Inside IoT.js](Inside-IoT.js.md)
++ - [Experimental Features](Experimental-Features.md)
++ - [Inside Validated Struct](Inside-IoT.js-Validated-Struct.md)
++ - [Logging Execution](Logging-IoT.js-execution.md)
++ - [Memory saving with libtuv](Memory-savings-with-libtuv.md)
++ - [Optimization Tips](Optimization-Tips.md)
++ - [JerryScript Debugger](Use-JerryScript-Debugger.md)
++ - [Writing New Builtin Module](Writing-New-Builtin-Module.md)
++ - [Extended API Guidelines](Extended-API-Guidelines.md)
--- /dev/null
--- /dev/null
++* [Coding Style Guideline for C](#coding-style-guideline-for-c)
++ * Validated Struct
++ * Header Files
++ * Formatting
++ * Naming
++ * Comments
++* [Coding Style Guideline for Javascript](#coding-style-guideline-for-javascript)
++ * Javascript Language Rules
++ * Javascript Style Rules
++ * Naming
++ * Formatting
++* [Coding Style Guideline for Python](#coding-style-guideline-for-python)
++
++
++# Coding Style Guideline for C
++
++Our coding style guideline is based on [google c++ coding standard](https://google.github.io/styleguide/cppguide.html),
++but modified due to some difference between C and C++.
++When this guideline is ambiguous, just follow the result of running `./tools/check_tidy.py`.
++
++Here are `./tools/check_tidy.py` options:
++```
++--autoedit: Automatically edit the detected clang format errors. No diffs will be displayed.
++```
++
++## Validated Struct
++Use [Validated Struct](../devs/Inside-IoT.js-Validated-Struct.md) whenever possible, for encapsulation and validity check.
++
++## Header Files
++
++### #define guard
++Use #define guard in all header files. `<FILE>_H` format is recommended.
++
++ #ifndef FILE_H
++ #define FILE_H
++ ...
++ #endif // FILE_H
++
++## Formatting
++
++### Line length
++maximum 80 characters in a line.
++
++### Indentation
++2 space indent at a time. Do not use a tab for indentation.
++
++### Vertical whitespace
++Add two blank lines between functions.
++
++Otherwise minimize use of vertical whitespace.
++
++This is more a principle than a rule: don't use blank lines when you don't have to. In particular, don't put more than two blank lines between functions, resist starting functions with a blank line, don't end functions with a blank line, and be discriminating with your use of blank lines inside functions.
++
++### Function call
++Write a function call all in a line if it fits. If not, break the line into multiple lines after assignment operator, or insert newline between parameters.
++Do not insert spaces after open paren and before close paren.
++
++ int value = foo(arg1, arg2, arg3);
++
++ int value =
++ foo(arg1, arg2, arg3);
++
++ int value = foo(arg1, arg2,
++ arg3);
++
++### Function Declaration and Definition
++Use named parameters in function declaration.
++
++ return_type function_name(int, char); // not allowed
++ return_type function_name(int arg1, char arg2); // Use this
++
++Return type should be on the same line as function name and parameters if it fits. If not, break between them aligned with the first argument.
++
++ return_type function_name(int arg1,
++ char arg2);
++
++If even first argument does not fit in a line, write it in a new line with 4 space indent.
++
++ return_type function_name(
++ int arg1, char arg2);
++
++
++The open curly brace should be at the same line. The close curly brace should be either at the same line as its open curly brace or at new line.
++
++ return_type function_name(int arg1, char arg2) { };
++ return_type function_name(int arg1, char arg2) {
++ ...
++ }
++ return_type function_name(int arg1, char arg2)
++ { // not allowed
++ ...
++ }
++
++### Conditionals
++Use a space between the if and open brace. Open brace on the same line as the if.
++
++ if (condition) {
++ ...
++ }
++
++Short conditional statements may be written without braces.
++
++ if (condition)
++ do_something();
++
++### Loops and Switches
++Use a space between the switch and loops(for, while, do-while) and open brace. Open brace on the same line as the switch and loops.
++
++ while (condition) {
++ ...
++ }
++
++Single loop body statement may be written without braces.
++
++ while (condition)
++ do_something(); // ok
++ for (condition)
++ do_something(); // ok
++
++
++## Naming
++
++### Type names
++Use lower cases and underscore for struct names, and add prefix `iotjs_` and suffix `_t`.
++
++ typedef struct {
++ ...
++ } iotjs_name_t;
++
++### Function names
++Use lower cases and underscore for function names.
++
++For constructors, destructor, and methods of validated struct `iotjs_mystruct_t`, use names starting with `iotjs_mystruct_*`.
++Constructor function name should be either `iotjs_mystruct_create` or `iotjs_mystruct_initialize`,
++depending on whether the constructor returns the instance as return value, or the constructor just initializes the instance passed by parameter.
++
++```c
++typedef struct {
++} IOTJS_VALIDATED_STRUCT(iotjs_mystruct_t);
++
++iotjs_mystruct_t iotjs_mystruct_create(); // Ok
++iotjs_mystruct_t* iotjs_mystruct_create(); // Ok
++void iotjs_mystruct_initialize(iotjs_mystruct_t*); // Ok
++
++void iotjs_mystruct_destroy();
++
++int iotjs_mystruct_method();
++```
++
++### Variable names
++Use lower cases and underscore for variable names.
++
++ int lower_case_variable;
++
++
++## Comments
++
++### Comment style
++Use either // or /* */ style comments. However, // style is much prefered.
++
++
++
++# Coding Style Guideline for Javascript
++
++This coding standard is based on [google javascript coding standard](https://google.github.io/styleguide/javascriptguide.xml)
++
++## Javascript Language Rules
++
++### var
++Always declare variable before use.
++
++### Semicolons
++Always use semicolons.
++
++### Function Declaration in blocks
++Do not declare functions within a block.
++
++### Wrapper objects of primitive types
++Do not use wrapper objects for primitive types.
++
++### with
++Do not use `with` statement.
++
++### Modifying prototypes of builtin objects
++Do not modify prototypes of builtin objects
++
++## Javascript Style Rules
++
++### Naming
++Use lowerCamelCase for varible names and function names.
++
++ var myFirstVariable;
++ function myFirstFunction {
++ ...
++ }
++
++Use UpperCamelCase for constructor names
++
++ function MyConstructorFunction(input) {
++ this.variable = input;
++ ...
++ }
++
++### Formatting
++Follow C/C++ formatting above.
++
++
++# Coding Style Guideline For Python
++
++The coding conventions for Python code follows [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/)
--- /dev/null
--- /dev/null
++### Getting Started with Examples
++As **IoT.js** is asynchronous and event-driven, programming style is pretty much different from traditional blocking synchronous style. This tutorial lets you know how to code with **IoT.js** mainly focused on asynchronous and event-driven style.
++
++#### Hello World
++Firstly, create a javascript file (e.g. `hello.js`) and open it. Then type as following.
++```javascript
++console.log('Hello, world!');
++```
++
++You must be familiar with the code above if you have ever worked with Javascript in web. This is exactly same way as in major web browsers.
++
++You can run it with:
++```
++$ ./iotjs hello.js
++```
++
++Then it gives:
++```
++Hello, world!
++```
++
++Pretty simple. But where did `console` come from? `console` is not defined in Global Object according to ECMAScript spec.
++
++The answer is `console` is a builtin module so it should have been `require`ed. However, `console` is a special case so we can use it directly without `require`. This is about Module System which we will cover later.
++
++#### File Reader
++To read a file, we need to import *File System* module.
++When importing a module, we use function `require`.
++*File System* module is abbreviated as `fs`. You can import it like:
++```javascript
++var fs = require('fs');
++```
++
++Then we can use APIs of `fs`. To read the whole file, use `readFile()`.
++```javascript
++fs.readFile("hello_iotjs.txt", // path
++ readFileCallback); // callback
++```
++Let's say we want to read `hello_iotjs.txt`. Just pass it as first argument.
++It may be enough for synchronous style but we must specify a callback function as last argument. `fs.readFile` does not wait for I/O to be done, it just goes on to next code. Sometime after file opening is completely done, callback will be called. This means that we must not implement `readFile` handling code on the next line, but in callback function.
++
++Take a look at the callback function for `fs.readFile` below.
++```javascript
++function readFileCallback(err, data) {
++ if (err) throw err;
++ console.log(data.toString());
++}
++```
++We can find two arguments in this function. We can think of them as the results of `fs.open`. In this case(`fs.readFile`), `err` and `data` are given. Of course, each API function has their own argument list.
++
++`err` is an `Error` object. We just throw it if an error has occurred. Otherwise we have successfully read the file content and it is stored in `data`. In this example, it only prints the file content but you can do anything you want.
++
++##### full code list
++```javascript
++var fs = require('fs');
++
++fs.readFile("hello_iotjs.txt", // path
++ readFileCallback); // callback
++
++function readFileCallback(err, data) {
++ if (err) throw err;
++ console.log(data.toString());
++}
++```
++
++#### TCP Echo Server
++`net` module provides APIs for creating servers and clients. In this tutorial, we are going to create a server only. We can connect to the server and test it with external tools(e.g. `nc`).
++
++Firstly, we need to require `net` module.
++```javascript
++var net = require('net');
++var port = 1235; // custom port number
++```
++Then create a server with `net.createServer()`. It could have some arguments
++```javascript
++var server = net.createServer();
++```
++After creating a server, make the server listen for connections.
++```javascript
++server.listen(port);
++```
++By calling `listen`, object `server` starts listening with given port. Of course `listen` is processed asynchronously but we do not have to specify a callback. What we want to do next is not necessarily done in the callback because we are just going to add some event handlers.
++
++**IoT.js** is event-driven. We can do a lot of stuff with event handlers.
++Both `Server` and `Socket` object inherits from `EventsEmitter`, so we can add event listeners for them. For servers, we probably want to add a listener for `'connection'` event which is emitted when a new connection is made. Take a look at the following.
++```javascript
++server.on('connection', function(socket) {
++ socket.on('data', function(data) {
++ socket.write("echo: " + data);
++ });
++});
++```
++In `File Reader` example, we defined callbacks outside and referred them as arguments. In this time the function is embedded as a Function Expression.
++
++When `'connection'` event is emitted, it creates a socket and we can get it from the first argument. In the same way we did for server, add a ``data`` listener for each socket which is emitted when data is received. As we are creating an echo server, what we want to do here is just send the `data` back to client. Note that to clarify this is an echoed data, `"echo: "` is prepended to it.
++
++That is all. We just implemented an echo server less than 10 lines. Actually, the server will run forever because we did not add code for closing the server. As long as the server is listening, it does not terminate even if there is no more *javascript* code to run. As this is a simple tutorial, just kill the process manually like pressing `Ctrl+C`
++
++##### full code list
++
++```javascript
++var net = require('net');
++var port = 1235;
++
++var server = net.createServer();
++server.listen(port, 5);
++server.on('connection', function(socket) {
++ socket.on('data', function(data) {
++ socket.write("echo: " + data);
++ });
++});
++```
++##### test the server
++We have created a server but not a client. Instead of implementing a client, we are going to use a unix tool `nc`.
++
++Run the server first:
++```
++$ ./iotjs echo_server.js &
++```
++
++Connect to the server with `nc`
++```
++$ nc localhost 1235
++```
++Type whatever you want to send, and the message will be echoed back.
++```
++hello, echo server!
++echo: hello, echo server!
++```
++
++### Module System
++Javascript(ECMAScript 5.1 or under) itself does not support module system. In web browsers, even though a web page loads several Javascript files, they are evaluated in the same context. To overcome this language limit, **IoT.js** supports [CommonJS](http://www.commonjs.org/) modules.
++
++We have used some of native modules through the examples above. When importing those modules, we use `require` function. Once `require`ed a module, we can use its APIs that are exported from the module. It will be covered in the section [Writing user modules](#writing-user-modules).
++
++#### Writing user modules
++When writing a module, APIs must be exposed by adding it in `exports` object. Otherwise it can be used only inside the module. Object `exports` will be returned when another module calls `require`.
++
++Let's write a sample module. Save it as `mymodule.js`
++```javascript
++exports.hello = 'Hello, IoT.js!'; // string
++exports.add = function(a, b) { // function
++ return a + b;
++}
++var local = 'local string'; // string (not exported)
++```
++Let's write another module that uses the module we just wrote. By calling `require`, we get its `exports` object. We will name it `mymodule_test.js`
++```javascript
++var mymodule = require('mymodule');
++console.log(mymodule.hello);
++console.log(mymodule.add(1, 2));
++console.log(mymodule.local);
++```
++Save two files in the same directory so **IoT.js** can automatically find `mymodule.js`. Then we are ready to go. Execute the later script then you will see:
++```
++$ ./iotjs mymodule_test.js
++Hello, IoT.js!
++3
++undefined
++```
++Note that `console.log(local)` prints `undefined`. It cannot be referred because it is not added in `exports`.
--- /dev/null
--- /dev/null
++* [Proposals, Get Answers and Report a Bug via Github Issues](#proposals-get-answers-and-report-a-bug-via-github-issues)
++* [Feature development process](#feature-development-process)
++* [Approval Path for PR(Pull Request)](#approval-path-for-prpull-request)
++* [Tips on GitHub Issues](#tips-on-github-issues)
++
++***
++
++It is the responsibility of IoT.js Maintainers and Reviewers to decide whether submitted code should be integrated into the master branch, returned for revision, or rejected.
++
++Individual developers maintain a local copy of the IoT.js codebase using the git revision control system. Git ensures that all participants are working with a common and up-to-date code base at all times. Each developer works to develop, debug, build, and validate their own code against the current codebase, so that when the time comes to integrate into the master branch of the project, their changes apply cleanly and with a minimum amount of merging effort.
++
++### Proposals, Get Answers and Report a Bug via Github Issues
++
++If you have a question about IoT.js code, have trouble any documentation, would like to suggest new feature, or find a bug, [review the current IoT.js issues](https://github.com/Samsung/iotjs/issues) in GitHub, and if necessary, [create a new issue](https://github.com/Samsung/iotjs/issues/new).
++
++**There are several labels on the Issue. Please choose proper labels on the purpose.**
++* **bug**
++* **community** : any issues on the community operation
++* **enhancement** : feature enhancement proposal
++* **help wanted**
++* **new feature request(proposal)** : new feature proposal
++* **project announcement** : general announcement on the project such as new release, new Maintainer/Reviewer and so on
++* **question** : any questions on the project
++
++and so on.
++
++### Feature development process
++
++The IoT.js Project development process is marked by the following highlights:
++* The feature development process starts with an author discussing a proposed feature with the Maintainers and Reviewers
++ - Open the issue with label 'new feature request(proposal)'
++* The Maintainers and Reviewers evaluate the idea, give feedback, and finally approve or reject the proposal.
++* The author shares the proposal with the community via **_Github issues with 'new feature request' label_**
++* The community provides feedback which can be used by the author to modify their proposal and share it with the community again.
++* The above steps are repeated until the community reaches a consensus according to the [Community Guidelines](Community-Guidelines.md).
++* After a consensus is reached, the author proceeds with the implementation and testing of the feature.
++* After the author is confident their code is ready for integration:
++ - The author generates a patch and signs off on their code.
++ - The author submits a patch according to the [Patch Submission Process](Patch-Submission-Process.md).
++* The Maintainers and Reviewers watch the pull request for the patch, test the code, and accept or reject the patch accordingly.
++* After the code passes code review, the Maintainers and Reviewers accept the code(integrated into the master branch), which completes the development process.
++* After a patch has been accepted, it remains the authoring developer's responsibility to maintain the code throughout its lifecycle, and to provide security and feature updates as needed.
++
++### Approval Path for PR(Pull Request)
++1. Developer should create/update PR to a given issue or enhancement
++2. If Developer works in a team, then peer-review by a colleague developer should be performed
++3. If peer-review was OK, then Developer should summon the component's maintainer
++4. Maintainer should check the code:
++ - make precommit testing is OK (performed automatically)
++ - No minor issues (unified implementation style, comments, etc.)
++ - No major issues (memory leak, crashes, breakage of ECMA logic, etc.)
++5. If Developer has to rework the solution then goto step 3
++6. If everything is OK, then Maintainer should approve the PR with +1(or LGTM)
++ - Code review can be performed by all the members of the project. However only Maintainer can give binding scores.
++7. When the PR get +2(2 LGTM from 2 mainatiners respectively), it should be merged.
++
++### Tips on GitHub Issues
++
++* Check existing [IoT.js issues](https://github.com/Samsung/iotjs/issues) for the answer to your issue.
++Duplicating an issue slows you and others. Search through open and closed issues to see if the problem you are running into has already been addressed.
++* If necessary, [open a new issue](https://github.com/Samsung/iotjs/issues/new).
++ - Clearly describe the issue.
++ + What did you expect to happen?
++ + What actually happened instead?
++ + How can someone else recreate the problem?
++ - Include system details(such as the hardware, library, and operating system you are using and their versions).
++ - Paste error output and logs in the issue or in a Gist(https://gist.github.com/).
++
++For more information about GitHub issues, refer to the [GitHub issues guidelines](https://guides.github.com/features/issues/).
--- /dev/null
--- /dev/null
++# Enabling Experimental Features
++
++This document provides a guide on how to write and build experimental features.
++
++## What's experimental build?
++
++Experimental build is an executable IoT.js including features that are not yet ready for wide use, so they are protected by an experimental status. Developers can opt in to enabling these features when building IoT.js, but they should be used with caution. Because the changes in experimental build can include not only a brand new module but also the existing modules stably used. So developers and users may face unexpected side effects. You should be aware that all the features handled in experimental build may change, be broken, or be removed in the future.
++
++## How to make IoT.js experimental build
++
++You need to make IoT.js using our build script, ["build.py"](https://github.com/Samsung/iotjs/blob/master/tools/build.py), with `--experimental` or `-e` option.
++
++ ```bash
++ tools/build.py --experimental
++
++ tools/build.py -e --iotjs-include-module experimental-module
++
++ tools/build.py -e --config=build.experimental.config
++ ```
++
++ For selecting modules to be included, you need to notify the script where your modules exist. You can use `--iotjs-include-module` or `--config` option for that. For further information, please refer to [Writing Builtin JavaScript Module](https://github.com/Samsung/iotjs/blob/master/docs/devs/Writing-New-Builtin-Module.md#writing-builtin-javascript-module).
++
++## Writing Code
++
++### Identifier for C Code
++
++Once you make IoT.js with `--experimental` option, a symbolic constant named `EXPERIMENTAL` is predefined in compile stage. You can use the identifier to seperate your experimental code from others as follows.
++
++```c
++#ifdef EXPERIMENTAL
++ // experimental
++#else
++ // normal
++#endif
++
++#ifndef EXPERIMENTAL
++ // normal
++#else
++ // experimental
++#endif
++```
++
++### Identifier for JavaScript Code
++
++In the case of javascript code, you can refer to `process.env.IOTJS_ENV` to check if running IoT.js is built with experimental features.
++
++```javascript
++if (process.env.IOTJS_ENV === 'experimental') {
++ // experimental
++} else {
++ // normal
++}
++```
++
++## Documentation
++
++When documenting a guide or an API reference about your experimental module, it's required to explicitly indicate that the features are experimental. Please put the same caution below in every single document.
++
++> :exclamation: This document describes an experimental feature and considerations. Please be aware that every experimental feature may change, be broken, or be removed in the future without any notice.
--- /dev/null
--- /dev/null
++Basically, our basic APIs are based on node.js. They will follow same form with node.js because of compatibility.<br>
++However, extended APIs need a guideline because they are implemented by many contributor. (for consistent usability)
++
++
++# Ground Rules
++
++## API naming rules
++1. The APIs which have similar role should have same API name.
++2. Basically, all APIs are async API. If you want to make sync API, you need to add `Sync` as a suffix.<br>For example, `readSync()`, `writeSync()`, and so on.
++
++## Generating an object
++1. The module object should be generated using `open()` API for consistent usability. (Do not use `New` constructor)
++2. `open()` API should have configuable as first argument and callback function as second argument.<br>callback function is always optional.
++
++For example, GPIO module generate an object like below:
++```javascript
++var gpio = require('gpio');
++
++var gpio10 = gpio.open({pin: 10, direction: gpio.DIRECTION.OUT},
++ function(err){console.log(err);});
++```
++
++## Minimize event generation
++1. The response of the API call uses callback function.
++2. Only generate event when user need to know something without any API call.
++3. The event which have similar role should have same event name.
++
++## Error generation
++1. `error` can be generated in both JS/native side.
++2. The `error` shoud be created in the place where it occurs.
++
++For example, error can be generated like below:
++
++In native side,
++```c
++iotjs_jargs_t jargs = iotjs_jargs_create(2);
++
++// kGpioErrRead: int
++if (result == kGpioErrRead) {
++ iotjs_jargs_append_error_with_code(&jargs, "GPIO Error", kGpioErrRead);
++}
++```
++
++In JavaScript side,
++```javascript
++if (!util.isNumber(value)) {
++ throw new TypeError('Bad arguments');
++}
++```
++
++## Type checking
++1. Type checking of API argument is possible both in JS and Native.
++2. To prevent type checking multiple times, perform type checking on the first function that receives the variable.
++3. Throw `error` when type checking is failed.
++
++
++# Recommended Rules
++1. Call `close()` api when process module occur `exit` event.
++2. If it is possible, use the functions provided by `libtuv` (File open, read, write, etc.)
++3. Callback function in API argument should be always optional.
--- /dev/null
-Validated Struct
-================
-
+ Validated struct is C struct wrapper for encapsulation and validity check.
+
+ * Validated Struct Declaration
+ * Constructors, Destructor, Methods
+ * Ownership of validated struct instance
+ * Case 1: Validated struct instance as local variable
+ * Case 2: Validated struct instance as parameter & return
+ * Case 3: Validated struct instance as member variable of other struct
+ * Case 4: Validated struct instance as data of asynchronous execution
+
+ # Validated Struct Declaration
+
+ ```c
+ typedef struct {
+ int a;
+ void* b;
+ } IOTJS_VALIDATED_STRUCT(iotjs_myclass_t);
+ ```
+
+ Above struct will make the member variable encapsulated by wrapping real members with wrapper like below.
+
+ ```c
+ typedef struct {
+ int a;
+ void* b;
+ } iotjs_myclass_t_impl_t;
+
+ typedef struct {
+ iotjs_myclass_impl_t unsafe;
+ /* More members for struct validity check exist in debug mode */
+ } iotjs_myclass_t;
+
+ int main() {
+ iotjs_myclass_t x;
+ }
+ ```
+
+ Only wizards will access the members directly by using `x.unsafe.a`, `x.unafe.b`, ... . Otherwize the members are only accessible with its accessor function.
+
+ See `src/iotjs_def.h` for more details on real implementation.
+
+ # Constructors, Destructor, Methods
+
+ You should create C++-like constructors, destructor and methods with provided accessor. Then you can access the encapsulated member variables using `_this` variable, which has almost same role with C++ `this` keyword.
+ You must call `destroy` for every validated structs you've created.
+
+ ```c
+ /* Constructor */
+ iotjs_myclass_t iotjs_myclass_create(int a) {
+ iotjs_myclass_t instance;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_myclass_t, &instance);
+
+ _this->a = a;
+ _this->b = malloc(a);
+
+ return instance;
+ }
+
+ /* Destructor */
+ void iotjs_myclass_destroy(iotjs_myclass_t* instance) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_myclass_t, instance);
+ free(_this->b);
+ }
+
+ /* Method */
+ int iotjs_myclass_get_a(iotjs_myclass_t* instance) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_myclass_t, instance);
+ return _this->a;
+ }
+
+ int main() {
+ /* Validated struct as local variable */
+ iotjs_myclass_t local_instance = iotjs_myclass_create(3);
+ printf("%d\n", iotjs_myclass_get_a(&local_instance));
+ iotjs_myclass_destroy(&local_instance);
+ return 0;
+ }
+ ```
+
+ # Ownership of validated struct instance
+
+ The ground rule is:
+
+ * Use `iotjs_classname_t` typed variable if the variable *is* responsible for destruction of instance.
+ * Use `iotjs_classname_t*` typed variable if the variable *is not* responsible for destruction of instance.
+
+ Below Case 1 ~ Case 4 shows the case-by-case example of the ownership rule.
+
+ ## Case 1: Validated struct instance as local variable
+ The `local_instance` variable in previous example was the local instance of validated struct.
+ Since `local_instance` should be destructed inside the function scope, `iotjs_myclass_t` type was used.
+
+ ## Case 2: Validated struct instance as parameter & return
+ Previous example also included the example of validated struct instance as parameter and return.
+ When accessing member variable `a` by calling `iotjs_myclass_get_a()`,
+ `iotjs_myclass_t*` type was used as the parameter type, since it *does not* move the responsibility to destruct the instance.
+
+ And when returning the newly created instance by calling `iotjs_myclass_create()`,
+ `iotjs_myclass_t` type was used as return type, since it *does* move the responsibility to destruct the instance.
+
+ ## Case 3: Validated struct instance as member variable of other struct
+
+ ```c
+ /* Validated struct as member variable of other struct */
+
+ typedef struct {
+ iotjs_myclass_t member_instance;
+ } IOTJS_VALIDATED_STRUCT(iotjs_otherclass_t)
+
+ iotjs_otherclass_t iotjs_otherclass_create() {
+ /* Initialization steps for iotjs_otherclass_t */
+ _this->member_instance = iotjs_myclass_create(3);
+ }
+
+ void iotjs_otherclass_destroy() {
+ /* Finalization steps for iotjs_otherclass_t */
+ iotjs_myclass_destroy(&_this->member_instance);
+ }
+ ```
+
+ In the case above, `iotjs_myclass_t` instance is used as member variable of other class.
+ Since `iotjs_otherclass_t` is responsible for finalizing the `member_instance`,
+ it owns the variable as `iotjs_myclass_t` type, not pointer type.
+
+ ## Case 4: Validated struct instance as data of asynchronous execution
+ Another usecase would be using validated struct as callback data.
+ Currently, our all asynchronous datas are wrapped with `iotjs_*wrap_t` type,
+ and they are destructed automatically.
+
+ ```c
+ /*
+ * Public APIs in iotjs_module_fs.h
+ */
+
+ typedef struct {
+ iotjs_reqwrap_t reqwrap;
+ uv_fs_t req;
+ } IOTJS_VALIDATED_STRUCT(iotjs_fsreqwrap_t);
+
+ iotjs_fsreqwrap_t* iotjs_fsreqwrap_create(const iotjs_jval_t* jcallback);
+ void iotjs_fsreqwrap_dispatched(iotjs_fsreqwrap_t* fsreqwrap);
+ ```
+
+ As you can see, constructor returns the `iotjs_fsreqwrap_t*` type,
+ because it does not pass the responsibility to destruct the return value.
+ It is destructed when request is dispatched, which can be informed by calling `iotjs_fsreqwrap_dispatched()`.
+ The destructor `iotjs_fsreqwrap_destroy()` is hidden in c file.
+
+ ```c
+ /*
+ * Implementation in iotjs_module_fs.c
+ */
+
+ iotjs_fsreqwrap_t* iotjs_fsreqwrap_create(const iotjs_jval_t* jcallback) {
+ iotjs_fsreqwrap_t* fsreqwrap = IOTJS_ALLOC(iotjs_fsreqwrap_t);
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_fsreqwrap_t, fsreqwrap);
+ iotjs_reqwrap_initialize(&_this->reqwrap, jcallback, (uv_req_t*)&_this->req);
+ return fsreqwrap;
+ }
+
+ static void iotjs_fsreqwrap_destroy(iotjs_fsreqwrap_t* fsreqwrap) { // private function
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_fsreqwrap_t, fsreqwrap);
+ uv_fs_req_cleanup(&_this->req);
+ iotjs_reqwrap_destroy(&_this->reqwrap);
+ IOTJS_RELEASE(fsreqwrap);
+ }
+
+ void iotjs_fsreqwrap_dispatched(iotjs_fsreqwrap_t* fsreqwrap) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_fsreqwrap_t, fsreqwrap);
+ iotjs_fsreqwrap_destroy(fsreqwrap);
+ }
+
+ /*
+ * Use of iotjs_fsreqwrap_t
+ */
+
+ void callback(uv_fs_t* req) {
+ do_something(req);
+ iotjs_fsreqwrap_dispatched(req); /* Call iotjs_*reqwrap_dispatched() when callback called */
+ }
+
+ void request(iotjs_jval_t* jcallback) {
+ iotjs_fsreqwrap_t* wrap = iotjs_fsreqwrap_create(jcallback);
+ uv_fs_request(loop, wrap->req, callback);
+ }
+ ```
+
+ In the case of tuv request wrapper, `iotjs_*reqwrap_dispatched()` should be called when the request has been dispatched.
+ In the case of tuv handle wrapper, `iotjs_handlewrap_close()` should be called when the handle has been closed.
+ in the case of JavaScript object wrapper, you don't have to do anything because JavaScript engine will call the destructor when the object becomes inaccessible.
+
+
--- /dev/null
--- /dev/null
++The IoT.js project uses the signed-off-by language and process, to give us a clear chain of trust for every patch received.
++
++> By making a contribution to this project, I certify that:
++
++> (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
++
++> (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
++
++> (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it.
++
++> (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project, under the same open source license.
++
++
++### Using the Signed-Off-By Process
++
++We have the same requirements for using the signed-off-by process as the Linux kernel. In short, you need to include a signed-off-by tag in every patch:
++
++"Signed-off-by:" this is a developer's certification that he or she has the right to submit the patch for inclusion into the project. It is an agreement to the Developer's Certificate of Origin (above). **Code without a proper signoff cannot be merged into the mainline.**
++
++You should use your real name and email address in the format below:
++
++> IoT.js-DCO-1.0-Signed-off-by: Random J Developer random@developer.example.org
++
++
++#### How to add DCO every single commit automatically.
++
++It is easy to forget adding DCO end of every commit message. Fortunately there is a nice way to do it automatically. Once you've clone the repository into your local machine, you can add `prepare commit message hook` in `.git/hooks` directory like this:
++
++```
++#!/usr/bin/env python
++
++import sys
++
++commit_msg_filepath = sys.argv[1]
++
++with open(commit_msg_filepath, "r+") as f:
++ content = f.read()
++ f.seek(0, 0)
++ f.write("%s\n\nIoT.js-DCO-1.0-Signed-off-by: <Your Name> <Your Email>" % content)
++```
++
++Please refer [Git Hooks](http://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) for more information.
--- /dev/null
--- /dev/null
++# Native Module vs JS Module
++
++This document provides a basic guide on when to write a builtin module in Javascript instead of C.
++
++## What are Native module and Javascipt module?
++
++Native module is mainly aimed to get a direct access to low-level API of the operation system and is written in C code. While, Javascript module mainly exists as a bridge between native module and users. And, in some situations, it also includes handy functions and handles errors for API coverage.
++
++## When to write JS module
++
++In many cases, a well-written native code could prove better performance than the JavaScript equivalent. So, a feature, where computational performance is important, is recommended to be written in native module. However, that doesn't mean that every module needs be written in C only. Because there are many cases where the regular Javascript code is useful. Here are a few ground rules as a guide on when to write Javascript module.
++
++1. Support Node.js API usages
++
++ One of IoT.js purposes is to support users who get used to Node.JS api as much as possible. So the builtin basic APIs should be implemented based on this purpose. A module in Node.Js generally consists a pair of native module and Javascript module. Even though there might be some optimization points on them, leave the pairs to facilitate future maintainance.
++
++2. Use Javascript module in the case where we can implement a feature more efficiently.
++
++ The `efficiently` implies effciency in terms of performance, memory, implementation time, and so on. If a certain feature could be easily and rapidly implemented in Javascript but no big difference on performance or memory compared with native module, write it in javascript module. The following includes such a case but not limited to: Type conversion, basic mathematical operations, simple functionality and so on.
++
++3. Avoid 'Reinventing the wheel'
++
++ In case that a well-peformed feature already exists in builtin modules, it's basically not allowed to wipe it out to native module since it's unnecessary.
++
++## Argument Validation & Type Conversion
++
++For avoiding security issue, argument validation must be handled in native module. However, native module should not take a role to convert the given type for extending API coverage. It should be done in Javascript module.
++
++ e.g) In case of `new Buffer(str[, encoding])`, native module has a responsiblity to validate if the type of the first argument is `string`. However, in user perspective, giving `Number` as the first argument also works since Javascript module appropriately handles the given type to pass it over to the corresponding native module.
--- /dev/null
-Optimization Tips
-=================
-
+ ## Tracing JerryScript heap usage
+
+ Adding below arguments when building and running IoT.js will show you the JerryScript memory status.
+
+ ```text
+ $ ./tools/build.py --jerry-memstat
+ $ ./build/bin/iotjs --memstat test.js
+ Heap stats:
+ Heap size = 262136 bytes
+ Allocated = 0 bytes
+ Waste = 0 bytes
+ Peak allocated = 24288 bytes
+ Peak waste = 261 bytes
+ Skip-ahead ratio = 2.6059
+ Average alloc iteration = 1.1284
+ Average free iteration = 19.3718
+
+ Pools stats:
+ Pool chunks: 0
+ Peak pool chunks: 735
+ Free chunks: 0
+ Pool reuse ratio: 0.3459
+ ```
+
+ Note that currently only JerryScript heap usage can be shown with memstat option, not IoT.js memory usage. You can use system profiler to trace IoT.js memory usage.
+
+ ## JerryScript 'external magic string' feature
+
+ When parsing and executing JavaScript module, JavaScript strings occupy a huge amount of space in JerryScript heap. To optimize this kind of heap usage, JerryScript has 'external magic string' feature. If you enable snapshot when building, build script will automatically generate `src/iotjs_string_ext.inl.h` file, which includes all of the JavaScript strings used in builtin modules. This file is used by JerryScript to reduce heap usage.
+
+ Since same strings will be included only once, you can use this information to get some hints on binary size reduction. Note that only strings with length<32 will be included in this list.
+
+ ## Placement of JerryScript heap (with an example of STM32F4 CCM Memory)
+
+ IoT.js uses two kind of heaps: System heap for normal usage, and separated JerryScript heap for javascript. JerryScript heap is implemented as c array with fixed length decided in static time. Its size can be ~512K.
+
+ For some devices, placing this kind of large memory block can be important issue. For example, STM32F4 chips have *Core Coupled Memory* (a.k.a. *ccm* memory), which is usually used as heap or stack. However, since compiler do not have any special knowledge about JerryScript heap, it can be treated as simple array.
+
+ You can make your compiler to place the JerryScript heap in specific section by using `--jerry-heap-section` argument when building IoT.js. Your argument will be used with below code in `deps/jerry/jerry-core/jcontext/jcontext.c`
+
+ ```c
+ #define JERRY_GLOBAL_HEAP_SECTION __attribute__ ((section (JERRY_HEAP_SECTION_ATTR)))
+
+ jmem_heap_t jerry_global_heap __attribute__ ((aligned (JMEM_ALIGNMENT))) JERRY_GLOBAL_HEAP_SECTION;
+ ```
--- /dev/null
--- /dev/null
++### To write a test case
++
++Depend on the purpose of the test case (whether it's a positive or negative one), place it under `test/run_pass` or `test/run_fail` directory. The required external resources should be placed into `test/resources`.
++
++All test case files must be named in the following form `test_<module name>[_<functionallity].js` where `<module name>`
++should match one of the JS modules name in the IoT.js. If there is a test case which can not tied to a
++module (like some js features) then the `iotjs` name can be used as module name. It is important to
++correctly specify the module name as the test executor relies on that information.
++
++1. Write a test case and place it into the proper directory.
++2. List up the test case in [test/testsets.json](https://github.com/Samsung/iotjs/blob/master/test/testsets.json), and set attributes (timeout, skip, ...) on the test case if it needs.
++
++
++### How to Test
++
++When you build ``iotjs`` binary successfully, you can run test driver with this binary.
++
++```bash
++/path/to/iotjs tools/check_test.js
++```
++
++#### Set test options
++
++Some basic options are provided.
++
++Existing test options are listed as follows;
++```
++start-from
++quiet=yes|no (default is yes)
++output-file
++skip-module
++output-coverage=yes|no (default is no)
++experimental=yes|no (default is no)
++```
++
++To give options, please use two dashes '--' **once** before the option name as described in the following sections.
++
++Options that may need explanations.
++* start-from: a test case file name where the driver starts.
++* quiet: a flag that indicates if the driver suppresses console outputs of test case.
++* output-file: a file name where the driver leaves output.
++* skip-module: a module list to skip test of specific modules.
++* output-coverage: a flag that indicates wether coverage data should be written to disk
++* experimental: a flag that indicates if tests for experimental are needed
++
++#### Options example
++
++```bash
++build/x86_64-linux/debug/bin/iotjs tools/check_test.js -- start-from=test_console.js quiet=no
++```
--- /dev/null
-Writing New Builtin Module
-==========================
+
+ This document provides a guide on how to write a builtin module for IoT.js.
+
+ Contents:
+
+ * Writing Builtin JavaScript Module
+ * Writing Native Module Builtin
+ - Using native module in JavaScript module
+ - Registering native module
+ - Native handler
+ * Arguments and Return
+ * Wrapping native object with JS object
+ * Callback
+
+ You can see more information on the [Optimization Tips](Optimization-Tips.md) page.
+
+ It will be easier to write a new IoT.js module if you have background on:
+
+ - [Node.js module](https://nodejs.org/api/modules.html) (for writing IoT.js JavaScript module)
+ - [Node.js native addon](https://nodejs.org/api/addons.html) (for writing IoT.js native module builtin)
+
+ ## Writing Builtin JavaScript Module
+
+ Builtin JavaScript module can be written in the same way as writing [Node.js module](https://nodejs.org/api/modules.html). JavaScript file should be located in `src/js/` directory, and you should notify to our build script that your module should be included in one of following ways:
+
+ * Use `./tools/build.py --iotjs-include-module mymodule` when building
+ * Add your module in `build.config` file
+
+ Your new module will look like below:
+
+ src/js/mymodule.js:
+ ```javascript
+ module.exports = {
+ foo: function() { console.log("OK"); },
+ bar: 123
+ }
+ ```
+
+ user.js:
+ ```javascript
+ var mymodule = require('mymodule');
+ mymodule.foo(); // prints "OK"
+ console.log(mymodule.bar); // prints "123"
+ ```
+
+ and execute:
+ ```sh
+ $ ./tools/build.py
+ $ ${PATH_TO}/iotjs user.js
+ OK
+ 123
+ ```
+
+ ## Writing Native Module Builtin
+
+ You can implement some part of the builtin module in C, to enhance performance and to fully exploit the H/W functionality, etc. It has similar concept with [Node.js native addon](https://nodejs.org/api/addons.html), but we have different set of APIs. Node.js uses its own binding layer with v8 API, but we use [our own binding layer](../../src/iotjs_binding.h) which wraps [JerryScript API](https://github.com/jerryscript-project/JerryScript/blob/master/jerry-core/jerryscript.h). You can see `src/iotjs_binding.*` files to find more APIs to communicate with JS-side values from native-side.
+
+ For simple explanation, `console` module will be used as an example.
+
+ ### Using native module in JavaScript module
+
+ Logging to console needs native functionality, so `console` JavaScript module in `src/js/console.js` passes its arguments into native handler like:
+
+ ```javascript
+ var consoleBuiltin = process.binding(process.binding.console);
+ ...
+ Console.prototype.log = consoleBuiltin.stdout(util.format.apply(this, arguments) + '\n');
+ ```
+
+ ### Registering native module
+
+ According to the code above, `process.binding.console` should be defined before evaluating JavaScript code. IoT.js source code can automatically register native module if some functions are implemented as expected. First you should register your new module into `MODULE_LIST` macro in `src/iotjs_module.h`:
+ ```c
+ #define MAP_MODULE_LIST(F) \
+ E(F, BUFFER, Buffer, buffer) \
+ E(F, CONSOLE, Console, console) \
+ E(F, CONSTANTS, Constants, constants) \
+ ...
+ ```
+
+ Then `iotjs_jval_t Init##ModuleName()` function will be called automatically when registering native module. We already have its implementation in `src/module/iotjs_module_console.c`:
+ ```c
+ iotjs_jval_t InitConsole() {
+ iotjs_jval_t console = iotjs_jval_create_object();
+
+ iotjs_jval_set_method(&console, "stdout", Stdout);
+ iotjs_jval_set_method(&console, "stderr", Stderr);
+
+ return console;
+ }
+ ```
+ The return value of initializer function (in this case, `iotjs_jval_t console`,) will be passed to JS-side, as a return value of calling `process.binding(process.binding.modulename)`. Calling `iotjs_jval_create_object()` will create a JavaScript object in c code.
+
+ And you might want to define some functions and properties to the newly created object. `iotjs_jval_set_method()` will register a native handler as a JavaScript function property. (That's how we was able to call `consoleBuiltin.stdout()` in JavaScript.) And `iotjs_jval_set_property_*()` will define a non-function property into object. You can find the example of registering a constant value as a JavaScript property in `src/module/iotjs_module_constants.c`.
+
+ ### Native handler
+
+ Native handler reads arguments from JavaScript, executes native operations, and returns the final value to JavaScript.
+
+ #### Arguments and Return
+
+ Let's see an example in `src/module/iotjs_module_console.c`:
+
+ ```c
+ JHANDLER_FUNCTION(Stdout) {
+ JHANDLER_CHECK_ARGS(1, string);
+
+ iotjs_string_t msg = JHANDLER_GET_ARG(0, string);
+ fprintf(stdout, "%s", iotjs_string_data(&msg));
+ iotjs_string_destroy(&msg);
+ }
+ ```
+
+ Using `JHANDLER_GET_ARG(index, type)` macro inside `JHANDLER_FUNCTION()` will read JS-side argument. Since JavaScript values can have dynamic types, you must check if argument has valid type with `JHANDLER_CHECK_ARGS(number_of_arguments, type1, type2, type3, ...)` macro, which throws JavaScript TypeError when given condition is not satisfied.
+
+ Calling `void iotjs_jhandler_return_*()` function inside `JHANDLER_FUNCTION()` will return value into JS-side. `undefined` will be returned if you didn't explicitly returned something, like normal JavaScript function does. Console methods doesn't have to return values, but you can easily find more examples from other modules.
+
+ #### Wrapping native object with JS object
+
+ `console` module is *state-free* module, i.e., console module implementation doesn't have to hold any values with it. It just passes value and that's all it does.
+
+ However, there are many cases that module should maintain its state. Maintaining the state in JS-side would be simple. But maintaining values in native-side is not an easy problem, because native-side values should follow the lifecycle of JS-side values. Let's take `Buffer` module as an example. `Buffer` should maintain the native buffer content and its length. And the native buffer content should be deallocated when JS-side buffer variable becomes unreachable.
+
+ There's `iotjs_jobjectwrap_t` struct for that purpose. if you create a new `iotjs_jobjectwrap_t` struct with JavaScript object as its argument and free handler, the registered free handler will be automatically called when its corresponding JavaScript object becomes unreachable. `Buffer` module also exploits this feature.
+
+ ```c
+ // This wrapper refer javascript object but never increase reference count
+ // If the object is freed by GC, then this wrapper instance will be also freed.
+ typedef struct {
+ iotjs_jval_t jobject;
+ } iotjs_jobjectwrap_t;
+
+ typedef struct {
+ iotjs_jobjectwrap_t jobjectwrap;
+ char* buffer;
+ size_t length;
+ } iotjs_bufferwrap_t;
+
+ static void iotjs_bufferwrap_destroy(iotjs_bufferwrap_t* bufferwrap);
+ IOTJS_DEFINE_NATIVE_HANDLE_INFO(bufferwrap);
+
+ iotjs_bufferwrap_t* iotjs_bufferwrap_create(const iotjs_jval_t* jbuiltin,
+ size_t length) {
+ iotjs_bufferwrap_t* bufferwrap = IOTJS_ALLOC(iotjs_bufferwrap_t);
+ iotjs_jobjectwrap_initialize(&_this->jobjectwrap,
+ jbuiltin,
+ &bufferwrap_native_info); /* Automatically called */
+ ...
+ }
+
+ void iotjs_bufferwrap_destroy(iotjs_bufferwrap_t* bufferwrap) {
+ ...
+ iotjs_jobjectwrap_destroy(&_this->jobjectwrap);
+ IOTJS_RELEASE(bufferwrap);
+ }
+ ```
+
+ You can use this code like below:
+
+ ```c
+ const iotjs_jval_t* jbuiltin = /*...*/;
+ iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_create(jbuiltin, length);
+ // Now `jbuiltin` object can be used in JS-side,
+ // and when it becomes unreachable, `iotjs_bufferwrap_destroy` will be called.
+ ```
+
+ #### Callback
+
+ Sometimes native handler should call JavaScript function directly. For general function calls (inside current tick), you can use `iotjs_jhelper_call()` function to call JavaScript function from native-side.
+
+ And for asynchronous callbacks, after `libtuv` calls your native function, if you want to call JS-side callback you should use `iotjs_make_callback()`. It will not only call the callback function, but also handle the exception, and process the next tick(i.e. it will call `iotjs_process_next_tick()`).
+
+ For asynchronous callbacks, you must consider the lifetime of JS-side callback objects. The lifetime of JS-side callback object should be extended until the native-side callback is really called. You can use `iotjs_reqwrap_t` and `iotjs_handlewrap_t` to achieve this.
+
+ (Work In Progress)
--- /dev/null
+ ## Pin
+ In order to use system IO, such as GPIO, PWM and ADC you need to know the pin name.
+ The `stm32f4dis` module has pin object which is designed to find a pin name easier.
+
+ **Example**
+
+ ```js
+
+ var pin = require('stm32f4dis').pin;
+
+ ```
+
+ ### GPIO Pin
+ P[port][pin]
+
+ A configured GPIO pin.
+
+ The `port` must be equal to a capital letter from 'A' to 'D'.
+
+ The `pin` must be equal to an integer from 0 to 15.
+
+ **Example**
+
+ ```js
+
+ var gpio = require('gpio');
+ var pin = require('stm32f4dis').pin;
+
+ gpio.open(pin.PD6);
+
+ ```
+
+ ### PWM Pin
+ PWM[timer].CH[channel]_[number]
+
+ A configured PWM pin.
+
+ The `timer` must be equal to an integer from 1 to 14.
+
+ The `channel` must be equal to an integer from 1 to 4, but it also depends on the `timer`.
+
+ The `number` must be equal to an integer form 1 to 2, and 3 in case of PWM3.CH1_3, PWM3.CH2_3 and PWM2.CH1_3.
+
+ **Example**
+
+ ```js
+
+ var pwm = require('pwm');
+ var pin = require('stm32f4dis').pin;
+
+ var pwm2 = new pwm(pin.PWM2.CH1_2);
+
+ ```
+
+ The following table shows the available PWM pin names and their corresponding
+ GPIO pins.
+
+ | PWM Pin Name | GPIO Name | PWM Pin Name | GPIO Name|
+ | :---: | :---: | :---: | :---: |
+ | PWM1.CH1_1 | PA8 | PWM4.CH1_1| PB6 |
+ | PWM1.CH1_2 | PE9 | PWM4.CH1_2| PD12 |
+ | PWM1.CH2_1 | PA9 | PWM4.CH2_1| PB7 |
+ | PWM1.CH2_2 | PE11 | PWM4.CH2_2| PD13 |
+ | PWM1.CH3_1 | PA10 | PWM4.CH3_1| PB8 |
+ | PWM1.CH3_2 | PE13 | PWM4.CH3_2| PD14 |
+ | PWM1.CH4_1 | PA11 | PWM4.CH4_1| PB9 |
+ | PWM1.CH4_2 | PE14 | PWM4.CH4_2| PD15 |
+ | PWM2.CH1_1| PA0 | PWM5.CH1_1| PA0 |
+ | PWM2.CH1_2| PA15 | PWM5.CH2_1| PA1 |
+ | PWM2.CH1_3| PA5 | PWM5.CH3_1| PA2 |
+ | PWM2.CH2_1| PA1 | PWM5.CH4_1| PA3 |
+ | PWM2.CH2_2| PB3 | PWM8.CH1_1| PC6 |
+ | PWM2.CH3_1| PA2| PWM8.CH2_1| PC7|
+ | PWM2.CH3_2| PB10| PWM8.CH3_1| PC8|
+ | PWM2.CH4_1| PA3 | PWM8.CH4_1| PC9 |
+ | PWM2.CH4_2| PB11 | PWM9.CH1_1 | PA2 |
+ | PWM3.CH1_1 | PA6 | PWM9.CH1_2 | PE5 |
+ | PWM3.CH1_2 | PB4 | PWM9.CH2_1 | PA3 |
+ | PWM3.CH1_3 | PC6 | PWM9.CH2_2 | PE6 |
+ | PWM3.CH2_1 | PA7 | PWM10.CH1_1 | PB8 |
+ | PWM3.CH2_2 | PB5 | PWM11.CH1_1 | PB9 |
+ | PWM3.CH2_3 | PC7 | PWM12.CH1_2 | PB14 |
+ | PWM3.CH3_1 | PA11 | PWM12.CH2_1 | PB15 |
+ | PWM3.CH3_2 | PE14 | PWM13.CH1_1 | PA6 |
+ | PWM3.CH4_1 | PB1 | PWM14.CH1_1 | PA7 |
+ | PWM3.CH4_2 | PC9 | | |
+
+ ### ADC Pin
+ ADC[number]_[timer]
+
+ A configured ADC pin.
+
+ The `number` must be equal to an integer from 1 to 3.
+
+ The `timer` must be equal to an integer from 0 to 15.
+
+ **Example**
+
+ ```js
+
+ var adc = require('adc');
+ var pin = require('stm32f4dis').pin;
+
+ var adc1 = new adc(pin.ADC1_3);
+
+ ```
+
+ The following table shows the available ADC pin names and their corresponding
+ GPIO pins.
+
+ | ADC Pin Name | GPIO Name |
+ | :--- | :---: |
+ | ADC1_0, ADC2_0, ADC3_0 | PA0 |
+ | ADC1_1, ADC2_1, ADC3_1 | PA1 |
+ | ADC1_2, ADC2_2, ADC3_2 | PA2 |
+ | ADC1_3, ADC2_3, ADC3_3 | PA3 |
+ | ADC1_4, ADC2_4 | PA4 |
+ | ADC1_5, ADC2_5 | PA5 |
+ | ADC1_6, ADC2_6 | PA6 |
+ | ADC1_7, ADC2_7 | PA7 |
+ | ADC1_8, ADC2_8 | PB0 |
+ | ADC1_9, ADC2_9 | PB1 |
+ | ADC1_10, ADC2_10, ADC3_10 | PC0 |
+ | ADC1_11, ADC2_11, ADC3_11 | PC1 |
+ | ADC1_12, ADC2_12, ADC3_12 | PC2 |
+ | ADC1_13, ADC2_13, ADC3_13 | PC3 |
+ | ADC1_14, ADC2_14 | PC4 |
+ | ADC1_15, ADC2_15 | PC5 |
+
+ ## UART Port Information
+
+ In order to use the UART on stm32f4-discovery board, you must use proper pins.
+
+ The stm32f4-discovery board supports 4 UART ports, such as USART2, USART3, UART5, USART6.
+ The UART5 port and the SDIO uses the same pin for connection. SDIO is enabled by default, so be careful when you enable the UART5 port.
+
+ The following table shows the U[S]ART pin map:
+
+ | U[S]ART Pin Name | GPIO Name |
+ | :--- | :---: |
+ | USART2_RX | PA3 |
+ | USART2_TX | PA2 |
+ | USART3_RX | PB11 |
+ | USART3_TX | PB10 |
+ | UART5_RX | PD2 |
+ | UART5_TX | PC12 |
+ | USART6_RX | PC7 |
+ | USART6_TX | PC6 |
+
+ Note: The name of the UART device cannot find by the `stm32f4dis.pin` module, because it can be changed in the NuttX configuration file. It should be '/dev/ttyS[0-3]'.
+
+ ### Enable USART1 and UART4
+
+ The current version of the NuttX does not support the USART1 and UART4 ports for stm32f4-discovery board.
+
+ The `config/nuttx/stm32f4dis/patch` file contains the implementations of the the USART1 and UART4 ports. It maps the PB6 and PB7 gpio pins to USART1_TX and USART2_RX, PA0 and PA1 gpio pins to UART4_TX and UART4_RX respectively.
+
+ Note: You can add more ports according to the patch file.
+
+ **Apply the patch**
+
+ ```bash
+
+ ~/workspace/nuttx$ patch -p1 < ../iotjs/config/nuttx/stm32f4dis/patch
+
+ ```
+
+ ## I2C Port Information
+
+ In order to use the I2C on stm32f4-discovery board, you must use proper pins.
+ Currently only I2C1 is supported.
+
+ The following table shows the I2C pin map:
++
+ | I2C Pin Name | GPIO Name |
+ | :--- | :---: |
+ | I2C1_SCL | PB8 |
+ | I2C1_SDA | PB7 |
++
++
++## SPI Bus Information
++
++The following table shows currently supported SPI pin number list.
++Currently only SPI1 is supported.
++
++| SPI Pin Name | GPIO Name |
++| :--- | :---: |
++| SPI1_SCK | PA5 |
++| SPI1_MISO | PA6 |
++| SPI1_MOSI | PA7 |
++| SPI1_NSS | PA15 |
--- /dev/null
--- /dev/null
++<html>
++<head>
++ <style>
++ .button {
++ background-color:#599bb3;
++ border-radius:8px;
++ display:inline-block;
++ cursor:pointer;
++ color:#ffffff;
++ font-family:Arial;
++ font-size:20px;
++ font-weight:bold;
++ padding:13px 32px;
++ text-decoration:none;
++ text-shadow:0px 1px 0px #3d768a;
++ }
++ .light {
++ background-color:#000000;
++ border-radius:20px;
++ display:inline-block;
++ cursor:pointer;
++ color:#ffffff;
++ font-family:Arial;
++ font-size:20px;
++ font-weight:bold;
++ padding:13px 32px;
++ text-decoration:none;
++ text-shadow:0px 1px 0px #3d768a;
++ }
++ </style>
++ <script language='javascript'>
++ function toggle() {
++ var xmlhttp = new XMLHttpRequest();
++ xmlhttp.onreadystatechange = function() {
++ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
++ updateLight();
++ }
++ };
++ xmlhttp.open("PUT", "toggle", true);
++ xmlhttp.send();
++ }
++ function updateLight() {
++ var xmlhttp = new XMLHttpRequest();
++ xmlhttp.onreadystatechange = function() {
++ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
++ var state = xmlhttp.responseText;
++ if (state == 'on') {
++ var light = document.getElementById('light');
++ light.innerText = 'on';
++ light.style.backgroundColor = '#EEEE00';
++ } else {
++ var light = document.getElementById('light');
++ light.innerText = 'off';
++ light.style.backgroundColor = '#000000';
++ }
++ }
++ };
++ xmlhttp.open("GET", "light", true);
++ xmlhttp.send();
++ }
++ </script>
++</head>
++<body>
++ <div>
++ <a href='javascript:toggle();' class='button'>toggle</a>
++ <div class='light' id='light'>off</div>
++ </div>
++ <script language='javascript'>
++ updateLight();
++ </script>
++</body>
++</html>
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 fs = require('fs');
++var http = require('http');
++var gpio = require('gpio');
++
++var port = 8080;
++var result = '';
++
++var ledPin = 16;
++
++var server = http.createServer(function(req, res) {
++ console.log('on request - url: ' + req.url);
++ if (req.url == '/') {
++ onIndex(req, res);
++ } else if (req.url == '/light') {
++ onLight(req, res);
++ } else if (req.url == '/toggle') {
++ onToggle(req, res);
++ }
++});
++
++
++function onIndex(req, res) {
++ fs.readFile('index.html', function(err, data) {
++ if (err) {
++ res.writeHead(500);
++ res.end();
++ } else {
++ res.writeHead(200);
++ res.end(data);
++ }
++ });
++}
++
++function onLight(req, res) {
++ gpio.readPin(ledPin, function(err, value) {
++ if (err) {
++ res.writeHead(500);
++ res.end();
++ } else {
++ res.writeHead(200);
++ res.end(value ? "on" : "off");
++ }
++ });
++}
++
++function onToggle(req, res) {
++ gpio.readPin(ledPin, function(err, value) {
++ if (err) {
++ res.writeHead(500);
++ res.end();
++ } else {
++ gpio.writePin(ledPin, !value, function(err) {
++ if (err) {
++ res.writeHead(500);
++ res.end();
++ } else {
++ res.writeHead(200);
++ res.end(value ? "on" : "off");
++ }
++ });
++ }
++ });
++}
++
++gpio.initialize();
++
++gpio.on('initialize', function() {
++ console.log('GPIO initilized');
++ gpio.setPin(ledPin, "out", function() {
++ console.log('GPIO led ready');
++ server.listen(port);
++ });
++});
++
++gpio.on('error', function(err) {
++ console.log(err);
++ process.exit(1);
++});
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++var options = {
++ hostname: '127.0.0.1',
++ port: 8080,
++ path: '/'
++};
++
++http.request(options, function (res) {
++ receive(res, function (data) {
++ console.log(data);
++ });
++}).end();
++
++function receive(incoming, callback) {
++ var data = '';
++
++ incoming.on('data', function (chunk) {
++ data += chunk;
++ });
++
++ incoming.on('end', function () {
++ callback ? callback(data) : '';
++ });
++}
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++
++var message = JSON.stringify({
++ greeting: 'Hello, IoT.JS!',
++ answer: '',
++});
++
++var options = {
++ hostname: '127.0.0.1',
++ port: 8080,
++ path: '/',
++ method: 'POST',
++ headers: {
++ 'Content-Length': message.length
++ }
++};
++
++http.request(options, function (res) {
++ receive(res, function (data) {
++ var obj = JSON.parse(data);
++ console.log(obj.answer);
++ });
++}).end(message);
++
++function receive(incoming, callback) {
++ var data = '';
++
++ incoming.on('data', function (chunk) {
++ data += chunk;
++ });
++
++ incoming.on('end', function () {
++ callback ? callback(data) : '';
++ });
++}
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++var port = 8080;
++
++http.createServer(function (req, res) {
++ if (req.method == 'GET') {
++ status(res, 'Hello, IoT.JS!');
++
++ } else if (req.method == 'POST') {
++ receive(req, function (data) {
++ var obj = JSON.parse(data);
++ obj.answer = 'Hello, There!'
++ status(res, obj);
++ });
++ }
++}).listen(port);
++
++function receive(incoming, callback) {
++ var data = '';
++
++ incoming.on('data', function (chunk) {
++ data += chunk;
++ });
++
++ incoming.on('end', function () {
++ callback ? callback(data) : '';
++ });
++}
++
++function status(res, data) {
++ var isJson = (typeof data === 'object');
++
++ if (isJson) {
++ data = JSON.stringify(data);
++ }
++
++ var headers = {
++ 'Access-Control-Allow-Origin': '*',
++ 'Access-Control-Allow-Headers':
++ 'Origin, X-Requested-With, Content-Type, Accept',
++ 'Content-Type': isJson ? 'application/json' : 'text/plain',
++ };
++
++ res.writeHead(200, headers);
++ res.end(data);
++};
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++
++var port = 7468;
++
++var msg = '';
++var socket = new net.Socket();
++
++var address = process.argv[2] ? process.argv[2] : "127.0.0.1";
++
++socket.connect(port, address);
++
++socket.on('data', function(data) {
++ msg += data;
++});
++
++socket.on('end', function() {
++ console.log(msg);
++ socket.end();
++});
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++
++var port = 7468;
++var server = net.createServer();
++
++server.listen(port, 5);
++
++server.on('connection', function(socket) {
++ socket.end('Hello IoT.js');
++});
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// for Raspberry Pi B and 2
++var GPIO_MAP = {
++ CTRL: {
++ // follows RPi2 GPIO control
++ ENABLE: 0x00020000,
++ DISABLE: 0x00000000,
++ OUT: 0x00010000,
++ IN: 0x00000000,
++ FLOAT: 0x00000000
++ },
++ PINS: {
++ LED1: { PIN: 11 },
++ LED2: { PIN: 12 },
++ LED3: { PIN: 13 },
++ LED4: { PIN: 15 },
++
++ LED5: { PIN: 16 },
++ BTN1: { PIN: 18 }
++ }
++};
++
++module.exports = GPIO_MAP;
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// for NuttX on STM32F4-discovery BB
++var GMS = 18; // mode shift
++var G_M_MASK = (3 << GMS);
++var G_INPUT = (0 << GMS);
++var G_OUTPUT = (1 << GMS);
++
++var GPS = (16); // pull up/dn shift
++var G_P_MASK = (3 << GPS);
++var G_FLOAT = (0 << GPS);
++var G_PULLUP = (1 << GPS);
++var G_PULLDOWN= (2 << GPS);
++
++var GTS = (4); // port shift
++var G_T_MASK= (7 << GTS);
++var G_PORTA = (0 << GTS);
++var G_PORTB = (1 << GTS);
++var G_PORTC = (2 << GTS);
++var G_PORTD = (3 << GTS);
++
++var GIS = (0);
++var G_I_MASK=(15 << GIS);
++var G_PIN0 = (0 << GIS);
++var G_PIN1 = (1 << GIS);
++var G_PIN2 = (2 << GIS);
++var G_PIN3 = (3 << GIS);
++var G_PIN4 = (4 << GIS);
++var G_PIN5 = (5 << GIS);
++var G_PIN6 = (6 << GIS);
++var G_PIN7 = (7 << GIS);
++var G_PIN8 = (8 << GIS);
++var G_PIN9 = (9 << GIS);
++var G_PIN10 =(10 << GIS);
++var G_PIN11 =(11 << GIS);
++var G_PIN12 =(12 << GIS);
++var G_PIN13 =(13 << GIS);
++var G_PIN14 =(14 << GIS);
++var G_PIN15 =(15 << GIS);
++
++var GPIO_MAP = {
++ CTRL: {
++ ENABLE : 0,
++ DISABLE : 0,
++ OUT: G_OUTPUT | G_PULLUP,
++ IN: G_INPUT | G_PULLDOWN,
++ FLOAT: G_OUTPUT | G_FLOAT
++ },
++ PINS: {
++ LED1: { PIN: G_PIN8 | G_PORTA },
++ LED2: { PIN: G_PIN10 | G_PORTA },
++ LED3: { PIN: G_PIN15 | G_PORTA },
++ LED4: { PIN: G_PIN11 | G_PORTD },
++
++ LED5: { PIN: G_PIN3 | G_PORTA },
++ BTN1: { PIN: G_PIN0 | G_PORTA }
++ }
++};
++
++module.exports = GPIO_MAP;
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// for linux on x86
++var GPIO_MAP = {
++ CTRL: {
++ // not used, maybe set to usb gpio later
++ ENABLE: 0x1000,
++ DISABLE: 0x2000,
++ IN: 0x0000,
++ OUT: 0x0100,
++ FLOAT: 0x0200,
++ },
++ PINS: {
++ LED1: { PIN: 1 },
++ LED2: { PIN: 2 },
++ LED3: { PIN: 3 },
++ LED4: { PIN: 4 },
++
++ LED5: { PIN: 11 },
++ BTN1: { PIN: 12 },
++ },
++};
++
++module.exports = GPIO_MAP;
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// reads GPIO configuration file for iot.js or node.js
++// provides simple method for pin open/close/map
++
++var cfgfile = "gpio-" + process.arch + "-" + process.platform + ".js";
++var gpiomap = require(cfgfile);
++
++function GpioCfg() {
++
++}
++
++
++GpioCfg.map = function(portname) {
++ return gpiomap.PINS[portname].PIN;
++}
++
++
++GpioCfg.enableout = function(portname) {
++ return gpiomap.PINS[portname].PIN |
++ gpiomap.CTRL.ENABLE |
++ gpiomap.CTRL.OUT;
++}
++
++
++GpioCfg.enablein = function(portname) {
++ return gpiomap.PINS[portname].PIN |
++ gpiomap.CTRL.ENABLE |
++ gpiomap.CTRL.IN;
++}
++
++
++GpioCfg.disablefloat = function(portname) {
++ return gpiomap.PINS[portname].PIN |
++ gpiomap.CTRL.DISABLE |
++ gpiomap.CTRL.FLOAT;
++}
++
++
++module.exports = GpioCfg;
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// LED blink sample for IoT.js and node.js
++var events = require("events")
++ , eventEmitter = new events.EventEmitter()
++ , gpio = require("iotjs-gpio")
++ , gpiocfg = require("gpiocfg.js")
++ , gpio_pout = ["LED1", "LED2", "LED3", "LED4"]
++ , gpio_ocnt = 4
++ , intervalId
++ , durationId;
++
++function gpio_setpins() {
++ var idx, portpin;
++ var pin_ready_cnt = 0;
++ for (idx=0; idx<gpio_ocnt; idx++) {
++ portpin = gpiocfg.enableout(gpio_pout[idx]);
++
++ gpio.pinmode(portpin, function(err) {
++ pin_ready_cnt += 1;
++ if (pin_ready_cnt >= gpio_ocnt) {
++ eventEmitter.emit("pins_ready");
++ }
++ });
++ }
++}
++
++
++function gpio_run() {
++ var on = 1;
++ var idx = 0;
++
++ console.log("start blinking...");
++ intervalId = setInterval(function() {
++ var portpin = gpiocfg.map(gpio_pout[idx]);
++ var err = gpio.write(portpin, on);
++ idx = idx + 1;
++ if (idx >= gpio_ocnt) {
++ idx = 0;
++ on = (on + 1) % 2;
++ }
++ }, 100);
++}
++
++
++function gpio_cleanup(timeout) {
++ durationId = setTimeout(function() {
++ clearInterval(intervalId);
++ clearTimeout(durationId);
++ console.log("blinking completed");
++
++ var idx, portpin;
++ for (idx=0; idx<gpio_ocnt; idx++) {
++ portpin = gpiocfg.map(gpio_pout[idx]);
++ gpio.write(portpin, 0);
++
++ portpin = gpiocfg.disablefloat(gpio_pout[idx]);
++ gpio.pinmode(portpin);
++ }
++ eventEmitter.emit("pins_done");
++ }, timeout);
++}
++
++
++gpio.initialize(function(err) {
++ gpio_setpins();
++});
++
++
++eventEmitter.on("pins_ready", function() {
++ gpio_run();
++ gpio_cleanup(10 * 1000); // run for 10 seconds
++});
++
++
++eventEmitter.on("pins_done", function() {
++ gpio.release();
++})
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// LED blink with button sample for IoT.js and node.js
++var events = require('events')
++ , eventEmitter = new events.EventEmitter()
++ , gpio = require("iotjs-gpio")
++ , gpiocfg = require("./gpiocfg.js")
++ , gpio_pout = ["LED1", "LED2", "LED3", "LED4", "LED5"]
++ , gpio_cled = 4
++ , gpio_ocnt = 5
++ , gpio_pinp = ["BTN1"]
++ , gpio_icnt = 1
++ , intervalId
++ , durationId;
++
++
++function gpio_setpins() {
++ var idx;
++ var pin_ready_cnt = 0;
++
++ function chk_pins(err) {
++ pin_ready_cnt += 1;
++ if (pin_ready_cnt >= gpio_ocnt+gpio_icnt) {
++ eventEmitter.emit('pins_ready');
++ }
++ }
++ var portpin;
++ for (idx=0; idx<gpio_ocnt; idx++) {
++ portpin = gpiocfg.enableout(gpio_pout[idx]);
++ gpio.pinmode(portpin, chk_pins);
++ }
++ for (idx=0; idx<gpio_icnt; idx++) {
++ portpin = gpiocfg.enablein(gpio_pinp[idx]);
++ gpio.pinmode(portpin, chk_pins);
++ }
++}
++
++
++function gpio_run() {
++ var on = 1;
++ var idx = 0;
++ var prein = 0;
++ var nowin;
++
++ console.log("start blinking...");
++ intervalId = setInterval( function() {
++ var portpin = gpiocfg.map(gpio_pout[idx]);
++ gpio.write(portpin, on);
++
++ idx = idx + 1;
++ if (idx >= gpio_cled) {
++ idx = 0;
++ on = (on + 1) % 2;
++ }
++
++ portpin = gpiocfg.map(gpio_pinp[0]);
++ gpio.read(portpin, function(err, val) {
++ if (err>=0) {
++ nowin = val>0 ? 1 : 0;
++ if (prein != nowin) {
++ portpin = gpiocfg.map(gpio_pout[4]);
++ gpio.write(portpin, nowin);
++ prein = nowin;
++ }
++ }
++ });
++ }, 100);
++}
++
++
++function gpio_cleanup(timeout) {
++ durationId = setTimeout( function() {
++ clearInterval(intervalId);
++ clearTimeout(durationId);
++ console.log('blinking completed');
++
++ var idx;
++ var portname;
++ var portpin;
++ for (idx=0; idx<gpio_ocnt; idx++) {
++ portpin = gpiocfg.map(gpio_pout[idx]);
++ gpio.write(portpin, 0);
++ portpin = gpiocfg.disablefloat(gpio_pout[idx]);
++ gpio.pinmode(portpin);
++ }
++
++ for (idx=0; idx<gpio_icnt; idx++) {
++ portpin = gpiocfg.map(gpio_pinp[idx]);
++ gpio.write(portpin, 0);
++ portpin = gpiocfg.disablefloat(gpio_pinp[idx]);
++ gpio.pinmode(portpin);
++ }
++
++ eventEmitter.emit('pins_done');
++ }, timeout );
++}
++
++gpio.initialize(function() {
++ gpio_setpins();
++});
++
++
++eventEmitter.on('pins_ready', function() {
++ gpio_run();
++ gpio_cleanup(10 * 1000); // run for 10 seconds
++});
++
++
++eventEmitter.on('pins_done', function() {
++ gpio.release();
++})
--- /dev/null
--- /dev/null
++/* 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.
++ */
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// GPIO for iotjs and node.js
++if (process.iotjs) {
++ module.exports = require('gpio');
++}
++else {
++ module.exports = require('./node-gpio.js')
++}
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++// node-gpio.js:
++// IoT.js GPIO control emulation on node.js
++var pi_gpio = require('pi-gpio');
++
++var GPIO_ENABLE = 0x00020000; // sync with iotjs gpio control
++var GPIO_OUTPUT = 0x00010000;
++var GPIO_MODEMASK= 0x00ff0000;
++var GPIO_PINMASK = 0x000000ff;
++
++function noop() {}
++
++function GPIO() {
++
++}
++
++GPIO.initialize = function(callback) {
++ process.nextTick(function(){
++ callback(0);
++ });
++};
++
++
++GPIO.release = function() {
++};
++
++
++GPIO.pinmode = function(port, callback) {
++ var direction = "";
++ var pinmode = port & GPIO_MODEMASK;
++
++ port = port & GPIO_PINMASK;
++ if (pinmode & GPIO_ENABLE) { // enable
++ if (pinmode & GPIO_OUTPUT) // output
++ direction = "out";
++ pi_gpio.open(port, direction, callback);
++ }
++ else {
++ pi_gpio.close(port, callback);
++ }
++}
++
++
++GPIO.write = function(port, val, callback) {
++ pi_gpio.write(port, val, (callback || noop));
++};
++
++
++GPIO.read = function(port, callback) {
++ pi_gpio.read(port, (callback || noop));
++};
++
++
++module.exports = GPIO;
--- /dev/null
--- /dev/null
++node_modules
--- /dev/null
--- /dev/null
++The MIT License
++
++Copyright (c) 2012 Rakesh Pai rakeshpai@gmail.com
++
++Permission is hereby granted, 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.
--- /dev/null
--- /dev/null
++pi-gpio
++=======
++
++pi-gpio is a simple node.js based library to help access the GPIO of the Raspberry Pi (Debian Wheezy). It's modelled loosely around the built-in ``fs`` module.
++It works with:
++* original Raspberry Pi (A and B)
++* model B revision 2 boards
++* Raspberry Pi Model A+
++* Raspberry Pi Model B+
++
++```javascript
++var gpio = require("pi-gpio");
++
++gpio.open(16, "output", function(err) { // Open pin 16 for output
++ gpio.write(16, 1, function() { // Set pin 16 high (1)
++ gpio.close(16); // Close pin 16
++ });
++});
++```
++
++## How you can help
++
++Ways you can help:
++
++ - Review the pull requests and test them on a Pi for correctness.
++ - Report Bugs.
++ - Fix a bug or add something awesome, Send a pull request.
++
++## About the pin configuration
++
++This couldn't have been more confusing. Raspberry Pi's physical pins are not laid out in any particular logical order. Most of them are given the names of the pins of the Broadcom chip it uses (BCM2835). There isn't even a logical relationship between the physical layout of the Raspberry Pi pin header and the Broadcom chip's pinout. The OS recognizes the names of the Broadcom chip and has nothing to do with the physical pin layout on the Pi. To add to the fun, the specs for the Broadcom chip are nearly impossible to get!
++
++This library simplifies all of this (hopefully), by abstracting away the Broadcom chip details. You only need to refer to the pins as they are on the physical pin layout on the Raspberry PI. For your reference, the pin layout follows. All the pins marked "GPIO" can be used with this library, using pin numbers as below.
++
++<table>
++ <tr>
++ <td>
++ P1 - 3.3v
++ </td>
++ <td>
++ 1
++ </td>
++ <td>
++ 2
++ </td>
++ <td>
++ 5v
++ </td>
++ </tr>
++ <tr>
++ <td>
++ I2C SDA
++ </td>
++ <td>
++ 3
++ </td>
++ <td >
++ 4
++ </td>
++ <td>
++ --
++ </td>
++ </tr>
++ <tr>
++ <td>
++ I2C SCL
++ </td>
++ <td>
++ 5
++ </td>
++ <td>
++ 6
++ </td>
++ <td>
++ Ground
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 7
++ </td>
++ <td>
++ 8
++ </td>
++ <td>
++ TX
++ </td>
++ </tr>
++ <tr>
++ <td>
++ --
++ </td>
++ <td>
++ 9
++ </td>
++ <td>
++ 10
++ </td>
++ <td>
++ RX
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 11
++ </td>
++ <td>
++ 12
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 13
++ </td>
++ <td>
++ 14
++ </td>
++ <td>
++ --
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 15
++ </td>
++ <td>
++ 16
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ --
++ </td>
++ <td>
++ 17
++ </td>
++ <td>
++ 18
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ SPI MOSI
++ </td>
++ <td>
++ 19
++ </td>
++ <td>
++ 20
++ </td>
++ <td>
++ --
++ </td>
++ </tr>
++ <tr>
++ <td>
++ SPI MISO
++ </td>
++ <td>
++ 21
++ </td>
++ <td>
++ 22
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ SPI SCLK
++ </td>
++ <td>
++ 23
++ </td>
++ <td>
++ 24
++ </td>
++ <td>
++ SPI CE0
++ </td>
++ </tr>
++ <tr>
++ <td>
++ --
++ </td>
++ <td>
++ 25
++ </td>
++ <td>
++ 26
++ </td>
++ <td>
++ SPI CE1
++ </td>
++ </tr>
++ <tr>
++ <td colspan="4">Model A+ and Model B+ additional pins</td>
++ </tr>
++ <tr>
++ <td>
++ ID_SD
++ </td>
++ <td>
++ 27
++ </td>
++ <td>
++ 28
++ </td>
++ <td>
++ ID_SC
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 29
++ </td>
++ <td>
++ 30
++ </td>
++ <td>
++ --
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 31
++ </td>
++ <td>
++ 32
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 33
++ </td>
++ <td>
++ 34
++ </td>
++ <td>
++ --
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 35
++ </td>
++ <td>
++ 36
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ GPIO
++ </td>
++ <td>
++ 37
++ </td>
++ <td>
++ 38
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++ <tr>
++ <td>
++ --
++ </td>
++ <td>
++ 39
++ </td>
++ <td>
++ 40
++ </td>
++ <td>
++ GPIO
++ </td>
++ </tr>
++</table>
++
++That gives you several GPIO pins to play with: pins 7, 11, 12, 13, 15, 16, 18 and 22 (with A+ and B+ giving 29, 31, 32, 33, 35, 37, 38 and 40). You should provide these physical pin numbers to this library, and not bother with what they are called internally. Easy-peasy.
++
++## Installation
++
++If you haven't already, get node and npm on the Pi. The simplest way is:
++
++ sudo apt-get install nodejs npm
++
++The Raspberry Pi's GPIO pins require you to be root to access them. That's totally unsafe for several reasons. To get around this problem, you should use the excellent [gpio-admin](https://github.com/quick2wire/quick2wire-gpio-admin).
++
++Do the following on your raspberry pi:
++
++ git clone git://github.com/quick2wire/quick2wire-gpio-admin.git
++ cd quick2wire-gpio-admin
++ make
++ sudo make install
++ sudo adduser $USER gpio
++
++After this, you will need to logout and log back in. [Details](http://quick2wire.com/2012/05/safe-controlled-access-to-gpio-on-the-raspberry-pi/), if you are interested.
++
++Next, ``cd`` to your project directory and use npm to install pi-gpio in your project.
++
++ npm install pi-gpio
++
++That's it!
++
++## Usage
++
++### .open(pinNumber, [options], [callback])
++
++Aliased to ``.export``
++
++Makes ``pinNumber`` available for use.
++
++* ``pinNumber``: The pin number to make available. Remember, ``pinNumber`` is the physical pin number on the Pi.
++* ``options``: (Optional) Should be a string, such as ``input`` or ``input pullup``. You can specify whether the pin direction should be `input` or `output` (or `in` or `out`). You can additionally set the internal pullup / pulldown resistor by sepcifying `pullup` or `pulldown` (or `up` or `down`). If options isn't provided, it defaults to `output`. If a direction (`input` or `output`) is not specified (eg. only `up`), then the direction defaults to `output`.
++* ``callback``: (Optional) Will be called when the pin is available for use. May receive an error as the first argument if something went wrong.
++
++### .close(pinNumber, [callback])
++
++Aliased to ``.unexport``
++
++Closes ``pinNumber``.
++
++* ``pinNumber``: The pin number to close. Again, ``pinNumber`` is the physical pin number on the Pi.
++* ``callback``: (Optional) Will be called when the pin is closed. Again, may receive an error as the first argument.
++
++### .setDirection(pinNumber, direction, [callback])
++
++Changes the direction from ``input`` to ``output`` or vice-versa.
++
++* ``pinNumber``: As usual.
++* ``direction``: Either ``input`` or ``in`` or ``output`` or ``out``.
++* ``callback``: Will be called when direction change is complete. May receive an error as usual.
++
++### .getDirection(pinNumber, [callback])
++
++Gets the direction of the pin. Acts like a getter for the method above.
++
++* ``pinNumber``: As usual
++* ``callback``: Will be called when the direction is received. The first argument could be an error. The second argument will either be ``in`` or ``out``.
++
++### .read(pinNumber, [callback])
++
++Reads the current value of the pin. Most useful if the pin is in the ``input`` direction.
++
++* ``pinNumber``: As usual.
++* ``callback``: Will receive a possible error object as the first argument, and the value of the pin as the second argument. The value will be either ``0`` or ``1`` (numeric).
++
++Example:
++```javascript
++gpio.read(16, function(err, value) {
++ if(err) throw err;
++ console.log(value); // The current state of the pin
++});
++```
++
++### .write(pinNumber, value, [callback])
++
++Writes ``value`` to ``pinNumber``. Will obviously fail if the pin is not in the ``output`` direction.
++
++* ``pinNumber``: As usual.
++* ``value``: Should be either a numeric ``0`` or ``1``. Any value that isn't ``0`` or ``1`` will be coerced to be boolean, and then converted to 0 (false) or 1 (true). Just stick to sending a numeric 0 or 1, will you? ;)
++* ``callback``: Will be called when the value is set. Again, might receive an error.
++
++## Misc
++
++* To run tests: ``npm install && npm test`` where you've got the checkout.
++* This module was created, ``git push``'ed and ``npm publish``'ed all from the Raspberry Pi! The Pi rocks!
++
++## Coming soon
++
++* Support for I2C and SPI (though it should already be possible to bit-bang the SPI protocol).
++* Any other suggestions?
++
++## License
++
++(The MIT License)
++
++Copyright (c) 2012 Rakesh Pai <rakeshpai@gmail.com>
++
++Permission is hereby granted, 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.
--- /dev/null
--- /dev/null
++{
++ "author": {
++ "name": "Rakesh Pai",
++ "email": "rakeshpai@gmail.com"
++ },
++ "name": "pi-gpio",
++ "description": "A simple node.js-based GPIO helper for the Raspberry Pi",
++ "version": "0.0.7",
++ "repository": {
++ "type": "git",
++ "url": "git+ssh://git@github.com/rakeshpai/pi-gpio.git"
++ },
++ "homepage": "https://github.com/rakeshpai/pi-gpio",
++ "main": "./pi-gpio",
++ "bugs": {
++ "url": "https://github.com/rakeshpai/pi-gpio/issues"
++ },
++ "tags": [
++ "raspberry",
++ "pi",
++ "gpio",
++ "simple"
++ ],
++ "dependencies": {},
++ "devDependencies": {
++ "mocha": "1.x",
++ "should": "1.x"
++ },
++ "optionalDependencies": {},
++ "engines": {
++ "node": "*"
++ },
++ "scripts": {
++ "test": "mocha --reporter spec"
++ },
++ "gitHead": "afc55dded1c41f08ce182d1c1ce3d1bc36d92260",
++ "_id": "pi-gpio@0.0.7",
++ "_shasum": "83762ca63b0a8916142e344f91db61cf2631ad18",
++ "_from": "pi-gpio@0.0.7",
++ "_npmVersion": "2.7.4",
++ "_nodeVersion": "0.10.25",
++ "_npmUser": {
++ "name": "rakeshpai",
++ "email": "rakeshpai@errorception.com"
++ },
++ "maintainers": [
++ {
++ "name": "rakeshpai",
++ "email": "rakeshpai@gmail.com"
++ }
++ ],
++ "dist": {
++ "shasum": "83762ca63b0a8916142e344f91db61cf2631ad18",
++ "tarball": "http://registry.npmjs.org/pi-gpio/-/pi-gpio-0.0.7.tgz"
++ },
++ "directories": {},
++ "_resolved": "http://registry.npmjs.org/pi-gpio/-/pi-gpio-0.0.7.tgz",
++ "readme": "ERROR: No README data found!"
++}
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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.
++ */
++
++"use strict";
++var fs = require("fs"),
++ path = require("path"),
++ exec = require("child_process").exec;
++
++var gpioAdmin = "gpio-admin",
++ sysFsPathOld = "/sys/devices/virtual/gpio", // pre 3.18.x kernel
++ sysFsPathNew = "/sys/class/gpio", // post 3.18.x kernel
++ sysFsPath;
++
++var rev = fs.readFileSync("/proc/cpuinfo").toString().split("\n").filter(function(line) {
++ return line.indexOf("Revision") == 0;
++})[0].split(":")[1].trim();
++
++// tests the device tree directory to determine the actual gpio path
++if (fs.existsSync('/sys/devices/soc')) {
++ sysFsPath = sysFsPathNew;
++} else {
++ sysFsPath = sysFsPathOld; // fallback for old kernels
++}
++
++rev = parseInt(rev, 16) < 3 ? 1 : 2; // http://elinux.org/RPi_HardwareHistory#Board_Revision_History
++
++var pinMapping = {
++ "3": 0,
++ "5": 1,
++ "7": 4,
++ "8": 14,
++ "10": 15,
++ "11": 17,
++ "12": 18,
++ "13": 21,
++ "15": 22,
++ "16": 23,
++ "18": 24,
++ "19": 10,
++ "21": 9,
++ "22": 25,
++ "23": 11,
++ "24": 8,
++ "26": 7,
++
++ // Model A+ and Model B+ pins
++ "29": 5,
++ "31": 6,
++ "32": 12,
++ "33": 13,
++ "35": 19,
++ "36": 16,
++ "37": 26,
++ "38": 20,
++ "40": 21
++};
++
++if (rev == 2) {
++ pinMapping["3"] = 2;
++ pinMapping["5"] = 3;
++ pinMapping["13"] = 27;
++}
++
++function isNumber(number) {
++ return !isNaN(parseInt(number, 10));
++}
++
++function noop() {}
++
++function handleExecResponse(method, pinNumber, callback) {
++ return function(err, stdout, stderr) {
++ if (err) {
++ console.error("Error when trying to", method, "pin", pinNumber);
++ console.error(stderr);
++ callback(err);
++ } else {
++ callback();
++ }
++ }
++}
++
++function sanitizePinNumber(pinNumber) {
++ if (!isNumber(pinNumber) || !isNumber(pinMapping[pinNumber])) {
++ throw new Error("Pin number isn't valid");
++ }
++
++ return parseInt(pinNumber, 10);
++}
++
++function sanitizeDirection(direction) {
++ direction = (direction || "").toLowerCase().trim();
++ if (direction === "in" || direction === "input") {
++ return "in";
++ } else if (direction === "out" || direction === "output" || !direction) {
++ return "out";
++ } else {
++ throw new Error("Direction must be 'input' or 'output'");
++ }
++}
++
++function sanitizeOptions(options) {
++ var sanitized = {};
++
++ options.split(" ").forEach(function(token) {
++ if (token == "in" || token == "input") {
++ sanitized.direction = "in";
++ }
++
++ if (token == "pullup" || token == "up") {
++ sanitized.pull = "pullup";
++ }
++
++ if (token == "pulldown" || token == "down") {
++ sanitized.pull = "pulldown";
++ }
++ });
++
++ if (!sanitized.direction) {
++ sanitized.direction = "out";
++ }
++
++ if (!sanitized.pull) {
++ sanitized.pull = "";
++ }
++
++ return sanitized;
++}
++
++var gpio = {
++ rev: rev,
++
++ open: function(pinNumber, options, callback) {
++ pinNumber = sanitizePinNumber(pinNumber);
++
++ if (!callback && typeof options === "function") {
++ callback = options;
++ options = "out";
++ }
++
++ options = sanitizeOptions(options);
++
++ exec(gpioAdmin + " export " + pinMapping[pinNumber] + " " + options.pull, handleExecResponse("open", pinNumber, function(err) {
++ if (err) return (callback || noop)(err);
++
++ gpio.setDirection(pinNumber, options.direction, callback);
++ }));
++ },
++
++ setDirection: function(pinNumber, direction, callback) {
++ pinNumber = sanitizePinNumber(pinNumber);
++ direction = sanitizeDirection(direction);
++
++ fs.writeFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/direction", direction, (callback || noop));
++ },
++
++ getDirection: function(pinNumber, callback) {
++ pinNumber = sanitizePinNumber(pinNumber);
++ callback = callback || noop;
++
++ fs.readFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/direction", "utf8", function(err, direction) {
++ if (err) return callback(err);
++ callback(null, sanitizeDirection(direction.trim()));
++ });
++ },
++
++ close: function(pinNumber, callback) {
++ pinNumber = sanitizePinNumber(pinNumber);
++
++ exec(gpioAdmin + " unexport " + pinMapping[pinNumber], handleExecResponse("close", pinNumber, callback || noop));
++ },
++
++ read: function(pinNumber, callback) {
++ pinNumber = sanitizePinNumber(pinNumber);
++
++ fs.readFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/value", function(err, data) {
++ if (err) return (callback || noop)(err);
++
++ (callback || noop)(null, parseInt(data, 10));
++ });
++ },
++
++ write: function(pinNumber, value, callback) {
++ pinNumber = sanitizePinNumber(pinNumber);
++
++ value = !!value ? "1" : "0";
++
++ fs.writeFile(sysFsPath + "/gpio" + pinMapping[pinNumber] + "/value", value, "utf8", callback);
++ }
++};
++
++gpio.export = gpio.open;
++gpio.unexport = gpio.close;
++
++module.exports = gpio;
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 gpio = require("../pi-gpio"),
++ should = require("should"),
++ fs = require("fs");
++
++describe("pi-gpio", function() {
++ describe(".open", function() {
++ it("should open without errors", function(done) {
++ gpio.open(16, "output", function(err) {
++ should.not.exist(err);
++ done();
++ });
++ });
++
++ it("should throw an error if the pin is invalid", function() {
++ try {
++ gpio.open(1);
++ } catch(e) {
++ e.should.exist;
++ }
++ });
++
++ it("should set the direction correctly", function(done) {
++ fs.readFile("/sys/devices/virtual/gpio/gpio23/direction", "utf8", function(err, data) {
++ should.not.exist(err);
++ data.trim().should.equal("out");
++ done();
++ });
++ });
++ });
++
++ describe(".close", function() {
++ it("should close an open pin", function(done) {
++ gpio.close(16, done);
++ });
++ });
++
++ describe(".setDirection", function() {
++ it("should set the direction of the pin", function(done) {
++ gpio.open(16, function(err) {
++ should.not.exist(err);
++
++ gpio.setDirection(16, "input", function(err) {
++ should.not.exist(err);
++
++ fs.readFile("/sys/devices/virtual/gpio/gpio23/direction", "utf8", function(err, data) {
++ should.not.exist(err);
++ data.trim().should.equal("in");
++ done();
++ });
++ });
++ });
++ });
++ });
++
++ describe(".getDirection", function() {
++ it("should get the direction of the pin", function(done) {
++ gpio.getDirection(16, function(err, direction) {
++ should.not.exist(err);
++
++ direction.should.equal("in");
++ done();
++ });
++ });
++ });
++
++ describe(".write", function() {
++ it("should write the value of the pin", function(done) {
++ gpio.setDirection(16, "output", function(err) {
++ should.not.exist(err);
++
++ gpio.write(16, "1", function(err) {
++ should.not.exist(err);
++
++ fs.readFile("/sys/devices/virtual/gpio/gpio23/value", "utf8", function(err, data) {
++ should.not.exist(err);
++ data.trim().should.equal("1");
++ done();
++ });
++ });
++ });
++ });
++ });
++
++ describe(".read", function() {
++ it("should read the value at the pin correctly", function(done) {
++ gpio.read(16, function(err, value) {
++ should.not.exist(err);
++
++ value.should.equal(1);
++ done();
++ });
++ });
++ });
++
++ after(function(done) {
++ gpio.close(16, done);
++ });
++});
--- /dev/null
--- /dev/null
++{
++ "name": "iotjs-gpio",
++ "version": "0.0.1",
++ "description": "iot.js and node.js common gpio",
++ "main": "iotjs-gpio.js",
++ "scripts": {
++ "test": "echo \"Error: no test specified\" && exit 1"
++ },
++ "dependencies" : {
++ "pi-gpio" : "0.0.7"
++ },
++ "author": "SaeHie Park <saehie.park@samsung.com>",
++ "license": "Apache-2.0"
++}
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 Gpio = require('gpio');
++var pin = require('systemio_pin').pin;
++
++var gpio = new Gpio();
++
++var gpio_led = gpio.open({
++ pin: pin.led1,
++ direction: gpio.DIRECTION.OUT
++}, function(err) {
++ if (!err) {
++ gpio_led.writeSync(true);
++
++ var interval = setInterval(function() {
++ gpio_led.read(function(err, value) {
++ if (!err) {
++ console.log("read value:%d", value);
++ gpio_led.write(!value);
++ } else {
++ clearInterval(interval);
++ }
++ });
++ }, 1000);
++ }
++});
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 gpio = require("gpio");
++
++gpio.initialize();
++
++gpio.on('initialize', function() {
++ console.log('GPIO initialized');
++ gpio.setPin(16, "out");
++});
++
++gpio.on('setpin', function(pin, dir, mode) {
++ console.log('setpin complete - pin: %d, direction: %s, mode: %s',
++ pin, dir, mode);
++ gpio.writePin(pin, true);
++ var interval = setInterval(function() {
++ gpio.readPin(pin, function(err, value) {
++ if (!err) {
++ console.log("read pin:%d value:%d", pin, value);
++ gpio.writePin(pin, !value);
++ } else {
++ clearInterval(interval);
++ }
++ });
++ }, 1000);
++});
++
++gpio.on('error', function(err) {
++ console.log(err);
++});
++
--- /dev/null
--- /dev/null
++## HTTP echo server and client.
++
++### Server
++```
++$ iotjs http-echo-server.js
++```
++
++
++### Client
++```
++$ iotjs http-echo-client.js <server ip> <message>
++```
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++var port = 8080;
++var address = process.argv[2];
++var message = process.argv[3];
++
++var req_options = {
++ host: address,
++ port: port,
++ method: 'POST',
++ headers: { 'Content-Length': message.length }
++};
++
++var req = http.request(req_options, function(res) {
++ var body = '';
++ res.on('data', function(data) {
++ body += data;
++ });
++ res.on('end', function() {
++ console.log(body);
++ });
++});
++
++
++req.end(message);
++
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++var port = 8080;
++
++var server = http.createServer(function(req, res) {
++ var body = '';
++ req.on('data', function(data) {
++ body += data;
++ });
++ req.on('end', function() {
++ res.writeHead(200, { 'Content-Type' : 'text/plain' });
++ res.end(body);
++ });
++});
++
++server.listen(port, 5);
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++
++var port = 8080;
++var server = http.createServer(function(req, res) {
++ res.writeHead(200, { 'Content-Type' : 'text/plain' });
++ res.end('Hello IoT.js');
++});
++
++server.listen(port, 5);
++
--- /dev/null
--- /dev/null
++<html>
++<h1><p>Hello IoT.js</p></h1>
++<html>
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++var fs = require('fs');
++
++
++var port = 8080;
++var htmlPath = './hello.html';
++
++var server = http.createServer(function(req, res) {
++ fs.readFile(htmlPath, function(err, data) {
++ if (err) {
++ res.writeHead(500);
++ res.end(err.toString());
++ } else {
++ res.writeHead(200, {
++ 'Content-Type' : 'text/html',
++ 'Content-Length' : data.length
++ });
++ res.end(data);
++ }
++ });
++});
++
++server.listen(port, 5);
++
--- /dev/null
--- /dev/null
++## HTTP state server and agent.
++
++### Server
++```
++$ iotjs http-state-server.js
++```
++
++
++### Agent
++```
++$ iotjs http-state-agent.js <server ip> <'GET' | 'POST' <new_state> >
++```
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++var port = 8080;
++var address = process.argv[2];
++var method = process.argv[3];
++var state = '';
++
++var req_options = {
++ host: address,
++ port: port,
++};
++
++if (method.toUpperCase() == 'GET') {
++ req_options.method = 'GET';
++} else if (method.toUpperCase() == 'POST') {
++ state = process.argv[4];
++ req_options.method = 'POST';
++ req_options.headers = { 'Content-Length': state.length };
++} else {
++ console.log('Invalid method: ' + method);
++ process.exit(1);
++}
++
++var req = http.request(req_options, function(res) {
++ var server_state = '';
++ res.on('data', function(data) {
++ server_state += data;
++ });
++ res.on('end', function() {
++ console.log('server state: ' + server_state);
++ });
++});
++
++
++req.end(state);
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 http = require('http');
++
++var port = 8080;
++var state = '';
++
++var server = http.createServer(function(req, res) {
++ var response = function() {
++ res.writeHead(200, { 'Content-Type' : 'text/plain',
++ 'Content-Length' : state.length });
++ res.end(state);
++ };
++
++ if (req.method == 'GET') {
++ response();
++ } else if (req.method == 'POST') {
++ var new_state = ''
++ req.on('data', function(data) {
++ new_state += data;
++ });
++ req.on('end', function() {
++ state = new_state;
++ response();
++ });
++ }
++});
++
++server.listen(port, 5);
++
--- /dev/null
--- /dev/null
++<html>
++<head>
++ <script language='javascript'>
++ var formula = '';
++ setInterval(function() {
++ var f = document.getElementById('formula');
++ if (formula != f.value) {
++ formula = f.value;
++
++ var xmlhttp = new XMLHttpRequest();
++ xmlhttp.onreadystatechange = function() {
++ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
++ document.getElementById('answer').innerText = xmlhttp.responseText;
++ }
++ };
++ xmlhttp.open("POST", "calculate", true);
++ xmlhttp.setRequestHeader("Content-type", "text/plain");
++ xmlhttp.setRequestHeader("Content-Length", formula.length);
++ xmlhttp.send(formula);
++ }
++ }, 2000);
++ </script>
++</head>
++<body>
++ <p>Input Formula:</p>
++ <p>
++ <input id='formula'></input>
++ =
++ <div id='answer'></div>
++ </p>
++</body>
++</html>
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 fs = require('fs');
++var http = require('http');
++
++
++var port = 8080;
++var result = '';
++
++var server = http.createServer(function(req, res) {
++ if (req.url == '/') {
++ onIndex(req, res);
++ } else if (req.url == '/calculate') {
++ onCalculate(req, res);
++ } else {
++ res.writeHead(500);
++ res.end();
++ }
++});
++
++
++function onIndex(req, res) {
++ fs.readFile('index.html', function(err, data) {
++ if (err) {
++ res.writeHead(500);
++ res.end();
++ } else {
++ res.writeHead(200);
++ res.end(data);
++ }
++ });
++}
++
++function onCalculate(req, res) {
++ var formula = '';
++
++ req.on('data', function(data) {
++ formula += data;
++ });
++
++ req.on('end', function() {
++ res.writeHead(200);
++ try {
++ result = eval(formula);
++ } catch (e) {
++ }
++ res.end(result);
++ });
++}
++
++server.listen(port);
--- /dev/null
--- /dev/null
++## Hello IoT.js calculator server example.
++
++### Server
++```
++$ iotjs server.js
++```
++
++
++### Client
++```
++$ iotjs client.js <server ip> <formula>
++```
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++var port = 7467;
++var address = process.argv[2];
++var formula = process.argv[3];
++
++var socket = new net.Socket();
++
++socket.connect(port, address, function() {
++ socket.end(formula);
++});
++
++var res = '';
++
++socket.on('data', function(data) {
++ res += data;
++});
++
++socket.on('end', function() {
++ console.log(formula + " = " + res);
++});
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++var port = 7467;
++var server = net.createServer({
++ allowHalfOpen: true
++});
++
++
++server.listen(port, 5);
++
++server.on('connection', function(socket) {
++ var formula = '';
++
++ socket.on('data', function(data) {
++ formula += data;
++ });
++
++ socket.on('end', function() {
++ socket.end("" + eval(formula));
++ });
++});
++
--- /dev/null
--- /dev/null
++## Simple server-client test
++
++Server will send 10000 bytes of string "012345678901234......789"
++
++### Server
++```
++$ iotjs server.js
++```
++
++### Client
++```
++$ iotjs client.js <server ip>
++```
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++var port = 7465;
++var address = process.argv[2] ? process.argv[2] : '127.0.0.1';
++
++var socket = net.Socket();
++
++socket.connect(port, address);
++
++var msg = '';
++socket.on('data', function(data) {
++ msg += data;
++});
++
++socket.on('end', function() {
++ console.log(msg.length);
++});
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++var port = 7465;
++var server = net.createServer();
++
++server.listen(port, 5);
++
++server.on('connection', function(socket) {
++ var i = 0;
++ var j = 0;
++ var limiti = 1000;
++ var limitj = 10;
++
++ var writing = function() {
++ var ok;
++ do {
++ ok = socket.write("" + j);
++ if (++j == limitj) {
++ j = 0;
++ if (++i == limiti) {
++ socket.end();
++ ok = false;
++ }
++ }
++ } while (ok);
++ };
++
++ socket.on('drain', writing);
++
++ writing();
++});
++
--- /dev/null
--- /dev/null
++## Hello IoT.js calculator server example.
++
++### Server
++```
++$ iotjs server.js
++```
++
++
++### Client
++```
++$ iotjs client.js <server ip>
++```
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++var port = 7468;
++
++var msg = '';
++var socket = new net.Socket();
++
++var address = process.argv[2] ? process.argv[2] : "127.0.0.1";
++
++socket.connect(port, address);
++
++socket.on('data', function(data) {
++ msg += data;
++});
++
++socket.on('end', function() {
++ console.log(msg);
++ socket.end();
++});
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 net = require('net');
++var port = 7468;
++var server = net.createServer();
++
++server.listen(port, 5);
++
++server.on('connection', function(socket) {
++ socket.end('Hello IoT.js');
++});
++
--- /dev/null
--- /dev/null
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
++ *
++ * 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 pin = {};
++
++if (process.platform === 'linux') {
++ pin.led1 = 20;
++} else if (process.platform === 'nuttx') {
++ var stm32_pin = require('stm32f4dis').pin;
++ pin.led1 = stm32_pin.PA10;
++} else {
++ throw new Error('Unsupported platform');
++}
++
++exports.pin = pin;
--- /dev/null
-#ifndef __NUTTX__
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 "iotjs_def.h"
+
+ #include "iotjs.h"
+ #include "iotjs_handlewrap.h"
+ #include "iotjs_js.h"
+ #include "iotjs_string_ext.h"
+
+ #include "jerryscript-debugger.h"
+ #ifndef __NUTTX__
+ #include "jerryscript-port-default.h"
+ #endif
+ #include "jerryscript-port.h"
+ #include "jerryscript.h"
+
+ #include <stdio.h>
+ #include <string.h>
+
+
+ /**
+ * Initialize JerryScript.
+ */
+ static bool iotjs_jerry_initialize(const iotjs_environment_t* env) {
+ // Set jerry run flags.
+ uint32_t jerry_flag = JERRY_INIT_EMPTY;
+
+ if (iotjs_environment_config(env)->memstat) {
+ jerry_flag |= JERRY_INIT_MEM_STATS;
-#ifndef __NUTTX__
++#if !defined(__NUTTX__) && !defined(__TIZENRT__)
+ jerry_port_default_set_log_level(JERRY_LOG_LEVEL_DEBUG);
+ #endif
+ }
+
+ if (iotjs_environment_config(env)->show_opcode) {
+ jerry_flag |= JERRY_INIT_SHOW_OPCODES;
++#if !defined(__NUTTX__) && !defined(__TIZENRT__)
+ jerry_port_default_set_log_level(JERRY_LOG_LEVEL_DEBUG);
+ #endif
+ }
+
+ if (iotjs_environment_config(env)->debugger) {
+ jerry_flag |= JERRY_INIT_DEBUGGER;
+ }
+
+ // Initialize jerry.
+ jerry_init((jerry_init_flag_t)jerry_flag);
+
+ if (iotjs_environment_config(env)->debugger) {
+ jerry_debugger_continue();
+ }
+
+ // Set magic strings.
+ iotjs_register_jerry_magic_string();
+
+ // Do parse and run to generate initial javascript environment.
+ jerry_value_t parsed_code = jerry_parse((jerry_char_t*)"", 0, false);
+ if (jerry_value_has_error_flag(parsed_code)) {
+ DLOG("jerry_parse() failed");
+ jerry_release_value(parsed_code);
+ return false;
+ }
+
+ jerry_value_t ret_val = jerry_run(parsed_code);
+ if (jerry_value_has_error_flag(ret_val)) {
+ DLOG("jerry_run() failed");
+ jerry_release_value(parsed_code);
+ jerry_release_value(ret_val);
+ return false;
+ }
+
+ jerry_release_value(parsed_code);
+ jerry_release_value(ret_val);
+ return true;
+ }
+
+
+ static void iotjs_jerry_release() {
+ jerry_cleanup();
+ }
+
+
+ static bool iotjs_run() {
+ // Evaluating 'iotjs.js' returns a function.
+ bool throws = false;
+ #ifndef ENABLE_SNAPSHOT
+ iotjs_jval_t jmain = iotjs_jhelper_eval("iotjs.js", strlen("iotjs.js"),
+ iotjs_s, iotjs_l, false, &throws);
+ #else
+ iotjs_jval_t jmain = iotjs_jhelper_exec_snapshot(iotjs_s, iotjs_l, &throws);
+ #endif
+
+ if (throws) {
+ iotjs_uncaught_exception(&jmain);
+ }
+
+ iotjs_jval_destroy(&jmain);
+
+ return !throws;
+ }
+
+
+ static bool iotjs_start(iotjs_environment_t* env) {
+ // Initialize commonly used jerry values
+ iotjs_binding_initialize();
+
+ // Bind environment to global object.
+ const iotjs_jval_t* global = iotjs_jval_get_global_object();
+ iotjs_jval_set_object_native_handle(global, (uintptr_t)(env), NULL);
+
+ // Initialize builtin modules.
+ iotjs_module_list_init();
+
+ // Initialize builtin process module.
+ const iotjs_jval_t* process =
+ iotjs_module_initialize_if_necessary(MODULE_PROCESS);
+
+ // Call the entry.
+ // load and call iotjs.js
+ iotjs_environment_go_state_running_main(env);
+
+ iotjs_jval_set_property_jval(global, "process", process);
+
+ iotjs_run();
+
+ // Run event loop.
+ iotjs_environment_go_state_running_loop(env);
+
+ bool more;
+ do {
+ more = uv_run(iotjs_environment_loop(env), UV_RUN_ONCE);
+ more |= iotjs_process_next_tick();
+ if (more == false) {
+ more = uv_loop_alive(iotjs_environment_loop(env));
+ }
+ jerry_value_t ret_val = jerry_run_all_enqueued_jobs();
+ if (jerry_value_has_error_flag(ret_val)) {
+ DLOG("jerry_run_all_enqueued_jobs() failed");
+ }
+ } while (more);
+
+ iotjs_environment_go_state_exiting(env);
+
+ // Emit 'exit' event.
+ iotjs_process_emit_exit(0);
+
+ // Release builtin modules.
+ iotjs_module_list_cleanup();
+
+ // Release commonly used jerry values.
+ iotjs_binding_finalize();
+
+ return true;
+ }
+
+
+ static void iotjs_uv_walk_to_close_callback(uv_handle_t* handle, void* arg) {
+ iotjs_handlewrap_t* handle_wrap = iotjs_handlewrap_from_handle(handle);
+ IOTJS_ASSERT(handle_wrap != NULL);
+
+ iotjs_handlewrap_close(handle_wrap, NULL);
+ }
+
+
+ int iotjs_entry(int argc, char** argv) {
+ // Initialize debug print.
+ init_debug_settings();
+
+ // Create environment.
+ iotjs_environment_t* env = (iotjs_environment_t*)iotjs_environment_get();
+
+ // Parse command line arguments.
+ if (!iotjs_environment_parse_command_line_arguments(env, (uint32_t)argc,
+ argv)) {
+ DLOG("iotjs_environment_parse_command_line_arguments failed");
+ return 1;
+ }
+
+ // Set event loop.
+ iotjs_environment_set_loop(env, uv_default_loop());
+
+ // Initialize JerryScript engine.
+ if (!iotjs_jerry_initialize(env)) {
+ DLOG("iotjs_jerry_initialize failed");
+ return 1;
+ }
+
+ // Start IoT.js
+ if (!iotjs_start(env)) {
+ DLOG("iotjs_start failed");
+ return 1;
+ }
+
+ // close uv loop.
+ // uv_stop(iotjs_environment_loop(env));
+ uv_walk(iotjs_environment_loop(env), iotjs_uv_walk_to_close_callback, NULL);
+ uv_run(iotjs_environment_loop(env), UV_RUN_DEFAULT);
+
+ int res = uv_loop_close(iotjs_environment_loop(env));
+ IOTJS_ASSERT(res == 0);
+
+ // Release JerryScript engine.
+ iotjs_jerry_release();
+
+ // Release environment.
+ iotjs_environment_release();
+
+ // Release debug print setting.
+ release_debug_settings();
+
+ return 0;
+ }
--- /dev/null
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 "iotjs_def.h"
+ #include "iotjs_binding.h"
+
+ #include <string.h>
+
+
+ static iotjs_jval_t jundefined;
+ static iotjs_jval_t jnull;
+ static iotjs_jval_t jtrue;
+ static iotjs_jval_t jfalse;
+ static iotjs_jval_t jglobal;
+
+ static iotjs_jargs_t jargs_empty;
+
+ static jerry_value_t iotjs_jval_as_raw(const iotjs_jval_t* jval);
+
+
+ iotjs_jval_t iotjs_jval_create_number(double v) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = jerry_create_number(v);
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_string(const iotjs_string_t* v) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ const jerry_char_t* data = (const jerry_char_t*)(iotjs_string_data(v));
+ jerry_size_t size = iotjs_string_size(v);
+
+ if (jerry_is_valid_utf8_string(data, size)) {
+ _this->value = jerry_create_string_sz_from_utf8(data, size);
+ } else {
+ _this->value =
+ jerry_create_error(JERRY_ERROR_TYPE,
+ (const jerry_char_t*)"Invalid UTF-8 string");
+ }
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_get_string_size(const iotjs_string_t* str) {
+ iotjs_jval_t str_val = iotjs_jval_create_string(str);
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, &str_val);
+
+ jerry_size_t size = jerry_get_string_size(_this->value);
+ iotjs_jval_t jval = iotjs_jval_create_number(size);
+
+ iotjs_jval_destroy(&str_val);
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_string_raw(const char* data) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = jerry_create_string((const jerry_char_t*)data);
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_object() {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = jerry_create_object();
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_array(uint32_t len) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = jerry_create_array(len);
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_byte_array(uint32_t len, const char* data) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ IOTJS_ASSERT(data != NULL);
+
+ _this->value = jerry_create_array(len);
+ for (uint32_t i = 0; i < len; i++) {
+ jerry_value_t val = jerry_create_number((double)data[i]);
+ jerry_set_property_by_index(_this->value, i, val);
+ jerry_release_value(val);
+ }
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_function(JHandlerType handler) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = jerry_create_external_function(handler);
+ IOTJS_ASSERT(jerry_value_is_constructor(_this->value));
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_error(const char* msg) {
+ return iotjs_jval_create_error_type(IOTJS_ERROR_COMMON, msg);
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_error_type(iotjs_error_t type, const char* msg) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ const jerry_char_t* jmsg = (const jerry_char_t*)(msg);
+ _this->value = jerry_create_error((jerry_error_t)type, jmsg);
+ jerry_value_clear_error_flag(&_this->value);
+
+ return jval;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_copied(const iotjs_jval_t* other) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = jerry_acquire_value(iotjs_jval_as_raw(other));
+ return jval;
+ }
+
+
+ static iotjs_jval_t iotjs_jval_create_raw(jerry_value_t val) {
+ iotjs_jval_t jval;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jval_t, &jval);
+
+ _this->value = val;
+
+ return jval;
+ }
+
+
+ void iotjs_jval_destroy(iotjs_jval_t* jval) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_jval_t, jval);
+ jerry_release_value(_this->value);
+ }
+
+
+ static void iotjs_jval_destroy_norelease(iotjs_jval_t* jval) {
+ IOTJS_VALIDATABLE_STRUCT_DESTRUCTOR_VALIDATE(iotjs_jval_t, jval);
+ }
+
+
+ iotjs_jval_t* iotjs_jval_get_undefined() {
+ return &jundefined;
+ }
+
+
+ iotjs_jval_t* iotjs_jval_get_null() {
+ return &jnull;
+ }
+
+
+ iotjs_jval_t* iotjs_jval_get_boolean(bool v) {
+ return v ? &jtrue : &jfalse;
+ }
+
+
+ iotjs_jval_t* iotjs_jval_get_global_object() {
+ return &jglobal;
+ }
+
+
+ #define TYPE_CHECKER_BODY(jval_type) \
+ bool iotjs_jval_is_##jval_type(const iotjs_jval_t* val) { \
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, val); \
+ return jerry_value_is_##jval_type(_this->value); \
+ }
+
+ FOR_EACH_JVAL_TYPES(TYPE_CHECKER_BODY)
+
+ #undef TYPE_CHECKER_BODY
+
+
+ bool iotjs_jval_as_boolean(const iotjs_jval_t* jval) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jval);
+ IOTJS_ASSERT(iotjs_jval_is_boolean(jval));
+ return jerry_get_boolean_value(_this->value);
+ }
+
+
+ double iotjs_jval_as_number(const iotjs_jval_t* jval) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jval);
+ IOTJS_ASSERT(iotjs_jval_is_number(jval));
+ return jerry_get_number_value(_this->value);
+ }
+
+
+ iotjs_string_t iotjs_jval_as_string(const iotjs_jval_t* jval) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jval);
+ IOTJS_ASSERT(iotjs_jval_is_string(jval));
+
+ jerry_size_t size = jerry_get_string_size(_this->value);
+
+ if (size == 0)
+ return iotjs_string_create();
+
+ char* buffer = iotjs_buffer_allocate(size + 1);
+ jerry_char_t* jerry_buffer = (jerry_char_t*)(buffer);
+
+ size_t check = jerry_string_to_char_buffer(_this->value, jerry_buffer, size);
+
+ IOTJS_ASSERT(check == size);
+ buffer[size] = '\0';
+
+ iotjs_string_t res = iotjs_string_create_with_buffer(buffer, size);
+
+ return res;
+ }
+
+
+ const iotjs_jval_t* iotjs_jval_as_object(const iotjs_jval_t* jval) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jval);
+ IOTJS_ASSERT(iotjs_jval_is_object(jval));
+ return jval;
+ }
+
+
+ const iotjs_jval_t* iotjs_jval_as_array(const iotjs_jval_t* jval) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jval);
+ IOTJS_ASSERT(iotjs_jval_is_array(jval));
+ return jval;
+ }
+
+
+ const iotjs_jval_t* iotjs_jval_as_function(const iotjs_jval_t* jval) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jval);
+ IOTJS_ASSERT(iotjs_jval_is_function(jval));
+ return jval;
+ }
+
+
+ static jerry_value_t iotjs_jval_as_raw(const iotjs_jval_t* jval) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jval);
+ return _this->value;
+ }
+
+
+ void iotjs_jval_set_method(const iotjs_jval_t* jobj, const char* name,
+ iotjs_native_handler_t handler) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ IOTJS_ASSERT(iotjs_jval_is_object(jobj));
+
+ iotjs_jval_t jfunc = iotjs_jval_create_function_with_dispatch(handler);
+ iotjs_jval_set_property_jval(jobj, name, &jfunc);
+ iotjs_jval_destroy(&jfunc);
+ }
+
+
+ void iotjs_jval_set_property_jval(const iotjs_jval_t* jobj, const char* name,
+ const iotjs_jval_t* val) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jobj);
+ IOTJS_ASSERT(iotjs_jval_is_object(jobj));
+
+ jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)(name));
+ jerry_value_t value = iotjs_jval_as_raw(val);
+ jerry_value_t ret_val = jerry_set_property(_this->value, prop_name, value);
+ jerry_release_value(prop_name);
+
+ IOTJS_ASSERT(!jerry_value_has_error_flag(ret_val));
+ jerry_release_value(ret_val);
+ }
+
+
+ void iotjs_jval_set_property_null(const iotjs_jval_t* jobj, const char* name) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ iotjs_jval_set_property_jval(jobj, name, iotjs_jval_get_null());
+ }
+
+
+ void iotjs_jval_set_property_undefined(const iotjs_jval_t* jobj,
+ const char* name) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ iotjs_jval_set_property_jval(jobj, name, iotjs_jval_get_undefined());
+ }
+
+
+ void iotjs_jval_set_property_boolean(const iotjs_jval_t* jobj, const char* name,
+ bool v) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ iotjs_jval_set_property_jval(jobj, name, iotjs_jval_get_boolean(v));
+ }
+
+
+ void iotjs_jval_set_property_number(const iotjs_jval_t* jobj, const char* name,
+ double v) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ iotjs_jval_t jval = iotjs_jval_create_number(v);
+ iotjs_jval_set_property_jval(jobj, name, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jval_set_property_string(const iotjs_jval_t* jobj, const char* name,
+ const iotjs_string_t* v) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ iotjs_jval_t jval = iotjs_jval_create_string(v);
+ iotjs_jval_set_property_jval(jobj, name, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jval_set_property_string_raw(const iotjs_jval_t* jobj,
+ const char* name, const char* v) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jval_t, jobj);
+ iotjs_jval_t jval = iotjs_jval_create_string_raw(v);
+ iotjs_jval_set_property_jval(jobj, name, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ iotjs_jval_t iotjs_jval_get_property(const iotjs_jval_t* jobj,
+ const char* name) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jobj);
+ IOTJS_ASSERT(iotjs_jval_is_object(jobj));
+
+ jerry_value_t prop_name = jerry_create_string((const jerry_char_t*)(name));
+ jerry_value_t res = jerry_get_property(_this->value, prop_name);
+ jerry_release_value(prop_name);
+
+ if (jerry_value_has_error_flag(res)) {
+ jerry_release_value(res);
+ return iotjs_jval_create_copied(iotjs_jval_get_undefined());
+ }
+
+ return iotjs_jval_create_raw(res);
+ }
+
+
+ void iotjs_jval_set_object_native_handle(const iotjs_jval_t* jobj,
+ uintptr_t ptr,
+ JNativeInfoType native_info) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jobj);
+ IOTJS_ASSERT(iotjs_jval_is_object(jobj));
+
+ jerry_set_object_native_pointer(_this->value, (void*)ptr, native_info);
+ }
+
+
+ uintptr_t iotjs_jval_get_object_native_handle(const iotjs_jval_t* jobj) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jobj);
+ IOTJS_ASSERT(iotjs_jval_is_object(jobj));
+
+ uintptr_t ptr = 0x0;
+ JNativeInfoType out_info;
+ jerry_get_object_native_pointer(_this->value, (void**)&ptr, &out_info);
+ return ptr;
+ }
+
+
+ uintptr_t iotjs_jval_get_object_from_jhandler(iotjs_jhandler_t* jhandler,
+ JNativeInfoType native_info) {
+ const iotjs_jval_t* jobj = JHANDLER_GET_THIS(object);
+ const IOTJS_DECLARE_THIS(iotjs_jval_t, jobj);
+
+ if (!jerry_value_is_object(_this->value)) {
+ return 0;
+ }
+
+ uintptr_t ptr = 0;
+ JNativeInfoType out_native_info;
+
+ if (jerry_get_object_native_pointer(_this->value, (void**)&ptr,
+ &out_native_info)) {
+ if (ptr && out_native_info == native_info) {
+ return ptr;
+ }
+ }
+
+ JHANDLER_THROW(COMMON, "Unsafe access");
+
+ return 0;
+ }
+
+
++uintptr_t iotjs_jval_get_arg_obj_from_jhandler(iotjs_jhandler_t* jhandler,
++ uint16_t index,
++ JNativeInfoType native_info) {
++ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
++
++ if (index >= _this->jargc) {
++ return 0;
++ }
++
++ const iotjs_jval_t jobj = _this->jargv[index];
++
++ if (!jerry_value_is_object(jobj.unsafe.value)) {
++ return 0;
++ }
++
++ uintptr_t ptr = 0;
++ JNativeInfoType out_native_info;
++
++ if (jerry_get_object_native_pointer(jobj.unsafe.value, (void**)&ptr,
++ &out_native_info)) {
++ if (ptr && out_native_info == native_info) {
++ return ptr;
++ }
++ }
++
++ JHANDLER_THROW(COMMON, "Unsafe access");
++
++ return 0;
++}
++
++
+ void iotjs_jval_set_property_by_index(const iotjs_jval_t* jarr, uint32_t idx,
+ const iotjs_jval_t* jval) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jarr);
+ IOTJS_ASSERT(iotjs_jval_is_object(jarr));
+
+ jerry_value_t value = iotjs_jval_as_raw(jval);
+ jerry_value_t ret_val = jerry_set_property_by_index(_this->value, idx, value);
+ IOTJS_ASSERT(!jerry_value_has_error_flag(ret_val));
+ jerry_release_value(ret_val);
+ }
+
+
+ iotjs_jval_t iotjs_jval_get_property_by_index(const iotjs_jval_t* jarr,
+ uint32_t idx) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jval_t, jarr);
+ IOTJS_ASSERT(iotjs_jval_is_object(jarr));
+
+ jerry_value_t res = jerry_get_property_by_index(_this->value, idx);
+
+ if (jerry_value_has_error_flag(res)) {
+ jerry_release_value(res);
+ return iotjs_jval_create_copied(iotjs_jval_get_undefined());
+ }
+
+ return iotjs_jval_create_raw(res);
+ }
+
+
+ iotjs_jval_t iotjs_jhelper_call(const iotjs_jval_t* jfunc,
+ const iotjs_jval_t* jthis,
+ const iotjs_jargs_t* jargs, bool* throws) {
+ IOTJS_ASSERT(iotjs_jval_is_object(jfunc));
+
+ jerry_value_t* jargv_ = NULL;
+ jerry_length_t jargc_ = iotjs_jargs_length(jargs);
+
+ #ifdef NDEBUG
+ jargv_ = (jerry_value_t*)jargs->unsafe.argv;
+ #else
+ if (jargc_ > 0) {
+ unsigned buffer_size = sizeof(iotjs_jval_t) * jargc_;
+ jargv_ = (jerry_value_t*)iotjs_buffer_allocate(buffer_size);
+ for (unsigned i = 0; i < jargc_; ++i) {
+ jargv_[i] = iotjs_jval_as_raw(iotjs_jargs_get(jargs, i));
+ }
+ }
+ #endif
+
+ jerry_value_t jfunc_ = iotjs_jval_as_raw(jfunc);
+ jerry_value_t jthis_ = iotjs_jval_as_raw(jthis);
+ jerry_value_t res = jerry_call_function(jfunc_, jthis_, jargv_, jargc_);
+
+ #ifndef NDEBUG
+ if (jargv_) {
+ iotjs_buffer_release((char*)jargv_);
+ }
+ #endif
+
+ *throws = jerry_value_has_error_flag(res);
+
+ jerry_value_clear_error_flag(&res);
+
+ return iotjs_jval_create_raw(res);
+ }
+
+
+ iotjs_jval_t iotjs_jhelper_call_ok(const iotjs_jval_t* jfunc,
+ const iotjs_jval_t* jthis,
+ const iotjs_jargs_t* jargs) {
+ bool throws;
+ iotjs_jval_t jres = iotjs_jhelper_call(jfunc, jthis, jargs, &throws);
+ IOTJS_ASSERT(!throws);
+ return jres;
+ }
+
+
+ iotjs_jval_t iotjs_jhelper_eval(const char* name, size_t name_len,
+ const uint8_t* data, size_t size,
+ bool strict_mode, bool* throws) {
+ jerry_value_t res =
+ jerry_parse_named_resource((const jerry_char_t*)name, name_len,
+ (const jerry_char_t*)data, size, strict_mode);
+
+ *throws = jerry_value_has_error_flag(res);
+
+ if (!*throws) {
+ jerry_value_t func = res;
+ res = jerry_run(func);
+ jerry_release_value(func);
+
+ *throws = jerry_value_has_error_flag(res);
+ }
+
+ jerry_value_clear_error_flag(&res);
+
+ return iotjs_jval_create_raw(res);
+ }
+
+
+ #ifdef ENABLE_SNAPSHOT
+ iotjs_jval_t iotjs_jhelper_exec_snapshot(const void* snapshot_p,
+ size_t snapshot_size, bool* throws) {
+ jerry_value_t res = jerry_exec_snapshot(snapshot_p, snapshot_size, false);
+ /* the snapshot buffer can be referenced
+ * until jerry_cleanup is not called */
+
+ *throws = jerry_value_has_error_flag(res);
+
+ jerry_value_clear_error_flag(&res);
+
+ return iotjs_jval_create_raw(res);
+ }
+ #endif
+
+
+ iotjs_jargs_t iotjs_jargs_create(uint16_t capacity) {
+ iotjs_jargs_t jargs;
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jargs_t, &jargs);
+
+ _this->capacity = capacity;
+ _this->argc = 0;
+ if (capacity > 0) {
+ unsigned buffer_size = sizeof(iotjs_jval_t) * capacity;
+ _this->argv = (iotjs_jval_t*)iotjs_buffer_allocate(buffer_size);
+ } else {
+ return jargs_empty;
+ }
+
+ return jargs;
+ }
+
+
+ static void iotjs_jargs_initialize_empty(iotjs_jargs_t* jargs) {
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jargs_t, jargs);
+ _this->capacity = 0;
+ _this->argc = 0;
+ _this->argv = NULL;
+ }
+
+
+ const iotjs_jargs_t* iotjs_jargs_get_empty() {
+ return &jargs_empty;
+ }
+
+
+ void iotjs_jargs_destroy(iotjs_jargs_t* jargs) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_jargs_t, jargs);
+
+ IOTJS_ASSERT(_this->argv == NULL || _this->argc > 0);
+ IOTJS_ASSERT(_this->argc <= _this->capacity);
+
+ if (_this->capacity > 0) {
+ for (unsigned i = 0; i < _this->argc; ++i) {
+ iotjs_jval_destroy(&_this->argv[i]);
+ }
+ iotjs_buffer_release((char*)_this->argv);
+ } else {
+ IOTJS_ASSERT(_this->argv == NULL);
+ }
+ }
+
+
+ uint16_t iotjs_jargs_length(const iotjs_jargs_t* jargs) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jargs_t, jargs);
+ return _this->argc;
+ }
+
+
+ void iotjs_jargs_append_jval(iotjs_jargs_t* jargs, const iotjs_jval_t* x) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jargs_t, jargs);
+ IOTJS_ASSERT(_this->argc < _this->capacity);
+ _this->argv[_this->argc++] = iotjs_jval_create_copied(x);
+ }
+
+
+ void iotjs_jargs_append_undefined(iotjs_jargs_t* jargs) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jargs_append_jval(jargs, iotjs_jval_get_undefined());
+ }
+
+
+ void iotjs_jargs_append_null(iotjs_jargs_t* jargs) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jargs_append_jval(jargs, iotjs_jval_get_null());
+ }
+
+
+ void iotjs_jargs_append_bool(iotjs_jargs_t* jargs, bool x) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jargs_append_jval(jargs, iotjs_jval_get_boolean(x));
+ }
+
+
+ void iotjs_jargs_append_number(iotjs_jargs_t* jargs, double x) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jval_t jval = iotjs_jval_create_number(x);
+ iotjs_jargs_append_jval(jargs, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jargs_append_string(iotjs_jargs_t* jargs, const iotjs_string_t* x) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jval_t jval = iotjs_jval_create_string(x);
+ iotjs_jargs_append_jval(jargs, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jargs_append_error(iotjs_jargs_t* jargs, const char* msg) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jval_t error = iotjs_jval_create_error(msg);
+ iotjs_jargs_append_jval(jargs, &error);
+ iotjs_jval_destroy(&error);
+ }
+
+
+ void iotjs_jargs_append_string_raw(iotjs_jargs_t* jargs, const char* x) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jargs_t, jargs);
+ iotjs_jval_t jval = iotjs_jval_create_string_raw(x);
+ iotjs_jargs_append_jval(jargs, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jargs_replace(iotjs_jargs_t* jargs, uint16_t index,
+ const iotjs_jval_t* x) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jargs_t, jargs);
+
+ IOTJS_ASSERT(index < _this->argc);
+
+ iotjs_jval_destroy(&_this->argv[index]);
+ _this->argv[index] = iotjs_jval_create_copied(x);
+ }
+
+
+ const iotjs_jval_t* iotjs_jargs_get(const iotjs_jargs_t* jargs,
+ uint16_t index) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jargs_t, jargs);
+
+ IOTJS_ASSERT(index < _this->argc);
+ return &_this->argv[index];
+ }
+
+
+ void iotjs_jhandler_initialize(iotjs_jhandler_t* jhandler,
+ const jerry_value_t jfunc,
+ const jerry_value_t jthis,
+ const jerry_value_t jargv[],
+ const uint16_t jargc) {
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_jhandler_t, jhandler);
+
+ _this->jfunc = iotjs_jval_create_raw(jfunc);
+ _this->jthis = iotjs_jval_create_raw(jthis);
+ _this->jret = iotjs_jval_create_copied(iotjs_jval_get_undefined());
+ #ifdef NDEBUG
+ _this->jargv = (iotjs_jval_t*)jargv;
+ #else
+ if (jargc > 0) {
+ unsigned buffer_size = sizeof(iotjs_jval_t) * jargc;
+ _this->jargv = (iotjs_jval_t*)iotjs_buffer_allocate(buffer_size);
+ for (int i = 0; i < jargc; ++i) {
+ _this->jargv[i] = iotjs_jval_create_raw(jargv[i]);
+ }
+ } else {
+ _this->jargv = NULL;
+ }
+ _this->finished = false;
+ #endif
+
+ _this->jargc = jargc;
+ }
+
+
+ void iotjs_jhandler_destroy(iotjs_jhandler_t* jhandler) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_jhandler_t, jhandler);
+ iotjs_jval_destroy_norelease(&_this->jfunc);
+ iotjs_jval_destroy_norelease(&_this->jthis);
+ iotjs_jval_destroy_norelease(&_this->jret);
+ #ifndef NDEBUG
+ if (_this->jargc > 0) {
+ for (int i = 0; i < _this->jargc; ++i) {
+ iotjs_jval_destroy_norelease(&_this->jargv[i]);
+ }
+ iotjs_buffer_release((char*)(_this->jargv));
+ } else {
+ IOTJS_ASSERT(_this->jargv == NULL);
+ }
+ #endif
+ }
+
+
+ const iotjs_jval_t* iotjs_jhandler_get_function(iotjs_jhandler_t* jhandler) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
+ return &_this->jfunc;
+ }
+
+
+ const iotjs_jval_t* iotjs_jhandler_get_this(iotjs_jhandler_t* jhandler) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
+ return &_this->jthis;
+ }
+
+
+ const iotjs_jval_t* iotjs_jhandler_get_arg(iotjs_jhandler_t* jhandler,
+ uint16_t index) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
+ IOTJS_ASSERT(index < _this->jargc);
+ return &_this->jargv[index];
+ }
+
+
+ uint16_t iotjs_jhandler_get_arg_length(iotjs_jhandler_t* jhandler) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
+ return _this->jargc;
+ }
+
+
+ void iotjs_jhandler_return_jval(iotjs_jhandler_t* jhandler,
+ const iotjs_jval_t* ret) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
+
+ #ifndef NDEBUG
+ IOTJS_ASSERT(_this->finished == false);
+ #endif
+
+ iotjs_jval_destroy(&_this->jret);
+ _this->jret = iotjs_jval_create_copied(ret);
+ #ifndef NDEBUG
+ _this->finished = true;
+ #endif
+ }
+
+
+ void iotjs_jhandler_return_undefined(iotjs_jhandler_t* jhandler) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jhandler_t, jhandler);
+ iotjs_jhandler_return_jval(jhandler, iotjs_jval_get_undefined());
+ }
+
+
+ void iotjs_jhandler_return_null(iotjs_jhandler_t* jhandler) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jhandler_t, jhandler);
+ iotjs_jhandler_return_jval(jhandler, iotjs_jval_get_null());
+ }
+
+
+ void iotjs_jhandler_return_boolean(iotjs_jhandler_t* jhandler, bool ret) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jhandler_t, jhandler);
+ iotjs_jhandler_return_jval(jhandler, iotjs_jval_get_boolean(ret));
+ }
+
+
+ void iotjs_jhandler_return_number(iotjs_jhandler_t* jhandler, double ret) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jhandler_t, jhandler);
+ iotjs_jval_t jval = iotjs_jval_create_number(ret);
+ iotjs_jhandler_return_jval(jhandler, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jhandler_return_string(iotjs_jhandler_t* jhandler,
+ const iotjs_string_t* ret) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jhandler_t, jhandler);
+ iotjs_jval_t jval = iotjs_jval_create_string(ret);
+ iotjs_jhandler_return_jval(jhandler, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jhandler_return_string_raw(iotjs_jhandler_t* jhandler,
+ const char* ret) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_jhandler_t, jhandler);
+ iotjs_jval_t jval = iotjs_jval_create_string_raw(ret);
+ iotjs_jhandler_return_jval(jhandler, &jval);
+ iotjs_jval_destroy(&jval);
+ }
+
+
+ void iotjs_jhandler_throw(iotjs_jhandler_t* jhandler, const iotjs_jval_t* err) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_jhandler_t, jhandler);
+ #ifndef NDEBUG
+ IOTJS_ASSERT(_this->finished == false);
+ #endif
+
+ iotjs_jval_destroy(&_this->jret);
+ _this->jret = iotjs_jval_create_copied(err);
+ jerry_value_set_error_flag(&_this->jret.unsafe.value);
+
+ #ifndef NDEBUG
+ _this->finished = true;
+ #endif
+ }
+
+
+ static jerry_value_t iotjs_native_dispatch_function(
+ const jerry_value_t jfunc, const jerry_value_t jthis,
+ const jerry_value_t jargv[], const JRawLengthType jargc) {
+ uintptr_t target_function_ptr = 0x0;
+ JNativeInfoType out_info;
+
+ if (!jerry_get_object_native_pointer(jfunc, (void**)&target_function_ptr,
+ &out_info)) {
+ const jerry_char_t* jmsg = (const jerry_char_t*)("Internal dispatch error");
+ return jerry_create_error((jerry_error_t)IOTJS_ERROR_COMMON, jmsg);
+ }
+
+ IOTJS_ASSERT(target_function_ptr != 0x0);
+
+ iotjs_jhandler_t jhandler;
+ iotjs_jhandler_initialize(&jhandler, jfunc, jthis, jargv, jargc);
+
+ ((iotjs_native_handler_t)target_function_ptr)(&jhandler);
+
+ jerry_value_t ret_val = jhandler.unsafe.jret.unsafe.value;
+ iotjs_jhandler_destroy(&jhandler);
+ return ret_val;
+ }
+
+
+ iotjs_jval_t iotjs_jval_create_function_with_dispatch(
+ iotjs_native_handler_t handler) {
+ iotjs_jval_t jfunc =
+ iotjs_jval_create_function(iotjs_native_dispatch_function);
+ iotjs_jval_set_object_native_handle(&jfunc, (uintptr_t)handler, NULL);
+ return jfunc;
+ }
+
+
+ void iotjs_binding_initialize() {
+ jundefined = iotjs_jval_create_raw(jerry_create_undefined());
+ jnull = iotjs_jval_create_raw(jerry_create_null());
+ jtrue = iotjs_jval_create_raw(jerry_create_boolean(true));
+ jfalse = iotjs_jval_create_raw(jerry_create_boolean(false));
+ jglobal = iotjs_jval_create_raw(jerry_get_global_object());
+
+ IOTJS_ASSERT(iotjs_jval_is_object(&jglobal));
+
+ iotjs_jargs_initialize_empty(&jargs_empty);
+
+ #ifdef NDEBUG
+ assert(sizeof(iotjs_jval_t) == sizeof(jerry_value_t));
+ #endif
+ }
+
+
+ void iotjs_binding_finalize() {
+ iotjs_jval_destroy(&jundefined);
+ iotjs_jval_destroy(&jnull);
+ iotjs_jval_destroy(&jtrue);
+ iotjs_jval_destroy(&jfalse);
+ iotjs_jval_destroy(&jglobal);
+ iotjs_jargs_destroy(&jargs_empty);
+ }
--- /dev/null
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 IOTJS_BINDING_H
+ #define IOTJS_BINDING_H
+
+ #include "iotjs_util.h"
+ #include "jerryscript.h"
+
+ #include <stdio.h>
+
+
+ typedef jerry_external_handler_t JHandlerType;
+ typedef const jerry_object_native_info_t* JNativeInfoType;
+ typedef jerry_length_t JRawLengthType;
+
+
+ typedef enum {
+ IOTJS_ERROR_COMMON = JERRY_ERROR_COMMON,
+ IOTJS_ERROR_EVAL = JERRY_ERROR_EVAL,
+ IOTJS_ERROR_RANGE = JERRY_ERROR_RANGE,
+ IOTJS_ERROR_REFERENCE = JERRY_ERROR_REFERENCE,
+ IOTJS_ERROR_SYNTAX = JERRY_ERROR_SYNTAX,
+ IOTJS_ERROR_TYPE = JERRY_ERROR_TYPE,
+ IOTJS_ERROR_URI = JERRY_ERROR_URI
+ } iotjs_error_t;
+
+
+ #define FOR_EACH_JVAL_TYPES(F) \
+ F(undefined) \
+ F(null) \
+ F(boolean) \
+ F(number) \
+ F(string) \
+ F(object) \
+ F(array) \
+ F(function)
+
+
+ typedef struct {
+ jerry_value_t value; // JavaScript value representation
+ } IOTJS_VALIDATED_STRUCT(iotjs_jval_t);
+
+ typedef struct {
+ iotjs_jval_t jfunc;
+ iotjs_jval_t jthis;
+ iotjs_jval_t* jargv;
+ iotjs_jval_t jret;
+ uint16_t jargc;
+ #ifndef NDEBUG
+ bool finished;
+ #endif
+ } IOTJS_VALIDATED_STRUCT(iotjs_jhandler_t);
+
+ typedef void (*iotjs_native_handler_t)(iotjs_jhandler_t* jhandler);
+
+
+ /* Constructors */
+ iotjs_jval_t iotjs_jval_create_number(double v);
+ iotjs_jval_t iotjs_jval_create_string(const iotjs_string_t* v);
+ iotjs_jval_t iotjs_jval_create_string_raw(const char* data);
+ iotjs_jval_t iotjs_jval_create_object();
+ iotjs_jval_t iotjs_jval_create_array(uint32_t len);
+ iotjs_jval_t iotjs_jval_create_byte_array(uint32_t len, const char* data);
+ iotjs_jval_t iotjs_jval_create_function(JHandlerType handler);
+ iotjs_jval_t iotjs_jval_create_error(const char* msg);
+ iotjs_jval_t iotjs_jval_create_error_type(iotjs_error_t type, const char* msg);
+ iotjs_jval_t iotjs_jval_create_copied(const iotjs_jval_t* other);
+
+ iotjs_jval_t iotjs_jval_get_string_size(const iotjs_string_t* str);
+
+ iotjs_jval_t* iotjs_jval_get_undefined();
+ iotjs_jval_t* iotjs_jval_get_null();
+ iotjs_jval_t* iotjs_jval_get_boolean(bool v);
+ iotjs_jval_t* iotjs_jval_get_global_object();
+
+ /* Destructor */
+ void iotjs_jval_destroy(iotjs_jval_t* jval);
+
+ #define THIS_JVAL const iotjs_jval_t* jval
+
+ /* Type Checkers */
+ bool iotjs_jval_is_undefined(THIS_JVAL);
+ bool iotjs_jval_is_null(THIS_JVAL);
+ bool iotjs_jval_is_boolean(THIS_JVAL);
+ bool iotjs_jval_is_number(THIS_JVAL);
+ bool iotjs_jval_is_string(THIS_JVAL);
+ bool iotjs_jval_is_object(THIS_JVAL);
+ bool iotjs_jval_is_array(THIS_JVAL);
+ bool iotjs_jval_is_function(THIS_JVAL);
+
+ /* Type Converters */
+ bool iotjs_jval_as_boolean(THIS_JVAL);
+ double iotjs_jval_as_number(THIS_JVAL);
+ iotjs_string_t iotjs_jval_as_string(THIS_JVAL);
+ const iotjs_jval_t* iotjs_jval_as_object(THIS_JVAL);
+ const iotjs_jval_t* iotjs_jval_as_array(THIS_JVAL);
+ const iotjs_jval_t* iotjs_jval_as_function(THIS_JVAL);
+
+ /* Methods for General JavaScript Object */
+ void iotjs_jval_set_method(THIS_JVAL, const char* name,
+ iotjs_native_handler_t handler);
+ void iotjs_jval_set_property_jval(THIS_JVAL, const char* name,
+ const iotjs_jval_t* value);
+ void iotjs_jval_set_property_null(THIS_JVAL, const char* name);
+ void iotjs_jval_set_property_undefined(THIS_JVAL, const char* name);
+ void iotjs_jval_set_property_boolean(THIS_JVAL, const char* name, bool v);
+ void iotjs_jval_set_property_number(THIS_JVAL, const char* name, double v);
+ void iotjs_jval_set_property_string(THIS_JVAL, const char* name,
+ const iotjs_string_t* v);
+ void iotjs_jval_set_property_string_raw(THIS_JVAL, const char* name,
+ const char* v);
+
+ iotjs_jval_t iotjs_jval_get_property(THIS_JVAL, const char* name);
+
+ void iotjs_jval_set_object_native_handle(THIS_JVAL, uintptr_t ptr,
+ JNativeInfoType native_info);
+ uintptr_t iotjs_jval_get_object_native_handle(THIS_JVAL);
+ uintptr_t iotjs_jval_get_object_from_jhandler(iotjs_jhandler_t* jhandler,
+ JNativeInfoType native_info);
++uintptr_t iotjs_jval_get_arg_obj_from_jhandler(iotjs_jhandler_t* jhandler,
++ uint16_t index,
++ JNativeInfoType native_info);
+
+ void iotjs_jval_set_property_by_index(THIS_JVAL, uint32_t idx,
+ const iotjs_jval_t* value);
+ iotjs_jval_t iotjs_jval_get_property_by_index(THIS_JVAL, uint32_t idx);
+
+
+ #undef THIS_JVAL
+
+
+ typedef struct {
+ uint16_t capacity;
+ uint16_t argc;
+ iotjs_jval_t* argv;
+ } IOTJS_VALIDATED_STRUCT(iotjs_jargs_t);
+
+
+ iotjs_jargs_t iotjs_jargs_create(uint16_t capacity);
+
+ const iotjs_jargs_t* iotjs_jargs_get_empty();
+
+ void iotjs_jargs_destroy(iotjs_jargs_t* jargs);
+
+ uint16_t iotjs_jargs_length(const iotjs_jargs_t* jargs);
+
+ void iotjs_jargs_append_jval(iotjs_jargs_t* jargs, const iotjs_jval_t* x);
+ void iotjs_jargs_append_undefined(iotjs_jargs_t* jargs);
+ void iotjs_jargs_append_null(iotjs_jargs_t* jargs);
+ void iotjs_jargs_append_bool(iotjs_jargs_t* jargs, bool x);
+ void iotjs_jargs_append_number(iotjs_jargs_t* jargs, double x);
+ void iotjs_jargs_append_string(iotjs_jargs_t* jargs, const iotjs_string_t* x);
+ void iotjs_jargs_append_string_raw(iotjs_jargs_t* jargs, const char* x);
+ void iotjs_jargs_append_error(iotjs_jargs_t* jargs, const char* msg);
+
+
+ void iotjs_jargs_replace(iotjs_jargs_t* jargs, uint16_t index,
+ const iotjs_jval_t* x);
+
+ const iotjs_jval_t* iotjs_jargs_get(const iotjs_jargs_t* jargs, uint16_t index);
+
+
+ // Calls JavaScript function.
+ iotjs_jval_t iotjs_jhelper_call(const iotjs_jval_t* jfunc,
+ const iotjs_jval_t* jthis,
+ const iotjs_jargs_t* jargs, bool* throws);
+
+ // Calls javascript function.
+ iotjs_jval_t iotjs_jhelper_call_ok(const iotjs_jval_t* jfunc,
+ const iotjs_jval_t* jthis,
+ const iotjs_jargs_t* jargs);
+
+ // Evaluates javascript source file.
+ iotjs_jval_t iotjs_jhelper_eval(const char* name, size_t name_len,
+ const uint8_t* data, size_t size,
+ bool strict_mode, bool* throws);
+ #ifdef ENABLE_SNAPSHOT
+ // Evaluates javascript snapshot.
+ iotjs_jval_t iotjs_jhelper_exec_snapshot(const void* snapshot_p,
+ size_t snapshot_size, bool* throws);
+ #endif
+
+
+ void iotjs_jhandler_initialize(iotjs_jhandler_t* jhandler,
+ const jerry_value_t jfunc,
+ const jerry_value_t jthis,
+ const jerry_value_t jargv[],
+ const uint16_t jargc);
+
+ void iotjs_jhandler_destroy(iotjs_jhandler_t* jhandler);
+
+ const iotjs_jval_t* iotjs_jhandler_get_function(iotjs_jhandler_t* jhandler);
+ const iotjs_jval_t* iotjs_jhandler_get_this(iotjs_jhandler_t* jhandler);
+ const iotjs_jval_t* iotjs_jhandler_get_arg(iotjs_jhandler_t* jhandler,
+ uint16_t index);
+ uint16_t iotjs_jhandler_get_arg_length(iotjs_jhandler_t* jhandler);
+
+ void iotjs_jhandler_return_jval(iotjs_jhandler_t* jhandler,
+ const iotjs_jval_t* ret);
+ void iotjs_jhandler_return_undefined(iotjs_jhandler_t* jhandler);
+ void iotjs_jhandler_return_null(iotjs_jhandler_t* jhandler);
+ void iotjs_jhandler_return_boolean(iotjs_jhandler_t* jhandler, bool x);
+ void iotjs_jhandler_return_number(iotjs_jhandler_t* jhandler, double x);
+ void iotjs_jhandler_return_string(iotjs_jhandler_t* jhandler,
+ const iotjs_string_t* x);
+ void iotjs_jhandler_return_string_raw(iotjs_jhandler_t* jhandler,
+ const char* x);
+
+ void iotjs_jhandler_throw(iotjs_jhandler_t* jhandler, const iotjs_jval_t* err);
+
+ iotjs_jval_t iotjs_jval_create_function_with_dispatch(
+ iotjs_native_handler_t handler);
+
+
+ #define JHANDLER_THROW(TYPE, message) \
+ iotjs_jval_t e = iotjs_jval_create_error_type(IOTJS_ERROR_##TYPE, message); \
+ iotjs_jhandler_throw(jhandler, &e); \
+ iotjs_jval_destroy(&e);
+
+ #define JHANDLER_CHECK(predicate) \
+ if (!(predicate)) { \
+ char buffer[64]; \
+ snprintf(buffer, 63, "Internal error (%s)", __func__); \
+ JHANDLER_THROW(COMMON, buffer) \
+ return; \
+ }
+
+ #define JHANDLER_CHECK_TYPE(jval, type) \
+ JHANDLER_CHECK(iotjs_jval_is_##type(jval));
+
+ #define JHANDLER_CHECK_ARG(index, type) \
+ JHANDLER_CHECK_TYPE(iotjs_jhandler_get_arg(jhandler, index), type);
+
+ #define JHANDLER_CHECK_ARG_IF_EXIST(index, type) \
+ if (iotjs_jhandler_get_arg_length(jhandler) > index) { \
+ JHANDLER_CHECK_TYPE(iotjs_jhandler_get_arg(jhandler, index), type); \
+ }
+
+ #define JHANDLER_CHECK_ARGS_0()
+
+ #define JHANDLER_CHECK_ARGS_1(type0) \
+ JHANDLER_CHECK_ARGS_0(); \
+ JHANDLER_CHECK_ARG(0, type0);
+
+ #define JHANDLER_CHECK_ARGS_2(type0, type1) \
+ JHANDLER_CHECK_ARGS_1(type0); \
+ JHANDLER_CHECK_ARG(1, type1);
+
+ #define JHANDLER_CHECK_ARGS_3(type0, type1, type2) \
+ JHANDLER_CHECK_ARGS_2(type0, type1); \
+ JHANDLER_CHECK_ARG(2, type2);
+
+ #define JHANDLER_CHECK_ARGS_4(type0, type1, type2, type3) \
+ JHANDLER_CHECK_ARGS_3(type0, type1, type2); \
+ JHANDLER_CHECK_ARG(3, type3);
+
+ #define JHANDLER_CHECK_ARGS_5(type0, type1, type2, type3, type4) \
+ JHANDLER_CHECK_ARGS_4(type0, type1, type2, type3); \
+ JHANDLER_CHECK_ARG(4, type4);
+
+ // Workaround for GCC type-limits warning
+ static inline bool ge(uint16_t a, uint16_t b) {
+ return a >= b;
+ }
+
+ #define JHANDLER_CHECK_ARGS(argc, ...) \
+ JHANDLER_CHECK(ge(iotjs_jhandler_get_arg_length(jhandler), argc)); \
+ JHANDLER_CHECK_ARGS_##argc(__VA_ARGS__)
+
+ #define JHANDLER_CHECK_THIS(type) \
+ JHANDLER_CHECK_TYPE(iotjs_jhandler_get_this(jhandler), type);
+
+ #define JHANDLER_GET_ARG(index, type) \
+ iotjs_jval_as_##type(iotjs_jhandler_get_arg(jhandler, index))
+
+ #define JHANDLER_GET_ARG_IF_EXIST(index, type) \
+ ((iotjs_jhandler_get_arg_length(jhandler) > index) \
+ ? (iotjs_jval_is_##type(iotjs_jhandler_get_arg(jhandler, index)) \
+ ? iotjs_jhandler_get_arg(jhandler, index) \
+ : NULL) \
+ : NULL)
+
+ #define JHANDLER_GET_THIS(type) \
+ iotjs_jval_as_##type(iotjs_jhandler_get_this(jhandler))
+
+ #define JHANDLER_FUNCTION(name) static void name(iotjs_jhandler_t* jhandler)
+
+ #if defined(EXPERIMENTAL) && !defined(DEBUG)
+ // This code branch is to be in #ifdef NDEBUG
+ #define DJHANDLER_CHECK_ARG(index, type) ((void)0)
+ #define DJHANDLER_CHECK_ARGS(argc, ...) ((void)0)
+ #define DJHANDLER_CHECK_THIS(type) ((void)0)
+ #define DJHANDLER_CHECK_ARG_IF_EXIST(index, type) ((void)0)
+ #else
+ #define DJHANDLER_CHECK_ARG(index, type) JHANDLER_CHECK_ARG(index, type)
+ #define DJHANDLER_CHECK_ARGS(argc, ...) JHANDLER_CHECK_ARGS(argc, __VA_ARGS__)
+ #define DJHANDLER_CHECK_THIS(type) JHANDLER_CHECK_THIS(type)
+ #define DJHANDLER_CHECK_ARG_IF_EXIST(index, type) \
+ JHANDLER_CHECK_ARG_IF_EXIST(index, type)
+ #endif
+
+ #define JHANDLER_DECLARE_THIS_PTR(type, name) \
+ iotjs_##type##_t* name = (iotjs_##type##_t*) \
+ iotjs_jval_get_object_from_jhandler(jhandler, &this_module_native_info); \
+ if (!name) { \
+ return; \
+ }
+
++#define JHANDLER_DECLARE_OBJECT_PTR(index, type, name) \
++ iotjs_##type##_t* name = (iotjs_##type##_t*) \
++ iotjs_jval_get_arg_obj_from_jhandler(jhandler, index, \
++ &this_module_native_info); \
++ if (!name) { \
++ return; \
++ }
++
+ void iotjs_binding_initialize();
+ void iotjs_binding_finalize();
+
+
+ #endif /* IOTJS_BINDING_H */
--- /dev/null
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 IOTJS_DEF_H
+ #define IOTJS_DEF_H
+
+
+ #ifndef IOTJS_MAX_READ_BUFFER_SIZE
+ #if defined(__NUTTX__) || defined(__TIZENRT__)
+ #define IOTJS_MAX_READ_BUFFER_SIZE 1023
+ #define IOTJS_MAX_PATH_SIZE 120
+ #else
+ #define IOTJS_MAX_READ_BUFFER_SIZE 65535
+ #define IOTJS_MAX_PATH_SIZE PATH_MAX
+ #endif
+ #endif
+
+
+ #ifndef IOTJS_ASSERT
+ #ifdef NDEBUG
+ #define IOTJS_ASSERT(x) ((void)(x))
+ #else
+ #define IOTJS_ASSERT(x) assert(x)
+ #endif
+ #endif
+
+
+ #if defined(__arm__)
+ #define TARGET_ARCH "arm"
+ #elif defined(__i686__)
+ #define TARGET_ARCH "ia32"
+ #elif defined(__x86_64__)
+ #define TARGET_ARCH "x64"
+ #else
+ #define TARGET_ARCH "unknown"
+ #endif
+
+
+ #if defined(__linux__)
+ #define TARGET_OS "linux"
+ #elif defined(__NUTTX__)
+ #define TARGET_OS "nuttx"
+ #elif defined(__APPLE__)
+ #define TARGET_OS "darwin"
+ #elif defined(__TIZENRT__)
+ #define TARGET_OS "tizenrt"
+ #else
+ #define TARGET_OS "unknown"
+ #endif
+
++#define IOTJS_VERSION "1.0.0"
++
+ #if !defined(STRINGIFY)
+ #define STRINGIFY(x) #x
+ #endif
+
+ #if !defined(TOSTRING)
+ #define TOSTRING(x) STRINGIFY(x)
+ #endif
+
+
+ #if !defined(TARGET_BOARD)
+ #define TARGET_BOARD "unknown"
+ #endif
+
+
+ #define IOTJS_VALID_MAGIC_SEQUENCE 0xfee1c001 /* feel cool */
+ #define IOTJS_INVALID_MAGIC_SEQUENCE 0xfee1badd /* feel bad */
+
+ #define IOTJS_DECLARE_THIS(iotjs_classname_t, x) \
+ iotjs_classname_t##_impl_t* _this = &(x)->unsafe;
+
+ /* Avoid compiler warnings if needed. */
+ #define IOTJS_UNUSED(x) ((void)(x))
+
+
+ #ifdef NDEBUG
+
+ #define IOTJS_VALIDATED_STRUCT(iotjs_classname_t) \
+ iotjs_classname_t##_impl_t; \
+ typedef struct iotjs_classname_t { \
+ iotjs_classname_t##_impl_t unsafe; \
+ } iotjs_classname_t;
+
+ #define IOTJS_VALIDATED_STRUCT_STATIC_INITIALIZER(...) __VA_ARGS__
+
+ #define IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_classname_t, x) \
+ IOTJS_DECLARE_THIS(iotjs_classname_t, x);
+ #define IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_classname_t, x) \
+ IOTJS_DECLARE_THIS(iotjs_classname_t, x);
+ #define IOTJS_VALIDATED_STRUCT_METHOD(iotjs_classname_t, x) \
+ IOTJS_DECLARE_THIS(iotjs_classname_t, x);
+
+ #define IOTJS_VALIDATABLE_STRUCT_DESTRUCTOR_VALIDATE(iotjs_classname_t, x)
+ #define IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_classname_t, x)
+
+ #else /* !NDEBUG */
+
+ #define IOTJS_VALIDATED_STRUCT(iotjs_classname_t) \
+ iotjs_classname_t##_impl_t; \
+ typedef struct iotjs_classname_t { \
+ iotjs_classname_t##_impl_t unsafe; \
+ uint32_t flag_create; \
+ char* valgrind_tracer; \
+ } iotjs_classname_t;
+
+ #define IOTJS_VALIDATED_STRUCT_STATIC_INITIALIZER(...) \
+ { IOTJS_VALID_MAGIC_SEQUENCE, iotjs_buffer_allocate(4), __VA_ARGS__ }
+
+ #define IOTJS_VALIDATE_FLAG(iotjs_classname_t, x) \
+ if ((x)->flag_create != IOTJS_VALID_MAGIC_SEQUENCE) { \
+ DLOG("`%s %s` is not initialized properly.", #iotjs_classname_t, #x); \
+ IOTJS_ASSERT(false); \
+ }
+
+ #define IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_classname_t, x) \
+ IOTJS_DECLARE_THIS(iotjs_classname_t, x); \
+ /* IOTJS_ASSERT((x)->flag_create != IOTJS_VALID_MAGIC_SEQUENCE); */ \
+ (x)->flag_create = IOTJS_VALID_MAGIC_SEQUENCE; \
+ (x)->valgrind_tracer = iotjs_buffer_allocate(4);
+
+ #define IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_classname_t, x) \
+ IOTJS_DECLARE_THIS(iotjs_classname_t, x); \
+ IOTJS_VALIDATE_FLAG(iotjs_classname_t, x); \
+ (x)->flag_create = IOTJS_INVALID_MAGIC_SEQUENCE; \
+ iotjs_buffer_release((x)->valgrind_tracer);
+
+ #define IOTJS_VALIDATED_STRUCT_METHOD(iotjs_classname_t, x) \
+ IOTJS_DECLARE_THIS(iotjs_classname_t, x); \
+ IOTJS_VALIDATE_FLAG(iotjs_classname_t, x);
+
+ #define IOTJS_VALIDATABLE_STRUCT_DESTRUCTOR_VALIDATE(iotjs_classname_t, x) \
+ IOTJS_VALIDATE_FLAG(iotjs_classname_t, x); \
+ (x)->flag_create = IOTJS_INVALID_MAGIC_SEQUENCE; \
+ iotjs_buffer_release((x)->valgrind_tracer);
+
+ #define IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_classname_t, x) \
+ IOTJS_VALIDATE_FLAG(iotjs_classname_t, x);
+
+ #endif /* NDEBUG */
+
+ #include <uv.h>
+ #include <assert.h>
+ #include <limits.h> /* PATH_MAX */
+ #include <stdbool.h>
+ #include <string.h>
+
+ // commonly used header files
+ #include "iotjs_binding.h"
+ #include "iotjs_binding_helper.h"
+ #include "iotjs_debuglog.h"
+ #include "iotjs_env.h"
+ #include "iotjs_magic_strings.h"
+ #include "iotjs_module.h"
+ #include "iotjs_string.h"
+ #include "iotjs_util.h"
+
+
+ #endif /* IOTJS_DEF_H */
--- /dev/null
+ /* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 IOTJS_STRING_CONSTANTS_H
+ #define IOTJS_STRING_CONSTANTS_H
+
+ #define IOTJS_MAGIC_STRING_0 "0"
+ #define IOTJS_MAGIC_STRING_1 "1"
+ #define IOTJS_MAGIC_STRING_2 "2"
+ #define IOTJS_MAGIC_STRING_3 "3"
+ #define IOTJS_MAGIC_STRING_ABORT "abort"
+ #define IOTJS_MAGIC_STRING_ADC "Adc"
+ #define IOTJS_MAGIC_STRING_ADDHEADER "addHeader"
+ #define IOTJS_MAGIC_STRING_ADDMEMBERSHIP "addMembership"
+ #define IOTJS_MAGIC_STRING_ADDRESS "address"
+ #define IOTJS_MAGIC_STRING_ARCH "arch"
+ #define IOTJS_MAGIC_STRING_ARGV "argv"
+ #define IOTJS_MAGIC_STRING_BAUDRATE "baudRate"
+ #define IOTJS_MAGIC_STRING_BIND "bind"
+ #define IOTJS_MAGIC_STRING_BINDCONTROL "bindControl"
+ #define IOTJS_MAGIC_STRING_BINDING "binding"
+ #define IOTJS_MAGIC_STRING_BINDRAW "bindRaw"
+ #define IOTJS_MAGIC_STRING_BINDUSER "bindUser"
+ #define IOTJS_MAGIC_STRING_BITORDER "bitOrder"
+ #define IOTJS_MAGIC_STRING_BITORDER_U "BITORDER"
+ #define IOTJS_MAGIC_STRING_BITSPERWORD "bitsPerWord"
+ #define IOTJS_MAGIC_STRING_BOARD "board"
+ #define IOTJS_MAGIC_STRING_BOTH_U "BOTH"
+ #define IOTJS_MAGIC_STRING_BUFFER "Buffer"
+ #define IOTJS_MAGIC_STRING__BUFFER "_buffer"
+ #define IOTJS_MAGIC_STRING__BUILTIN "_builtin"
++#define IOTJS_MAGIC_STRING_BUS "bus"
+ #define IOTJS_MAGIC_STRING_BYTELENGTH "byteLength"
+ #define IOTJS_MAGIC_STRING_BYTEPARSED "byteParsed"
+ #define IOTJS_MAGIC_STRING_CA "ca"
+ #define IOTJS_MAGIC_STRING_CERT "cert"
+ #define IOTJS_MAGIC_STRING_CHDIR "chdir"
+ #define IOTJS_MAGIC_STRING_CHIP "chip"
+ #define IOTJS_MAGIC_STRING_CHIPSELECT "chipSelect"
+ #define IOTJS_MAGIC_STRING_CHIPSELECT_U "CHIPSELECT"
+ #define IOTJS_MAGIC_STRING_CLOSE "close"
+ #define IOTJS_MAGIC_STRING_CLOSESYNC "closeSync"
+ #define IOTJS_MAGIC_STRING_CODE "code"
+ #define IOTJS_MAGIC_STRING_COMPARE "compare"
+ #define IOTJS_MAGIC_STRING_COMPILE "compile"
+ #define IOTJS_MAGIC_STRING_COMPILENATIVEPTR "compileNativePtr"
+ #define IOTJS_MAGIC_STRING_CONNECT "connect"
+ #define IOTJS_MAGIC_STRING_COPY "copy"
+ #define IOTJS_MAGIC_STRING_CREATEREQUEST "createRequest"
+ #define IOTJS_MAGIC_STRING__CREATESTAT "_createStat"
+ #define IOTJS_MAGIC_STRING_CREATETCP "createTCP"
+ #define IOTJS_MAGIC_STRING_CWD "cwd"
+ #define IOTJS_MAGIC_STRING_DATABITS "dataBits"
+ #define IOTJS_MAGIC_STRING_DEVICE "device"
+ #define IOTJS_MAGIC_STRING_DIRECTION "direction"
+ #define IOTJS_MAGIC_STRING_DIRECTION_U "DIRECTION"
+ #define IOTJS_MAGIC_STRING_DOEXIT "doExit"
+ #define IOTJS_MAGIC_STRING_DROPMEMBERSHIP "dropMembership"
+ #define IOTJS_MAGIC_STRING_DUTYCYCLE "dutyCycle"
+ #define IOTJS_MAGIC_STRING_EDGE "edge"
+ #define IOTJS_MAGIC_STRING_EDGE_U "EDGE"
+ #define IOTJS_MAGIC_STRING_EMIT "emit"
+ #define IOTJS_MAGIC_STRING_EMITEXIT "emitExit"
+ #define IOTJS_MAGIC_STRING_ENV "env"
+ #define IOTJS_MAGIC_STRING_ERRNAME "errname"
+ #define IOTJS_MAGIC_STRING_EXECUTE "execute"
+ #define IOTJS_MAGIC_STRING_EXPORT "export"
+ #define IOTJS_MAGIC_STRING_FALLING_U "FALLING"
+ #define IOTJS_MAGIC_STRING_FAMILY "family"
+ #define IOTJS_MAGIC_STRING_FINISH "finish"
+ #define IOTJS_MAGIC_STRING_FINISHREQUEST "finishRequest"
+ #define IOTJS_MAGIC_STRING_FLOAT "FLOAT"
+ #define IOTJS_MAGIC_STRING_FSTAT "fstat"
+ #define IOTJS_MAGIC_STRING_GETADDRINFO "getaddrinfo"
+ #define IOTJS_MAGIC_STRING_GETSOCKNAME "getsockname"
+ #define IOTJS_MAGIC_STRING_GPIO "Gpio"
+ #define IOTJS_MAGIC_STRING_HANDLER "handler"
+ #define IOTJS_MAGIC_STRING_HANDLETIMEOUT "handleTimeout"
+ #define IOTJS_MAGIC_STRING_HEADERS "headers"
+ #define IOTJS_MAGIC_STRING_HEXWRITE "hexWrite"
+ #define IOTJS_MAGIC_STRING_HIGH "HIGH"
+ #define IOTJS_MAGIC_STRING_HOME "HOME"
+ #define IOTJS_MAGIC_STRING_HOST "host"
+ #define IOTJS_MAGIC_STRING_HTTPPARSER "HTTPParser"
+ #define IOTJS_MAGIC_STRING_IN "IN"
+ #define IOTJS_MAGIC_STRING__INCOMING "_incoming"
+ #define IOTJS_MAGIC_STRING_IOTJS_ENV "IOTJS_ENV"
+ #define IOTJS_MAGIC_STRING_IOTJS_PATH "IOTJS_PATH"
+ #define IOTJS_MAGIC_STRING_IOTJS "iotjs"
+ #define IOTJS_MAGIC_STRING_IPV4 "IPv4"
+ #define IOTJS_MAGIC_STRING_IPV6 "IPv6"
+ #define IOTJS_MAGIC_STRING_ISALIVEEXCEPTFOR "isAliveExceptFor"
+ #define IOTJS_MAGIC_STRING_ISDEVUP "isDevUp"
+ #define IOTJS_MAGIC_STRING_KEY "key"
+ #define IOTJS_MAGIC_STRING_LENGTH "length"
+ #define IOTJS_MAGIC_STRING_LISTEN "listen"
+ #define IOTJS_MAGIC_STRING_LOOPBACK "loopback"
+ #define IOTJS_MAGIC_STRING_LSB "LSB"
+ #define IOTJS_MAGIC_STRING_MAXSPEED "maxSpeed"
+ #define IOTJS_MAGIC_STRING_METHOD "method"
+ #define IOTJS_MAGIC_STRING_METHODS "methods"
+ #define IOTJS_MAGIC_STRING_MKDIR "mkdir"
+ #define IOTJS_MAGIC_STRING_MODE "mode"
+ #define IOTJS_MAGIC_STRING_MODE_U "MODE"
+ #define IOTJS_MAGIC_STRING_MSB "MSB"
+ #define IOTJS_MAGIC_STRING_NATIVE_SOURCES "native_sources"
+ #define IOTJS_MAGIC_STRING_NONE "NONE"
+ #define IOTJS_MAGIC_STRING_ONBODY "OnBody"
+ #define IOTJS_MAGIC_STRING_ONCLOSE "onclose"
+ #define IOTJS_MAGIC_STRING_ONCLOSED "onClosed"
+ #define IOTJS_MAGIC_STRING_ONCONNECTION "onconnection"
+ #define IOTJS_MAGIC_STRING_ONDATA "onData"
+ #define IOTJS_MAGIC_STRING_ONEND "onEnd"
+ #define IOTJS_MAGIC_STRING_ONERROR "onError"
+ #define IOTJS_MAGIC_STRING_ONHEADERSCOMPLETE "OnHeadersComplete"
+ #define IOTJS_MAGIC_STRING_ONHEADERS "OnHeaders"
+ #define IOTJS_MAGIC_STRING_ONMESSAGECOMPLETE "OnMessageComplete"
+ #define IOTJS_MAGIC_STRING_ONMESSAGE "onmessage"
+ #define IOTJS_MAGIC_STRING__ONNEXTTICK "_onNextTick"
+ #define IOTJS_MAGIC_STRING_ONREAD "onread"
+ #define IOTJS_MAGIC_STRING_ONSOCKET "onSocket"
+ #define IOTJS_MAGIC_STRING_ONTIMEOUT "onTimeout"
+ #define IOTJS_MAGIC_STRING__ONUNCAUGHTEXCEPTION "_onUncaughtException"
+ #define IOTJS_MAGIC_STRING_ONWRITABLE "onWritable"
+ #define IOTJS_MAGIC_STRING_OPENDRAIN "OPENDRAIN"
+ #define IOTJS_MAGIC_STRING_OPEN "open"
+ #define IOTJS_MAGIC_STRING_OUT "OUT"
+ #define IOTJS_MAGIC_STRING_OWNER "owner"
+ #define IOTJS_MAGIC_STRING_PAUSE "pause"
+ #define IOTJS_MAGIC_STRING_PERIOD "period"
+ #define IOTJS_MAGIC_STRING_PIN "pin"
+ #define IOTJS_MAGIC_STRING_PLATFORM "platform"
+ #define IOTJS_MAGIC_STRING_PORT "port"
+ #define IOTJS_MAGIC_STRING_PROTOTYPE "prototype"
+ #define IOTJS_MAGIC_STRING_PULLDOWN "PULLDOWN"
+ #define IOTJS_MAGIC_STRING_PULLUP "PULLUP"
+ #define IOTJS_MAGIC_STRING_PUSHPULL "PUSHPULL"
+ #define IOTJS_MAGIC_STRING_READDIR "readdir"
+ #define IOTJS_MAGIC_STRING_READ "read"
+ #define IOTJS_MAGIC_STRING_READSOURCE "readSource"
+ #define IOTJS_MAGIC_STRING_READSTART "readStart"
+ #define IOTJS_MAGIC_STRING_READSYNC "readSync"
+ #define IOTJS_MAGIC_STRING_READUINT8 "readUInt8"
+ #define IOTJS_MAGIC_STRING_RECVSTART "recvStart"
+ #define IOTJS_MAGIC_STRING_RECVSTOP "recvStop"
+ #define IOTJS_MAGIC_STRING_REF "ref"
+ #define IOTJS_MAGIC_STRING_REINITIALIZE "reinitialize"
+ #define IOTJS_MAGIC_STRING_RENAME "rename"
+ #define IOTJS_MAGIC_STRING_REQUEST "REQUEST"
+ #define IOTJS_MAGIC_STRING_RESPONSE "RESPONSE"
+ #define IOTJS_MAGIC_STRING_RESUME "resume"
+ #define IOTJS_MAGIC_STRING__REUSEADDR "_reuseAddr"
+ #define IOTJS_MAGIC_STRING_RISING_U "RISING"
+ #define IOTJS_MAGIC_STRING_RMDIR "rmdir"
+ #define IOTJS_MAGIC_STRING_SEND "send"
+ #define IOTJS_MAGIC_STRING_SENDREQUEST "sendRequest"
+ #define IOTJS_MAGIC_STRING_SETADDRESS "setAddress"
+ #define IOTJS_MAGIC_STRING_SETBROADCAST "setBroadcast"
+ #define IOTJS_MAGIC_STRING_SETDUTYCYCLE "setDutyCycle"
+ #define IOTJS_MAGIC_STRING_SETENABLE "setEnable"
+ #define IOTJS_MAGIC_STRING_SETFILTER "setFilter"
+ #define IOTJS_MAGIC_STRING_SETFREQUENCY "setFrequency"
+ #define IOTJS_MAGIC_STRING_SETKEEPALIVE "setKeepAlive"
+ #define IOTJS_MAGIC_STRING_SETMULTICASTLOOPBACK "setMulticastLoopback"
+ #define IOTJS_MAGIC_STRING_SETMULTICASTTTL "setMulticastTTL"
+ #define IOTJS_MAGIC_STRING_SETPERIOD "setPeriod"
+ #define IOTJS_MAGIC_STRING_SETTIMEOUT "setTimeout"
+ #define IOTJS_MAGIC_STRING_SETTTL "setTTL"
+ #define IOTJS_MAGIC_STRING_SHOULDKEEPALIVE "shouldkeepalive"
+ #define IOTJS_MAGIC_STRING_SHUTDOWN "shutdown"
+ #define IOTJS_MAGIC_STRING_SLICE "slice"
+ #define IOTJS_MAGIC_STRING_SPI "Spi"
+ #define IOTJS_MAGIC_STRING_START "start"
+ #define IOTJS_MAGIC_STRING_STAT "stat"
+ #define IOTJS_MAGIC_STRING_STATUS_MSG "status_msg"
+ #define IOTJS_MAGIC_STRING_STATUS "status"
+ #define IOTJS_MAGIC_STRING_STDERR "stderr"
+ #define IOTJS_MAGIC_STRING_STDOUT "stdout"
+ #define IOTJS_MAGIC_STRING_STOP "stop"
+ #define IOTJS_MAGIC_STRING_TOHEXSTRING "toHexString"
+ #define IOTJS_MAGIC_STRING_TOSTRING "toString"
+ #define IOTJS_MAGIC_STRING_TRANSFERARRAY "transferArray"
+ #define IOTJS_MAGIC_STRING_TRANSFERBUFFER "transferBuffer"
+ #define IOTJS_MAGIC_STRING_UNEXPORT "unexport"
+ #define IOTJS_MAGIC_STRING_UNLINK "unlink"
+ #define IOTJS_MAGIC_STRING_UNREF "unref"
+ #define IOTJS_MAGIC_STRING_UPGRADE "upgrade"
+ #define IOTJS_MAGIC_STRING_URL "url"
++#define IOTJS_MAGIC_STRING_VERSION "version"
+ #define IOTJS_MAGIC_STRING_WRITESYNC "writeSync"
+ #define IOTJS_MAGIC_STRING_WRITEUINT8 "writeUInt8"
+ #define IOTJS_MAGIC_STRING_WRITE "write"
+ #define IOTJS_MAGIC_STRING__WRITE "_write"
+
+ #endif /* IOTJS_STRING_CONSTANTS_H */
--- /dev/null
- return this._builtin.compare(otherBuffer) == 0;
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 bufferBuiltin = process.binding(process.binding.buffer);
+ var util = require('util');
+
+
+ function checkInt(buffer, value, offset, ext, max, min) {
+ if (value > max || value < min)
+ throw new TypeError('value is out of bounds');
+ if (offset + ext > buffer.length)
+ throw new RangeError('index out of range');
+ }
+
+
+ function checkOffset(offset, ext, length) {
+ if (offset + ext > length)
+ throw new RangeError('index out of range');
+ }
+
+
+ // Buffer constructor
+ // [1] new Buffer(size)
+ // [2] new Buffer(buffer)
+ // [3] new Buffer(string)
+ // [4] new Buffer(string, encoding)
+ // [5] new Buffer(array)
+ function Buffer(subject, encoding) {
+ if (!util.isBuffer(this)) {
+ return new Buffer(subject);
+ }
+
+ if (util.isNumber(subject)) {
+ this.length = subject > 0 ? subject >>> 0 : 0;
+ } else if (util.isString(subject)) {
+ this.length = Buffer.byteLength(subject, encoding);
+ } else if (util.isBuffer(subject) || util.isArray(subject)) {
+ this.length = subject.length;
+ } else {
+ throw new TypeError('Bad arguments: Buffer(string|number|Buffer|Array)');
+ }
+
+ this._builtin = new bufferBuiltin(this, this.length);
+
+ if (util.isString(subject)) {
+ if (!util.isUndefined(encoding) && util.isString(encoding)) {
+ switch (encoding) {
+ case 'hex':
+ if (this._builtin.hexWrite(subject, 0, this.length) != this.length) {
+ throw new TypeError('Invalid hex string');
+ }
+ break;
+ default:
+ this.write(subject);
+ }
+ } else {
+ this.write(subject);
+ }
+ } else if (util.isBuffer(subject)) {
+ subject.copy(this);
+ } else if (util.isArray(subject)) {
+ for (var i = 0; i < this.length; ++i) {
+ this._builtin.writeUInt8(subject[i], i);
+ }
+ }
+ }
+
+
+ // Buffer.byteLength(string)
+ Buffer.byteLength = function(str, encoding) {
+ var len = bufferBuiltin.byteLength(str);
+
+ if (!util.isUndefined(encoding) && util.isString(encoding)) {
+ switch (encoding) {
+ case 'hex':
+ return len >>> 1;
+ }
+ }
+ return len;
+ };
+
+
+ // Buffer.concat(list)
+ Buffer.concat = function(list) {
+ if (!util.isArray(list)) {
+ throw new TypeError('Bad arguments: Buffer.concat([Buffer])');
+ }
+
+ var length = 0;
+ for (var i = 0; i < list.length; ++i) {
+ if (!util.isBuffer(list[i])) {
+ throw new TypeError('Bad arguments: Buffer.concat([Buffer])');
+ }
+ length += list[i].length;
+ }
+
+ var buffer = new Buffer(length);
+ var pos = 0;
+ for (var i = 0; i < list.length; ++i) {
+ list[i].copy(buffer, pos);
+ pos += list[i].length;
+ }
+
+ return buffer;
+ };
+
+
+ // Buffer.isBuffer(object)
+ Buffer.isBuffer = function(object) {
+ return util.isBuffer(object);
+ };
+
+
+ // buffer.equals(otherBuffer)
+ Buffer.prototype.equals = function(otherBuffer) {
+ if (!util.isBuffer(otherBuffer)) {
+ throw new TypeError('Bad arguments: buffer.equals(Buffer)');
+ }
+
- return this._builtin.compare(otherBuffer);
++ return this._builtin.compare(otherBuffer._builtin) == 0;
+ };
+
+
+ // buffer.compare(otherBuffer)
+ Buffer.prototype.compare = function(otherBuffer) {
+ if (!util.isBuffer(otherBuffer)) {
+ throw new TypeError('Bad arguments: buffer.compare(Buffer)');
+ }
+
++ return this._builtin.compare(otherBuffer._builtin);
+ };
+
+
+ // buffer.copy(target[, targetStart[, sourceStart[, sourceEnd]]])
+ // [1] buffer.copy(target)
+ // [2] buffer.copy(target, targetStart)
+ // [3] buffer.copy(target, targetStart, sourceStart)
+ // [4] buffer.copy(target, targetStart, sourceStart, sourceEnd)
+ // * targetStart - default to 0
+ // * sourceStart - default to 0
+ // * sourceEnd - default to buffer.length
+ Buffer.prototype.copy = function(target, targetStart, sourceStart, sourceEnd) {
+ if (!util.isBuffer(target)) {
+ throw new TypeError('Bad arguments: buff.copy(Buffer)');
+ }
+
+ targetStart = util.isUndefined(targetStart) ? 0 : ~~targetStart;
+ sourceStart = util.isUndefined(sourceStart) ? 0 : ~~sourceStart;
+ sourceEnd = util.isUndefined(sourceEnd) ? this.length : ~~ sourceEnd;
+
+ if ((sourceEnd > sourceStart) && (targetStart < 0)) {
+ throw new RangeError('Attempt to write outside buffer bounds');
+ }
+
+ return this._builtin.copy(target, targetStart, sourceStart, sourceEnd);
+ };
+
+
+ // buffer.write(string[, offset[, length]])
+ // [1] buffer.write(string)
+ // [2] buffer.write(string, offset)
+ // [3] buffer.write(string, offset, length)
+ // * offset - default to 0
+ // * length - default to buffer.length - offset
+ Buffer.prototype.write = function(string, offset, length) {
+ if (!util.isString(string)) {
+ throw new TypeError('Bad arguments: buff.write(string)');
+ }
+
+ offset = util.isUndefined(offset) ? 0 : ~~offset;
+ if (string.length > 0 && (offset < 0 || offset >= this.length)) {
+ throw new RangeError('Attempt to write outside buffer bounds');
+ }
+
+ var remaining = this.length - offset;
+ length = util.isUndefined(length) ? remaining : ~~length;
+
+ return this._builtin.write(string, offset, length);
+ };
+
+
+ // buff.slice([start[, end]])
+ // [1] buff.slice()
+ // [2] buff.slice(start)
+ // [3] buff.slice(start, end)
+ // * start - default to 0
+ // * end - default to buff.length
+ Buffer.prototype.slice = function(start, end) {
+ start = util.isUndefined(start) ? 0 : ~~start;
+ end = util.isUndefined(end) ? this.length : ~~end;
+
+ return this._builtin.slice(start, end);
+ };
+
+
+ // buff.toString([encoding,[,start[, end]]])
+ // [1] buff.toString()
+ // [2] buff.toString(start)
+ // [3] buff.toString(start, end)
+ // [4] buff.toString('hex')
+ // * start - default to 0
+ // * end - default to buff.length
+ Buffer.prototype.toString = function(start, end) {
+ if (util.isString(start) && start === "hex" && util.isUndefined(end)) {
+ return this._builtin.toHexString();
+ }
+ start = util.isUndefined(start) ? 0 : ~~start;
+ end = util.isUndefined(end) ? this.length : ~~end;
+
+ return this._builtin.toString(start, end);
+ };
+
+
+ // buff.writeUInt8(value, offset[,noAssert])
+ // [1] buff.writeUInt8(value, offset)
+ // [2] buff.writeUInt8(value, offset, noAssert)
+ Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
+ value = +value;
+ offset = offset >>> 0;
+ if (!noAssert)
+ checkInt(this, value, offset, 1, 0xff, 0);
+ this._builtin.writeUInt8(value & 0xff, offset);
+ return offset + 1;
+ };
+
+
+ // buff.writeUInt16LE(value, offset[,noAssert])
+ // [1] buff.writeUInt16LE(value, offset)
+ // [2] buff.writeUInt16LE(value, offset, noAssert)
+ Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
+ value = +value;
+ offset = offset >>> 0;
+ if (!noAssert)
+ checkInt(this, value, offset, 2, 0xffff, 0);
+ this._builtin.writeUInt8(value & 0xff, offset);
+ this._builtin.writeUInt8((value >>> 8) & 0xff, offset + 1);
+ return offset + 2;
+ };
+
+
+ // buff.writeUInt32LE(value, offset[,noAssert])
+ // [1] buff.writeUInt32LE(value, offset)
+ // [2] buff.writeUInt32LE(value, offset, noAssert)
+ Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
+ value = +value;
+ offset = offset >>> 0;
+ if (!noAssert)
+ checkInt(this, value, offset, 4, 0xffffffff, 0);
+ this._builtin.writeUInt8((value >>> 24) & 0xff, offset + 3);
+ this._builtin.writeUInt8((value >>> 16) & 0xff, offset + 2);
+ this._builtin.writeUInt8((value >>> 8) & 0xff, offset + 1);
+ this._builtin.writeUInt8(value & 0xff, offset);
+ return offset + 4;
+ };
+
+
+ // buff.readUInt8(offset[,noAssert])
+ // [1] buff.readUInt8(offset)
+ // [2] buff.readUInt8(offset, noAssert)
+ Buffer.prototype.readUInt8 = function(offset, noAssert) {
+ offset = offset >>> 0;
+ if (!noAssert)
+ checkOffset(offset, 1, this.length);
+ return this._builtin.readUInt8(offset);
+ };
+
+
+ // buff.readInt8(offset[,noAssert])
+ // [1] buff.readInt8(offset)
+ // [2] buff.readInt8(offset, noAssert)
+ Buffer.prototype.readInt8 = function(offset, noAssert) {
+ offset = offset >>> 0;
+ if (!noAssert)
+ checkOffset(offset, 1, this.length);
+ var val = this._builtin.readUInt8(offset);
+ return !(val & 0x80) ? val : (0xff - val + 1) * -1;
+ };
+
+
+ // buff.readUInt16LE(offset[,noAssert])
+ // [1] buff.readUInt16LE(offset)
+ // [2] buff.readUInt16LE(offset, noAssert)
+ Buffer.prototype.readUInt16LE = function(offset, noAssert) {
+ offset = offset >>> 0;
+ if (!noAssert)
+ checkOffset(offset, 2, this.length);
+ return this._builtin.readUInt8(offset) |
+ (this._builtin.readUInt8(offset + 1) << 8);
+ };
+
+
+ // buff.fill(value)
+ Buffer.prototype.fill = function(value) {
+ if (util.isNumber(value)) {
+ value = value & 255;
+ for (var i = 0; i < this.length; i++) {
+ this._builtin.writeUInt8(value, i);
+ }
+ }
+ return this;
+ };
+
+
+ module.exports = Buffer;
+ module.exports.Buffer = Buffer;
--- /dev/null
- // validate device
- if (util.isObject(configuration)) {
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 util = require('util');
+ var spi = process.binding(process.binding.spi);
+
+ var defaultConfiguration = {
+ mode : spi.MODE[0],
+ chipSelect : spi.CHIPSELECT.NONE,
+ maxSpeed : 500000,
+ bitsPerWord : 8,
+ bitOrder : spi.BITORDER.MSB,
+ loopback : false
+ };
+
+
+ function Spi() {
+ if (!(this instanceof Spi)) {
+ return new Spi();
+ }
+ }
+
+ Spi.prototype.open = function(configuration, callback) {
+ return spiBusOpen(configuration, callback);
+ };
+
+ Spi.prototype.MODE = spi.MODE;
+ Spi.prototype.CHIPSELECT = spi.CHIPSELECT;
+ Spi.prototype.BITORDER = spi.BITORDER;
+
+
+ function spiBusOpen(configuration, callback) {
+ var _binding = null;
+
+ function SpiBus(configuration, callback) {
+ var self = this;
+
- throw new TypeError(
- 'Bad configuration - device is mandatory and String');
++ if (process.platform === 'linux') {
+ if (!util.isString(configuration.device)) {
- } else {
- throw new TypeError('Bad arguments - configuration should be Object');
++ throw new TypeError('Bad configuration - device: String');
++ }
++ } else if (process.platform === 'nuttx') {
++ if (!util.isNumber(configuration.bus)) {
++ throw new TypeError('Bad configuration - bus: Number');
+ }
- return _binding.close(function(err) {
+ }
+
+ // validate mode
+ var mode = configuration.mode;
+ if (!util.isUndefined(mode)) {
+ if (mode !== spi.MODE[0] && mode !== spi.MODE[1] &&
+ mode !== spi.MODE[2] && mode !== spi.MODE[3]) {
+ throw new TypeError(
+ 'Bad arguments - mode should be MODE[0], [1], [2] or [3]');
+ }
+ } else {
+ configuration.mode = defaultConfiguration.mode;
+ }
+
+ // validate chip-select
+ var chipSelect = configuration.chipSelect;
+ if (!util.isUndefined(chipSelect)) {
+ if (chipSelect != spi.CHIPSELECT.NONE &&
+ chipSelect != spi.CHIPSELECT.HIGH) {
+ throw new TypeError(
+ 'Bad arguments - chipSelect should be CHIPSELECT.NONE or HIGH');
+ }
+ } else {
+ configuration.chipSelect = defaultConfiguration.chipSelect;
+ }
+
+ // validate max speed
+ if (!util.isUndefined(configuration.maxSpeed)) {
+ if (!util.isNumber(configuration.maxSpeed)) {
+ throw new TypeError('Bad arguments - maxSpeed should be Number');
+ }
+ } else {
+ configuration.maxSpeed = defaultConfiguration.maxSpeed
+ }
+
+ // validate bits per word
+ var bitsPerWord = configuration.bitsPerWord;
+ if (!util.isUndefined(bitsPerWord)) {
+ if (bitsPerWord != 8 && bitsPerWord != 9) {
+ throw new TypeError('Bad arguments - bitsPerWord should be 8 or 9');
+ }
+ } else {
+ configuration.bitsPerWord = defaultConfiguration.bitsPerWord;
+ }
+
+ // validate bit order
+ var bitOrder = configuration.bitOrder;
+ if (!util.isUndefined(bitOrder)) {
+ if (bitOrder != spi.BITORDER.MSB && bitOrder != spi.BITORDER.LSB) {
+ throw new TypeError(
+ 'Bad arguments - bitOrder should be BITORDER.MSB or LSB');
+ }
+ } else {
+ configuration.bitOrder = defaultConfiguration.bitOrder;
+ }
+
+ // validate loopback
+ var loopback = configuration.loopback;
+ if (!util.isUndefined(loopback)) {
+ if (!util.isBoolean(loopback)) {
+ throw new TypeError('Bad arguments - loopback should be Boolean');
+ }
+ } else {
+ configuration.loopback = defaultConfiguration.loopback;
+ }
+
+ _binding = new spi.Spi(configuration, function(err) {
+ util.isFunction(callback) && callback.call(self, err);
+ });
+
+ process.on('exit', (function(self) {
+ return function() {
+ if (!util.isNull(_binding)) {
+ self.closeSync();
+ }
+ };
+ })(this));
+ }
+
+ SpiBus.prototype.transfer = function(txBuffer, rxBuffer, callback) {
+ var self = this;
+
+ if (util.isNull(_binding)) {
+ throw new Error('SPI bus is not opened');
+ }
+
+ if (util.isUndefined(txBuffer.length) || util.isUndefined(rxBuffer.length)
+ || txBuffer.length <= 0 || rxBuffer.length <= 0
+ || txBuffer.length != rxBuffer.length) {
+ throw new Error('Bad arguments - buffer length');
+ }
+
+ var rxLength = rxBuffer.length;
+ var afterCallback = function(err, buffer) {
+ for (var i = 0; i < rxLength; i++) {
+ rxBuffer[i] = buffer[i];
+ }
+
+ util.isFunction(callback) && callback.call(self, err);
+ };
+
+ if (util.isArray(txBuffer) && util.isArray(rxBuffer)) {
+ _binding.transferArray(txBuffer, rxBuffer, afterCallback);
+ } else if (util.isBuffer(txBuffer) && util.isBuffer(rxBuffer)) {
+ _binding.transferBuffer(txBuffer, rxBuffer, afterCallback);
+ } else {
+ throw new TypeError('Bad arguments - buffer should be Array or Buffer');
+ }
+ };
+
+ SpiBus.prototype.transferSync = function(txBuffer, rxBuffer) {
+ if (util.isNull(_binding)) {
+ throw new Error('SPI bus is not opened');
+ }
+
+ if (util.isUndefined(txBuffer.length) || util.isUndefined(rxBuffer.length)
+ || txBuffer.length <= 0 || rxBuffer.length <= 0
+ || txBuffer.length != rxBuffer.length) {
+ throw new Error('Bad arguments - buffer length');
+ }
+
+ var data = null;
+ if (util.isArray(txBuffer) && util.isArray(rxBuffer)) {
+ data = _binding.transferArray(txBuffer, rxBuffer);
+ } else if (util.isBuffer(txBuffer) && util.isBuffer(rxBuffer)) {
+ data = _binding.transferBuffer(txBuffer, rxBuffer);
+ } else {
+ throw new TypeError('Bad arguments - buffer should be Array or Buffer');
+ }
+
+ if (data !== null && (util.isArray(data) || util.isBuffer(data)) &&
+ data.length === rxBuffer.length) {
+ for (var i = 0; i < rxBuffer.length; i++) {
+ rxBuffer[i] = data[i];
+ }
+ } else {
+ throw new Error('Spi Transfer Error');
+ }
+ };
+
+ SpiBus.prototype.close = function(callback) {
+ var self = this;
+
+ if (util.isNull(_binding)) {
+ throw new Error('SPI bus is not opened');
+ }
+
- return _binding.close();
++ _binding.close(function(err) {
+ util.isFunction(callback) && callback.call(self, err);
+ });
++ _binding = null;
+ };
+
+ SpiBus.prototype.closeSync = function() {
+ if (util.isNull(_binding)) {
+ throw new Error('SPI bus is not opened');
+ }
+
++ _binding.close();
++ _binding = null;
+ };
+
+ return new SpiBus(configuration, callback);
+ }
+
+
+ module.exports = Spi;
--- /dev/null
- DJHANDLER_CHECK_ARGS(1, object);
-
- const iotjs_jval_t* jdst_buffer = JHANDLER_GET_ARG(0, object);
- iotjs_bufferwrap_t* dst_buffer_wrap =
- iotjs_bufferwrap_from_jbuffer(jdst_buffer);
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 "iotjs_def.h"
+ #include "iotjs_module_buffer.h"
+
+ #include <math.h>
+ #include <stdlib.h>
+ #include <string.h>
+
+
+ IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(bufferwrap);
+
+
+ iotjs_bufferwrap_t* iotjs_bufferwrap_create(const iotjs_jval_t* jbuiltin,
+ size_t length) {
+ iotjs_bufferwrap_t* bufferwrap = IOTJS_ALLOC(iotjs_bufferwrap_t);
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_bufferwrap_t, bufferwrap);
+
+ iotjs_jobjectwrap_initialize(&_this->jobjectwrap, jbuiltin,
+ &this_module_native_info);
+ if (length > 0) {
+ _this->length = length;
+ _this->buffer = iotjs_buffer_allocate(length);
+ IOTJS_ASSERT(_this->buffer != NULL);
+ } else {
+ _this->length = 0;
+ _this->buffer = NULL;
+ }
+
+ IOTJS_ASSERT(
+ bufferwrap ==
+ (iotjs_bufferwrap_t*)(iotjs_jval_get_object_native_handle(jbuiltin)));
+
+ return bufferwrap;
+ }
+
+
+ static void iotjs_bufferwrap_destroy(iotjs_bufferwrap_t* bufferwrap) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_bufferwrap_t, bufferwrap);
+ if (_this->buffer != NULL) {
+ iotjs_buffer_release(_this->buffer);
+ }
+ iotjs_jobjectwrap_destroy(&_this->jobjectwrap);
+ IOTJS_RELEASE(bufferwrap);
+ }
+
+
+ iotjs_bufferwrap_t* iotjs_bufferwrap_from_jbuiltin(
+ const iotjs_jval_t* jbuiltin) {
+ IOTJS_ASSERT(iotjs_jval_is_object(jbuiltin));
+ iotjs_bufferwrap_t* buffer =
+ (iotjs_bufferwrap_t*)iotjs_jval_get_object_native_handle(jbuiltin);
+ IOTJS_ASSERT(buffer != NULL);
+ return buffer;
+ }
+
+
+ iotjs_bufferwrap_t* iotjs_bufferwrap_from_jbuffer(const iotjs_jval_t* jbuffer) {
+ IOTJS_ASSERT(iotjs_jval_is_object(jbuffer));
+ iotjs_jval_t jbuiltin =
+ iotjs_jval_get_property(jbuffer, IOTJS_MAGIC_STRING__BUILTIN);
+ iotjs_bufferwrap_t* buffer = iotjs_bufferwrap_from_jbuiltin(&jbuiltin);
+ iotjs_jval_destroy(&jbuiltin);
+ return buffer;
+ }
+
+
+ iotjs_jval_t* iotjs_bufferwrap_jbuiltin(iotjs_bufferwrap_t* bufferwrap) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_bufferwrap_t, bufferwrap);
+ return iotjs_jobjectwrap_jobject(&_this->jobjectwrap);
+ }
+
+
+ iotjs_jval_t iotjs_bufferwrap_jbuffer(iotjs_bufferwrap_t* bufferwrap) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_bufferwrap_t, bufferwrap);
+ iotjs_jval_t* jbuiltin = iotjs_bufferwrap_jbuiltin(bufferwrap);
+ return iotjs_jval_get_property(jbuiltin, IOTJS_MAGIC_STRING__BUFFER);
+ }
+
+
+ char* iotjs_bufferwrap_buffer(iotjs_bufferwrap_t* bufferwrap) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_bufferwrap_t, bufferwrap);
+ return _this->buffer;
+ }
+
+
+ size_t iotjs_bufferwrap_length(iotjs_bufferwrap_t* bufferwrap) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_bufferwrap_t, bufferwrap);
+ #ifndef NDEBUG
+ iotjs_jval_t jbuf = iotjs_bufferwrap_jbuffer(bufferwrap);
+ iotjs_jval_t jlength =
+ iotjs_jval_get_property(&jbuf, IOTJS_MAGIC_STRING_LENGTH);
+ size_t length = iotjs_jval_as_number(&jlength);
+ IOTJS_ASSERT(length == _this->length);
+ iotjs_jval_destroy(&jbuf);
+ iotjs_jval_destroy(&jlength);
+ #endif
+ return _this->length;
+ }
+
+
+ static size_t bound_range(size_t index, size_t low, size_t upper) {
+ if (index == SIZE_MAX) {
+ return low;
+ }
+ if (index > upper) {
+ return upper;
+ }
+ return index;
+ }
+
+
+ static int8_t hex2bin(char c) {
+ if (c >= '0' && c <= '9')
+ return (int8_t)(c - '0');
+ if (c >= 'A' && c <= 'F')
+ return (int8_t)(10 + (c - 'A'));
+ if (c >= 'a' && c <= 'f')
+ return (int8_t)(10 + (c - 'a'));
+
+ return (int8_t)(-1);
+ }
+
+
+ static size_t hex_decode(char* buf, size_t len, const char* src,
+ const size_t srcLen) {
+ size_t i;
+
+ for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) {
+ int8_t a = hex2bin(src[i * 2 + 0]);
+ int8_t b = hex2bin(src[i * 2 + 1]);
+ if (a == -1 || b == -1)
+ return i;
+ buf[i] = (a << 4) | b;
+ }
+
+ return i;
+ }
+
+
++static size_t iotjs_convert_double_to_sizet(double value) {
++ size_t new_value;
++
++ if (value < 0 || isnan(value) || isinf(value)) {
++ new_value = SIZE_MAX;
++ } else {
++ new_value = (size_t)value;
++ }
++
++ return new_value;
++}
++
++
+ int iotjs_bufferwrap_compare(const iotjs_bufferwrap_t* bufferwrap,
+ const iotjs_bufferwrap_t* other) {
+ const IOTJS_VALIDATED_STRUCT_METHOD(iotjs_bufferwrap_t, bufferwrap);
+
+ const char* other_buffer = other->unsafe.buffer;
+ size_t other_length = other->unsafe.length;
+
+ size_t i = 0;
+ size_t j = 0;
+ while (i < _this->length && j < other_length) {
+ if (_this->buffer[i] < other_buffer[j]) {
+ return -1;
+ } else if (_this->buffer[i] > other_buffer[j]) {
+ return 1;
+ }
+ ++i;
+ ++j;
+ }
+ if (j < other_length) {
+ return -1;
+ } else if (i < _this->length) {
+ return 1;
+ }
+ return 0;
+ }
+
+ size_t iotjs_bufferwrap_copy_internal(iotjs_bufferwrap_t* bufferwrap,
+ const char* src, size_t src_from,
+ size_t src_to, size_t dst_from) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_bufferwrap_t, bufferwrap);
+ size_t copied = 0;
+ size_t dst_length = _this->length;
+ for (size_t i = src_from, j = dst_from; i < src_to && j < dst_length;
+ ++i, ++j) {
+ *(_this->buffer + j) = *(src + i);
+ ++copied;
+ }
+ return copied;
+ }
+
+
+ size_t iotjs_bufferwrap_copy(iotjs_bufferwrap_t* bufferwrap, const char* src,
+ size_t len) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_bufferwrap_t, bufferwrap);
+ return iotjs_bufferwrap_copy_internal(bufferwrap, src, 0, len, 0);
+ }
+
+
+ iotjs_jval_t iotjs_bufferwrap_create_buffer(size_t len) {
+ iotjs_jval_t* jglobal = iotjs_jval_get_global_object();
+
+ iotjs_jval_t jbuffer =
+ iotjs_jval_get_property(jglobal, IOTJS_MAGIC_STRING_BUFFER);
+ IOTJS_ASSERT(iotjs_jval_is_function(&jbuffer));
+
+ iotjs_jargs_t jargs = iotjs_jargs_create(1);
+ iotjs_jargs_append_number(&jargs, len);
+
+ iotjs_jval_t jres =
+ iotjs_jhelper_call_ok(&jbuffer, iotjs_jval_get_undefined(), &jargs);
+ IOTJS_ASSERT(iotjs_jval_is_object(&jres));
+
+ iotjs_jargs_destroy(&jargs);
+ iotjs_jval_destroy(&jbuffer);
+
+ return jres;
+ }
+
+
+ JHANDLER_FUNCTION(Buffer) {
+ DJHANDLER_CHECK_THIS(object);
+ DJHANDLER_CHECK_ARGS(2, object, number);
+
+ const iotjs_jval_t* jbuiltin = JHANDLER_GET_THIS(object);
+ const iotjs_jval_t* jbuffer = JHANDLER_GET_ARG(0, object);
+ size_t length = JHANDLER_GET_ARG(1, number);
+
+ iotjs_jval_set_property_jval(jbuiltin, IOTJS_MAGIC_STRING__BUFFER, jbuffer);
+
+ iotjs_bufferwrap_t* buffer_wrap = iotjs_bufferwrap_create(jbuiltin, length);
+ IOTJS_UNUSED(buffer_wrap);
+ }
+
+
+ JHANDLER_FUNCTION(Compare) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, src_buffer_wrap);
-#define DECLARE_SIZE_T_FROM_DOUBLE(n, d) \
- size_t n; \
- do { \
- if (d < 0 || isnan(d) || isinf(d)) { \
- n = SIZE_MAX; \
- } else { \
- n = (size_t)d; \
- } \
- } while (0)
-
-
++ JHANDLER_DECLARE_OBJECT_PTR(0, bufferwrap, dst_buffer_wrap);
+
+ int compare = iotjs_bufferwrap_compare(src_buffer_wrap, dst_buffer_wrap);
+ iotjs_jhandler_return_number(jhandler, compare);
+ }
+
+
- DECLARE_SIZE_T_FROM_DOUBLE(dst_start, JHANDLER_GET_ARG(1, number));
+ JHANDLER_FUNCTION(Copy) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, src_buffer_wrap);
+ DJHANDLER_CHECK_ARGS(4, object, number, number, number);
+
+ const iotjs_jval_t* jdst_buffer = JHANDLER_GET_ARG(0, object);
+ iotjs_bufferwrap_t* dst_buffer_wrap =
+ iotjs_bufferwrap_from_jbuffer(jdst_buffer);
+
+ size_t dst_length = iotjs_bufferwrap_length(dst_buffer_wrap);
+ size_t src_length = iotjs_bufferwrap_length(src_buffer_wrap);
+
- DECLARE_SIZE_T_FROM_DOUBLE(src_start, JHANDLER_GET_ARG(2, number));
++ size_t dst_start = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(1, number));
+ dst_start = bound_range(dst_start, 0, dst_length);
+
- DECLARE_SIZE_T_FROM_DOUBLE(src_end, JHANDLER_GET_ARG(3, number));
++ size_t src_start = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(2, number));
+ src_start = bound_range(src_start, 0, src_length);
+
- DECLARE_SIZE_T_FROM_DOUBLE(offset, JHANDLER_GET_ARG(1, number));
++ size_t src_end = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(3, number));
+ src_end = bound_range(src_end, 0, src_length);
+
+ if (src_end < src_start) {
+ src_end = src_start;
+ }
+
+ const char* src_data = iotjs_bufferwrap_buffer(src_buffer_wrap);
+ size_t copied = iotjs_bufferwrap_copy_internal(dst_buffer_wrap, src_data,
+ src_start, src_end, dst_start);
+
+ iotjs_jhandler_return_number(jhandler, copied);
+ }
+
+
+ JHANDLER_FUNCTION(Write) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+ DJHANDLER_CHECK_ARGS(3, string, number, number);
+
+ iotjs_string_t src = JHANDLER_GET_ARG(0, string);
+
+ size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap);
- DECLARE_SIZE_T_FROM_DOUBLE(length, JHANDLER_GET_ARG(2, number));
++ size_t offset = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(1, number));
+ offset = bound_range(offset, 0, buffer_length);
+
- DECLARE_SIZE_T_FROM_DOUBLE(offset, JHANDLER_GET_ARG(1, number));
++ size_t length = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(2, number));
+ length = bound_range(length, 0, buffer_length - offset);
+ length = bound_range(length, 0, iotjs_string_size(&src));
+
+ const char* src_data = iotjs_string_data(&src);
+ size_t copied =
+ iotjs_bufferwrap_copy_internal(buffer_wrap, src_data, 0, length, offset);
+
+ iotjs_jhandler_return_number(jhandler, copied);
+
+ iotjs_string_destroy(&src);
+ }
+
+
+ JHANDLER_FUNCTION(WriteUInt8) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+ DJHANDLER_CHECK_ARGS(2, number, number);
+
+ const char src[] = { (char)JHANDLER_GET_ARG(0, number) };
+ size_t length = 1;
+
+ size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap);
- DECLARE_SIZE_T_FROM_DOUBLE(offset, JHANDLER_GET_ARG(1, number));
++ size_t offset = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(1, number));
+ offset = bound_range(offset, 0, buffer_length);
+ length = bound_range(length, 0, buffer_length - offset);
+ length = bound_range(length, 0, 1);
+
+ size_t copied =
+ iotjs_bufferwrap_copy_internal(buffer_wrap, src, 0, length, offset);
+
+ iotjs_jhandler_return_number(jhandler, copied);
+ }
+
+
+ JHANDLER_FUNCTION(HexWrite) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+ DJHANDLER_CHECK_ARGS(3, string, number, number);
+
+ iotjs_string_t src = JHANDLER_GET_ARG(0, string);
+
+ size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap);
- DECLARE_SIZE_T_FROM_DOUBLE(length, JHANDLER_GET_ARG(2, number));
++ size_t offset = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(1, number));
+ offset = bound_range(offset, 0, buffer_length);
- DECLARE_SIZE_T_FROM_DOUBLE(offset, JHANDLER_GET_ARG(0, number));
++
++ size_t length = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(2, number));
+ length = bound_range(length, 0, buffer_length - offset);
+
+ const char* src_data = iotjs_string_data(&src);
+ unsigned src_length = iotjs_string_size(&src);
+ char* src_buf = iotjs_buffer_allocate(length);
+
+ size_t nbytes = hex_decode(src_buf, length, src_data, src_length);
+
+ size_t copied =
+ iotjs_bufferwrap_copy_internal(buffer_wrap, src_buf, 0, nbytes, offset);
+
+ iotjs_jhandler_return_number(jhandler, copied);
+
+ iotjs_buffer_release(src_buf);
+ iotjs_string_destroy(&src);
+ }
+
+
+ JHANDLER_FUNCTION(ReadUInt8) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+ DJHANDLER_CHECK_ARGS(1, number);
+
+ size_t buffer_length = iotjs_bufferwrap_length(buffer_wrap);
- DECLARE_SIZE_T_FROM_DOUBLE(start, JHANDLER_GET_ARG(0, number));
++ size_t offset = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(0, number));
+ offset = bound_range(offset, 0, buffer_length - 1);
+
+ char* buffer = iotjs_bufferwrap_buffer(buffer_wrap);
+
+ iotjs_jhandler_return_number(jhandler, (uint8_t)buffer[offset]);
+ }
+
+
+ JHANDLER_FUNCTION(Slice) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+ DJHANDLER_CHECK_ARGS(2, number, number);
+
+ int64_t start = JHANDLER_GET_ARG(0, number);
+ int64_t end = JHANDLER_GET_ARG(1, number);
+ size_t start_idx, end_idx;
+
+ if (start < 0) {
+ size_t len = iotjs_bufferwrap_length(buffer_wrap);
+ if ((size_t)(-start) > len) {
+ start_idx = SIZE_MAX;
+ } else {
+ start_idx = (size_t)start + len;
+ }
+ } else {
+ start_idx = (size_t)start;
+ }
+ start_idx = bound_range(start_idx, 0, iotjs_bufferwrap_length(buffer_wrap));
+
+ if (end < 0) {
+ size_t len = iotjs_bufferwrap_length(buffer_wrap);
+ if ((size_t)(-end) > len) {
+ end_idx = SIZE_MAX;
+ } else {
+ end_idx = (size_t)end + len;
+ }
+ } else {
+ end_idx = (size_t)end;
+ }
+ end_idx = bound_range(end_idx, 0, iotjs_bufferwrap_length(buffer_wrap));
+
+ if (end_idx < start_idx) {
+ end_idx = start_idx;
+ }
+
+ size_t length = (size_t)(end_idx - start_idx);
+
+ iotjs_jval_t jnew_buffer = iotjs_bufferwrap_create_buffer(length);
+ iotjs_bufferwrap_t* new_buffer_wrap =
+ iotjs_bufferwrap_from_jbuffer(&jnew_buffer);
+ iotjs_bufferwrap_copy_internal(new_buffer_wrap,
+ iotjs_bufferwrap_buffer(buffer_wrap),
+ start_idx, end_idx, 0);
+
+ iotjs_jhandler_return_jval(jhandler, &jnew_buffer);
+ iotjs_jval_destroy(&jnew_buffer);
+ }
+
+
+ JHANDLER_FUNCTION(ToString) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+ DJHANDLER_CHECK_ARGS(2, number, number);
+
- DECLARE_SIZE_T_FROM_DOUBLE(end, JHANDLER_GET_ARG(1, number));
++ size_t start = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(0, number));
+ start = bound_range(start, 0, iotjs_bufferwrap_length(buffer_wrap));
++
++ size_t end = iotjs_convert_double_to_sizet(JHANDLER_GET_ARG(1, number));
+ end = bound_range(end, 0, iotjs_bufferwrap_length(buffer_wrap));
+
+ if (end < start) {
+ end = start;
+ }
+
+ size_t length = end - start;
+
+ const char* data = iotjs_bufferwrap_buffer(buffer_wrap) + start;
+ length = strnlen(data, length);
+ iotjs_string_t str = iotjs_string_create_with_size(data, length);
+
+ iotjs_jhandler_return_string(jhandler, &str);
+
+ iotjs_string_destroy(&str);
+ }
+
+
+ JHANDLER_FUNCTION(ToHexString) {
+ JHANDLER_DECLARE_THIS_PTR(bufferwrap, buffer_wrap);
+
+ size_t length = iotjs_bufferwrap_length(buffer_wrap);
+ const char* data = iotjs_bufferwrap_buffer(buffer_wrap);
+
+ char* buffer = iotjs_buffer_allocate(length * 2);
+ iotjs_string_t str = iotjs_string_create_with_buffer(buffer, length * 2);
+
+ for (size_t i = 0; i < length; i++) {
+ memcpy(buffer, &"0123456789abcdef"[data[i] >> 4 & 0xF], 1);
+ buffer++;
+ memcpy(buffer, &"0123456789abcdef"[data[i] >> 0 & 0xF], 1);
+ buffer++;
+ }
+
+ iotjs_jhandler_return_string(jhandler, &str);
+ iotjs_string_destroy(&str);
+ }
+
+
+ JHANDLER_FUNCTION(ByteLength) {
+ DJHANDLER_CHECK_THIS(object);
+ DJHANDLER_CHECK_ARGS(1, string);
+
+ iotjs_string_t str = JHANDLER_GET_ARG(0, string);
+ iotjs_jval_t size = iotjs_jval_get_string_size(&str);
+
+ iotjs_jhandler_return_jval(jhandler, &size);
+ iotjs_string_destroy(&str);
+ iotjs_jval_destroy(&size);
+ }
+
+
+ iotjs_jval_t InitBuffer() {
+ iotjs_jval_t buffer = iotjs_jval_create_function_with_dispatch(Buffer);
+
+ iotjs_jval_t prototype = iotjs_jval_create_object();
+ iotjs_jval_t byte_length =
+ iotjs_jval_create_function_with_dispatch(ByteLength);
+
+ iotjs_jval_set_property_jval(&buffer, IOTJS_MAGIC_STRING_PROTOTYPE,
+ &prototype);
+ iotjs_jval_set_property_jval(&buffer, IOTJS_MAGIC_STRING_BYTELENGTH,
+ &byte_length);
+
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_COMPARE, Compare);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_COPY, Copy);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_WRITE, Write);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_HEXWRITE, HexWrite);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_WRITEUINT8, WriteUInt8);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_READUINT8, ReadUInt8);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_SLICE, Slice);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_TOSTRING, ToString);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_TOHEXSTRING,
+ ToHexString);
+
+ iotjs_jval_destroy(&prototype);
+ iotjs_jval_destroy(&byte_length);
+
+ return buffer;
+ }
--- /dev/null
+ /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 "iotjs_def.h"
+ #include "iotjs_js.h"
+ #include "jerryscript-debugger.h"
+
+ #include <stdlib.h>
+
+
+ JHANDLER_FUNCTION(Binding) {
+ JHANDLER_CHECK_ARGS(1, number);
+
+ ModuleKind module_kind = (ModuleKind)JHANDLER_GET_ARG(0, number);
+
+ const iotjs_jval_t* jmodule =
+ iotjs_module_initialize_if_necessary(module_kind);
+
+ iotjs_jhandler_return_jval(jhandler, jmodule);
+ }
+
+
+ static iotjs_jval_t WrapEval(const char* name, size_t name_len,
+ const char* source, size_t length, bool* throws) {
+ static const char* wrapper[2] = { "(function(exports, require, module) {",
+ "\n});\n" };
+
+ size_t len0 = strlen(wrapper[0]);
+ size_t len1 = strlen(wrapper[1]);
+
+ size_t buffer_length = len0 + len1 + length;
+ char* buffer = iotjs_buffer_allocate(buffer_length);
+ memcpy(buffer, wrapper[0], len0);
+ memcpy(buffer + len0, source, length);
+ memcpy(buffer + len0 + length, wrapper[1], len1);
+
+ iotjs_jval_t res = iotjs_jhelper_eval(name, name_len, (uint8_t*)buffer,
+ buffer_length, false, throws);
+
+ iotjs_buffer_release(buffer);
+
+ return res;
+ }
+
+
+ JHANDLER_FUNCTION(Compile) {
+ JHANDLER_CHECK_ARGS(2, string, string);
+
+ iotjs_string_t file = JHANDLER_GET_ARG(0, string);
+ iotjs_string_t source = JHANDLER_GET_ARG(1, string);
+
+ const char* filename = iotjs_string_data(&file);
+ const iotjs_environment_t* env = iotjs_environment_get();
+
+ if (iotjs_environment_config(env)->debugger) {
+ jerry_debugger_stop();
+ }
+
+ bool throws;
+ iotjs_jval_t jres =
+ WrapEval(filename, strlen(filename), iotjs_string_data(&source),
+ iotjs_string_size(&source), &throws);
+
+ if (!throws) {
+ iotjs_jhandler_return_jval(jhandler, &jres);
+ } else {
+ iotjs_jhandler_throw(jhandler, &jres);
+ }
+
+ iotjs_string_destroy(&file);
+ iotjs_string_destroy(&source);
+ iotjs_jval_destroy(&jres);
+ }
+
+
+ JHANDLER_FUNCTION(CompileNativePtr) {
+ JHANDLER_CHECK_ARGS(1, string);
+
+ iotjs_string_t id = JHANDLER_GET_ARG(0, string);
+ const char* name = iotjs_string_data(&id);
+
+ int i = 0;
+ while (natives[i].name != NULL) {
+ if (!strcmp(natives[i].name, name)) {
+ break;
+ }
+
+ i++;
+ }
+
+ if (natives[i].name != NULL) {
+ bool throws;
+ #ifdef ENABLE_SNAPSHOT
+ iotjs_jval_t jres = iotjs_jhelper_exec_snapshot(natives[i].code,
+ natives[i].length, &throws);
+ #else
+ iotjs_jval_t jres =
+ WrapEval(name, iotjs_string_size(&id), (const char*)natives[i].code,
+ natives[i].length, &throws);
+ #endif
+
+ if (!throws) {
+ iotjs_jhandler_return_jval(jhandler, &jres);
+ } else {
+ iotjs_jhandler_throw(jhandler, &jres);
+ }
+ iotjs_jval_destroy(&jres);
+ } else {
+ iotjs_jval_t jerror = iotjs_jval_create_error("Unknown native module");
+ iotjs_jhandler_throw(jhandler, &jerror);
+ iotjs_jval_destroy(&jerror);
+ }
+
+ iotjs_string_destroy(&id);
+ }
+
+
+ JHANDLER_FUNCTION(ReadSource) {
+ JHANDLER_CHECK_ARGS(1, string);
+
+ iotjs_string_t path = JHANDLER_GET_ARG(0, string);
+ iotjs_string_t code = iotjs_file_read(iotjs_string_data(&path));
+
+ iotjs_jhandler_return_string(jhandler, &code);
+
+ iotjs_string_destroy(&path);
+ iotjs_string_destroy(&code);
+ }
+
+
+ JHANDLER_FUNCTION(Cwd) {
+ JHANDLER_CHECK_ARGS(0);
+
+ char path[IOTJS_MAX_PATH_SIZE];
+ size_t size_path = sizeof(path);
+ int err = uv_cwd(path, &size_path);
+ if (err) {
+ JHANDLER_THROW(COMMON, "cwd error");
+ return;
+ }
+ iotjs_jhandler_return_string_raw(jhandler, path);
+ }
+
+ JHANDLER_FUNCTION(Chdir) {
+ JHANDLER_CHECK_ARGS(1, string);
+
+ iotjs_string_t path = JHANDLER_GET_ARG(0, string);
+ int err = uv_chdir(iotjs_string_data(&path));
+
+ if (err) {
+ iotjs_string_destroy(&path);
+ JHANDLER_THROW(COMMON, "chdir error");
+ return;
+ }
+
+ iotjs_string_destroy(&path);
+ }
+
+
+ JHANDLER_FUNCTION(DoExit) {
+ JHANDLER_CHECK_ARGS(1, number);
+
+ // Release builtin modules.
+ iotjs_module_list_cleanup();
+
+ // Release commonly used jerry values.
+ iotjs_binding_finalize();
+
+ int exit_code = JHANDLER_GET_ARG(0, number);
+ exit(exit_code);
+ }
+
+
+ void SetNativeSources(iotjs_jval_t* native_sources) {
+ for (int i = 0; natives[i].name; i++) {
+ iotjs_jval_set_property_jval(native_sources, natives[i].name,
+ iotjs_jval_get_boolean(true));
+ }
+ }
+
+
+ static void SetProcessEnv(iotjs_jval_t* process) {
+ const char *homedir, *iotjspath, *iotjsenv;
+
+ homedir = getenv("HOME");
+ if (homedir == NULL) {
+ homedir = "";
+ }
+
+ iotjspath = getenv("IOTJS_PATH");
+ if (iotjspath == NULL) {
+ #if defined(__NUTTX__) || defined(__TIZENRT__)
+ iotjspath = "/mnt/sdcard";
+ #else
+ iotjspath = "";
+ #endif
+ }
+
+ #if defined(EXPERIMENTAL)
+ iotjsenv = "experimental";
+ #else
+ iotjsenv = "";
+ #endif
+
+ iotjs_jval_t env = iotjs_jval_create_object();
+ iotjs_jval_set_property_string_raw(&env, IOTJS_MAGIC_STRING_HOME, homedir);
+ iotjs_jval_set_property_string_raw(&env, IOTJS_MAGIC_STRING_IOTJS_PATH,
+ iotjspath);
+ iotjs_jval_set_property_string_raw(&env, IOTJS_MAGIC_STRING_IOTJS_ENV,
+ iotjsenv);
+
+ iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_ENV, &env);
+
+ iotjs_jval_destroy(&env);
+ }
+
+
+ static void SetProcessIotjs(iotjs_jval_t* process) {
+ // IoT.js specific
+ iotjs_jval_t iotjs = iotjs_jval_create_object();
+ iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_IOTJS, &iotjs);
+
+ iotjs_jval_set_property_string_raw(&iotjs, IOTJS_MAGIC_STRING_BOARD,
+ TOSTRING(TARGET_BOARD));
+ iotjs_jval_destroy(&iotjs);
+ }
+
+
+ static void SetProcessArgv(iotjs_jval_t* process) {
+ const iotjs_environment_t* env = iotjs_environment_get();
+ uint32_t argc = iotjs_environment_argc(env);
+
+ iotjs_jval_t argv = iotjs_jval_create_array(argc);
+
+ for (uint32_t i = 0; i < argc; ++i) {
+ const char* argvi = iotjs_environment_argv(env, i);
+ iotjs_jval_t arg = iotjs_jval_create_string_raw(argvi);
+ iotjs_jval_set_property_by_index(&argv, i, &arg);
+ iotjs_jval_destroy(&arg);
+ }
+ iotjs_jval_set_property_jval(process, IOTJS_MAGIC_STRING_ARGV, &argv);
+
+ iotjs_jval_destroy(&argv);
+ }
+
+
+ iotjs_jval_t InitProcess() {
+ iotjs_jval_t process = iotjs_jval_create_object();
+
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_BINDING, Binding);
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_COMPILE, Compile);
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_COMPILENATIVEPTR,
+ CompileNativePtr);
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_READSOURCE, ReadSource);
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_CWD, Cwd);
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_CHDIR, Chdir);
+ iotjs_jval_set_method(&process, IOTJS_MAGIC_STRING_DOEXIT, DoExit);
+ SetProcessEnv(&process);
+
+ // process.native_sources
+ iotjs_jval_t native_sources = iotjs_jval_create_object();
+ SetNativeSources(&native_sources);
+ iotjs_jval_set_property_jval(&process, IOTJS_MAGIC_STRING_NATIVE_SOURCES,
+ &native_sources);
+ iotjs_jval_destroy(&native_sources);
+
+ // process.platform
+ iotjs_jval_set_property_string_raw(&process, IOTJS_MAGIC_STRING_PLATFORM,
+ TARGET_OS);
+
+ // process.arch
+ iotjs_jval_set_property_string_raw(&process, IOTJS_MAGIC_STRING_ARCH,
+ TARGET_ARCH);
+
++ // process.version
++ iotjs_jval_set_property_string_raw(&process, IOTJS_MAGIC_STRING_VERSION,
++ IOTJS_VERSION);
++
+ // Set iotjs
+ SetProcessIotjs(&process);
+
+ SetProcessArgv(&process);
+
+ // Binding module id.
+ iotjs_jval_t jbinding =
+ iotjs_jval_get_property(&process, IOTJS_MAGIC_STRING_BINDING);
+
+ #define ENUMDEF_MODULE_LIST(upper, Camel, lower) \
+ iotjs_jval_set_property_number(&jbinding, #lower, MODULE_##upper);
+
+ MAP_MODULE_LIST(ENUMDEF_MODULE_LIST)
+
+ #undef ENUMDEF_MODULE_LIST
+
+ iotjs_jval_destroy(&jbinding);
+
+ return process;
+ }
--- /dev/null
-
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 "iotjs_def.h"
+ #include "iotjs_module_spi.h"
+ #include "iotjs_module_buffer.h"
+ #include "iotjs_objectwrap.h"
+ #include <unistd.h>
+
+
+ IOTJS_DEFINE_NATIVE_HANDLE_INFO_THIS_MODULE(spi);
+
+ static iotjs_spi_t* iotjs_spi_create(const iotjs_jval_t* jspi) {
+ iotjs_spi_t* spi = IOTJS_ALLOC(iotjs_spi_t);
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_spi_t, spi);
+ iotjs_jobjectwrap_initialize(&_this->jobjectwrap, jspi,
+ &this_module_native_info);
+
++#if defined(__linux__)
+ _this->device = iotjs_string_create("");
++#endif
+
+ return spi;
+ }
+
+
+ static void iotjs_spi_destroy(iotjs_spi_t* spi) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_spi_t, spi);
+ iotjs_jobjectwrap_destroy(&_this->jobjectwrap);
++
++#if defined(__linux__)
+ iotjs_string_destroy(&_this->device);
++#endif
++
+ IOTJS_RELEASE(spi);
+ }
+
+
+ #define THIS iotjs_spi_reqwrap_t* spi_reqwrap
+
+
+ static iotjs_spi_reqwrap_t* iotjs_spi_reqwrap_create(
+ const iotjs_jval_t* jcallback, iotjs_spi_t* spi, SpiOp op) {
+ iotjs_spi_reqwrap_t* spi_reqwrap = IOTJS_ALLOC(iotjs_spi_reqwrap_t);
+ IOTJS_VALIDATED_STRUCT_CONSTRUCTOR(iotjs_spi_reqwrap_t, spi_reqwrap);
+
+ iotjs_reqwrap_initialize(&_this->reqwrap, jcallback, (uv_req_t*)&_this->req);
+
+ _this->req_data.op = op;
+ _this->spi_instance = spi;
+
+ return spi_reqwrap;
+ }
+
+
+ static void iotjs_spi_reqwrap_destroy(THIS) {
+ IOTJS_VALIDATED_STRUCT_DESTRUCTOR(iotjs_spi_reqwrap_t, spi_reqwrap);
+ iotjs_reqwrap_destroy(&_this->reqwrap);
+ IOTJS_RELEASE(spi_reqwrap);
+ }
+
+
+ static void iotjs_spi_reqwrap_dispatched(THIS) {
+ IOTJS_VALIDATABLE_STRUCT_METHOD_VALIDATE(iotjs_spi_reqwrap_t, spi_reqwrap);
+ iotjs_spi_reqwrap_destroy(spi_reqwrap);
+ }
+
+
+ static uv_work_t* iotjs_spi_reqwrap_req(THIS) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_reqwrap_t, spi_reqwrap);
+ return &_this->req;
+ }
+
+
+ static const iotjs_jval_t* iotjs_spi_reqwrap_jcallback(THIS) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_reqwrap_t, spi_reqwrap);
+ return iotjs_reqwrap_jcallback(&_this->reqwrap);
+ }
+
+
+ iotjs_spi_reqwrap_t* iotjs_spi_reqwrap_from_request(uv_work_t* req) {
+ return (iotjs_spi_reqwrap_t*)(iotjs_reqwrap_from_request((uv_req_t*)req));
+ }
+
+
+ iotjs_spi_reqdata_t* iotjs_spi_reqwrap_data(THIS) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_reqwrap_t, spi_reqwrap);
+ return &_this->req_data;
+ }
+
+
+ iotjs_spi_t* iotjs_spi_instance_from_reqwrap(THIS) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_reqwrap_t, spi_reqwrap);
+ return _this->spi_instance;
+ }
+
+
+ #undef THIS
+
+
+ static int iotjs_spi_get_array_data(char** buf, const iotjs_jval_t* jarray) {
+ iotjs_jval_t jlength =
+ iotjs_jval_get_property(jarray, IOTJS_MAGIC_STRING_LENGTH);
+ IOTJS_ASSERT(!iotjs_jval_is_undefined(&jlength));
+
+ size_t length = iotjs_jval_as_number(&jlength);
+ IOTJS_ASSERT((int)length >= 0);
+ *buf = iotjs_buffer_allocate(length);
+
+ for (size_t i = 0; i < length; i++) {
+ iotjs_jval_t jdata = iotjs_jval_get_property_by_index(jarray, i);
+ (*buf)[i] = iotjs_jval_as_number(&jdata);
+ iotjs_jval_destroy(&jdata);
+ }
+
+ iotjs_jval_destroy(&jlength);
+
+ return (int)length;
+ }
+
+
+ static void iotjs_spi_set_array_buffer(iotjs_spi_t* spi,
+ const iotjs_jval_t* jtx_buf,
+ const iotjs_jval_t* jrx_buf) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
+ int tx_buf_len = iotjs_spi_get_array_data(&_this->tx_buf_data, jtx_buf);
+ int rx_buf_len = iotjs_spi_get_array_data(&_this->rx_buf_data, jrx_buf);
+
+ IOTJS_ASSERT(_this->tx_buf_data != NULL && _this->rx_buf_data != NULL);
+ IOTJS_ASSERT(tx_buf_len > 0 && rx_buf_len > 0 && tx_buf_len == rx_buf_len);
+
+ _this->buf_len = tx_buf_len;
+ }
+
+
+ static void iotjs_spi_set_buffer(iotjs_spi_t* spi, const iotjs_jval_t* jtx_buf,
+ const iotjs_jval_t* jrx_buf) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
+ iotjs_bufferwrap_t* tx_buf = iotjs_bufferwrap_from_jbuffer(jtx_buf);
+ iotjs_bufferwrap_t* rx_buf = iotjs_bufferwrap_from_jbuffer(jrx_buf);
+
+ _this->tx_buf_data = iotjs_bufferwrap_buffer(tx_buf);
+ uint8_t tx_buf_len = iotjs_bufferwrap_length(tx_buf);
+ _this->rx_buf_data = iotjs_bufferwrap_buffer(rx_buf);
+ uint8_t rx_buf_len = iotjs_bufferwrap_length(rx_buf);
+
+ IOTJS_ASSERT(_this->tx_buf_data != NULL && _this->rx_buf_data != NULL);
+ IOTJS_ASSERT(tx_buf_len > 0 && rx_buf_len > 0 && tx_buf_len == rx_buf_len);
+
+ _this->buf_len = tx_buf_len;
+ }
+
+
+ static void iotjs_spi_release_buffer(iotjs_spi_t* spi) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
+ iotjs_buffer_release(_this->tx_buf_data);
+ iotjs_buffer_release(_this->rx_buf_data);
+ }
+
+
+ static void iotjs_spi_set_configuration(iotjs_spi_t* spi,
+ const iotjs_jval_t* joptions) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
++#if defined(__linux__)
+ iotjs_jval_t jdevice =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_DEVICE);
+ _this->device = iotjs_jval_as_string(&jdevice);
+ iotjs_jval_destroy(&jdevice);
- case kSpiOpTransfer:
-
++#elif defined(__NUTTX__)
++ iotjs_jval_t jbus = iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_BUS);
++ _this->bus = iotjs_jval_as_number(&jbus);
++ iotjs_jval_destroy(&jbus);
++#endif
+ iotjs_jval_t jmode =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_MODE);
+ _this->mode = (SpiMode)iotjs_jval_as_number(&jmode);
+ iotjs_jval_destroy(&jmode);
+
+ iotjs_jval_t jchip_select =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_CHIPSELECT);
+ _this->chip_select = (SpiChipSelect)iotjs_jval_as_number(&jchip_select);
+ iotjs_jval_destroy(&jchip_select);
+
+ iotjs_jval_t jmax_speed =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_MAXSPEED);
+ _this->max_speed = iotjs_jval_as_number(&jmax_speed);
+ iotjs_jval_destroy(&jmax_speed);
+
+ iotjs_jval_t jbits_per_word =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_BITSPERWORD);
+ _this->bits_per_word = (SpiOrder)iotjs_jval_as_number(&jbits_per_word);
+ iotjs_jval_destroy(&jbits_per_word);
+
+ iotjs_jval_t jbit_order =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_BITORDER);
+ _this->bit_order = (SpiOrder)iotjs_jval_as_number(&jbit_order);
+ iotjs_jval_destroy(&jbit_order);
+
+ iotjs_jval_t jloopback =
+ iotjs_jval_get_property(joptions, IOTJS_MAGIC_STRING_LOOPBACK);
+ _this->loopback = iotjs_jval_as_boolean(&jloopback);
+ iotjs_jval_destroy(&jloopback);
+ }
+
+
+ /*
+ * SPI worker function
+ */
+ static void iotjs_spi_transfer_worker(uv_work_t* work_req) {
+ SPI_WORKER_INIT;
+
+ if (!iotjs_spi_transfer(spi)) {
+ req_data->result = false;
+ return;
+ }
+
+ req_data->result = true;
+ }
+
+
+ static void iotjs_spi_close_worker(uv_work_t* work_req) {
+ SPI_WORKER_INIT;
+
+ if (!iotjs_spi_close(spi)) {
+ req_data->result = false;
+ return;
+ }
+
+ req_data->result = true;
+ }
+
+
+ static void iotjs_spi_after_work(uv_work_t* work_req, int status) {
+ iotjs_spi_reqwrap_t* req_wrap = iotjs_spi_reqwrap_from_request(work_req);
+ iotjs_spi_reqdata_t* req_data = iotjs_spi_reqwrap_data(req_wrap);
+ iotjs_spi_t* spi = iotjs_spi_instance_from_reqwrap(req_wrap);
+
+ iotjs_jargs_t jargs = iotjs_jargs_create(2);
+
+ bool result = req_data->result;
+
+ if (status) {
+ iotjs_jargs_append_error(&jargs, "System error");
+ } else {
+ switch (req_data->op) {
+ case kSpiOpOpen:
+ if (!result) {
+ iotjs_jargs_append_error(&jargs, "Failed to export SPI device");
+ } else {
+ iotjs_jargs_append_null(&jargs);
+ }
+ break;
- iotjs_spi_release_buffer(spi);
++ case kSpiOpTransferArray:
++ case kSpiOpTransferBuffer:
+ if (!result) {
+ iotjs_jargs_append_error(&jargs, "Cannot transfer from SPI device");
+ } else {
+ iotjs_jargs_append_null(&jargs);
+
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
+ // Append read data
+ iotjs_jval_t result_data =
+ iotjs_jval_create_byte_array(_this->buf_len, _this->rx_buf_data);
+ iotjs_jargs_append_jval(&jargs, &result_data);
+ iotjs_jval_destroy(&result_data);
+ }
- SPI_ASYNC(transfer, spi, jcallback, kSpiOpTransfer);
++
++ if (req_data->op == kSpiOpTransferArray)
++ iotjs_spi_release_buffer(spi);
++
+ break;
+ case kSpiOpClose:
+ if (!result) {
+ iotjs_jargs_append_error(&jargs, "Failed to unexport SPI device");
+ } else {
+ iotjs_jargs_append_null(&jargs);
+ }
+ break;
+ default: {
+ IOTJS_ASSERT(!"Unreachable");
+ break;
+ }
+ }
+ }
+
+ const iotjs_jval_t* jcallback = iotjs_spi_reqwrap_jcallback(req_wrap);
+ iotjs_make_callback(jcallback, iotjs_jval_get_undefined(), &jargs);
+
+ iotjs_jargs_destroy(&jargs);
+
+ iotjs_spi_reqwrap_dispatched(req_wrap);
+ }
+
+
+ iotjs_spi_t* iotjs_spi_get_instance(const iotjs_jval_t* jspi) {
+ uintptr_t handle = iotjs_jval_get_object_native_handle(jspi);
+ return (iotjs_spi_t*)(handle);
+ }
+
+
+ #define SPI_ASYNC(call, this, jcallback, op) \
+ do { \
+ uv_loop_t* loop = iotjs_environment_loop(iotjs_environment_get()); \
+ iotjs_spi_reqwrap_t* req_wrap = \
+ iotjs_spi_reqwrap_create(jcallback, this, op); \
+ uv_work_t* req = iotjs_spi_reqwrap_req(req_wrap); \
+ uv_queue_work(loop, req, iotjs_spi_##call##_worker, iotjs_spi_after_work); \
+ } while (0)
+
+
+ JHANDLER_FUNCTION(SpiConstructor) {
+ DJHANDLER_CHECK_THIS(object);
+ DJHANDLER_CHECK_ARGS(2, object, function);
+
+ // Create SPI object
+ const iotjs_jval_t* jspi = JHANDLER_GET_THIS(object);
+ iotjs_spi_t* spi = iotjs_spi_create(jspi);
+ IOTJS_ASSERT(spi == iotjs_spi_get_instance(jspi));
+
+ // Set configuration
+ const iotjs_jval_t* jconfiguration = JHANDLER_GET_ARG(0, object);
+ iotjs_spi_set_configuration(spi, jconfiguration);
+
+ const iotjs_jval_t* jcallback = JHANDLER_GET_ARG(1, function);
+ SPI_ASYNC(open, spi, jcallback, kSpiOpOpen);
+ }
+
+
+ // FIXME: do not need transferArray if array buffer is implemented.
+ JHANDLER_FUNCTION(TransferArray) {
+ JHANDLER_DECLARE_THIS_PTR(spi, spi);
+
+ DJHANDLER_CHECK_ARGS(2, array, array);
+ DJHANDLER_CHECK_ARG_IF_EXIST(2, function);
+
+ const iotjs_jval_t* jcallback = JHANDLER_GET_ARG_IF_EXIST(2, function);
+
+ iotjs_spi_set_array_buffer(spi, JHANDLER_GET_ARG(0, array),
+ JHANDLER_GET_ARG(1, array));
+
+ if (jcallback) {
- SPI_ASYNC(transfer, spi, jcallback, kSpiOpTransfer);
++ SPI_ASYNC(transfer, spi, jcallback, kSpiOpTransferArray);
+ } else {
+ if (!iotjs_spi_transfer(spi)) {
+ JHANDLER_THROW(COMMON, "SPI Transfer Error");
+ } else {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
+ iotjs_jval_t result =
+ iotjs_jval_create_byte_array(_this->buf_len, _this->rx_buf_data);
+ iotjs_jhandler_return_jval(jhandler, &result);
+ iotjs_jval_destroy(&result);
+ }
++
++ iotjs_spi_release_buffer(spi);
+ }
+ }
+
+
+ JHANDLER_FUNCTION(TransferBuffer) {
+ JHANDLER_DECLARE_THIS_PTR(spi, spi);
+
+ DJHANDLER_CHECK_ARGS(2, object, object);
+ DJHANDLER_CHECK_ARG_IF_EXIST(2, function);
+
+ const iotjs_jval_t* jcallback = JHANDLER_GET_ARG_IF_EXIST(2, function);
+
+ iotjs_spi_set_buffer(spi, JHANDLER_GET_ARG(0, object),
+ JHANDLER_GET_ARG(1, object));
+
+ if (jcallback) {
++ SPI_ASYNC(transfer, spi, jcallback, kSpiOpTransferBuffer);
+ } else {
+ if (!iotjs_spi_transfer(spi)) {
+ JHANDLER_THROW(COMMON, "SPI Transfer Error");
+ } else {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
+ iotjs_jval_t result =
+ iotjs_jval_create_byte_array(_this->buf_len, _this->rx_buf_data);
+ iotjs_jhandler_return_jval(jhandler, &result);
+ iotjs_jval_destroy(&result);
+ }
+ }
+ }
+
+
+ JHANDLER_FUNCTION(Close) {
+ JHANDLER_DECLARE_THIS_PTR(spi, spi);
+
+ DJHANDLER_CHECK_ARG_IF_EXIST(0, function);
+
+ const iotjs_jval_t* jcallback = JHANDLER_GET_ARG_IF_EXIST(0, function);
+
+ if (jcallback) {
+ SPI_ASYNC(close, spi, jcallback, kSpiOpClose);
+ } else {
+ if (!iotjs_spi_close(spi)) {
+ JHANDLER_THROW(COMMON, "SPI Close Error");
+ }
+ }
+
+ iotjs_jhandler_return_null(jhandler);
+ }
+
+
+ iotjs_jval_t InitSpi() {
+ iotjs_jval_t jspi = iotjs_jval_create_object();
+ iotjs_jval_t jspiConstructor =
+ iotjs_jval_create_function_with_dispatch(SpiConstructor);
+ iotjs_jval_set_property_jval(&jspi, IOTJS_MAGIC_STRING_SPI, &jspiConstructor);
+
+ iotjs_jval_t prototype = iotjs_jval_create_object();
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_TRANSFERARRAY,
+ TransferArray);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_TRANSFERBUFFER,
+ TransferBuffer);
+ iotjs_jval_set_method(&prototype, IOTJS_MAGIC_STRING_CLOSE, Close);
+ iotjs_jval_set_property_jval(&jspiConstructor, IOTJS_MAGIC_STRING_PROTOTYPE,
+ &prototype);
+ iotjs_jval_destroy(&prototype);
+ iotjs_jval_destroy(&jspiConstructor);
+
+ // SPI mode properties
+ iotjs_jval_t jmode = iotjs_jval_create_object();
+ iotjs_jval_set_property_number(&jmode, IOTJS_MAGIC_STRING_0, kSpiMode_0);
+ iotjs_jval_set_property_number(&jmode, IOTJS_MAGIC_STRING_1, kSpiMode_1);
+ iotjs_jval_set_property_number(&jmode, IOTJS_MAGIC_STRING_2, kSpiMode_2);
+ iotjs_jval_set_property_number(&jmode, IOTJS_MAGIC_STRING_3, kSpiMode_3);
+ iotjs_jval_set_property_jval(&jspi, IOTJS_MAGIC_STRING_MODE_U, &jmode);
+ iotjs_jval_destroy(&jmode);
+
+ // SPI mode properties
+ iotjs_jval_t jcs = iotjs_jval_create_object();
+ iotjs_jval_set_property_number(&jcs, IOTJS_MAGIC_STRING_NONE, kSpiCsNone);
+ iotjs_jval_set_property_number(&jcs, IOTJS_MAGIC_STRING_HIGH, kSpiCsHigh);
+ iotjs_jval_set_property_jval(&jspi, IOTJS_MAGIC_STRING_CHIPSELECT_U, &jcs);
+ iotjs_jval_destroy(&jcs);
+
+ // SPI order properties
+ iotjs_jval_t jbit_order = iotjs_jval_create_object();
+ iotjs_jval_set_property_number(&jbit_order, IOTJS_MAGIC_STRING_MSB,
+ kSpiOrderMsb);
+ iotjs_jval_set_property_number(&jbit_order, IOTJS_MAGIC_STRING_LSB,
+ kSpiOrderLsb);
+ iotjs_jval_set_property_jval(&jspi, IOTJS_MAGIC_STRING_BITORDER_U,
+ &jbit_order);
+ iotjs_jval_destroy(&jbit_order);
+
+ return jspi;
+ }
--- /dev/null
- kSpiOpTransfer,
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 IOTJS_MODULE_SPI_H
+ #define IOTJS_MODULE_SPI_H
+
+ #include "iotjs_def.h"
+ #include "iotjs_module_buffer.h"
+ #include "iotjs_objectwrap.h"
+ #include "iotjs_reqwrap.h"
+
+
++#if defined(__NUTTX__)
++#include <nuttx/spi/spi.h>
++#endif
++
+ typedef enum {
+ kSpiOpOpen,
-
++ kSpiOpTransferArray,
++ kSpiOpTransferBuffer,
+ kSpiOpClose,
+ } SpiOp;
+
+ typedef enum {
+ kSpiMode_0,
+ kSpiMode_1,
+ kSpiMode_2,
+ kSpiMode_3,
+ } SpiMode;
+
+ typedef enum {
+ kSpiCsNone,
+ kSpiCsHigh,
+ } SpiChipSelect;
+
+ typedef enum { kSpiOrderMsb, kSpiOrderLsb } SpiOrder;
+
+
+ typedef struct {
+ iotjs_jobjectwrap_t jobjectwrap;
++#if defined(__linux__)
+ iotjs_string_t device;
+ int32_t device_fd;
++#elif defined(__NUTTX__)
++ int bus;
++ uint32_t cs_chip;
++ struct spi_dev_s* spi_dev;
++#endif
+ SpiMode mode;
+ SpiChipSelect chip_select;
+ SpiOrder bit_order;
+ uint8_t bits_per_word;
+ uint16_t delay;
+ uint32_t max_speed;
+ bool loopback;
+
+ // SPI buffer
+ char* tx_buf_data;
+ char* rx_buf_data;
+ uint8_t buf_len;
+
+ } IOTJS_VALIDATED_STRUCT(iotjs_spi_t);
+
+
+ typedef struct {
+ bool result;
+ SpiOp op;
+ } iotjs_spi_reqdata_t;
+
+
+ typedef struct {
+ iotjs_reqwrap_t reqwrap;
+ uv_work_t req;
+ iotjs_spi_reqdata_t req_data;
+ iotjs_spi_t* spi_instance;
+ } IOTJS_VALIDATED_STRUCT(iotjs_spi_reqwrap_t);
+
+
+ #define THIS iotjs_spi_reqwrap_t* spi_reqwrap
+
+ iotjs_spi_reqwrap_t* iotjs_spi_reqwrap_from_request(uv_work_t* req);
+ iotjs_spi_reqdata_t* iotjs_spi_reqwrap_data(THIS);
+
+ iotjs_spi_t* iotjs_spi_instance_from_reqwrap(THIS);
+
+ #undef THIS
+
+
+ #define SPI_WORKER_INIT \
+ iotjs_spi_reqwrap_t* req_wrap = iotjs_spi_reqwrap_from_request(work_req); \
+ iotjs_spi_reqdata_t* req_data = iotjs_spi_reqwrap_data(req_wrap); \
+ iotjs_spi_t* spi = iotjs_spi_instance_from_reqwrap(req_wrap);
+
+
+ bool iotjs_spi_transfer(iotjs_spi_t* spi);
+ bool iotjs_spi_close(iotjs_spi_t* spi);
+
+ void iotjs_spi_open_worker(uv_work_t* work_req);
+
+
+ #endif /* IOTJS_MODULE_SPI_H */
--- /dev/null
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 defined(__NUTTX__)
+
+
+ #include <nuttx/drivers/pwm.h>
+ #include <stdlib.h>
+ #include <sys/ioctl.h>
+
+ #include "iotjs_def.h"
+ #include "iotjs_systemio-nuttx.h"
+ #include "modules/iotjs_module_pwm.h"
+
+
+ #define PWM_DEVICE_PATH_FORMAT "/dev/pwm%d"
+ #define PWM_DEVICE_PATH_BUFFER_SIZE 12
+
+
+ static bool iotjs_pwm_set_options(iotjs_pwm_t* pwm) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_pwm_t, pwm);
+
+ int fd = _this->device_fd;
+ if (fd < 0) {
+ DDLOG("%s - file open failed", __func__);
+ return false;
+ }
+
+ struct pwm_info_s info;
+
+ // Clamp so that the value inverted fits into uint32
+ if (_this->period < 2.33E-10)
+ _this->period = 2.33E-10;
+ info.frequency = (uint32_t)(1.0 / _this->period);
+
+ double duty_value = _this->duty_cycle * (1 << 16); // 16 bit timer
+ if (duty_value > 0xffff)
+ duty_value = 0xffff;
+ else if (duty_value < 1)
+ duty_value = 1;
+ info.duty = (ub16_t)duty_value;
+
+ DDDLOG("%s - frequency: %d, duty: %d", __func__, info.frequency, info.duty);
+
+ // Set Pwm info
+ if (ioctl(fd, PWMIOC_SETCHARACTERISTICS, (unsigned long)((uintptr_t)&info)) <
+ 0) {
+ return false;
+ }
+
+ return true;
+ }
+
+
+ void iotjs_pwm_open_worker(uv_work_t* work_req) {
+ PWM_WORKER_INIT;
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_pwm_t, pwm);
+
+ int timer = SYSIO_GET_TIMER(_this->pin);
+ char path[PWM_DEVICE_PATH_BUFFER_SIZE] = { 0 };
+
+ if (snprintf(path, PWM_DEVICE_PATH_BUFFER_SIZE, PWM_DEVICE_PATH_FORMAT,
+ timer) < 0) {
+ req_data->result = false;
+ return;
+ }
+
+ struct pwm_lowerhalf_s* pwm_lowerhalf =
+ iotjs_pwm_config_nuttx(timer, _this->pin);
+
+ DDDLOG("%s - path: %s, timer: %d\n", __func__, path, timer);
+
+ if (pwm_register(path, pwm_lowerhalf) != 0) {
+ req_data->result = false;
+ return;
+ }
+
+ // File open
+ _this->device_fd = open(path, O_RDONLY);
+ if (_this->device_fd < 0) {
+ DDLOG("%s - file open failed", __func__);
+ req_data->result = false;
+ return;
+ }
+
+ if (!iotjs_pwm_set_options(pwm)) {
+ req_data->result = false;
++ return;
+ }
+
+ req_data->result = true;
+ }
+
+
+ bool iotjs_pwm_set_period(iotjs_pwm_t* pwm) {
+ return iotjs_pwm_set_options(pwm);
+ }
+
+
+ bool iotjs_pwm_set_dutycycle(iotjs_pwm_t* pwm) {
+ return iotjs_pwm_set_options(pwm);
+ }
+
+
+ bool iotjs_pwm_set_enable(iotjs_pwm_t* pwm) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_pwm_t, pwm);
+
+ int fd = _this->device_fd;
+ if (fd < 0) {
+ DDLOG("%s - file open failed", __func__);
+ return false;
+ }
+
+ DDDLOG("%s - enable: %d", __func__, _this->enable);
+
+ int ret;
+ if (_this->enable) {
+ ret = ioctl(fd, PWMIOC_START, 0);
+ } else {
+ ret = ioctl(fd, PWMIOC_STOP, 0);
+ }
+
+ if (ret < 0) {
+ DDLOG("%s - setEnable failed", __func__);
+ return false;
+ }
+
+ return true;
+ }
+
+
+ bool iotjs_pwm_close(iotjs_pwm_t* pwm) {
+ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_pwm_t, pwm);
+
+ int fd = _this->device_fd;
+ if (fd < 0) {
+ DDLOG("%s - file not opened", __func__);
+ return false;
+ }
+
+ DDDLOG("%s", __func__);
+
+ // Close file
+ close(fd);
+ _this->device_fd = -1;
+
+ uint32_t timer = SYSIO_GET_TIMER(_this->pin);
+ char path[PWM_DEVICE_PATH_BUFFER_SIZE] = { 0 };
+ if (snprintf(path, PWM_DEVICE_PATH_BUFFER_SIZE - 1, PWM_DEVICE_PATH_FORMAT,
+ timer) < 0) {
+ return false;
+ }
+
+ // Release driver
+ unregister_driver(path);
+
+ iotjs_gpio_unconfig_nuttx(_this->pin);
+
+ return true;
+ }
+
+
+ #endif // __NUTTX__
--- /dev/null
-/* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
++/* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 defined(__NUTTX__)
+
++#include <nuttx/board.h>
+
++#include "iotjs_systemio-nuttx.h"
++#include "chip.h"
+ #include "modules/iotjs_module_spi.h"
+
+
+ bool iotjs_spi_transfer(iotjs_spi_t* spi) {
- IOTJS_ASSERT(!"Not implemented");
- return false;
++ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
++
++ struct spi_dev_s* spi_dev = _this->spi_dev;
++
++ SPI_LOCK(spi_dev, true);
++
++ SPI_SETFREQUENCY(spi_dev, _this->max_speed);
++
++ SPI_SETMODE(spi_dev, _this->mode);
++ SPI_SETBITS(spi_dev, _this->bits_per_word);
++
++ // Select the SPI
++ iotjs_gpio_write_nuttx(_this->cs_chip, false);
++
++ SPI_EXCHANGE(spi_dev, _this->tx_buf_data, _this->rx_buf_data, _this->buf_len);
++
++ // Unselect the SPI device
++ iotjs_gpio_write_nuttx(_this->cs_chip, true);
++
++ SPI_LOCK(spi_dev, false);
++
++ return true;
+ }
+
+
+ bool iotjs_spi_close(iotjs_spi_t* spi) {
- IOTJS_ASSERT(!"Not implemented");
- return false;
++ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
++
++ iotjs_gpio_unconfig_nuttx(_this->cs_chip);
++
++ return true;
+ }
+
++
+ void iotjs_spi_open_worker(uv_work_t* work_req) {
- IOTJS_ASSERT(!"Not implemented");
-}
++ SPI_WORKER_INIT;
++ IOTJS_VALIDATED_STRUCT_METHOD(iotjs_spi_t, spi);
+
++ switch (_this->bus) {
++ case 1:
++ _this->cs_chip = (GPIO_OUTPUT | GPIO_PUSHPULL | GPIO_SPEED_50MHz |
++ GPIO_PORTA | GPIO_PIN15 | GPIO_OUTPUT_SET);
++ break;
++ default:
++ req_data->result = false;
++ return;
++ }
+
-void iotjs_spi_transfer_worker(uv_work_t* work_req) {
- IOTJS_ASSERT(!"Not implemented");
-}
++ iotjs_gpio_config_nuttx(_this->cs_chip);
+
++ if (!(_this->spi_dev = iotjs_spi_config_nuttx(_this->bus, _this->cs_chip))) {
++ DLOG("%s - SPI open failed %d", __func__, _this->bus);
++ req_data->result = false;
++ return;
++ }
+
-void iotjs_spi_close_worker(uv_work_t* work_req) {
- IOTJS_ASSERT(!"Not implemented");
++ req_data->result = true;
+ }
+
+
+ #endif // __NUTTX__
--- /dev/null
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 IOTJS_SYSTEMIO_ARM_NUTTX_H
+ #define IOTJS_SYSTEMIO_ARM_NUTTX_H
+
+ #include <stdint.h>
+
++#include "iotjs_def.h"
++
++void iotjs_gpio_config_nuttx(uint32_t pin);
+ void iotjs_gpio_unconfig_nuttx(uint32_t pin);
++void iotjs_gpio_write_nuttx(uint32_t pin, bool value);
+
+
+ #if ENABLE_MODULE_ADC || ENABLE_MODULE_PWM
+
+ #define SYSIO_TIMER_PIN_SHIFT 21 /* Bits 21-24: Timer number */
+ #define SYSIO_TIMER_PIN_MASK 15
+ #define SYSIO_TIMER_NUMBER(n) ((n) << SYSIO_TIMER_PIN_SHIFT)
+ #define SYSIO_GET_TIMER(n) \
+ (((n) >> SYSIO_TIMER_PIN_SHIFT) & SYSIO_TIMER_PIN_MASK)
+
+ #endif /* ENABLE_MODULE_ADC || ENABLE_MODULE_PWM */
+
+
+ #if ENABLE_MODULE_ADC
+
+ #include <nuttx/analog/adc.h>
+
+ #define ADC_NUMBER_SHIFT 25 /* Bits 25-26: ADC number */
+ #define ADC_NUMBER_MASK 3
+ #define ADC_NUMBER(n) ((n) << ADC_NUMBER_SHIFT)
+ #define ADC_GET_NUMBER(n) (((n) >> ADC_NUMBER_SHIFT) & ADC_NUMBER_MASK)
+
+ struct adc_dev_s* iotjs_adc_config_nuttx(int number, int timer, uint32_t pin);
+
+ #endif /* ENABLE_MODULE_ADC */
+
+
+ #if ENABLE_MODULE_I2C
+
+ #include <nuttx/i2c/i2c_master.h>
+
+ struct i2c_master_s* iotjs_i2c_config_nuttx(int port);
+ int iotjs_i2c_unconfig_nuttx(struct i2c_master_s* i2c);
+
+ #endif /* ENABLE_MODULE_I2C */
+
+
+ #if ENABLE_MODULE_PWM
+
+ #include <nuttx/drivers/pwm.h>
+
+ struct pwm_lowerhalf_s* iotjs_pwm_config_nuttx(int timer, uint32_t pin);
+
+ #endif /* ENABLE_MODULE_PWM */
+
+
++#if ENABLE_MODULE_SPI
++
++#include <nuttx/spi/spi.h>
++
++struct spi_dev_s* iotjs_spi_config_nuttx(int bus, uint32_t cs_chip);
++
++#endif /* ENABLE_MODULE_SPI */
++
++
+ #endif /* IOTJS_SYSTEMIO_ARM_NUTTX_H */
--- /dev/null
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 defined(__NUTTX__) && TARGET_BOARD == STM32F4DIS
+
+ #include <stdint.h>
+
+ #include "../iotjs_systemio-nuttx.h"
+ #include "stm32_gpio.h"
+
+
++void iotjs_gpio_config_nuttx(uint32_t pin) {
++ stm32_configgpio(pin);
++}
++
++
+ void iotjs_gpio_unconfig_nuttx(uint32_t pin) {
+ stm32_unconfiggpio(pin);
+ }
+
+
++void iotjs_gpio_write_nuttx(uint32_t pin, bool value) {
++ stm32_gpiowrite(pin, value);
++}
++
++
+ #if ENABLE_MODULE_ADC
+
+ #include "stm32_adc.h"
+
+ struct adc_dev_s* iotjs_adc_config_nuttx(int number, int timer, uint32_t pin) {
+ stm32_configgpio(pin);
+
+ uint8_t channel_list[1] = { timer };
+ return stm32_adcinitialize(number, channel_list, 1);
+ }
+
+ #endif /* ENABLE_MODULE_ADC */
+
+
+ #if ENABLE_MODULE_I2C
+
+ #include "stm32_i2c.h"
+
+ struct i2c_master_s* iotjs_i2c_config_nuttx(int port) {
+ return stm32_i2cbus_initialize(port);
+ }
+
+
+ int iotjs_i2c_unconfig_nuttx(struct i2c_master_s* i2c) {
+ return stm32_i2cbus_uninitialize(i2c);
+ }
+
+ #endif /* ENABLE_MODULE_I2C */
+
+
+ #if ENABLE_MODULE_PWM
+
+ #include "stm32_pwm.h"
+
+ struct pwm_lowerhalf_s* iotjs_pwm_config_nuttx(int timer, uint32_t pin) {
+ // Set alternative function
+ stm32_configgpio(pin);
+
+ // PWM initialize
+ return stm32_pwminitialize(timer);
+ }
+
+ #endif /* ENABLE_MODULE_PWM */
+
+
++#if ENABLE_MODULE_SPI
++
++#include "stm32_spi.h"
++
++struct spi_dev_s* iotjs_spi_config_nuttx(int bus, uint32_t cs_chip) {
++ stm32_configgpio(cs_chip);
++
++ return stm32_spibus_initialize(bus);
++}
++
++#endif /* ENABLE_MODULE_PWM */
++
++
+ #endif // __NUTTX__
--- /dev/null
-var spi1 = spi.open({device: '/dev/spidev0.0'}, function() {
+ /* Copyright 2016-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 assert = require('assert');
+ var Spi = require('spi');
+
+ var spi = new Spi();
+
++var configuration = {};
++
++if (process.platform === 'linux') {
++ configuration.device = '/dev/spidev0.0';
++} else if (process.platform === 'nuttx') {
++ configuration.bus = 1;
++} else {
++ assert.fail();
++}
++
+ // Buffer test
++var spi1 = spi.open(configuration, function() {
+ var data = 'Hello IoTjs';
+ var tx = new Buffer(data);
+ var rx = new Buffer(11);
+
+ this.transferSync(tx, rx);
+ var value = '';
+ for (var i = 0; i < 11; i++) {
+ value += String.fromCharCode(rx[i]);
+ }
+ console.log(value);
+ assert.equal(value, data);
+
+ setTimeout(function() {
+ spi1.transfer(tx, rx, function(err) {
+ assert.equal(err, null);
+ assert.equal(rx.length, 11);
+
+ var value = '';
+ for (var i = 0; i < 11; i++) {
+ value += String.fromCharCode(rx[i]);
+ }
+ console.log(value);
+ assert.equal(value, data);
+
+ spi1.close();
+ });
+ }, 500);
+ });
--- /dev/null
-var spi0 = spi.open({
- device: '/dev/spidev0.0'
-}, function() {
+ /* Copyright 2017-present Samsung Electronics Co., Ltd. and other contributors
+ *
+ * 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 assert = require('assert');
+ var Spi = require('spi');
+
+ var spi = new Spi();
+
++var configuration = {};
++
++if (process.platform === 'linux') {
++ configuration.device = '/dev/spidev0.0';
++} else if (process.platform === 'nuttx') {
++ configuration.bus = 1;
++} else {
++ assert.fail();
++}
++
+ // mcp3008 test
+ var channel = 0;
++var spi0 = spi.open(configuration, function() {
+ var mode = (8 + channel) << 4;
+ var tx = [1, mode, 0];
+ var rx = [0, 0, 0];
+
+ spi0.transferSync(tx, rx);
+ console.log(((rx[1] & 0x03) << 8) + rx[2]);
+
+ var loopCnt = 10;
+ var loop = setInterval(function() {
+ spi0.transfer(tx, rx, function(err) {
+ assert.equal(err, null);
+ assert.equal(rx.length, 3);
+
+ var value = ((rx[1] & 0x03) << 8) + rx[2];
+ console.log(value);
+
+ if (--loopCnt < 0) {
+ spi0.closeSync();
+ clearInterval(loop);
+ console.log('finish test');
+ }
+
+ });
+ }, 500);
+ });
--- /dev/null
-def process_modules(options):
- print_progress('Analyze modules')
-
- includes, excludes = resolve_modules(options)
- modules = analyze_module_dependency(includes, excludes)
-
- print('Selected js modules: %s' % ', '.join(modules['js']))
- print('Selected native modules: %s' % ', '.join(modules['native']))
-
- options.js_modules = modules['js']
- options.native_modules = modules['native']
- options.iotjs_exclude_module = excludes
-
-
+ #!/usr/bin/env python
+
+ # Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
+ #
+ # 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.
+
+ from __future__ import print_function
+ try:
+ basestring
+ except:
+ # in Python 3.x there is no basestring just str
+ basestring = str
+
+ import argparse
+ import json
+ import sys
+ import re
+ import os
+
+ from js2c import js2c
+ from module_analyzer import resolve_modules, analyze_module_dependency
+ from common_py import path
+ from common_py.system.filesystem import FileSystem as fs
+ from common_py.system.executor import Executor as ex
+ from common_py.system.platform import Platform
+
+ platform = Platform()
+
+
+ # Initialize build options.
+ def init_options():
+ # Check config options.
+ arg_config = list(filter(lambda x: x.startswith('--config='), sys.argv))
+ config_path = path.BUILD_CONFIG_PATH
+
+ if arg_config:
+ config_path = arg_config[-1].split('=', 1)[1]
+
+ # Read config file and apply it to argv.
+ argv = []
+ with open(config_path, 'rb') as f:
+ config = json.loads(f.read().decode('ascii'))
+ config_option = config['build_option']
+ for opt_key in config_option:
+ opt_val = config_option[opt_key]
+ if isinstance(opt_val, basestring) and opt_val != '':
+ argv.append('--%s=%s' % (opt_key, opt_val))
+ elif isinstance(opt_val, bool):
+ if opt_val:
+ argv.append('--%s' % opt_key)
+ elif isinstance(opt_val, int):
+ argv.append('--%s=%s' % (opt_key, opt_val))
+ elif isinstance(opt_val, list):
+ for val in opt_val:
+ argv.append('--%s=%s' % (opt_key, val))
+
+ # Apply command line argument to argv.
+ argv = argv + sys.argv[1:]
+
+ # Prepare argument parser.
+ parser = argparse.ArgumentParser()
+
+ parser.add_argument('--buildtype',
+ choices=['debug', 'release'], default='debug',
+ help='Specify the build type: %(choices)s (default: %(default)s)')
+
+ parser.add_argument('--builddir', default=path.BUILD_ROOT,
+ help='Specify the build directory (default: %(default)s)')
+ parser.add_argument('--buildlib', action='store_true', default=False,
+ help='Build IoT.js library only (default: %(default)s)')
+
+ parser.add_argument('--clean', action='store_true', default=False,
+ help='Clean build directory before build (default: %(default)s)')
+
+ parser.add_argument('--config', default=path.BUILD_CONFIG_PATH,
+ help='Specify the config file (default: %(default)s)',
+ dest='config_path')
+
+ parser.add_argument('--target-arch',
+ choices=['arm', 'x86', 'i686', 'x86_64', 'x64'],
+ default=platform.arch(),
+ help='Specify the target architecture: '
+ '%(choices)s (default: %(default)s)')
+ parser.add_argument('--target-os',
+ choices=['linux', 'darwin', 'osx', 'nuttx', 'tizen', 'tizenrt'],
+ default=platform.os(),
+ help='Specify the target os: %(choices)s (default: %(default)s)')
+
+ parser.add_argument('--target-board',
+ choices=['none', 'artik10', 'stm32f4dis', 'rpi2', 'artik05x'],
+ default='none', help='Specify the targeted board (if needed): '
+ '%(choices)s (default: %(default)s)')
+ parser.add_argument('--nuttx-home', default=None, dest='sysroot',
+ help='Specify the NuttX base directory (required for NuttX build)')
+
+ parser.add_argument('--cross-compile', dest='cross_compile',
+ action='store', help='Specify the cross compilation toolkit prefix.')
+ parser.add_argument('--sysroot', action='store',
+ help='The location of the development tree root directory (sysroot).'
+ 'Must be compatible with used toolchain.')
+
+ parser.add_argument('--cmake-param',
+ action='append', default=[],
+ help='Specify additional cmake parameters '
+ '(can be used multiple times)')
+ parser.add_argument('--compile-flag',
+ action='append', default=[],
+ help='Specify additional compile flags (can be used multiple times)')
+ parser.add_argument('--link-flag',
+ action='append', default=[],
+ help='Specify additional linker flags (can be used multiple times)')
+
+ parser.add_argument('--external-include-dir',
+ action='append', default=[],
+ help='Specify additional external include directory '
+ '(can be used multiple times)')
+ parser.add_argument('--external-static-lib',
+ action='append', default=[],
+ help='Specify additional external static library '
+ '(can be used multiple times)')
+ parser.add_argument('--external-shared-lib',
+ action='append', default=[],
+ help='Specify additional external shared library '
+ '(can be used multiple times)')
+
+ parser.add_argument('--iotjs-include-module',
+ action='store', default=set(), type=lambda x: set(x.split(',')),
+ help='Specify iotjs modules which should be included '
+ '(format: module_1,module_2,...)')
+ parser.add_argument('--iotjs-exclude-module',
+ action='store', default=set(), type=lambda x: set(x.split(',')),
+ help='Specify iotjs modules which should be excluded '
+ '(format: module_1,module_2,...)')
+
+ parser.add_argument('--iotjs-minimal-profile',
+ action='store_true', default=False,
+ help='Build IoT.js with minimal profile')
+
+ parser.add_argument('--jerry-cmake-param',
+ action='append', default=[],
+ help='Specify additional cmake parameters for JerryScript '
+ '(can be used multiple times')
+ parser.add_argument('--jerry-compile-flag',
+ action='append', default=[],
+ help='Specify additional compile flags for JerryScript '
+ '(can be used multiple times')
+ parser.add_argument('--jerry-lto',
+ action='store_true', default=False,
+ help='Build JerryScript with LTO enabled')
+
+ parser.add_argument('--jerry-heap-section',
+ action='store', default=None,
+ help='Specify the name of the JerryScript heap section')
+ parser.add_argument('--jerry-heaplimit',
+ type=int, default=config['build_option']['jerry-heaplimit'],
+ help='Specify the size of the JerryScript max heap size '
+ '(default: %(default)s)')
+
+ parser.add_argument('--jerry-memstat',
+ action='store_true', default=False,
+ help='Enable JerryScript heap statistics')
+
+ parser.add_argument('--jerry-profile',
+ choices=['es5.1', 'es2015-subset'], default='es5.1',
+ help='Specify the profile for JerryScript: %(choices)s'
+ ' (default: %(default)s)')
+ parser.add_argument('--jerry-debugger',
+ action='store_true', default=False,
+ help='Enable JerryScript-debugger')
+ parser.add_argument('--jerry-debugger-port',
+ type=int, default=5001,
+ help='Specify the port of JerryScript-debugger (default: %(default)s)')
+ parser.add_argument('--no-init-submodule',
+ action='store_true', default=False,
+ help='Disable initialization of git submodules')
+ parser.add_argument('--no-check-valgrind',
+ action='store_true', default=False,
+ help='Disable test execution with valgrind after build')
+ parser.add_argument('--no-check-test',
+ action='store_true', default=False,
+ help='Disable test exection after build')
+ parser.add_argument('--no-parallel-build',
+ action='store_true', default=False,
+ help='Disable parallel build')
+ parser.add_argument('--no-snapshot',
+ action='store_true', default=False,
+ help='Disable snapshot generation for IoT.js')
+ parser.add_argument('-e', '--experimental',
+ action='store_true', default=False,
+ help='Enable to build experimental features')
+
+ options = parser.parse_args(argv)
+ options.config = config
+
+ return options
+
+
+ def adjust_options(options):
+ # First fix some option inconsistencies.
+ if options.target_os in ['nuttx', 'tizenrt']:
+ options.buildlib = True
+ if not options.sysroot:
+ ex.fail('--sysroot needed for nuttx target')
+
+ options.sysroot = fs.abspath(options.sysroot)
+ if not fs.exists(options.sysroot):
+ ex.fail('NuttX sysroot %s does not exist' % options.sysroot)
+
+ if options.target_arch == 'x86':
+ options.target_arch = 'i686'
+ if options.target_arch == 'x64':
+ options.target_arch = 'x86_64'
+
+ if options.target_os == 'darwin':
+ options.no_check_valgrind = True
+
+ if options.target_board in ['rpi2', 'artik10', 'artik05x']:
+ options.no_check_valgrind = True
+ elif options.target_board == 'none':
+ options.target_board = None
+
+ if options.iotjs_minimal_profile:
+ options.no_check_test = True
+
+ # Then add calculated options.
+ options.host_tuple = '%s-%s' % (platform.arch(), platform.os())
+ options.target_tuple = '%s-%s' % (options.target_arch, options.target_os)
+
+ options.host_build_root = fs.join(path.PROJECT_ROOT,
+ options.builddir,
+ 'host',
+ options.host_tuple,
+ options.buildtype)
+ options.host_build_bins = fs.join(options.host_build_root, 'bin')
+
+ options.build_root = fs.join(path.PROJECT_ROOT,
+ options.builddir,
+ options.target_tuple,
+ options.buildtype)
+ options.build_bins = fs.join(options.build_root, 'bin')
+ options.build_libs = fs.join(options.build_root, 'lib')
+
+ cmake_path = fs.join(path.PROJECT_ROOT, 'cmake', 'config', '%s.cmake')
+ options.cmake_toolchain_file = cmake_path % options.target_tuple
+ options.host_cmake_toolchain_file = cmake_path % options.host_tuple
+
+ # Specify the file of JerryScript profile.
+ options.jerry_profile = fs.join(path.JERRY_PROFILE_ROOT,
+ options.jerry_profile + '.profile')
+
+
+ def print_build_option(options):
+ print('=================================================')
+ option_vars = vars(options)
+ for opt in option_vars:
+ print(' --%s: %s' % (opt, option_vars[opt]))
+ print()
+
+
+ def print_progress(msg):
+ print('==> %s\n' % msg)
+
+
+ def init_submodule():
+ ex.check_run_cmd('git', ['submodule', 'init'])
+ ex.check_run_cmd('git', ['submodule', 'update'])
+
+
+ def build_cmake_args(options, for_jerry=False):
+ cmake_args = []
+ # compile flags
+ compile_flags = []
+
+ config_compile_flags = options.config['compile_flags']
+ compile_flags += config_compile_flags['os'][options.target_os]
+ compile_flags += config_compile_flags['arch'][options.target_arch]
+ compile_flags += config_compile_flags['buildtype'][options.buildtype]
+ if options.target_board:
+ compile_flags += config_compile_flags['board'][options.target_board]
+
+ compile_flags += options.compile_flag
+ compile_flags += options.jerry_compile_flag if for_jerry else []
+
+ cmake_args.append("-DCMAKE_C_FLAGS='%s'" % (' '.join(compile_flags)))
+
+ # link flags
+ link_flags = []
+
+ config_link_flags = options.config['link_flags']
+ link_flags += config_link_flags['os'][options.target_os]
+ link_flags += options.link_flag
+
+ if options.jerry_lto:
+ link_flags.append('-flto')
+
+ cmake_args.append("-DCMAKE_EXE_LINKER_FLAGS='%s'" % (' '.join(link_flags)))
+
+ # external include dir
+ include_dirs = []
+ if options.target_os in ['nuttx', 'tizenrt'] and options.sysroot:
+ include_dirs.append('%s/include' % options.sysroot)
+ if options.target_board == 'stm32f4dis':
+ include_dirs.append('%s/arch/arm/src/stm32' % options.sysroot)
+
+ if options.target_os == 'tizenrt':
+ include_dirs.append('%s/../framework/include/iotbus' % options.sysroot)
+
+ include_dirs.extend(options.external_include_dir)
+ cmake_args.append("-DEXTERNAL_INCLUDE_DIR='%s'" % (' '.join(include_dirs)))
+
+ return cmake_args
+
+
+ def run_make(options, build_home, *args):
+ make_opt = ['-C', build_home]
+ make_opt.extend(args)
+ if not options.no_parallel_build:
+ make_opt.append('-j')
+
+ ex.check_run_cmd('make', make_opt)
+
+
+ def get_on_off(boolean_value):
+ if boolean_value:
+ return 'ON'
+
+ return 'OFF'
+
+
+ def build_iotjs(options):
+ print_progress('Build IoT.js')
+
+ # Set IoT.js cmake options.
+ cmake_opt = [
+ '-B%s' % options.build_root,
+ '-H%s' % path.PROJECT_ROOT,
+ "-DCMAKE_TOOLCHAIN_FILE='%s'" % options.cmake_toolchain_file,
+ '-DCMAKE_BUILD_TYPE=%s' % options.buildtype.capitalize(),
+ '-DTARGET_OS=%s' % options.target_os,
+ '-DTARGET_BOARD=%s' % options.target_board,
+ '-DPLATFORM_DESCRIPTOR=%s' % options.target_tuple,
+ '-DENABLE_LTO=%s' % get_on_off(options.jerry_lto), # --jerry-lto
+ '-DENABLE_SNAPSHOT=%s' % get_on_off(not options.no_snapshot),
+ '-DENABLE_MINIMAL=%s' % get_on_off(options.iotjs_minimal_profile),
+ '-DBUILD_LIB_ONLY=%s' % get_on_off(options.buildlib), # --build-lib
+ # --jerry-memstat
+ '-DFEATURE_MEM_STATS=%s' % get_on_off(options.jerry_memstat),
+ # --iotjs-include-module
+ "-DIOTJS_INCLUDE_MODULE='%s'" % ','.join(options.iotjs_include_module),
+ # --iotjs-exclude-module
+ "-DIOTJS_EXCLUDE_MODULE='%s'" % ','.join(options.iotjs_exclude_module),
+ # --jerry-profile
+ "-DFEATURE_PROFILE='%s'" % options.jerry_profile,
+ ]
+
+ if options.target_os in ['nuttx', 'tizenrt']:
+ cmake_opt.append("-DEXTERNAL_LIBC_INTERFACE='%s'" %
+ fs.join(options.sysroot, 'include'))
+ cmake_opt.append("-DTARGET_SYSTEMROOT='%s'" % options.sysroot)
+ cmake_opt.append("-DEXTERNAL_CMAKE_SYSTEM_PROCESSOR=arm")
+
+ # --jerry-heaplimit
+ if options.jerry_heaplimit:
+ cmake_opt.append('-DMEM_HEAP_SIZE_KB=%d' % options.jerry_heaplimit)
+
+ # --jerry-heap-section
+ if options.jerry_heap_section:
+ cmake_opt.append("-DJERRY_HEAP_SECTION_ATTR='%s'" %
+ options.jerry_heap_section)
+
+ # --jerry-debugger
+ if options.jerry_debugger:
+ cmake_opt.append('-DFEATURE_DEBUGGER=ON')
+ cmake_opt.append('-DFEATURE_DEBUGGER_PORT=%d' %
+ options.jerry_debugger_port)
+
+ # --cmake-param
+ cmake_opt.extend(options.cmake_param)
+
+ # --external-static-lib
+ cmake_opt.append("-DEXTERNAL_STATIC_LIB='%s'" %
+ (' '.join(options.external_static_lib)))
+
+ # --external-shared-lib
+ shared_libs = []
+ shared_libs.extend(options.external_shared_lib)
+ shared_libs.extend(options.config['shared_libs']['os'][options.target_os])
+ cmake_opt.append("-DEXTERNAL_SHARED_LIB='%s'" % (' '.join(shared_libs)))
+
+ # --jerry-cmake-param
+ if options.jerry_cmake_param:
+ cmake_opt.append("-DEXTRA_JERRY_CMAKE_PARAMS='%s'" %
+ ' '.join(options.jerry_cmake_param))
+
+ # --experimental
+ if options.experimental:
+ options.compile_flag.append('-DEXPERIMENTAL')
+
+ # Add common cmake options.
+ cmake_opt.extend(build_cmake_args(options))
+
+ # Run cmake.
+ ex.check_run_cmd('cmake', cmake_opt)
+
+ run_make(options, options.build_root)
+
+
- process_modules(options)
-
+ def run_checktest(options):
+ checktest_quiet = 'yes'
+ if os.getenv('TRAVIS') == "true":
+ checktest_quiet = 'no'
+
+ # IoT.js executable
+ iotjs = fs.join(options.build_root, 'bin', 'iotjs')
+ build_args = ['quiet=' + checktest_quiet]
+ if options.iotjs_exclude_module:
+ skip_module = ','.join(options.iotjs_exclude_module)
+ build_args.append('skip-module=' + skip_module)
+
+ # experimental
+ if options.experimental:
+ build_args.append('experimental=' + 'yes');
+
+ fs.chdir(path.PROJECT_ROOT)
+ code = ex.run_cmd(iotjs, [path.CHECKTEST_PATH] + build_args)
+ if code != 0:
+ ex.fail('Failed to pass unit tests')
+ if not options.no_check_valgrind:
+ code = ex.run_cmd('valgrind', ['--leak-check=full',
+ '--error-exitcode=5',
+ '--undef-value-errors=no',
+ iotjs,
+ path.CHECKTEST_PATH] + build_args)
+ if code == 5:
+ ex.fail('Failed to pass valgrind test')
+ if code != 0:
+ ex.fail('Failed to pass unit tests in valgrind environment')
+
+
+ if __name__ == '__main__':
+ # Initialize build option object.
+ options = init_options()
+ adjust_options(options)
+ print_build_option(options)
+
+ if options.clean:
+ print_progress('Clear build directory')
+ fs.rmtree(options.build_root)
+ fs.rmtree(options.host_build_root)
+
+ # Perform init-submodule.
+ if not options.no_init_submodule:
+ print_progress('Initialize submodule')
+ init_submodule()
+
+ build_iotjs(options)
+
+ # Run tests.
+ if not options.no_check_test:
+ print_progress('Run tests')
+ if options.buildlib:
+ print("Skip unit tests - build target is library\n")
+ elif (options.host_tuple == options.target_tuple or
+ (options.host_tuple == 'x86_64-linux' and
+ options.target_tuple == 'i686-linux')):
+ run_checktest(options)
+ else:
+ print("Skip unit tests - target-host pair is not allowed\n")
+
+ print("\n%sIoT.js Build Succeeded!!%s\n" % (ex._TERM_GREEN, ex._TERM_EMPTY))